log4net.ILog.Info(object)

Here are the examples of the csharp api log4net.ILog.Info(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

592 Examples 7

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static SmsClientId RegisterClient(string CMServerName, string ClientName, string DomainName, string CertPath, SecureString preplaced, ILog log)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))
            {
                // Create a registration request
                ConfigMgrRegistrationRequest registrationRequest = new ConfigMgrRegistrationRequest();

                // Add our certificate for message signing
                registrationRequest.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                // Set the destination hostname
                registrationRequest.Settings.HostName = CMServerName;

                log.Info($"[{ClientName}] - Running Discovery...");
                // Discover local properties for registration metadata
                registrationRequest.Discover();
                registrationRequest.AgentIdenreplacedy = "MyCustomClient";
                registrationRequest.ClientFqdn = ClientName + "." + DomainName;
                registrationRequest.NetBiosName = ClientName;
                log.Info("About to try to register " + registrationRequest.ClientFqdn);

                // Register client and wait for a confirmation with the SMSID

                registrationRequest.Settings.Compression = MessageCompression.Zlib;
                registrationRequest.Settings.ReplyCompression = MessageCompression.Zlib;
                log.Info($"[{ClientName}] - Message Zipped successfully, registering...");
                SmsClientId clientId = registrationRequest.RegisterClient(Sender, TimeSpan.FromMinutes(5));
                log.Info($"[{ClientName}] - Got SMSID from CM Server for this client of {clientId}...");
                return clientId;
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void RegisterClient(int thisIndex)
        {
            GetWait();
            string ThisFilePath = System.IO.Directory.GetCurrentDirectory();
            Device ThisClient = Devices[thisIndex];
            log.Info($"[{ThisClient.Name}] - Beginning to process");
            //Update UI
            FireProgress(thisIndex, "CreatingCert...", 15);
            log.Info($"[{ThisClient.Name}] - About to generate cert at {ThisFilePath}...");
            X509Certificate2 newCert = FauxDeployCMAgent.CreateSelfSignedCertificate(ThisClient.Name);
            string myPath = ExportCert(newCert, ThisClient.Name, ThisFilePath);
            log.Info($"[{ThisClient.Name}] - Cert generated at {myPath}!");
            //Update UI
            FireProgress(thisIndex, "CertCreated!", 25);
            System.Threading.Thread.Sleep(1500);
            FireProgress(thisIndex, "Registering Client...", 30);
            SmsClientId clientId;
            log.Info($"[{ThisClient.Name}] - About to register with CM...");
            try
            {
                clientId = FauxDeployCMAgent.RegisterClient(CmServer, ThisClient.Name, DomainName, myPath, Preplacedword, log);
            }
            catch (Exception e)
            {
                log.Error($"[{ThisClient.Name}] - Failed to register with {e.Message}...");
                if (noisy)
                {
                    System.Windows.MessageBox.Show(" We failed with " + e.Message);
                    throw;
                }
                FireProgress(thisIndex, "ManagementPointErrorResponse...", 100);
                return;
            }
            //SmsClientId clientId = FauxDeployCMAgent.RegisterClient(CmServer, ThisClient.Name, DomainName, myPath, Preplacedword);

            FireProgress(thisIndex, "Starting Inventory...", 50);
            FauxDeployCMAgent.SendDiscovery(CmServer, ThisClient.Name, DomainName, SiteCode, myPath, Preplacedword, clientId, log, InventoryIsChecked);

            FireProgress(thisIndex, "RequestingPolicy", 75);
            //FauxDeployCMAgent.GetPolicy(CMServer, SiteCode, myPath, Preplacedword, clientId);

            FireProgress(thisIndex, "SendingCustom", 85);
            FauxDeployCMAgent.SendCustomDiscovery(CmServer, ThisClient.Name, SiteCode, ThisFilePath, CustomClientRecords);

            FireProgress(thisIndex, "Complete", 100);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 1upD

static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            log.Info("Starting NailsCmd random map generator...");

            CommandLine.Parser.Default.ParseArguments<Options>(args)
             .WithParsed<Options>(opts => RunOptionsAndReturnExitCode(opts))
             .WithNotParsed<Options>((errs) => HandleParseError(errs));

            log.Info("NailsCmd completed.");

        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

public void Export(NailsMap map)
        {
            try
            {

            log.Info(string.Format("Exporting Nails map data to VMF file: {0}", this._filename));

            // Make a deep copy of the stored VMF to add instances to
            VMF output_vmf = new VMFParser.VMF(this._vmf.ToVMFStrings());
            int i = 0;

            foreach(NailsCube cube in map.NailsCubes)
            {
                int x_pos = cube.X * this._horizontal_scale;
                int y_pos = cube.Y * this._horizontal_scale;
                int z_pos = cube.Z * this._vertical_scale;

                var faces = cube.GetFaces();

                if (faces.Contains(NailsCubeFace.Floor))
                {
                    instanceData instance = this.MakeInstance("floor", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Front))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Left))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 90, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Back))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 180, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Right))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 270, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Ceiling))
                {
                    instanceData instance = this.MakeInstance("ceiling", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }
            }


            using (StreamWriter sw = new StreamWriter(new FileStream(this._filename, FileMode.Create)))
            {
                var vmfStrings = output_vmf.ToVMFStrings();
                foreach (string line in vmfStrings)
                {
                    sw.WriteLine(line);
                }
            }

            log.Info(string.Format("Wrote to VMF file: {0}", this._filename));

            } catch (Exception e)
            {
                log.Error("VMFAdapter.Export(): Caught exception: ", e);
                log.Info(string.Format("Failed to write to VMF file: {0}", this._filename));
            }


        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

