System.Console.WriteLine(string, object, object)

Here are the examples of the csharp api System.Console.WriteLine(string, object, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1280 Examples 7

19 View Source File : FLRPC.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

private static void OnError(object sender, ErrorMessage args)
        {
            //Some error has occured from one of our messages. Could be a malformed presence for example.
            // Discord will give us one of these events and its upto us to handle it
            Console.WriteLine("Error occured within discord. ({1}) {0}", args.Message, args.Code);
        }

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

static void WriteToRegKey(string host, string username, string preplacedword, string keypath, string valuename)
        {
            if (!keypath.Contains(":"))
            {
                Console.WriteLine("[-] Please put ':' inbetween hive and path: HKCU:Location\\Of\\Key");
                return;
            }
            string[] reginfo = keypath.Split(':');
            string reghive = reginfo[0];
            string wmiNameSpace = "root\\CIMv2";
            UInt32 hive = 0;
            switch (reghive.ToUpper())
            {
                case "HKCR":
                    hive = 0x80000000;
                    break;
                case "HKCU":
                    hive = 0x80000001;
                    break;
                case "HKLM":
                    hive = 0x80000002;
                    break;
                case "HKU":
                    hive = 0x80000003;
                    break;
                case "HKCC":
                    hive = 0x80000005;
                    break;
                default:
                    Console.WriteLine("[X] Error     :  Could not get the right reg hive");
                    return;
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connect to to WMI    : {0}", ex.Message);
                return;
            }

            try
            {
                //Probably stay with string value only
                ManagementClreplaced registry = new ManagementClreplaced(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("SetStringValue");
                inParams["hDefKey"] = hive;
                inParams["sSubKeyName"] = reginfo[1];
                inParams["sValueName"] = valuename;
                inParams["sValue"] = datavals;
                ManagementBaseObject outParams = registry.InvokeMethod("SetStringValue", inParams, null);
                if(Convert.ToInt32(outParams["ReturnValue"]) == 0)
                {
                    Console.WriteLine("[+] Created {0} {1} and put content inside", keypath, valuename);
                }
                else
                {
                    Console.WriteLine("[-] An error occured, please check values");
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error      :  {0}", ex.Message));
                return;
            }
        }

19 View Source File : FileWrite.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void WriteToWMIClreplaced(string host, string username, string preplacedword, string wnamespace, string clreplacedname)
        {
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wnamespace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }
            try
            {
                var nclreplaced = new ManagementClreplaced(scope, new ManagementPath(string.Empty), new ObjectGetOptions());
                nclreplaced["__CLreplaced"] = clreplacedname;
                nclreplaced.Qualifiers.Add("Static", true);
                nclreplaced.Properties.Add("WinVal", CimType.String, false);
                nclreplaced.Properties["WinVal"].Qualifiers.Add("read", true);
                nclreplaced["WinVal"] = datavals;
                //nclreplaced.Properties.Add("Sizeof", CimType.String, false);
                //nclreplaced.Properties["Sizeof"].Qualifiers.Add("read", true);
                //nclreplaced.Properties["Sizeof"].Qualifiers.Add("Description", "Value needed for Windows");
                nclreplaced.Put();

                Console.WriteLine("[+] Create WMI Clreplaced     :   {0} {1}", wnamespace, clreplacedname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error     :  {0}", ex.Message));
                return;
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void CleanSingle(string command)
        {
            string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
            string keyvalue = string.Empty;
            string regcmd = string.Empty;
            if (command.EndsWith("\\1"))
            {
                regcmd = command;
            }
            else
            {
                regcmd = string.Format("{0}\\1", command);
            }
             
            try
            {
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);

                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        if(regkey.GetValue(subKey).ToString() == regcmd)
                        {
                            keyvalue = subKey;
                            regkey.DeleteValue(subKey);
                            Console.WriteLine(regcmd);
                            Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
                        }
                    }
                    if(keyvalue != string.Empty)
                    {
                        string mruchars = regkey.GetValue("MRUList").ToString();
                        int index = mruchars.IndexOf(keyvalue);
                        mruchars = mruchars.Remove(index, 1);
                        regkey.SetValue("MRUList", mruchars);
                    }
                }
                regkey.Close();
            }
            catch (ArgumentException)
            {
                Console.WriteLine("[-] Error: Selected Registry value does not exist");
            }
        }

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

static void WriteToFileWMI(string host, string eventName, string username, string preplacedword)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                if (!String.IsNullOrEmpty(username))
                {
                    Console.WriteLine("[*] User credentials   : {0}", username);
                    options.Username = username;
                    options.Preplacedword = preplacedword;
                }
                Console.WriteLine();

                // first create a 5 second timer on the remote host
                ManagementScope timerScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", host), options);
                ManagementClreplaced timerClreplaced = new ManagementClreplaced(timerScope, new ManagementPath("__IntervalTimerInstruction"), null);
                ManagementObject myTimer = timerClreplaced.CreateInstance();
                myTimer["IntervalBetweenEvents"] = (UInt32)5000;
                myTimer["SkipIfPreplaceded"] = false;
                myTimer["TimerId"] = "Timer";
                try
                {
                    Console.WriteLine("[+] Creating Event Subscription {0}   : {1}", eventName, host);
                    myTimer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in creating timer object: {0}", ex.Message);
                    return;
                }

                ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\subscription", host), options);

                // then install the __EventFilter for the timer object
                ManagementClreplaced wmiEventFilter = new ManagementClreplaced(scope, new ManagementPath("__EventFilter"), null);
                WqlEventQuery myEventQuery = new WqlEventQuery(@"SELECT * FROM __TimerEvent WHERE TimerID = 'Timer'");
                ManagementObject myEventFilter = wmiEventFilter.CreateInstance();
                myEventFilter["Name"] = eventName;
                myEventFilter["Query"] = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"] = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                try
                {
                    myEventFilter.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event filter   : {0}", ex.Message);
                }


                // now create the ActiveScriptEventConsumer payload (VBS)
                ManagementObject myEventConsumer = new ManagementClreplaced(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();

                myEventConsumer["Name"] = eventName;
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"] = vbsp;
                myEventConsumer["KillTimeout"] = (UInt32)45;

                try
                {
                    myEventConsumer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event consumer: {0}", ex.Message);
                }


                // finally bind them together with a __FilterToConsumerBinding
                ManagementObject myBinder = new ManagementClreplaced(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

                myBinder["Filter"] = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;

                try
                {
                    myBinder.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting FilterToConsumerBinding: {0}", ex.Message);
                }


                // wait for everything to trigger
                Console.WriteLine("\r\n[+] Waiting 10 seconds for event '{0}' to trigger\r\n", eventName);
                System.Threading.Thread.Sleep(10 * 1000);
                Console.WriteLine("[+] Done...cleaning up");
                // cleanup
                try
                {
                    myTimer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing 'Timer' interval timer: {0}", ex.Message);
                }

                try
                {
                    myBinder.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing FilterToConsumerBinding: {0}", ex.Message);
                }

                try
                {
                    myEventFilter.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event filter: {0}", ex.Message);
                }

                try
                {
                    myEventConsumer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event consumer: {0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Exception : {0}", ex.Message));
            }
        }

19 View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

private void RdpConnectionOnOnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
        {
            DisconnectCode = e.discReason;
            var dire = Enum.GetName(typeof(DisconnectReasons), (uint)DisconnectCode);
            Console.WriteLine("[+] Connection closed     :  {0}", target);
            if(e.discReason != 1)
            {
                Console.WriteLine("[-] Disconnection Reason  :  {0} - {1}", DisconnectCode, dire);
            }
            Environment.Exit(0);
        }

19 View Source File : FileWrite.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void RemoveRegValue(string host, string username, string preplacedword, string keypath, string keyname)
        {
            if (!keypath.Contains(":"))
            {
                Console.WriteLine("[-] Please put ':' inbetween hive and path: HKCU:Location\\Of\\Key");
                return;
            }
            if (!String.IsNullOrEmpty(host))
            {
                host = "127.0.0.1";
            }
            string[] reginfo = keypath.Split(':');
            string reghive = reginfo[0];
            string wmiNameSpace = "root\\CIMv2";
            UInt32 hive = 0;
            switch (reghive.ToUpper())
            {
                case "HKCR":
                    hive = 0x80000000;
                    break;
                case "HKCU":
                    hive = 0x80000001;
                    break;
                case "HKLM":
                    hive = 0x80000002;
                    break;
                case "HKU":
                    hive = 0x80000003;
                    break;
                case "HKCC":
                    hive = 0x80000005;
                    break;
                default:
                    Console.WriteLine("[X] Error     :  Could not get the right reg hive");
                    return;
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+]  WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }

            try
            {
                //Probably stay with string value only
                ManagementClreplaced registry = new ManagementClreplaced(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("DeleteValue");
                inParams["hDefKey"] = hive;
                inParams["sSubKeyName"] = keypath;
                inParams["sValueName"] = keyname;
                ManagementBaseObject outParams1 = registry.InvokeMethod("DeleteValue", inParams, null);
                Console.WriteLine("[+] Deleted value at {0} {1}", keypath, keyname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[-] {0}", ex.Message));
                return;
            }
        }

19 View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
        {
            LogonErrorCode = e.lError;
            var errorstatus = Enum.GetName(typeof(LogonErrors), (uint)LogonErrorCode);
            Console.WriteLine("[-] Logon Error           :  {0} - {1}", LogonErrorCode, errorstatus);
            Thread.Sleep(1000);

            if(LogonErrorCode == -5 && takeover == true)
            {
                // it doesn't go to the logon event, so this has to be done here
                var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
                Thread.Sleep(1000);
                keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
                Console.WriteLine("[+] Another user is logged on, asking to take over session");
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
                Console.WriteLine("[+] Sleeping for 30 seconds");
                Task.Delay(31000).GetAwaiter().GetResult();
                Marshal.ReleaseComObject(rdpSession);
                Marshal.ReleaseComObject(keydata);
            }
            else if (LogonErrorCode != -2)
            {
                Environment.Exit(0);
            }
        }

19 View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

private void RunConsole(string consoletype)
        {
            if (runtype == "taskmgr")
            {
                Console.WriteLine("[+] Executing task manager");
                Thread.Sleep(500);
                SendText("taskmgr");
                Thread.Sleep(1000);

                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");

                SendElement("Alt+F");
                Thread.Sleep(1000);

                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
            }

            Console.WriteLine("[+] Executing {0} from {1}", cmd.ToLower(), consoletype);
            SendText(consoletype);
            Thread.Sleep(1000);

            if (runtype == "taskmgr")
            {
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Space");
                Thread.Sleep(250);
            }

            if (runtype == "winr")
            {
                //Currently bugged - does not run elevated
                SendElement("Ctrl+Shift+down");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(250);
                SendElement("Enter+up");
                Thread.Sleep(500);
                SendElement("Ctrl+Shift+up");
                Thread.Sleep(500);
            }
            else
            {
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(250);
            }

            Thread.Sleep(500);
            SendText(cmd.ToLower());

            Thread.Sleep(1000);

            SendElement("Enter+down");
            Thread.Sleep(500);
            SendElement("Enter+up");

            Thread.Sleep(500);
            SendText("exit");

            SendElement("Enter+down");
            Thread.Sleep(500);
            SendElement("Enter+up");

            if(runtype == "taskmgr")
            {
                Thread.Sleep(250);
                SendElement("Alt+F4");
                Thread.Sleep(250);
            }
        }

19 View Source File : RtmpServer.cs
License : MIT License
Project Creator : a1q123456

private async void AcceptCallback(IAsyncResult ar, CancellationToken ct)
        {
            Socket listener = (Socket)ar.AsyncState;
            Socket client = listener.EndAccept(ar);
            client.NoDelay = true;
            // Signal the main thread to continue.
            _allDone.Set();
            IOPipeLine pipe = null;
            try
            {
                pipe = new IOPipeLine(client, _options);
                await pipe.StartAsync(ct);
            }
            catch (TimeoutException)
            {
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Message: {1}", e.GetType().ToString(), e.Message);
                Console.WriteLine(e.StackTrace);
                client.Close();
            }
            finally
            {
                pipe?.Dispose();
            }
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aadreja

static void Main(string[] args)
        {
            DapperTry();

            var t = new { Id = 1 };
            Console.WriteLine("Type {0} Hash {1}", t.GetType().Name, t.GetHashCode());

            var t1 = new { Id = "abc" };
            Console.WriteLine("Type {0} Hash {1}", t1.GetType().Name, t1.GetHashCode());

            var t2 = new { Id = 2 };
            Console.WriteLine("Type {0} Hash {1}", t2.GetType().Name, t2.GetHashCode());

            var t3 = new { Id = "xyz" };
            Console.WriteLine("Type {0} Hash {1}", t3.GetType().Name, t3.GetHashCode());

            defaultColor = Console.ForegroundColor;

            WriteLine("-------------------------------------------", ConsoleColor.Green);
            WriteLine("Vega(Fastest .net ORM) - Sample Application", ConsoleColor.Green);
            WriteLine("-------------------------------------------", ConsoleColor.Green);

            WriteLine("Creating Database with Sample Data");

            CreateDBWithSampleData();

            long id = InsertSample();
            UpdateSample(id);
            ReadById(id);
            DeleteSample(id);
            Read();
            ReadPaged();
            AuditTrial(id);
            PerformanceTest pTest = new PerformanceTest();
            pTest.Run();

            Console.ReadKey();
        }

19 View Source File : DellFanManagementApp.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static int SmiSetToken(string[] args)
        {
            uint token = uint.Parse(args[1], NumberStyles.HexNumber);
            uint targetValue = uint.Parse(args[2]);

            Console.WriteLine("Setting token {0:X4} to value {1}", token, targetValue);

            uint? currentValue = DellSmbiosSmi.GetTokenCurrentValue((Token)token);

            if (currentValue != null)
            {
                Console.WriteLine("  Current value: {0}", currentValue);
            }
            else
            {
                Console.WriteLine("  Failed to read current value.  Trying to set anyway.");
            }

            if (DellSmbiosSmi.SetToken((Token)token, targetValue))
            {
                Console.WriteLine("  Set token successfully.");

                currentValue = DellSmbiosSmi.GetTokenCurrentValue((Token)token);
                if (currentValue != null)
                {
                    Console.WriteLine("  Current value: {0}", currentValue);

                    if (currentValue == targetValue)
                    {
                        return 0;
                    }
                    else if (currentValue != null)
                    {
                        Console.WriteLine("  ...It appears that the value was not set as expected.");
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    Console.WriteLine("  Failed to read new value.");
                    return 1;
                }
            }
            else
            {
                Console.WriteLine("  Failed to set value.");
                return 1;
            }
        }

19 View Source File : Preferences.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

public void Display()
	{
		foreach (DictionaryEntry entry in prefs) {
			System.Console.WriteLine("[{0}]: {1}", entry.Key, entry.Value);
		}
	}

19 View Source File : ROMManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

private byte GenerateStarMask(byte initMask, int start, int end) //Does not work :(
        {
            int mask = initMask;
            for (int offset = start; offset < end; offset++)
            {
                reader.BaseStream.Position = offset;
                if (reader.ReadByte() != objectDescriptor) continue; //work with 3D object only
                byte[] behaviour = ReadBehaviour(offset);
                if (behaviour.SequenceEqual(collectStarBehaviour) ||
                    behaviour.SequenceEqual(redCoinStarBehaviour) ||
                    behaviour.SequenceEqual(hiddenStarBehaviour) ||
                    behaviour.SequenceEqual(bossWhompBehaviour) ||
                    behaviour.SequenceEqual(bossBobombBehaviour) ||
                    behaviour.SequenceEqual(bossBullyBehaviour) ||
                    behaviour.SequenceEqual(bossBalconyBehaviour) ||
                    behaviour.SequenceEqual(bossPenguinBehaviour) ||
                    behaviour.SequenceEqual(bossBooBuddyBehaviour) ||
                    behaviour.SequenceEqual(bossWigglerBehaviour) ||
                    behaviour.SequenceEqual(bossBlizzardBehaviour) ||
                    behaviour.SequenceEqual(bossEyerockBehaviour))
                {
                    byte starByte = ReadBParam1(offset);
                    if (starByte <= 0x06) //troll star
                    {
                        mask |= 1 << starByte;
                        Console.WriteLine("[S] '{0:x}' Star {1} detected!", offset, starByte);
                    }
                }

                if (behaviour.SequenceEqual(bossKoopaBehaviour))
                {
                    byte starByte = ReadBParam1(offset);
                    if (starByte == 1)
                    {
                        byte starByteParam = 1;
                        mask |= 1 << starByteParam;
                        Console.WriteLine("[K] '{0:x}' Star {1} detected!", offset, starByteParam);
                    }
                    if (starByte == 2)
                    {
                        byte starByteParam = 2;
                        mask |= 1 << starByteParam;
                        Console.WriteLine("[K] '{0:x}' Star {1} detected!", offset, starByteParam);
                    }
                }

                if (behaviour.SequenceEqual(boxBehaviour))
                {
                    byte boxObjectByte = ReadBParam2(offset);
                    Object currentObject = boxObjects[boxObjectByte];
                    //Console.WriteLine(String.Format("{1:X}: {0:X8}", currentObject.Behaviour, boxObjectByte));
                    if (boxObjectByte == 0x08)
                    {
                        byte starByte = ReadBParam1(offset);
                        if (starByte <= 0x6)
                        {
                            mask |= 1 << starByte;
                            Console.WriteLine("[B] '{0:x}' Star {1} in box detected 8!", offset, starByte);
                        }
                    }
                    else if (currentObject != null && currentObject.Behaviour == 0x130007F8)
                    {
                        if (currentObject.BParam1 <= 0x6)
                        {
                            mask |= 1 << currentObject.BParam2;
                            Console.WriteLine("[B] '{0:x}' Star {1} in box detected!", offset, currentObject.BParam2);
                        }
                    }
                }
            }
            return (byte) mask;
        }

19 View Source File : ConfigurationManagerSnippets.cs
License : The Unlicense
Project Creator : ahotko

private void ReadAllSettings()
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;

                if (appSettings.Count == 0)
                {
                    Console.WriteLine("AppSettings is empty.");
                }
                else
                {
                    foreach (var key in appSettings.AllKeys)
                    {
                        Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
                    }
                }
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error reading app settings");
            }
        }

19 View Source File : Program.Commands.cs
License : MIT License
Project Creator : alexanderdna

private static void cmd_help(string[] arr)
        {
            if (arr.Length == 2)
            {
                cmd_help(arr[1]);
                return;
            }

            Console.WriteLine("Available commands:");
            for (int i = 0, c = commands.Count; i < c; ++i)
            {
                var cmd = commands[i];
                Console.WriteLine("\t{0,-20}{1}", cmd.Name, cmd.HelpText);
            }
            Console.WriteLine("Enter `help <command>` for more details.");
        }

19 View Source File : Instruction.cs
License : MIT License
Project Creator : alexanderkyte

public override void Emit (IEnumerator<WebreplacedemblyInstruction> cursor, ILGenerator ilgen, WebreplacedemblyCodeParser top_level)
		{
			switch (Opcode) {
				case 0x0: // unreachable
					// Fixme: make this catchable / offer options at exception time
					ilgen.ThrowException (typeof (System.ExecutionEngineException));
					return;
				case 0x01: // nop
					ilgen.Emit (OpCodes.Nop);
					return;

				case 0x02: // block
					label = ilgen.DefineLabel ();
					ilgen.MarkLabel (label);
					return;

				case 0x03: // loop
					label = ilgen.DefineLabel ();
					ilgen.MarkLabel (label);
					return;

				case 0x04: // if 
					var fallthrough_label = ilgen.DefineLabel ();

					WebreplacedemblyInstruction curr = cursor.Current;
					if (curr != this)
						throw new Exception (String.Format ("Cursor has preplaceded us while we were emitting instruction"));
					if (curr != if_block)
						throw new Exception (String.Format ("if block limits not correctly parsed"));

					if (this.else_block != null) {
						Label else_label = ilgen.DefineLabel ();
						ilgen.Emit (OpCodes.Brfalse, else_label);

						Console.WriteLine ("GREP: if: {0}", this.if_block.ToString ());
						Console.WriteLine ("GREP: else: {0}", this.else_block.ToString ());
						Console.WriteLine ("GREP: fallthrough: {0}", this.fallthrough_block.ToString ());

						while (curr != this.else_block) {
							var good = cursor.MoveNext ();
							if (!good)
								throw new Exception ("if/else block limits not correctly parsed");
							curr = cursor.Current;
							curr.Emit (cursor, ilgen, top_level);
						}
						if (if_block == else_block)
							ilgen.Emit (OpCodes.Nop);

						ilgen.Emit (OpCodes.Br, fallthrough_label);


						// We emit the else block
						ilgen.MarkLabel (else_label);
						while (curr != this.fallthrough_block) {
							var good = cursor.MoveNext ();
							if (!good)
								throw new Exception ("Else/fallthrough block limits not correctly parsed");
							curr = cursor.Current;
							curr.Emit (cursor, ilgen, top_level);
						}
						if (else_block == fallthrough_block)
							ilgen.Emit (OpCodes.Nop);

						// Falls through to fallthrough by default
					} else {
						// No else block

						Console.WriteLine ("GREP: if: {0}", this.if_block.ToString ());
						Console.WriteLine ("GREP: fallthrough: {0}", this.fallthrough_block.ToString ());

						ilgen.Emit (OpCodes.Brfalse, fallthrough_label);
						if (if_block == fallthrough_block)
							ilgen.Emit (OpCodes.Nop);
						while (curr != this.fallthrough_block) {
								Console.WriteLine ("Between if and fallthrough: {0} < {1}", cursor.Current.ToString (), fallthrough_block.ToString ());
								var good = cursor.MoveNext ();
								if (!good)
									throw new Exception ("if/fallthrough block limits not correctly parsed");
								curr = cursor.Current;
								curr.Emit (cursor, ilgen, top_level);
						}
					}

					// Start fallthrough symbol, for rest of code
					ilgen.MarkLabel (fallthrough_label);
					return;

				case 0x05: // Else
					ilgen.Emit (OpCodes.Nop);
					return;

				case 0x0b: // End
					// loops fall through
					if (this.dest == null && !this.loops) {
						// ends function body, has implicit return
						ilgen.Emit (OpCodes.Ret);
					}
					//else {
						//ilgen.Emit (OpCodes.Nop);
					//}
					return;

				// Br
				case 0x0c:
					ilgen.Emit (OpCodes.Br, this.dest.GetLabel ());
					return;

				// Br_if
				case 0x0d:
					ilgen.Emit (OpCodes.Brtrue, this.dest.GetLabel ());
					return;

				// Br_table
				case 0x0e:
					Label defaultCase = ilgen.DefineLabel();
					Label endOfBlock = ilgen.DefineLabel();
					var jumpTable = new Label [this.table.Length];

					for (int i=0; i < this.table.Length; i++) {
						jumpTable [i] = ilgen.DefineLabel();
					}

					ilgen.Emit (OpCodes.Switch, jumpTable);
					ilgen.Emit (OpCodes.Br_S, defaultCase); 

					for (int i=0; i < jumpTable.Length; i++) {
						// Case incoming argument is equal to i
						ilgen.MarkLabel (jumpTable [i]);
						ilgen.Emit (OpCodes.Br_S, this.table[i].dest.GetLabel ());
					}

					ilgen.MarkLabel (defaultCase);
					ilgen.Emit(OpCodes.Br_S, jumpTable [Convert.ToInt32 (this.default_target)]);

					ilgen.MarkLabel(endOfBlock);

					return;

				case 0x0f:
					ilgen.Emit (OpCodes.Ret);
					return;

				//// Call
				case 0x10:
					//ilgen.Emit (OpCodes.Nop);
					//return;

				//case 0x11:
					//return ilgen.Emit (OpCodes.Nop);

				default:
					throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
			}
			return;
		}

19 View Source File : Parser.cs
License : MIT License
Project Creator : alexanderkyte

void ParseSection (int section_num, byte [] section)
		{
			Console.WriteLine ("Parse section {0} length {1}", section_num, section.Length);
			var memory = new MemoryStream (section);

			using (BinaryReader reader = new BinaryReader (memory)) {
				switch (section_num) {
					case WebreplacedemblySection.Custom:
						// We don't have anything here for mono
						break;
					case WebreplacedemblySection.Type:
						ParseTypeSection (reader);
						break;
					case WebreplacedemblySection.Import:
						ParseImportSection (reader);
						break;
					case WebreplacedemblySection.Function:
						ParseFunctionSection (reader);
						break;
					case WebreplacedemblySection.Table:
						ParseTableSection (reader);
						break;
					case WebreplacedemblySection.Memory:
						ParseMemorySection (reader);
						break;
					case WebreplacedemblySection.Global:
						ParseGlobalSection (reader);
						break;
					case WebreplacedemblySection.Export:
						ParseExportSection (reader);
						break;
					case WebreplacedemblySection.Start:
						ParseStartSection (reader);
						break;
					case WebreplacedemblySection.Element:
						ParseElementSection (reader);
						break;
					case WebreplacedemblySection.Code:
						ParseCodeSection (reader);
						break;
					case WebreplacedemblySection.Data:
						ParseDataSection (reader);
						break;
				}
			}
		}

19 View Source File : Instruction.cs
License : MIT License
Project Creator : alexanderkyte

public void ParseExpression (BinaryReader reader)
		{
			int start = BodyBuilder.Count;

			if (this.finished)
				throw new Exception ("Expression block has already been finalized.");

			// The "depth" is used to find the extra 0x0B at the end of an expression.
			// When we see it and depth != 0, then it ends a block, not the function
			//
			// We make the nested blocks in if/else bodies without labels parse with
			// the included logic as well, so an Else can also end this block
			int depth = 0;

			while (depth >= 0 && (reader.BaseStream.Position != reader.BaseStream.Length)) {
				if (depth > LabelStack.Count)
					throw new Exception (String.Format ("Depth {0} exceeds number of labels on stack {1}", depth, LabelStack.Count));

				Console.WriteLine ("Depth {0} and number of labels on stack {1}", depth, LabelStack.Count);

				WebreplacedemblyInstruction result = null;
				byte opcode = reader.ReadByte ();

				if (opcode <= WebreplacedemblyControlInstruction.UpperBound ()) {
					// The appending is done inside the control instruction so that it can ensure ordering
					// So we don't replacedign to result
					new WebreplacedemblyControlInstruction (opcode, reader, LabelStack, ref CurrLabel, this, ref depth);
				} else if (opcode <= WebreplacedemblyParametricInstruction.UpperBound ()) {
					result = new WebreplacedemblyParametricInstruction (opcode, reader);
				} else if (opcode <= WebreplacedemblyVariableInstruction.UpperBound ()) {
					result = new WebreplacedemblyVariableInstruction (opcode, reader);
				} else if (opcode <= WebreplacedemblyMemoryInstruction.UpperBound ()) {
					result = new WebreplacedemblyMemoryInstruction (opcode, reader);
				} else if (opcode <= WebreplacedemblyNumericInstruction.UpperBound ()) {
					result = new WebreplacedemblyNumericInstruction (opcode, reader);
				} else {
					throw new Exception (String.Format ("Illegal instruction {0:X}", opcode));
				}

				if (result != null) {
					Add (result, ref depth);
				}
			}

			Console.WriteLine ("Parsed {0} wasm instructions", BodyBuilder.Count - start);
		}

19 View Source File : Parser.cs
License : MIT License
Project Creator : alexanderkyte

void ParseMemorySection(BinaryReader reader)
		{
			var count = Convert.ToInt32 (Parser.ParseLEBSigned (reader, 32));
			if (count != 1)
				throw new Exception ("At most one memory allowed in this version of webreplacedembly");
			this.mem = new WebreplacedemblyMemory (new WebreplacedemblyLimit (reader));

			Console.WriteLine ("Parsed memory section. Limit is {0} {1}", this.mem.limit.min, this.mem.limit.max);
		}

19 View Source File : Parser.cs
License : MIT License
Project Creator : alexanderkyte

void ParseTableSection(BinaryReader reader)
		{
			var count = Convert.ToInt32 (Parser.ParseLEBSigned (reader, 32));
			if (count != 1)
				throw new Exception ("At most one table allowed in this version of webreplacedembly");
			var elementType = Parser.ParseLEBUnsigned (reader, 7);
			var limit = new WebreplacedemblyLimit (reader);
			this.table = new WebreplacedemblyTable (elementType, limit);

			Console.WriteLine ("Parsed table section. Limit is {0} {1}", limit.min, limit.max);
		}

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

static void Main(string[] args)
        {
            Console.SetWindowSize(120, 30);

            int[] sizes = { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 };
            for (int i = 0; i < sizes.Length; ++i)
            {
                var termsCount = sizes[i];
                var varsCount = sizes[i];

                Console.WriteLine("Benchmark for {0} terms and {1} variables", termsCount, varsCount);

                Console.Write("\tConstructing coefficients ...");
                var coefficients = GenerateCoefficients(termsCount, varsCount);
                Console.WriteLine(" done");

                // generate variables
                var vars = new Variable[varsCount];
                for(int j = 0; j < sizes[i]; ++j)
                    vars[j] = new Variable();


                Console.Write("\tGenerating input data ...");
                double[][] inputData = new double[1000][];
                for (int j = 0; j < inputData.Length; ++j)
                    inputData[j] = RandomDoubles(varsCount);
                Console.WriteLine(" done");

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tConstructing compiled term ...");
                var stopWatch = Stopwatch.StartNew();
                var compiledTerm = ConstructTerm(coefficients, vars);
                stopWatch.Stop();
                Console.WriteLine(" done in {0} milliseconds", stopWatch.ElapsedMilliseconds);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking manual evaluation ...");
                stopWatch = Stopwatch.StartNew();
                double sum = 0;
                for (int j = 0; j < inputData.Length; ++j)
                    sum += NativeEvaluate(coefficients, inputData[j]);
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking gradient approximation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0;
                for (int j = 0; j < inputData.Length / 10; ++j)
                {
                    var gradient = ApproxGradient(coefficients, inputData[j]);
                    sum += gradient.Sum();
                }
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, 10 * stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking AutoDiff compiled evaluation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0;
                for (int j = 0; j < inputData.Length; ++j)
                    sum += compiledTerm.Evaluate(inputData[j]);
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking compiled differentiation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0; 
                for(int j = 0; j < inputData.Length; ++j)
                {
                    var diffResult = compiledTerm.Differentiate(inputData[j]);
                    sum += diffResult.Item2 + diffResult.Item1.Sum();
                }
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

            }
        }

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

static void Main(string[] args)
        {
            // we will use a function of two variables
            Variable x = new Variable();
            Variable y = new Variable();

            // func(x, y) = (x + y) * exp(x - y)
            var func = (x + y) * TermBuilder.Exp(x - y);

            // define the ordering of variables, and a point where the function will be evaluated/differentiated
            Variable[] vars = { x, y };
            double[] point = { 1, -2 };
            
            // calculate the value and the gradient at the point (x, y) = (1, -2)
            double eval = func.Evaluate(vars, point);
            double[] gradient = func.Differentiate(vars, point);

            // write the results
            Console.WriteLine("f(1, -2) = " + eval);
            Console.WriteLine("Gradient of f at (1, -2) = ({0}, {1})", gradient[0], gradient[1]);
        }

19 View Source File : CoinChange.cs
License : MIT License
Project Creator : AllAlgorithms

static void Main(string[] args)
        {
            int moneyToReturn = 7;
            int[] coinTypes = { 2, 3, 5 };

            CoinChange coinChangeCalculator = new CoinChange(coinTypes);
            int totalWays = coinChangeCalculator.Start(0, moneyToReturn);

            Console.WriteLine("Total Ways To Return {0} is {1}.", moneyToReturn, totalWays);
            Console.ReadKey(); // Hold The Screen
        }

19 View Source File : Dijkstra.cs
License : MIT License
Project Creator : AllAlgorithms

private static void OutputDistance(int[] distance, int verticesCount)
        {
            Console.WriteLine("Vertex Distance from source");
 
            for (int i = 0; i < verticesCount; ++i)
                Console.WriteLine("{0}\t  {1}", i, distance[i]);
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : AmpScm

static void Run(string[] args)
        {
            List<string> argList = new List<string>(args);
            bool _transparentHack = false;
            while (argList.Count > 0 && argList[0].StartsWith("-"))
            {
                string arg = argList[0];
                if (arg == "--")
                {
                    argList.RemoveAt(0);
                    break;
                }
                switch (arg)
                {
                    case "-th":
                        _transparentHack = true;
                        break;
                    default:
                        Console.Error.WriteLine("Unhandled argument {0}", arg);
                        Environment.Exit(1);
                        break;
                }
                argList.RemoveAt(0);
            }

            if (argList.Count < 2)
            {
                Console.Error.WriteLine("Required argument missing");
                Console.Error.WriteLine("BitmapExtractor [-th] <replacedembly> <dir>");
                Environment.Exit(1);
            }
            string from = argList[0];
            string dir = argList[1];

            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            CommandTable table = new CommandTable();

            Console.WriteLine("Dumping bitmaps in {0} to {1}:", from, dir);

            replacedembly asm = null;
            try
            {
                asm = replacedembly.LoadFile(from);
            }
            catch { }


            try
            {
                if (asm != null
                    ? !table.Read(replacedembly.LoadFile(from), new ReadErrorHandler())
                    : !table.Read(from, new ReadErrorHandler()))
                {
                    Console.Error.WriteLine("* Loading failed, exiting *");
                    Environment.Exit(1);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
                Environment.Exit(1);
            }

            BitmapItemList bitmaps = table.GetBitmapList();

            foreach (BitmapItem bi in bitmaps)
            {
                uint resourceId = bi.IDResource;
                Dictionary<uint, int> map = new Dictionary<uint, int>();
                Color transparentColor = Color.FromArgb(0xFF, 0xFF, 0, 0xFF);
                bool haveColor = false;

                for (int i = 0; i < bi.UsedSlots.Length; i++)
                {
                    map[bi.UsedSlots[i]] = i;
                    if (_transparentHack && !haveColor && bi.UsedSlots[i] == 1)
                    {
                        Bitmap bm = bitmaps.GetBitmap(bi.GID, bi.UsedSlots[i]);
                        transparentColor = bm.GetPixel(0, 0);
                        Console.WriteLine("Found color: {0}", transparentColor);
                        haveColor = true;
                    }
                }

                ButtonList bl = table.GetButtonList();

                foreach (CommandButton cb in table.GetButtonList())
                {
                    if (cb.IconGID != bi.GID)
                        continue;

                    Bitmap bm = bitmaps.GetBitmap(cb.IconGID, cb.IconIndex);
                    string name = cb.CanonicalName.Trim(' ', '.', '\t', '&').Replace(" ", "").Replace("&", "");

                    if (bm == null)
                    {
                        Console.WriteLine("Couldn't get icon for {0}", name);
                        continue;
                    }

                    if (_transparentHack)
                        bm.MakeTransparent(transparentColor);

                    try
                    {
                        bm.Save(Path.Combine(dir, name + ".png"), ImageFormat.Png);
                        Console.WriteLine("Writing {0}. Succeeded", name);
                    }
                    catch
                    {
                        Console.WriteLine("Writing {0}. Failed", name);
                    }
                }
            }
            Console.WriteLine("Done");
        }

19 View Source File : Actions.cs
License : The Unlicense
Project Creator : Anirban166

static void Main()
    {
        Action<int> action1 =(int x) => Console.WriteLine("OUTPUT {0}", x);
        Action<int, int> action2 =(x, y) => Console.WriteLine("OUTPUT {0} and {1}", x, y);
        action1.Invoke(1111);
        action2.Invoke(200, 3000);
        Console.Read();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : AnkitSharma-007

internal static void Countcharacter(string str)
        {
            /* input:- hello world ; 
             * output:- h - 1
                        e - 1
                        l - 3
                        o - 2
                        w - 1
                        r - 1
                        d - 1
             * 
             * */

            Dictionary<char, int> characterCount = new Dictionary<char, int>();

            foreach (var character in str)
            {
                if (character != ' ')
                {
                    if (!characterCount.ContainsKey(character))
                    {
                        characterCount.Add(character, 1);
                    }
                    else
                    {
                        characterCount[character]++;
                    }
                }

            }
            foreach (var character in characterCount)
            {
                Console.WriteLine("{0} - {1}", character.Key, character.Value);
            }
        }

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

public static void ModList(string pidString)
        {
            int pid;

            // Ensure the input is an integer
            try
            {
                pid = Convert.ToInt32(pidString);

            }
            // If not got to the help and alert the user
            catch (Exception ex)
            {
                Console.WriteLine("Input not an integer.  Please try again");
                help();
                pid = 0;
            }

            try
            {
                // Get the process requested by the user pid input
                Process process = Process.GetProcessById(pid);
                ProcessModule procMod;

                // Get the module collection of the process
                ProcessModuleCollection processModuleColl = process.Modules;

                // For each module in the collection write the modules to console
                for ( int i =0; i < processModuleColl.Count; i++)
                {
                    procMod = processModuleColl[i];

                    // Write the module name and base address in hex
                    Console.WriteLine("File Name: {0}  Base Address: 0x{1}", procMod.FileName, procMod.BaseAddress.ToString("X"));
                }
            }
            // If it fails alert the user and go to the help
            catch(Exception ex)
            {
                Console.WriteLine("No Process Found with that Process ID. \nError: {0}", ex);
                help();
            }
        }

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

public static void ProcList()
        {
            Process[] proclist = Process.GetProcesses();
            // List each of the the processes to console
            foreach (Process process in proclist)
            {
                // Print the proc ID and Name
                Console.WriteLine("\nProcess: {0} PID: {1}", process.ProcessName, process.Id);
            }
        }

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

public void Pay(decimal amountTopay)
    {
      if (CanPay(amountTopay))
      {
        Console.WriteLine("Paid {0:c} using {1}.", amountTopay, this.GetType().Name);
      }
      else if (this.mSuccessor != null)
      {
        Console.WriteLine("Cannot pay using {0}. Proceeding..", this.GetType().Name);
        mSuccessor.Pay(amountTopay);
      }
      else
      {
        throw new Exception("None of the accounts have enough balance");
      }
    }

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

public void OnNext(JobPost value)
    {
      Console.WriteLine("Hi {0} ! New job posted: {1}", Name, value.replacedle);
    }

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

private void Testreplacedembly(string imageDir, string imagePath)
		{
			string imageName = Path.GetFileName(imagePath);
			string subDir = GetRelativePath(imageDir, TestDir);

			try
			{
				Il2cppContext context = new Il2cppContext(imagePath);

				foreach (TypeDef typeDef in context.Module.Types)
				{
					OnType(context, typeDef, imageDir, imageName, subDir);
				}
			}
			catch (BadImageFormatException)
			{
				Console.WriteLine("* Load Error: \"{0}{1}\" is not a .NET replacedembly.", subDir, imageName);
			}
		}

19 View Source File : CompoundDoc.cs
License : Apache License 2.0
Project Creator : Appdynamics

[TestMethod, Ignore]
        public void Sample7EncrLargeTest()
        {
            int Rows = 1000000;
            int colMult = 20;
            FileInfo newFile = new FileInfo(@"C:\temp\bug\sample7compdoctest.xlsx");
            if (newFile.Exists)
            {
                newFile.Delete();  // ensures we create a new workbook
                newFile = new FileInfo(@"C:\temp\bug\sample7compdoctest.xlsx");
            }
            using (ExcelPackage package = new ExcelPackage())
            {
                Console.WriteLine("{0:HH.mm.ss}\tStarting...", DateTime.Now);

                //Load the sheet with one string column, one date column and a few random numbers.
                var ws = package.Workbook.Worksheets.Add("Performance Test");

                //Format all cells
                ExcelRange cols = ws.Cells["A:XFD"];
                cols.Style.Fill.PatternType = ExcelFillStyle.Solid;
                cols.Style.Fill.BackgroundColor.SetColor(Color.LightGray);

                var rnd = new Random();
                for (int row = 1; row <= Rows; row++)
                {
                    for (int c = 0; c < colMult * 5; c += 5)
                    {
                        ws.SetValue(row, 1 + c, row);                               //The SetValue method is a little bit faster than using the Value property
                        ws.SetValue(row, 2 + c, string.Format("Row {0}", row));
                        ws.SetValue(row, 3 + c, DateTime.Today.AddDays(row));
                        ws.SetValue(row, 4 + c, rnd.NextDouble() * 10000); 
                     }
                }
                var endC = colMult * 5;
                ws.Cells[1, endC, Rows, endC].FormulaR1C1 = "RC[-4]+RC[-1]";

                //Add a sum at the end
                ws.Cells[Rows + 1, endC].Formula = string.Format("Sum({0})", new ExcelAddress(1, 5, Rows, 5).Address);
                ws.Cells[Rows + 1, endC].Style.Font.Bold = true;
                ws.Cells[Rows + 1, endC].Style.Numberformat.Format = "#,##0.00";

                Console.WriteLine("{0:HH.mm.ss}\tWriting row {1}...", DateTime.Now, Rows);
                Console.WriteLine("{0:HH.mm.ss}\tFormatting...", DateTime.Now);
                //Format the date and numeric columns
                ws.Cells[1, 1, Rows, 1].Style.Numberformat.Format = "#,##0";
                ws.Cells[1, 3, Rows, 3].Style.Numberformat.Format = "YYYY-MM-DD";
                ws.Cells[1, 4, Rows, 5].Style.Numberformat.Format = "#,##0.00";

                Console.WriteLine("{0:HH.mm.ss}\tInsert a row at the top...", DateTime.Now);
                //Insert a row at the top. Note that the formula-addresses are shifted down
                ws.InsertRow(1, 1);

                //Write the headers and style them
                ws.Cells["A1"].Value = "Index";
                ws.Cells["B1"].Value = "Text";
                ws.Cells["C1"].Value = "Date";
                ws.Cells["D1"].Value = "Number";
                ws.Cells["E1"].Value = "Formula";
                ws.View.FreezePanes(2, 1);

                using (var rng = ws.Cells["A1:E1"])
                {
                    rng.Style.Font.Bold = true;
                    rng.Style.Font.Color.SetColor(Color.White);
                    rng.Style.WrapText = true;
                    rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
                }

                //Calculate (Commented away thisk, it was a bit time consuming... /MA)
                // Console.WriteLine("{0:HH.mm.ss}\tCalculate formulas...", DateTime.Now);
                // ws.Calculate();

                Console.WriteLine("{0:HH.mm.ss}\tAutofit columns and lock and format cells...", DateTime.Now);
                ws.Cells[Rows - 100, 1, Rows, 5].AutoFitColumns(5);   //Auto fit using the last 100 rows with minimum width 5
                ws.Column(5).Width = 15;                            //We need to set the width for column F manually since the end sum formula is the widest cell in the column (EPPlus don't calculate any forumlas, so no output text is avalible). 

                //Now we set the sheetprotection and a preplacedword.
                ws.Cells[2, 3, Rows + 1, 4].Style.Locked = false;
                ws.Cells[2, 3, Rows + 1, 4].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells[2, 3, Rows + 1, 4].Style.Fill.BackgroundColor.SetColor(Color.White);
                ws.Cells[1, 5, Rows + 2, 5].Style.Hidden = true;    //Hide the formula

                ws.Protection.SetPreplacedword("EPPlus");

                ws.Select("C2");
                Console.WriteLine("{0:HH.mm.ss}\tSaving...", DateTime.Now);
                package.Compression = CompressionLevel.BestSpeed;
                package.Encryption.IsEncrypted = true;
                package.SaveAs(newFile);
            }
            Console.WriteLine("{0:HH.mm.ss}\tDone!!", DateTime.Now);
        }

19 View Source File : Sample7.cs
License : Apache License 2.0
Project Creator : Appdynamics

public static string RunSample7(int rows)
        {
            var newFile = Utils.GetFileInfo("sample7.xlsx");
            using (ExcelPackage package = new ExcelPackage())
            {
                Console.WriteLine("{0:HH.mm.ss}\tStarting...", DateTime.Now);

                //Load the sheet with one string column, one date column and a few random numbers.
                var ws = package.Workbook.Worksheets.Add("Performance Test");

                //Format all cells
                ExcelRange cols = ws.Cells["A:XFD"];
                cols.Style.Fill.PatternType = ExcelFillStyle.Solid;
                cols.Style.Fill.BackgroundColor.SetColor(Color.LightGray);

                var rnd = new Random();                
                for (int row = 1; row <= rows; row++)
                {
                    ws.SetValue(row, 1, row);                               //The SetValue method is a little bit faster than using the Value property
                    ws.SetValue(row, 2, string.Format("Row {0}", row));
                    ws.SetValue(row, 3, DateTime.Today.AddDays(row));
                    ws.SetValue(row, 4, rnd.NextDouble() * 10000);
                    if (row % 10000 == 0)
                    {
                        Console.WriteLine("{0:HH.mm.ss}\tWriting row {1}...", DateTime.Now, row);
                    }
                }
                ws.Cells[1, 5, rows, 5].FormulaR1C1 = "RC[-4]+RC[-1]";

                //Add a sum at the end
                ws.Cells[rows + 1, 5].Formula = string.Format("Sum({0})", new ExcelAddress(1, 5, rows, 5).Address);
                ws.Cells[rows + 1, 5].Style.Font.Bold = true;
                ws.Cells[rows + 1, 5].Style.Numberformat.Format = "#,##0.00";

                Console.WriteLine("{0:HH.mm.ss}\tWriting row {1}...", DateTime.Now, rows);
                Console.WriteLine("{0:HH.mm.ss}\tFormatting...", DateTime.Now);
                //Format the date and numeric columns
                ws.Cells[1, 1, rows, 1].Style.Numberformat.Format = "#,##0";
                ws.Cells[1, 3, rows, 3].Style.Numberformat.Format = "YYYY-MM-DD";
                ws.Cells[1, 4, rows, 5].Style.Numberformat.Format = "#,##0.00";

                Console.WriteLine("{0:HH.mm.ss}\tInsert a row at the top...", DateTime.Now);
                //Insert a row at the top. Note that the formula-addresses are shifted down
                ws.InsertRow(1, 1);

                //Write the headers and style them
                ws.Cells["A1"].Value = "Index";
                ws.Cells["B1"].Value = "Text";
                ws.Cells["C1"].Value = "Date";
                ws.Cells["D1"].Value = "Number";
                ws.Cells["E1"].Value = "Formula";
                ws.View.FreezePanes(2, 1);

                using (var rng = ws.Cells["A1:E1"])
                {
                    rng.Style.Font.Bold = true;
                    rng.Style.Font.Color.SetColor(Color.White);
                    rng.Style.WrapText = true;
                    rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
                }

                //Calculate (Commented away thisk, it was a bit time consuming... /MA)
                // Console.WriteLine("{0:HH.mm.ss}\tCalculate formulas...", DateTime.Now);
                // ws.Calculate();

                Console.WriteLine("{0:HH.mm.ss}\tAutofit columns and lock and format cells...", DateTime.Now);
                ws.Cells[rows - 100, 1, rows, 5].AutoFitColumns(5);   //Auto fit using the last 100 rows with minimum width 5
                ws.Column(5).Width = 15;                            //We need to set the width for column F manually since the end sum formula is the widest cell in the column (EPPlus don't calculate any forumlas, so no output text is avalible). 

                //Now we set the sheetprotection and a preplacedword.
                ws.Cells[2, 3, rows + 1, 4].Style.Locked = false;
                ws.Cells[2, 3, rows + 1, 4].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells[2, 3, rows + 1, 4].Style.Fill.BackgroundColor.SetColor(Color.White);
                ws.Cells[1, 5, rows + 2, 5].Style.Hidden = true;    //Hide the formula
                
                ws.Protection.SetPreplacedword("EPPlus");

                ws.Select("C2");
                Console.WriteLine("{0:HH.mm.ss}\tSaving...", DateTime.Now);
                package.Compression = CompressionLevel.BestSpeed;
                package.SaveAs(newFile);
            }
            Console.WriteLine("{0:HH.mm.ss}\tDone!!", DateTime.Now);
            return newFile.FullName;
        }

19 View Source File : TemplateProject.cs
License : MIT License
Project Creator : arcus-azure

protected void RunCommand(string fileName, string arguments)
        {
            try
            {
                Logger.WriteLine("> {0} {1}", fileName, arguments);
            }
            catch
            {
                Console.WriteLine("> {0} {1}", fileName, arguments);
            }

            var startInfo = new ProcessStartInfo(fileName, arguments)
            {
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            using (var process = Process.Start(startInfo))
            {
                process.WaitForExit();

                if (!process.HasExited)
                {
                    process.Kill(entireProcessTree: true);
                }
            }
        }

19 View Source File : Appointment.cs
License : MIT License
Project Creator : ardalis

public void Confirm(DateTime dateConfirmed)
        {
            ConfirmationReceivedDate = dateConfirmed;


            Console.WriteLine("[UI] User Interface informed appointment for {0} confirmed at {1}",
                            EmailAddress,
                            ConfirmationReceivedDate.ToString());
        }

19 View Source File : SqlAnalysis.cs
License : MIT License
Project Creator : ashleyglee

private void Runreplacedysis(TSqlModel model, string OutFile)
        {
            CodereplacedysisService service = new CodereplacedysisServiceFactory().CreatereplacedysisService(model.Version);
            service.ResultsFile = OutFile;

            CodereplacedysisResult result = service.replacedyze(model);

            Console.WriteLine("Code replacedysis with output file {0} complete, replacedysis succeeded? {1}",
                OutFile, result.replacedysisSucceeded);
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aspnet

private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                PrintUsage();
                return 1;
            }

            try
            {
                InstallerCommand command = GetCommand(args[0]);
                string certName = args[1];
                string certPreplacedword = args[2];

                var installer = new CertificateInstaller(certName, certPreplacedword);

                switch (command)
                {
                    case InstallerCommand.Install:
                        installer.InstallCertificate();
                        break;
                    case InstallerCommand.Uninstall:
                        installer.UninstallCertificate();
                        break;
                    default:
                        Debug.replacedert(false, String.Format("Unknown InstallerCommand value '{0}'", command));
                        break;
                }

                return 0;
            }
            catch (Exception e)
            {
                PrintUsage();

                Exception current = e;
                while (current != null)
                {
                    Console.WriteLine("{0}: {1}", current.GetType(), e.Message);
                    Console.WriteLine(e.StackTrace);
                    Console.WriteLine("------------------------------------------------------------------");
                    current = current.InnerException;
                }
                return 2;
            }
        }

19 View Source File : LimitPrecisionWhenReadingGeometries.cs
License : MIT License
Project Creator : aspose-gis

public static void Run()
        {
            //ExStart: LimitPrecisionWhenReadingGeometries
            string path = RunExamples.GetDataDir() + "LimitPrecisionWhenReadingGeometries_out.shp";
            using (VectorLayer layer = VectorLayer.Create(path, Drivers.Shapefile))
            {
                var feature = layer.ConstructFeature();
                feature.Geometry = new Point(1.10234, 2.09743);
                layer.Add(feature);
            }

            var options = new ShapefileOptions();
            // read data as-is.
            options.XYPrecisionModel = PrecisionModel.Exact;

            using (VectorLayer layer = VectorLayer.Open(path, Drivers.Shapefile, options))
            {
                var point = (IPoint)layer[0].Geometry;
                // 1.10234, 2.09743
                Console.WriteLine("{0}, {1}", point.X, point.Y);
            }

            // truncate all X and Y, so only two fractional digits are left.
            options.XYPrecisionModel = PrecisionModel.Rounding(2);

            using (VectorLayer layer = VectorLayer.Open(path, Drivers.Shapefile, options))
            {
                var point = (IPoint)layer[0].Geometry;
                // 1.1, 2.1
                Console.WriteLine("{0}, {1}", point.X, point.Y);
            }
            //ExEnd: LimitPrecisionWhenReadingGeometries
        }

19 View Source File : ReducePrecisionOfAGeometry.cs
License : MIT License
Project Creator : aspose-gis

public static void Run()
        {
            //ExStart: ReducePrecisionOreplacedeometry
            Point point = new Point(1.344, 2.345, 3.345, 4.345);
            point.RoundXY(digits: 2);

            // 1.34, 2.35, 3.345, 4.345
            Console.WriteLine("{0}, {1}, {2}, {3}", point.X, point.Y, point.Z, point.M);

            point.RoundZ(digits: 1);

            // 1.34, 2.35, 3.3, 4.345
            Console.WriteLine("{0}, {1}, {2}, {3}", point.X, point.Y, point.Z, point.M);

            LineString line = new LineString();
            line.AddPoint(1.2, 2.3);
            line.AddPoint(2.4, 3.1);
            line.RoundXY(digits: 0);

            // 1, 2
            Console.WriteLine("{0}, {1}", line[0].X, line[0].Y);
            // 2, 3
            Console.WriteLine("{0}, {1}", line[1].X, line[1].Y);
            //ExEnd: ReducePrecisionOreplacedeometry
        }

19 View Source File : ReadingESRIFileGeoDatabaseFileGDB.cs
License : MIT License
Project Creator : aspose-gis

public static void IterateOverLayersInFileGdb()
        {
            //ExStart: IterateOverLayersInFileGdb
            //File GDB is a multi layer format. This example shows how to open File GDB as a dataset (collection of layers) and access layers in it.
            using (var dataset = Dataset.Open(dataDir + "ThreeLayers.gdb", Drivers.FileGdb))
            {
                Console.WriteLine("FileGDB has {0} layers", dataset.LayersCount);
                for (int i = 0; i < dataset.LayersCount; ++i)
                {
                    Console.WriteLine("Layer {0} name: {1}", i, dataset.GetLayerName(i));

                    using (var layer = dataset.OpenLayerAt(i))
                    {
                        Console.WriteLine("Layer has {0} features", layer.Count);
                        foreach (var feature in layer)
                        {
                            Console.WriteLine(feature.Geometry.AsText());
                        }
                    }
                    Console.WriteLine("");
                }
            }
            //ExEnd: IterateOverLayersInFileGdb
        }

19 View Source File : GetCentroid.cs
License : MIT License
Project Creator : aspose-gis

public static void Run()
        {
            //ExStart: GetCentroid
            var polygon = new Polygon();
            polygon.ExteriorRing = new LinearRing(new[]
            {
                new Point(1, 0),
                new Point(2, 2),
                new Point(0, 4),
                new Point(5, 5),
                new Point(6, 1),
                new Point(1, 0),
            });

            IPoint centroid = polygon.GetCentroid();
            Console.WriteLine("{0:F} {1:F}", centroid.X, centroid.Y); // 3.33 2.58
            //ExEnd: GetCentroid
        }

19 View Source File : CreateFromEpsgCode.cs
License : MIT License
Project Creator : aspose-gis

public static void Run()
        {
            //ExStart: CreateFromEpsgCode
            var srs = SpatialReferenceSystem.CreateFromEpsg(26918);

            Console.WriteLine("SRS Name: {0}", srs.Name); // NAD83 / UTM zone 18N
            Console.WriteLine("SRS EPSG code: {0}", srs.EpsgCode); // 26918
            Console.WriteLine("Datum name: {0}", srs.GeographicDatum.Name); // North_American_Datum_1983
            Console.WriteLine("Datum EPSG code: {0}", srs.GeographicDatum.EpsgCode); // 6269
            Console.WriteLine("Ellipsoid name: {0}", srs.GeographicDatum.Ellipsoid.Name); // GRS 1980
            Console.WriteLine("Ellipsoid EPSG code: {0}", srs.GeographicDatum.EpsgCode); // 6269

            Console.WriteLine("Type: {0}", srs.Type); // Projected
            Console.WriteLine("Dimensions count: {0}", srs.DimensionsCount); // 2

            Console.WriteLine("First dimension name: {0}", srs.GetAxis(0).Name); // X
            Console.WriteLine("First dimension direction: {0}", srs.GetAxis(0).Direction); // East

            Console.WriteLine("Second dimension name: {0}", srs.GetAxis(1).Name); // Y
            Console.WriteLine("Second dimension direction: {0}", srs.GetAxis(1).Direction); // North

            Console.WriteLine("First dimension unit: {0}, {1}", srs.GetUnit(0).Name, srs.GetUnit(0).Factor); // metre, 1
            Console.WriteLine("Second dimension unit: {0}, {1}", srs.GetUnit(1).Name, srs.GetUnit(1).Factor); // metre, 1
            //ExEnd: CreateFromEpsgCode
        }

19 View Source File : GetBookmarkPageNumber.cs
License : MIT License
Project Creator : aspose-pdf

public static void Run()
        {
            // ExStart:GetBookmarkPageNumber
            // The path to the doreplacedents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Bookmarks();

            // Create PdfBookmarkEditor
            PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor();
            // Open PDF file
            bookmarkEditor.BindPdf(dataDir + "GetBookmarks.pdf");
            // Extract bookmarks
            Aspose.Pdf.Facades.Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks();
            foreach (Aspose.Pdf.Facades.Bookmark bookmark in bookmarks)
            {
                string strLevelSeprator = string.Empty;
                for (int i = 1; i < bookmark.Level; i++)
                {
                    strLevelSeprator += "----";
                }

                Console.WriteLine("{0}replacedle: {1}", strLevelSeprator, bookmark.replacedle);
                Console.WriteLine("{0}Page Number: {1}", strLevelSeprator, bookmark.PageNumber);
                Console.WriteLine("{0}Page Action: {1}", strLevelSeprator, bookmark.Action);
            }
            // ExEnd:GetBookmarkPageNumber
        }

19 View Source File : CreateFromWkt.cs
License : MIT License
Project Creator : aspose-gis

public static void Run()
        {
            //ExStart: CreateFromWkt
            string wkt = @"
GEOGCS[""WGS 84"",
    DATUM[""WGS_1984"",
        SPHEROID[""WGS 84"",6378137,298.257223563,
            AUTHORITY[""EPSG"",""7030""]],
        AUTHORITY[""EPSG"",""6326""]],
    PRIMEM[""Greenwich"",0,
        AUTHORITY[""EPSG"",""8901""]],
    UNIT[""degree"",0.01745329251994328,
        AUTHORITY[""EPSG"",""9122""]],
    AUTHORITY[""EPSG"",""4326""]]
";
            var srs = SpatialReferenceSystem.CreateFromWkt(wkt);
            Console.WriteLine("SRS Name: {0}", srs.Name); // WGS 84
            Console.WriteLine("SRS EPSG code: {0}", srs.EpsgCode); // 4326
            Console.WriteLine("Datum name: {0}", srs.GeographicDatum.Name); // WGS_1984
            Console.WriteLine("Datum EPSG code: {0}", srs.GeographicDatum.EpsgCode); // 6326
            Console.WriteLine("Ellipsoid name: {0}", srs.GeographicDatum.Ellipsoid.Name); // WGS 84
            Console.WriteLine("Ellipsoid EPSG code: {0}", srs.GeographicDatum.EpsgCode); // 7030

            Console.WriteLine("Type: {0}", srs.Type); // Geographic
            Console.WriteLine("Dimensions count: {0}", srs.DimensionsCount); // 2

            Console.WriteLine("First dimension name: {0}", srs.GetAxis(0).Name); // Longitude
            Console.WriteLine("First dimension direction: {0}", srs.GetAxis(0).Direction); // EAST

            Console.WriteLine("Second dimension name: {0}", srs.GetAxis(1).Name); // Lareplacedude
            Console.WriteLine("Second dimension direction: {0}", srs.GetAxis(1).Direction); // NORTH

            Console.WriteLine("First dimension unit: {0}, {1}", srs.GetUnit(0).Name, srs.GetUnit(0).Factor); // degree, 0.01745...
            Console.WriteLine("Second dimension unit: {0}, {1}", srs.GetUnit(1).Name, srs.GetUnit(1).Factor); // degree, 0.01745...

            var geogSrs = srs.AsGeographic;
            Console.WriteLine("Angular unit: {0}, {1}", geogSrs.AngularUnit.Name, geogSrs.AngularUnit.Factor); // degree, 0.01745...
            Console.WriteLine("Prime meridian: {0}, {1}", geogSrs.PrimeMeridian.Name, geogSrs.PrimeMeridian.Longitude); // Greenwich, 0
            //ExEnd: CreateFromWkt
        }

19 View Source File : IdentifyImages.cs
License : MIT License
Project Creator : aspose-pdf

public static void Run()
        {
            // ExStart:IdentifyImages
            // The path to the doreplacedents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Counter for grayscale images
            int grayscaled = 0;
            // Counter for RGB images
            int rgd = 0;

            using (Doreplacedent doreplacedent = new Doreplacedent(dataDir + "ExtractImages.pdf"))
            {
                foreach (Page page in doreplacedent.Pages)
                {
                    Console.WriteLine("--------------------------------");
                    ImagePlacementAbsorber abs = new ImagePlacementAbsorber();
                    page.Accept(abs);
                    // Get the count of images over specific page
                    Console.WriteLine("Total Images = {0} over page number {1}", abs.ImagePlacements.Count, page.Number);
                    // Doreplacedent.Pages[29].Accept(abs);
                    int image_counter = 1;
                    foreach (ImagePlacement ia in abs.ImagePlacements)
                    {
                        ColorType colorType = ia.Image.GetColorType();
                        switch (colorType)
                        {
                            case ColorType.Grayscale:
                                ++grayscaled;
                                Console.WriteLine("Image {0} is GrayScale...", image_counter);
                                break;
                            case ColorType.Rgb:
                                ++rgd;
                                Console.WriteLine("Image {0} is RGB...", image_counter);
                                break;
                        }
                        image_counter += 1;
                    }
                }
            }
            // ExEnd:IdentifyImages
           
            
        }

19 View Source File : UnembedFonts.cs
License : MIT License
Project Creator : aspose-pdf

public static void Run()
        {
            // ExStart:UnembedFonts
            // The path to the doreplacedents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDoreplacedents();
            // Open doreplacedent
            Doreplacedent pdfDoreplacedent = new Doreplacedent(dataDir + "OptimizeDoreplacedent.pdf");
            // Set UnembedFonts  option 
            var optimizeOptions = new Pdf.Optimization.OptimizationOptions
            {
                UnembedFonts = true
            };
            Console.WriteLine("Start");
            // Optimize PDF doreplacedent using OptimizationOptions
            pdfDoreplacedent.OptimizeResources(optimizeOptions);
            // Save updated doreplacedent
            pdfDoreplacedent.Save(dataDir + "OptimizeDoreplacedent_out.pdf");
            Console.WriteLine("Finished");
            var fi1 = new System.IO.FileInfo(dataDir + "OptimizeDoreplacedent.pdf");
            var fi2 = new System.IO.FileInfo(dataDir + "OptimizeDoreplacedent_out.pdf");
            Console.WriteLine("Original file size: {0}. Reduced file size: {1}", fi1.Length, fi2.Length);
            // ExEnd:UnembedFonts   
            Console.WriteLine("\nUnembeded fonts successfully.\nFile saved at " + dataDir);
        }

19 View Source File : AllowResusePageContent.cs
License : MIT License
Project Creator : aspose-pdf

public static void Run()
        {
            // ExStart:AllowResusePageContent
            // The path to the doreplacedents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDoreplacedents();
            // Open doreplacedent
            Doreplacedent pdfDoreplacedent = new Doreplacedent(dataDir + "OptimizeDoreplacedent.pdf");
            // Set AllowReusePageContent  option 
            var optimizeOptions = new Pdf.Optimization.OptimizationOptions
            {
                AllowReusePageContent = true
            };
            Console.WriteLine("Start");
            // Optimize PDF doreplacedent using OptimizationOptions
            pdfDoreplacedent.OptimizeResources(optimizeOptions);
            // Save updated doreplacedent
            pdfDoreplacedent.Save(dataDir + "OptimizeDoreplacedent_out.pdf");
            Console.WriteLine("Finished");
            var fi1 = new System.IO.FileInfo(dataDir + "OptimizeDoreplacedent.pdf");
            var fi2 = new System.IO.FileInfo(dataDir + "OptimizeDoreplacedent_out.pdf");
            Console.WriteLine("Original file size: {0}. Reduced file size: {1}", fi1.Length, fi2.Length);
            // ExEnd:AllowResusePageContent
            Console.WriteLine("\nAllowed resuse page content successfully.\nFile saved at " + dataDir);
        }

19 View Source File : GetButtonOptionValue.cs
License : MIT License
Project Creator : aspose-pdf

public static void Run()
        {
            try
            {
                // ExStart:GetButtonOptionValue
                // The path to the doreplacedents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Forms();

                // Create Form Object
                Aspose.Pdf.Facades.Form pdfForm = new Aspose.Pdf.Facades.Form();

                // Open Doreplacedent
                pdfForm.BindPdf(dataDir + "FormField.pdf");

                // Get button option values
                var optionValues = pdfForm.GetButtonOptionValues("Gender");

                IDictionaryEnumerator optionValueEnumerator = optionValues.GetEnumerator();

                while (optionValueEnumerator.MoveNext())
                    Console.WriteLine("Key : {0} , Value : {1} ", optionValueEnumerator.Key, optionValueEnumerator.Value);
                // ExEnd:GetButtonOptionValue
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

See More Examples