private static void insertInstanceIntoVMF(instanceData instance, VMF output_vmf)
        {
            try
            {
                IList<int> list = null;

                VBlock instance_block = new VBlock("enreplacedy");
                instance_block.Body.Add(new VProperty("id", instance.ent_id.ToString()));
                instance_block.Body.Add(new VProperty("clreplacedname", "func_instance"));
                instance_block.Body.Add(new VProperty("angles", "0 " + instance.rotation + " 0"));
                instance_block.Body.Add(new VProperty("origin", instance.xpos + " " + instance.ypos + " " + instance.zpos));
                instance_block.Body.Add(new VProperty("file", instance.filename));
                output_vmf.Body.Add(instance_block);
            }
            catch (Exception e)
            {
                log.Error("VMFAdapter.insertInstanceIntoVMF(): Caught exception: ", e);
                log.Info(string.Format("Failed to insert instance: {0}", instance.filename));
            }
        }

19 View Source File : NailsConfig.cs
License : MIT License
Project Creator : 1upD

public static void WriteConfiguration(string filepath,  NailsConfig config)
		{
			try
			{
				log.Info(string.Format("Writing Nails configuration to file: {0}", filepath));

				XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));

				StreamWriter writer = new StreamWriter(filepath);
				serializer.Serialize(writer, config);
				writer.Close();
			}
			catch (Exception e)
			{
				log.Error(string.Format("Error writing Nails configuration to file: {0}", filepath), e);
			}
		}

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
            string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))

            {
                //X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);

                log.Info($"Got SMSID from registration of: {clientId}");

                // create base DDR Message
                ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
                {
                    // Add necessary discovery data
                    SmsId = clientId,
                    ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
                    SiteCode = SiteCode,
                    DomainName = domainName,
                    NetBiosName = clientName
                };

                ddrMessage.Discover();
                // Add our certificate for message signing
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
                ddrMessage.Settings.HostName = CMServerName;
                ddrMessage.Settings.Compression = MessageCompression.Zlib;
                ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
                if (enumerateAndAddCustomDdr)
                {
                    //see current value for the DDR message
                    var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");

                    ////retrieve actual setting
                    string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                                        select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();

                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();

                    ////retrieve reported value
                    xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());

                    ////Set OS to correct setting
                    xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";

                    ////Remove the instance
                    ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));

                    CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
                    {
                        PlatformId = osCaption
                    };
                    InventoryInstance instance = new InventoryInstance(FixedOSRecord);

                    ////Add new instance
                    ddrMessage.DdrInstances.Add(instance);
                }

                ddrMessage.SendMessage(Sender);

                ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
                hinvMessage.Settings.HostName = CMServerName;
                hinvMessage.SmsId = clientId;
                hinvMessage.Settings.Compression = MessageCompression.Zlib;
                hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                //hinvMessage.Settings.Security.EncryptMessage = true;
                hinvMessage.Discover();

                var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
                foreach (string Clreplaced in Clreplacedes)
                {
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
                foreach (string Clreplaced in SMSClreplacedes)
                {
                    log.Info($"---Adding clreplaced : [{Clreplaced}]");
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                hinvMessage.Validate(Sender);
                hinvMessage.SendMessage(Sender);
            };
        }

19 View Source File : App.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

protected override void OnStartup(StartupEventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("        =============  Started Logging  =============        ");
            base.OnStartup(e);
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

protected virtual void OnPropertyChanged(string name)
        {
            var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
                log.Info($"Changing property {name}");
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void FireProgress(int thisIndex, string statusMessage, int percentageComplete)
        {
            Device ThisClient = Devices[thisIndex];
            ThisClient.ProcessProgress = percentageComplete;
            log.Info($"Updating item {ThisClient.Name} to state {statusMessage}");
            switch
                (statusMessage)
            {
                case "CreatingCert...":
                    ThisClient.Status = "Creating Cert...";
                    break;

                case "CertCreated":
                    ThisClient.ImageSource = "Images\\step02.png";
                    ThisClient.Status = "Registering...";
                    break;

                case "Registering Client...":
                    ThisClient.ImageSource = "Images\\step02.png";
                    ThisClient.Status = "Starting Inventory...";
                    break;

                case "Starting Inventory...":
                    ThisClient.ImageSource = "Images\\step02.png";
                    ThisClient.Status = "Starting Inventory...";
                    break;

                case "SendingDiscovery":
                    ThisClient.ImageSource = "Images\\step03.png";
                    ThisClient.Status = "Sending Discovery...";
                    break;

                case "RequestingPolicy":
                    ThisClient.ImageSource = "Images\\step03.png";
                    ThisClient.Status = "Requesting Policy...";
                    break;

                case "SendingCustom":
                    ThisClient.ImageSource = "Images\\step03.png";
                    ThisClient.Status = "Sending Custom DDRs..";
                    break;

                case "Complete":
                    ThisClient.ImageSource = "Images\\step03.png";
                    ThisClient.Status = "Complete!";
                    break;

                case "ManagementPointErrorResponse...":
                    ThisClient.ImageSource = "Images\\step03.png";
                    ThisClient.Status = "Skipping!";
                    break;

                default:
                    break;
            }
        }

19 View Source File : AlifeConfigurator.cs
License : MIT License
Project Creator : 1upD

public static List<BaseAgent> ReadConfiguration(string filepath)
        {
            List<BaseAgent> agents = null;
            try
            {
                log.Info(string.Format("Loading artificial life configuration from file: {0}", filepath));
                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamReader reader = new StreamReader(filepath);
                agents = (List<BaseAgent>)serializer.Deserialize(reader);
                reader.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error reading artificial life configuration in file: {0}", filepath), e);
            }

            return agents;
        }

19 View Source File : AlifeConfigurator.cs
License : MIT License
Project Creator : 1upD

public static void WriteConfiguration(string filepath, List<BaseAgent> agents)
        {
            try
            {
                log.Info(string.Format("Writing artificial life configuration from file: {0}", filepath));

                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamWriter writer = new StreamWriter(filepath);
                serializer.Serialize(writer, agents);
                writer.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error writing artificial life configuration to file: {0}", filepath), e);
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

protected override void OnClosed(EventArgs e)
        {
            log.Info("The form is now closing.");
            log.Info("saving settings");
            ClientFaux.Properties.Settings.Default.Save();
            base.OnClosed(e);
        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

public NailsMap Import()
        {
            try {
            // Reset adapter VMF
            this._vmf = new VMF();


            NailsMap map = new NailsMap();

            List<string> lines = new List<string>();

            using (StreamReader sr = new StreamReader(new FileStream(this._filename, FileMode.OpenOrCreate)))
            {
                while (!sr.EndOfStream)
                {
                    lines.Add(sr.ReadLine());
                }
            }


            VMF input_vmf = new VMF(lines.ToArray());

            for (int blockIndex = 0; blockIndex < input_vmf.Body.Count; blockIndex++)
            {
                // Should this object be included when the VMF is output?
                bool includeThisBlock = true;
                // Get the next object from the VMF
                var obj  = input_vmf.Body[blockIndex];

                try
                {
                // Try to cast to block
                VMFParser.VBlock block = (VMFParser.VBlock)obj;
                

                // If this block is an enreplacedy
                if (block.Name == "enreplacedy")
                {
                    
                    var body = block.Body;
                    foreach (var innerObj in body) {
                        try
                        {
                            VMFParser.VProperty prop = (VMFParser.VProperty)innerObj;

                            // If this block is an instance
                            if (prop.Name == "clreplacedname" && prop.Value == "func_instance")
                            {
                                VProperty fileProperty = (VProperty)body.Where(p => p.Name == "file").ToList()[0];
                                var filePathParts = fileProperty.Value.Split('/');

                                // If this is a nails instance
                                if (filePathParts[0] == "Nails")
                                {
                                    // Get position
                                    VProperty originProperty = (VProperty)body.Where(p => p.Name == "origin").ToList()[0];
                                    var originParts = originProperty.Value.Split(' ');
                                    int x_pos = int.Parse(originParts[0]) / this._horizontal_scale;
                                    int y_pos = int.Parse(originParts[1]) / this._horizontal_scale;
                                    int z_pos = int.Parse(originParts[2]) / this._vertical_scale;
                                    string style = filePathParts[1];
                                    map.MarkLocation(style, x_pos, y_pos, z_pos);

                                        // Remove this block from the vmf
                                        includeThisBlock = false;

                                }

                                break;
                            }

                        } catch (InvalidCastException e)
                        {
                                    log.Error("Invalid cast exception. VMF Object is not a VProperty.", e);
                        }
                    }
                }
            } catch(InvalidCastException e)
                {
                        log.Error("Invalid cast exception. VMF object is not a VBlock.", e);
                }
                // If this object is not a Nails block, add it to the adapter's VMF to be output later
                if (includeThisBlock)
                {
                    this._vmf.Body.Add(obj);
                }

            }

            return map;

        } catch (Exception e)
            {
                log.Error("VMFAdapter.Import(): Caught exception: ", e);
                log.Info(string.Format("Failed to read from VMF file: {0}", this._filename));
            }

            return null;
}

19 View Source File : NailsConfig.cs
License : MIT License
Project Creator : 1upD

public static NailsConfig ReadConfiguration(string filepath)
		{
			NailsConfig config = null;
			try
			{
				log.Info(string.Format("Loading Nails configuration from file: {0}", filepath));
				XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));

				StreamReader reader = new StreamReader(filepath);
				config = (NailsConfig)serializer.Deserialize(reader);
				reader.Close();
			}
			catch (Exception e)
			{
				log.Error(string.Format("Error reading Nails configuration in file: {0}", filepath), e);
			}

			return config;
		}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Agasper

static void PrintUsage()
        {
            log.Info("Usage: AsertNet.exe --filename=\"<filename>\"");
            log.Info("Additional parameters:");
            log.Info("--renameall - Perform renaming all things");
            log.Info("--renamemethods - Perform renaming methods");
            log.Info("--renamemethodparams - Perform renaming method parameters");
            log.Info("--renametypes - Perform renaming types");
            log.Info("--renamefields - Perform renaming fields");
            log.Info("--renameprops - Perform renaming props");
            log.Info("--renameevents - Perform renaming events");
            log.Info("--softrenaming - Renaming to hex symbols instead of unreadable UTF-8");
            log.Info("");
            log.Info("--hideintegers - Replacing every integer constant with masked value");
            log.Info("--hidestrings - Move all the string to the special module");
            log.Info("--encryptstrings - Xor all the string (if used will auto enable --hidestrings)");
            log.Info("");
            log.Info("--anreplacedamper - Inject checksum verification");
            log.Info("--unitylib - Location of UnityEngine.dll (required for anti tampering)");
        }

19 View Source File : AntiTampering.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public static string Sign(string resultreplacedemblyFilename)
        {
            log.Info("Signing module...");
            var aInfo = Signing.Signer.Signreplacedembly(resultreplacedemblyFilename);
            log.Info("Module signed with token " + aInfo.HexToken);
            return aInfo.HexToken;
        }

19 View Source File : AntiTampering.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public static void AddCallToUnity(ModuleDefMD unityModule, string hash)
        {
            log.Info("Adding hash to Unity...");

            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string applicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef tamperClreplaced = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(UnityCertificate).MetadataToken));
            MethodDef checkerMethod = tamperClreplaced.FindMethod("GetHash");

            typeModule.Types.Remove(tamperClreplaced);
            unityModule.Types.Add(tamperClreplaced);

            checkerMethod.Body.Instructions[1].Operand = hash;

            //foreach (var i in checkerMethod.Body.Instructions)
            //    Console.WriteLine(i);
        }

19 View Source File : AntiTampering.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public static void AddCallToModule(ModuleDefMD module)
        {
            log.Info("Adding hash checking to the replacedembly...");
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string applicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef tamperClreplaced = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(AsertSigning).MetadataToken));

            typeModule.Types.Remove(tamperClreplaced);
            module.Types.Add(tamperClreplaced);

            MethodDef cctor = module.GlobalType.FindOrCreateStaticConstructor();

            //foreach (var p in cctor.Body.Instructions)
                //Console.WriteLine(p);

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, tamperClreplaced.FindMethod("Expose")));


            //var t = Type.GetType("UnityEngine.UnityCertificate, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
            //Console.WriteLine(t);
            //Console.WriteLine(t.GetMethod("GetHash", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public));
            //var methodInfo = t.GetMethod("GetHash", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            //string h__ = methodInfo.Invoke(null, null).ToString();

            //throw new Exception("asd");




            //foreach (TypeDef type in module.Types)
            //{
            //    if (type.IsGlobalModuleType) 
            //        continue;
                
            //    foreach (MethodDef method in type.Methods)
            //    {
            //        if (!method.HasBody) 
            //            continue;
            //        if (method.IsConstructor)
            //        {
            //            method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Nop));
            //            method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));
            //        }
            //    }
            //}
        }

19 View Source File : ConstantProtection.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public void Protect()
        {
            log.Info("Injecting masking clreplaced...");
            InjectMasker();
            log.Info("Protecting modules...");
            foreach (TypeDef type in module.Types)
            {
                ProtectType(type);
            }
        }

19 View Source File : Renamer.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public void RenameModule()
        {
            log.Info("Renaming things...");
            foreach (TypeDef type in module.Types)
            {
                RenameType(type);
            }   
        }

19 View Source File : Asert.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public void AnreplacedamperingInjectUnity(string hash, string unityLibFilename)
        {
            log.Info("Reading file " + unityLibFilename);
            var unityModule = ModuleDefMD.Load(unityLibFilename);
            Anreplacedampering.AddCallToUnity(unityModule, hash);
            unityModule.Write(unityLibFilename);
            log.Info("Unity lib updated");
        }

19 View Source File : Asert.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public void Save(string filename)
        {
            module.Write(filename);
            log.Info("File Saved to " + filename);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Agasper

public static void Main(string[] args)
        {
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string ApplicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            XmlConfigurator.Configure(new FileInfo(Path.Combine(ApplicationPath, "logging.xml")));

            log.Info("Asert Unity Build Protection");
            log.Info("Copyright (c) 2017 - Alexander Melkozerov");
            log.Info("-------------------------------------------------");

            Arguments parsedArgs = new Arguments(args);

            if (!parsedArgs.ContainsArg("filename"))
            {
                PrintUsage();
                return;
            }
            string filename = parsedArgs["filename"];


            if (parsedArgs.ContainsArg("anreplacedamper") && !parsedArgs.ContainsArg("unitylib"))
            {
                log.Error("You're going to use anti tampering protection, but forgot to specify location of the unityengine.dll with --unitylib argument");
                return;
            }

            Asert asert = new Asert(filename)
            {
                StrongRenaming = !parsedArgs.ContainsArg("softrenaming"),
                RenameEvents = parsedArgs.ContainsArg("renameevents") || parsedArgs.ContainsArg("renameall"),
                RenameProps = parsedArgs.ContainsArg("renameprops") || parsedArgs.ContainsArg("renameall"),
                RenameFields = parsedArgs.ContainsArg("renamefields") || parsedArgs.ContainsArg("renameall"),
                RenameTypes = parsedArgs.ContainsArg("renametypes") || parsedArgs.ContainsArg("renameall"),
                RenameMethodParams = parsedArgs.ContainsArg("renamemethodparams") || parsedArgs.ContainsArg("renameall"),
                RenameMethods = parsedArgs.ContainsArg("renamemethods") || parsedArgs.ContainsArg("renameall"),

                HideStrings = parsedArgs.ContainsArg("hidestrings"),
                HideIntegers = parsedArgs.ContainsArg("hideintegers"),
                EncryptStrings = parsedArgs.ContainsArg("encryptstrings"),

            };

			if (parsedArgs.ContainsArg("anreplacedamper"))
				asert.AnreplacedamperingProtect();
            asert.ProtectConstants();
            asert.PerformRenaming();
            asert.Save(filename);
            if (parsedArgs.ContainsArg("anreplacedamper"))
            {
                asert.AnreplacedamperingInjectUnity(asert.AnreplacedamperingSign(filename), parsedArgs["unitylib"]);
            }
        }

19 View Source File : Controller.cs
License : MIT License
Project Creator : AlturosDestinations

private void RegisterWebApi(int port)
        {
            var url = $"http://*:{port}";
            var fullUrl = url.Replace("*", "localhost");

            Log.Info($"{nameof(RegisterWebApi)} - Swagger: {fullUrl}/swagger/");

            try
            {
                this._webApp = WebApp.Start(url, (app) =>
                {
                    //Use JSON friendly default settings
                    var defaultSettings = new JsonSerializerSettings
                    {
                        Formatting = Formatting.Indented,
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Converters = new List<JsonConverter> { new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }, }
                    };
                    JsonConvert.DefaultSettings = () => { return defaultSettings; };

                    var config = new HttpConfiguration();
                    config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(this._container);

                    //Specify JSON as the default media type
                    config.Formatters.Clear();
                    config.Formatters.Add(new JsonMediaTypeFormatter());
                    config.Formatters.JsonFormatter.SerializerSettings = defaultSettings;

                    //Route all requests to the RootController by default
                    config.Routes.MapHttpRoute("api", "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
                    config.MapHttpAttributeRoutes();

                    //Tell swagger to generate doreplacedentation based on the XML doc file output from msbuild
                    config.EnableSwagger(c =>
                    {
                        c.SingleApiVersion("1.0", SystemName);
                    }).EnableSwaggerUi();

                    app.UseWebApi(config);
                });
            }
            catch (Exception exception)
            {
                Log.Error($"{nameof(RegisterWebApi)} - run first AllowWebserver.cmd", exception);
            }
        }

19 View Source File : Math.cs
License : Apache License 2.0
Project Creator : apache

public int Subtract(int left, int right)
		{
			int result = left - right;
			if (log.IsInfoEnabled) log.Info(""+left+" - "+right+" = "+result);
			return result;
		}

19 View Source File : EntryPoint.cs
License : Apache License 2.0
Project Creator : apache

[STAThread]
		static void Main(string[] args)
		{
			if (log.IsInfoEnabled) log.Info(args);

			if (args.Length != 2)
			{
				log.Error("Must supply 2 command line arguments");
			}
			else
			{
				int left = int.Parse(args[0]);
				int right = int.Parse(args[1]);
				int result = 0;

				if (log.IsDebugEnabled) log.Debug("Adding ["+left+"] to ["+right+"]");

				result = (new SimpleModule.Math()).Add(left, right);

				if (log.IsDebugEnabled) log.Debug("Result ["+result+"]");

				Console.Out.WriteLine(result);


				if (log.IsDebugEnabled) log.Debug("Subtracting ["+right+"] from ["+left+"]");

				result = (new SharedModule.Math()).Subtract(left, right);

				if (log.IsDebugEnabled) log.Debug("Result ["+result+"]");

				Console.Out.WriteLine(result);
			}
		}

19 View Source File : Math.cs
License : Apache License 2.0
Project Creator : apache

public int Add(int left, int right)
		{
			int result = left + right;
			if (log.IsInfoEnabled) log.Info(""+left+" + "+right+" = "+result);
			return result;
		}

19 View Source File : LoggingExample.cs
License : Apache License 2.0
Project Creator : apache

public static void Main(string[] args)
		{
			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");

			// Log a debug message. Test if debug is enabled before
			// attempting to log the message. This is not required but
			// can make running without logging faster.
			if (log.IsDebugEnabled) log.Debug("This is a debug message");

			try
			{
				Bar();
			}
			catch(Exception ex)
			{
				// Log an error with an exception
				log.Error("Exception thrown from method Bar", ex);
			}

			log.Error("Hey this is an error!");

			// Push a message on to the Nested Diagnostic Context stack
			using(log4net.NDC.Push("NDC_Message"))
			{
				log.Warn("This should have an NDC message");

				// Set a Mapped Diagnostic Context value  
				log4net.MDC.Set("auth", "auth-none");
				log.Warn("This should have an MDC message for the key 'auth'");

			} // The NDC message is popped off the stack at the end of the using {} block

			log.Warn("See the NDC has been popped of! The MDC 'auth' key is still with us.");

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] End");

			Console.Write("Press Enter to exit...");
			Console.ReadLine();
		}

19 View Source File : LoggingExample.cs
License : Apache License 2.0
Project Creator : apache

public static void Main(string[] args)
		{
			log4net.ThreadContext.Properties["session"] = 21;

			// Hookup the FireEventAppender event
			if (FireEventAppender.Instance != null)
			{
				FireEventAppender.Instance.MessageLoggedEvent += new MessageLoggedEventHandler(FireEventAppender_MessageLoggedEventHandler);
			}

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");

			// Log a debug message. Test if debug is enabled before
			// attempting to log the message. This is not required but
			// can make running without logging faster.
			if (log.IsDebugEnabled) log.Debug("This is a debug message");

			// Log a custom object as the log message
			log.Warn(new MsgObj(42, "So long and thanks for all the fish"));

			try
			{
				Bar();
			}
			catch(Exception ex)
			{
				// Log an error with an exception
				log.Error("Exception thrown from method Bar", ex);
			}

			log.Error("Hey this is an error!");

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] End");

			Console.Write("Press Enter to exit...");
			Console.ReadLine();
		}

19 View Source File : LoggingExample.cs
License : Apache License 2.0
Project Creator : apache

public static void Main(string[] args)
		{
			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [SampleLayoutsApp] Start");

			// Log a debug message. Test if debug is enabled before
			// attempting to log the message. This is not required but
			// can make running without logging faster.
			if (log.IsDebugEnabled) log.Debug("This is a debug message");

			log.Info("This is a long line of logging text. This should test if the LineWrappingLayout works. This text should be wrapped over multiple lines of output. Could you get a log message longer than this?");

			log.Error("Hey this is an error!");

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [SampleLayoutsApp] End");

			Console.Write("Press Enter to exit...");
			Console.ReadLine();
		}

19 View Source File : RemotingClient.cs
License : Apache License 2.0
Project Creator : apache

static void Main(string[] args)
		{
			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [RemotingClient] Start");

			log.Fatal("First Fatal message");

			for(int i=0; i<8; i++)
			{
				log.Debug("Hello");
			}

			// Log a message with an exception and nested exception
			log.Error("An exception has occured", new Exception("Some exception", new Exception("Some nested exception")));

			for(int i=0; i<8; i++)
			{
				log.Debug("There");
			}

			// Stress test can be called here
			//StessTest();

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [RemotingClient] End");
		}

19 View Source File : RemotingServer.cs
License : Apache License 2.0
Project Creator : apache

static void Main(string[] args)
		{
			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [RemotingServer] Start");

			// Configure remoting. This loads the TCP channel as specified in the .config file.
			RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

			// Publish the remote logging server. This is done using the log4net plugin.
			log4net.LogManager.GetRepository().PluginMap.Add(new log4net.Plugin.RemoteLoggingServerPlugin("LoggingSink"));

			// Wait for the user to exit
			Console.WriteLine("Press 0 and ENTER to Exit");
			String keyState = "";
			while (String.Compare(keyState,"0", true) != 0)
			{
				keyState = Console.ReadLine();
			}

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [RemotingServer] End");
		}

19 View Source File : WebForm1.aspx.cs
License : Apache License 2.0
Project Creator : apache

private void btnCalcAdd_Click(object sender, System.EventArgs e)
		{
			if (log.IsDebugEnabled) log.Debug("txtAdd1=[" + txtAdd1.Text + "] txtAdd2=[" + txtAdd2.Text + "]");

			int result = m_MathAdd.Add(int.Parse(txtAdd1.Text), int.Parse(txtAdd2.Text));

			if (log.IsInfoEnabled) log.Info("result=[" + result + "]");
			
			txtAdd3.Text = result.ToString();
		}

19 View Source File : WebForm1.aspx.cs
License : Apache License 2.0
Project Creator : apache

private void btnCalcSub_Click(object sender, System.EventArgs e)
		{
			if (log.IsDebugEnabled) log.Debug("txtSub1=[" + txtSub1.Text + "] txtSub2=[" + txtSub2.Text + "]");

			int result = m_MathSub.Subtract(int.Parse(txtSub1.Text), int.Parse(txtSub2.Text));

			if (log.IsInfoEnabled) log.Info("result=[" + result + "]");
			
			txtSub3.Text = result.ToString();
		}

19 View Source File : EntryPoint.cs
License : Apache License 2.0
Project Creator : apache

public static void Main() 
		{
			// Uncomment the next line to enable log4net internal debugging
			// log4net.helpers.LogLog.InternalDebugging = true;

			// This will instruct log4net to look for a configuration file
			// called ConsoleApp.exe.config in the application base
			// directory (i.e. the directory containing ConsoleApp.exe)
			log4net.Config.XmlConfigurator.Configure();

			// Create a logger
			ILog log = LogManager.GetLogger(typeof(EntryPoint));

			// Log an info level message
			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");

			// Invoke static LogEvents method on LoggingExample clreplaced
			LoggingExample.LogEvents(); 

			Console.Write("Press Enter to exit...");
			Console.ReadLine();

			if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Stop");

			// It's not possible to use shutdown hooks in the .NET Compact Framework,
			// so you have manually shutdown log4net to free all resoures.
			LogManager.Shutdown();
		}

19 View Source File : Math.cs
License : Apache License 2.0
Project Creator : apache

public int Subtract(int left, int right)
		{
			int result = left - right;
			if (log.IsInfoEnabled) log.Info("" + left + " - " + right + " = " + result);
			return result;
		}

19 View Source File : EntryPoint.cs
License : Apache License 2.0
Project Creator : apache

[STAThread]
		public static void Main(string[] args)
		{
			if (log.IsInfoEnabled) log.Info(args);

			if (args.Length != 2)
			{
				log.Error("Must supply 2 command line arguments");
			}
			else
			{
				int left = int.Parse(args[0]);
				int right = int.Parse(args[1]);
				int result = 0;

				if (log.IsDebugEnabled) log.Debug("Adding [" + left + "] to [" + right + "]");

				result = (new SimpleModule.Math()).Add(left, right);

				if (log.IsDebugEnabled) log.Debug("Result [" + result + "]");

				Console.Out.WriteLine(result);


				if (log.IsDebugEnabled) log.Debug("Subtracting [" + right + "] from [" + left + "]");

				result = (new SharedModule.Math()).Subtract(left, right);

				if (log.IsDebugEnabled) log.Debug("Result [" + result + "]");

				Console.Out.WriteLine(result);
			}
		}

19 View Source File : Math.cs
License : Apache License 2.0
Project Creator : apache

public int Add(int left, int right)
		{
			int result = left + right;
			if (log.IsInfoEnabled) log.Info("" + left + " + " + right + " = " + result);
			return result;
		}

19 View Source File : EntryPoint.cs
License : Apache License 2.0
Project Creator : apache

static void Main(string[] args)
		{
			if (log.IsInfoEnabled) log.Info(args);

			if (args.Length != 2)
			{
				log.Error("Must supply 2 command line arguments");
			}
			else
			{
				int left = int.Parse(args[0]);
				int right = int.Parse(args[1]);
				int result = 0;

				if (log.IsDebugEnabled) log.Debug("Adding ["+left+"] to ["+right+"]");

				result = (new SimpleModule.Math()).Add(left, right);

				if (log.IsDebugEnabled) log.Debug("Result ["+result+"]");

				Console.Out.WriteLine(result);


				if (log.IsDebugEnabled) log.Debug("Subtracting ["+right+"] from ["+left+"]");

				result = (new SharedModule.Math()).Subtract(left, right);

				if (log.IsDebugEnabled) log.Debug("Result ["+result+"]");

				Console.Out.WriteLine(result);
			}
		}

19 View Source File : ThreadContextTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestThreadPropertiesPattern()
		{
			StringAppender stringAppender = new StringAppender();
			stringAppender.Layout = new PatternLayout("%property{" +  Utils.PROPERTY_KEY + "}");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadProperiesPattern");

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no thread properties value set");
			stringAppender.Reset();

			ThreadContext.Properties[Utils.PROPERTY_KEY] = "val1";

			log1.Info("TestMessage");
			replacedert.AreEqual("val1", stringAppender.GetString(), "Test thread properties value set");
			stringAppender.Reset();

			ThreadContext.Properties.Remove(Utils.PROPERTY_KEY);

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test thread properties value removed");
			stringAppender.Reset();
		}

19 View Source File : ThreadContextTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestThreadStackPatternNullVal2()
		{
			StringAppender stringAppender = new StringAppender();
            stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern");

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no thread stack value set");
			stringAppender.Reset();

			using(ThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val1"))
			{
				log1.Info("TestMessage");
				replacedert.AreEqual("val1", stringAppender.GetString(), "Test thread stack value set");
				stringAppender.Reset();

				using(ThreadContext.Stacks[Utils.PROPERTY_KEY].Push(null))
				{
					log1.Info("TestMessage");
					replacedert.AreEqual("val1 ", stringAppender.GetString(), "Test thread stack value pushed null");
					stringAppender.Reset();
				}
			}

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test thread stack value removed");
			stringAppender.Reset();
		}

19 View Source File : ShutdownTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestShutdownAndReconfigure()
		{
			// Create unique repository
			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());

			// Create appender and configure repos
			StringAppender stringAppender = new StringAppender();
			stringAppender.Layout = new PatternLayout("%m");
			BasicConfigurator.Configure(rep, stringAppender);

			// Get logger from repos
			ILog log1 = LogManager.GetLogger(rep.Name, "logger1");

			log1.Info("TestMessage1");
			replacedert.AreEqual("TestMessage1", stringAppender.GetString(), "Test logging configured");
			stringAppender.Reset();

			rep.Shutdown();

			log1.Info("TestMessage2");
			replacedert.AreEqual("", stringAppender.GetString(), "Test not logging while shutdown");
			stringAppender.Reset();

			// Create new appender and configure
			stringAppender = new StringAppender();
			stringAppender.Layout = new PatternLayout("%m");
			BasicConfigurator.Configure(rep, stringAppender);

			log1.Info("TestMessage3");
			replacedert.AreEqual("TestMessage3", stringAppender.GetString(), "Test logging re-configured");
			stringAppender.Reset();
		}

19 View Source File : StringFormatTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestFormatString()
		{
			StringAppender stringAppender = new StringAppender();
			stringAppender.Layout = new PatternLayout("%message");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestFormatString");

			// ***
			log1.Info("TestMessage");
			replacedert.AreEqual("TestMessage", stringAppender.GetString(), "Test simple INFO event");
			stringAppender.Reset();


			// ***
			log1.DebugFormat("Before {0} After", "Middle");
			replacedert.AreEqual("Before Middle After", stringAppender.GetString(), "Test simple formatted DEBUG event");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("Before {0} After", "Middle");
			replacedert.AreEqual("Before Middle After", stringAppender.GetString(), "Test simple formatted INFO event");
			stringAppender.Reset();

			// ***
			log1.WarnFormat("Before {0} After", "Middle");
			replacedert.AreEqual("Before Middle After", stringAppender.GetString(), "Test simple formatted WARN event");
			stringAppender.Reset();

			// ***
			log1.ErrorFormat("Before {0} After", "Middle");
			replacedert.AreEqual("Before Middle After", stringAppender.GetString(), "Test simple formatted ERROR event");
			stringAppender.Reset();

			// ***
			log1.FatalFormat("Before {0} After", "Middle");
			replacedert.AreEqual("Before Middle After", stringAppender.GetString(), "Test simple formatted FATAL event");
			stringAppender.Reset();


			// ***
			log1.InfoFormat("Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("Before Middle After End", stringAppender.GetString(), "Test simple formatted INFO event 2");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("IGNORE THIS WARNING - EXCEPTION EXPECTED Before {0} After {1} {2}", "Middle", "End");
			replacedert.AreEqual(STRING_FORMAT_ERROR, stringAppender.GetString(), "Test formatting error");
			stringAppender.Reset();
		}

19 View Source File : StringFormatTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestLogFormatApi_Info()
		{
			StringAppender stringAppender = new StringAppender();
			stringAppender.Layout = new PatternLayout("%level:%message");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestLogFormatApi_Info");

			// ***
			log1.Info("TestMessage");
			replacedert.AreEqual("INFO:TestMessage", stringAppender.GetString(), "Test simple INFO event 1");
			stringAppender.Reset();

			// ***
			log1.Info("TestMessage", null);
			replacedert.AreEqual("INFO:TestMessage", stringAppender.GetString(), "Test simple INFO event 2");
			stringAppender.Reset();

			// ***
			log1.Info("TestMessage", new Exception("Exception message"));
			replacedert.AreEqual("INFO:TestMessageSystem.Exception: Exception message" + Environment.NewLine, stringAppender.GetString(), "Test simple INFO event 3");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("a{0}", "1");
			replacedert.AreEqual("INFO:a1", stringAppender.GetString(), "Test formatted INFO event with 1 parm");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("a{0}b{1}", "1", "2");
			replacedert.AreEqual("INFO:a1b2", stringAppender.GetString(), "Test formatted INFO event with 2 parm");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("a{0}b{1}c{2}", "1", "2", "3");
			replacedert.AreEqual("INFO:a1b2c3", stringAppender.GetString(), "Test formatted INFO event with 3 parm");
			stringAppender.Reset();


			// ***
			log1.InfoFormat("a{0}b{1}c{2}d{3}e{4}f", "Q", "W", "E", "R", "T", "Y");
			replacedert.AreEqual("INFO:aQbWcEdReTf", stringAppender.GetString(), "Test formatted INFO event with 5 parms (only 4 used)");
			stringAppender.Reset();

			// ***
			log1.InfoFormat(null, "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("INFO:Before Middle After End", stringAppender.GetString(), "Test formatting with null provider");
			stringAppender.Reset();

			// ***
			log1.InfoFormat(new CultureInfo("en"), "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("INFO:Before Middle After End", stringAppender.GetString(), "Test formatting with 'en' provider");
			stringAppender.Reset();
		}

19 View Source File : ThreadContextTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestThreadStackPattern()
		{
			StringAppender stringAppender = new StringAppender();
            stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern");

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no thread stack value set");
			stringAppender.Reset();

			using(ThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val1"))
			{
				log1.Info("TestMessage");
				replacedert.AreEqual("val1", stringAppender.GetString(), "Test thread stack value set");
				stringAppender.Reset();
			}

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test thread stack value removed");
			stringAppender.Reset();
		}

19 View Source File : ThreadContextTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestThreadStackPattern2()
		{
			StringAppender stringAppender = new StringAppender();
            stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern");

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no thread stack value set");
			stringAppender.Reset();

			using(ThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val1"))
			{
				log1.Info("TestMessage");
				replacedert.AreEqual("val1", stringAppender.GetString(), "Test thread stack value set");
				stringAppender.Reset();

				using(ThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val2"))
				{
					log1.Info("TestMessage");
					replacedert.AreEqual("val1 val2", stringAppender.GetString(), "Test thread stack value pushed 2nd val");
					stringAppender.Reset();
				}
			}

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test thread stack value removed");
			stringAppender.Reset();
		}

19 View Source File : ThreadContextTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestThreadStackPatternNullVal()
		{
			StringAppender stringAppender = new StringAppender();
            stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern");

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no thread stack value set");
			stringAppender.Reset();

			using(ThreadContext.Stacks[Utils.PROPERTY_KEY].Push(null))
			{
				log1.Info("TestMessage");
				replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test thread stack value set");
				stringAppender.Reset();
			}

			log1.Info("TestMessage");
			replacedert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test thread stack value removed");
			stringAppender.Reset();
		}

19 View Source File : ThreadContextTest.cs
License : Apache License 2.0
Project Creator : apache

private static void ExecuteBackgroundThread()
		{
            ILog log = LogManager.GetLogger(TestBackgroundThreadContextPropertyRepository, "ExecuteBackGroundThread");
			ThreadContext.Properties["DateTimeTodayToString"] = DateTime.Today.ToString();

			log.Info("TestMessage");

			Repository.Hierarchy.Hierarchy hierarchyLoggingRepository = (Repository.Hierarchy.Hierarchy)log.Logger.Repository;
			StringAppender stringAppender = (StringAppender)hierarchyLoggingRepository.Root.Appenders[0];

			replacedert.AreEqual(DateTime.Today.ToString(), stringAppender.GetString());
		}

19 View Source File : StringFormatTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
		public void TestLogFormatApi_NoInfo()
		{
			StringAppender stringAppender = new StringAppender();
			stringAppender.Threshold = Level.Warn;
			stringAppender.Layout = new PatternLayout("%level:%message");

			ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(rep, stringAppender);

			ILog log1 = LogManager.GetLogger(rep.Name, "TestLogFormatApi_Info");

			// ***
			log1.Info("TestMessage");
			replacedert.AreEqual("", stringAppender.GetString(), "Test simple INFO event 1");
			stringAppender.Reset();

			// ***
			log1.Info("TestMessage", null);
			replacedert.AreEqual("", stringAppender.GetString(), "Test simple INFO event 2");
			stringAppender.Reset();

			// ***
			log1.Info("TestMessage", new Exception("Exception message"));
			replacedert.AreEqual("", stringAppender.GetString(), "Test simple INFO event 3");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("a{0}", "1");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted INFO event with 1 parm");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("a{0}b{1}", "1", "2");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted INFO event with 2 parm");
			stringAppender.Reset();

			// ***
			log1.InfoFormat("a{0}b{1}c{2}", "1", "2", "3");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted INFO event with 3 parm");
			stringAppender.Reset();


			// ***
			log1.InfoFormat("a{0}b{1}c{2}d{3}e{4}f", "Q", "W", "E", "R", "T", "Y");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatted INFO event with 5 parms (only 4 used)");
			stringAppender.Reset();

			// ***
			log1.InfoFormat(null, "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatting with null provider");
			stringAppender.Reset();

			// ***
			log1.InfoFormat(new CultureInfo("en"), "Before {0} After {1}", "Middle", "End");
			replacedert.AreEqual("", stringAppender.GetString(), "Test formatting with 'en' provider");
			stringAppender.Reset();
		}

See More Examples