int.Parse(string, System.Globalization.NumberStyles, System.IFormatProvider)

Here are the examples of the csharp api int.Parse(string, System.Globalization.NumberStyles, System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4666 Examples 7

19 View Source File : ExprPlainReader.cs
License : MIT License
Project Creator : 0x1000000

public bool TryGetInt32(IPlainItem node, string propertyName, out int value)
        {
            value = default;
            if (this.TryGetSubNode(node.Id, propertyName, null, out var prop) && prop.Value != null)
            {
                value = int.Parse(prop.Value, CultureInfo.InvariantCulture);
                return true;
            }
            return false;
        }

19 View Source File : IntegrationTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public async Task Test_ParallelOnly()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                from val1  in Get1().AsParallel()
                from val2  in Get2().AsParallel()
                from val3S in Get3Str().AsParallel()
                from val4  in Get4().AsParallel()
                select val1 + val2 + int.Parse(val3S) + val4;


            sw.Stop();

            replacedert.AreEqual(9, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

19 View Source File : IntegrationTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public async Task Test_SequentialAndLet()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                from one in Get1().AsParallel()

                let oneA = one

                from two in Get2().AsParallel()
                from freeStr in Get3Str().AsParallel()

                let free = int.Parse(freeStr)//Intermediate expr 

                from eight in  Add5(free).replacedequential()//Here all the previous results can be used

                from oneB in Get1().AsParallel()
                from twoA in Get2().AsParallel()
                
                from six in Add5(oneB).replacedequential()//Here all the previous results can be used 
                
                select one + oneA + two + int.Parse(freeStr) + free + eight + oneB + twoA + six;


            sw.Stop();

            replacedert.AreEqual(27, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs*3);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs*3 + LagMs);
        }

19 View Source File : IntegrationTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public async Task Test_ParallelAndLet()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                from one in Get1().AsParallel()

                let oneA = one

                from two in Get2().AsParallel()
                from freeStr in Get3Str().AsParallel()

                let free = int.Parse(freeStr)//Intermediate expr 

                from oneB in Get1().AsParallel()
                from twoA in Get2().AsParallel()
                
                select one + oneA + two + int.Parse(freeStr) + free + oneB + twoA;


            sw.Stop();

            replacedert.AreEqual(13, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private unsafe string ProcessOutputImage(List<string> outputLayers, OutputMode outputMode)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            string reply = string.Empty;

            List<Surface> outputImages = null;
            Exception error = null;

            try
            {
                outputImages = new List<Surface>(outputLayers.Count);

                for (int i = 0; i < outputLayers.Count; i++)
                {
                    if (!TryGetValue(outputLayers[i], "layer=", out string packedLayerArgs))
                    {
                        throw new InvalidOperationException("Expected a layer message argument.");
                    }

                    string[] layerArgs = packedLayerArgs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if (layerArgs.Length != 4)
                    {
                        throw new InvalidOperationException("A layer message argument must have 4 values.");
                    }

                    string sharedMemoryName = layerArgs[0];
                    int width = int.Parse(layerArgs[1], NumberStyles.Integer, CultureInfo.InvariantCulture);
                    int height = int.Parse(layerArgs[2], NumberStyles.Integer, CultureInfo.InvariantCulture);
                    int stride = int.Parse(layerArgs[3], NumberStyles.Integer, CultureInfo.InvariantCulture);

                    Surface output = null;
                    bool disposeOutput = true;

                    try
                    {
                        output = new Surface(width, height);

                        using (MemoryMappedFile file = MemoryMappedFile.OpenExisting(sharedMemoryName))
                        {
                            using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                            {
                                byte* sourceScan0 = null;
                                RuntimeHelpers.PrepareConstrainedRegions();
                                try
                                {
                                    accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref sourceScan0);

                                    for (int y = 0; y < output.Height; y++)
                                    {
                                        byte* src = sourceScan0 + (y * stride);
                                        ColorBgra* dst = output.GetRowAddressUnchecked(y);

                                        Buffer.MemoryCopy(src, dst, stride, stride);
                                    }
                                }
                                finally
                                {
                                    if (sourceScan0 != null)
                                    {
                                        accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                                    }
                                }
                            }
                        }

                        outputImages.Add(output);
                        disposeOutput = false;
                    }
                    finally
                    {
                        if (disposeOutput)
                        {
                            output?.Dispose();
                        }
                    }
                }

                // Set the first output layer as the active layer.
                // This allows multiple G'MIC effects to be "layered" using the Apply button.
                layers[0].Dispose();
                layers[0] = new GmicLayer(outputImages[0].Clone(), true);
            }
            catch (Exception ex)
            {
                error = ex;
            }

            OutputImageState?.Dispose();
            OutputImageState = new OutputImageState(error, outputImages);

            RaiseOutputImageChanged();

            return reply;
        }

19 View Source File : BloonCreator.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

internal static bool SpawnBloon(ref SpawnBloonButton __instance) {
            for (int i = 0; i < bloons.Count; i++)
                if (__instance.model.display.Equals(bloons[i].display)) {
                    int amount = int.Parse(__instance.count.text);
                    int delay = int.Parse(__instance.rate.text);

                    BloonTaskRunner.bloonQueue.Enqueue(new(bloons[i], amount, delay));

                    return false;
                }

            return true;
        }

19 View Source File : UraganoBuilder.cs
License : MIT License
Project Creator : 1100100

public void AddServer(IConfigurationSection configurationSection)
        {
            UraganoSettings.ServerSettings = new ServerSettings();
            if (configurationSection.Exists())
            {
                var addressSection = configurationSection.GetSection("address");
                if (addressSection.Exists())
                    UraganoSettings.ServerSettings.Address = addressSection.Value.ReplaceIpPlaceholder();

                var portSection = configurationSection.GetSection("port");
                if (portSection.Exists())
                    UraganoSettings.ServerSettings.Port = int.Parse(portSection.Value);

                var weightSection = configurationSection.GetSection("weight");
                if (weightSection.Exists())
                    UraganoSettings.ServerSettings.Weight = int.Parse(weightSection.Value);

                var certUrlSection = configurationSection.GetSection("certurl");
                if (certUrlSection.Exists() && !string.IsNullOrWhiteSpace(certUrlSection.Value))
                {
                    if (!File.Exists(certUrlSection.Value))
                        throw new FileNotFoundException($"Certificate file {certUrlSection.Value} not found.");
                    UraganoSettings.ServerSettings.X509Certificate2 = new X509Certificate2(certUrlSection.Value, configurationSection.GetValue<string>("certpwd"));
                }
            }
            RegisterServerServices();
        }

19 View Source File : CommonMethods.cs
License : MIT License
Project Creator : 1100100

internal static ZooKeeperClientConfigure ReadZooKeeperClientConfigure(IConfigurationSection configurationSection)
        {
            var client = new ZooKeeperClientConfigure();
            if (configurationSection.Exists())
            {
                var connection = configurationSection.GetSection("ConnectionString");
                if (connection.Exists())
                    client.ConnectionString = connection.Value;
                var sessionTimeout = configurationSection.GetSection("SessionTimeout");
                if (sessionTimeout.Exists())
                    client.SessionTimeout = int.Parse(sessionTimeout.Value);

                var canBeReadOnly = configurationSection.GetSection("CanBeReadOnly");
                if (canBeReadOnly.Exists())
                    client.CanBeReadOnly = bool.Parse(canBeReadOnly.Value);
            }
            return client;
        }

19 View Source File : ConsulServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

public async Task<IReadOnlyList<ServiceDiscoveryInfo>> QueryServiceAsync(string serviceName, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
                throw new ArgumentNullException(nameof(serviceName));
            using (var consul = new ConsulClient(conf =>
            {
                conf.Address = ConsulClientConfigure.Address;
                conf.Datacenter = ConsulClientConfigure.Datacenter;
                conf.Token = ConsulClientConfigure.Token;
                conf.WaitTime = ConsulClientConfigure.WaitTime;
            }))
            {
                try
                {
                    var result = await consul.Health.Service(serviceName, "", true, cancellationToken);

                    if (result.StatusCode != HttpStatusCode.OK)
                    {
                        Logger.LogError("Query the service {0} failed:{0}", serviceName, result.StatusCode);
                        return new List<ServiceDiscoveryInfo>();
                    }

                    if (!result.Response.Any())
                        return new List<ServiceDiscoveryInfo>();

                    return result.Response.Select(p => new ServiceDiscoveryInfo(p.Service.ID, p.Service.Address, p.Service.Port, int.Parse(p.Service.Meta?.FirstOrDefault(m => m.Key == "X-Weight").Value ?? "0"), bool.Parse(p.Service.Meta?.FirstOrDefault(m => m.Key == "X-Tls").Value ?? "false"), p.Service.Meta)).ToList();
                }
                catch (Exception ex)
                {
                    Logger.LogError("Query the service {2} error:{0}\n{1}", ex.Message, ex.StackTrace, serviceName);
                    throw;
                }
            }
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 1694439208

private void button2_Click(object sender, EventArgs e)
        {
            int a = int.Parse(textBox2.Text);
            int s = getStr(a);
            string data = NativeAPI.GetPtrToStr_u(s);
            label2.Text = data;
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 1694439208

private void button3_Click(object sender, EventArgs e)
        {
            string data = NativeAPI.GetPtrToStr_u(int.Parse(textBox3.Text));
            MessageBox.Show(data);
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 1694439208

private void button5_Click(object sender, EventArgs e)
        {
            byte[] jmp_inst =
            {
                233,0,0,0,0,//JMP Address
            };
            int Method = NativeAPI.GetMethodPTR(typeof(WeChetHook), "Callback");
            textBox3.Text = (3212659 + int.Parse(label1.Text)).ToString();

            List<byte> byteSource = new List<byte>();
            byteSource.AddRange(new byte[] { 199, 134, 236, 2, 0, 0 });//mov dword [esi+0x000002EC],
            byteSource.AddRange(BitConverter.GetBytes(int.Parse(textBox3.Text) + 5));//0x00000000  把hook的后五个字节地址压进寄存器
            byteSource.AddRange(jmp_inst);//让他跳到跳板函数
            //这部分根据实际情况填写
            byteSource.Add(185);//补充替换的汇编指令
            byteSource.AddRange(BitConverter.GetBytes(int.Parse(label1.Text) + 19255272));//补充替换的汇编指令地址
            //开始hook
            Inline_Hook.InlineHook(int.Parse(textBox3.Text),5, byteSource.ToArray(), getInt(Method),11+10,"接收消息",(obj) =>{
                StringBuilder sb = new StringBuilder();
                sb.Append("接收消息:");
                int a = 0x68;
                //System.Windows.Forms.MessageBox.Show("esp:"+a.ToString());
                try
                {
                    if (obj.ESP == 0)
                        return;
                    int MsgPtr = NativeAPI.ReadMemoryValue(obj.ESP);
                    if (MsgPtr == 0)
                        return;
                    MsgPtr = NativeAPI.ReadMemoryValue(MsgPtr);
                    if (MsgPtr == 0)
                        return;
                    MsgPtr = NativeAPI.ReadMemoryValue(MsgPtr + 0x68);
                    if (MsgPtr == 0)
                        return;
                    int len = NativeAPI.lstrlenW(MsgPtr);
                    if (len == 0)
                        return;
                    sb.Append(NativeAPI.ReadMemoryStrValue(MsgPtr, len*2+2));
                    sb.Append("\r\n");
                    listBox1.Items.Add(sb.ToString());
                }
                catch (Exception es)
                {
                    File.AppendAllText("error.txt", es.Message);
                }
            });
        }

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

private async void CreateClientsButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceExpander.IsExpanded = true;

            string BaseName = NewClientName.Text;
            int CountOfMachines = (Int32.TryParse(NumberOfClients.Text, out int unUsed)) ? Int32.Parse(NumberOfClients.Text) : 1;
            int BeginningWith = (!StartingNumber.Text.Length.Equals(0)) ? Int32.Parse(StartingNumber.Text) : 0;
            List<String> DeviceList = new List<string>();
            int current = 0;
            object lockCurrent = new object();
            var progress = new Progress<int>(_ => IdCounter++) as IProgress<int>;

            for (int i = BeginningWith; i <= CountOfMachines; i++)
            {
                string ThisClient = BaseName + i;
                DeviceList.Add(ThisClient);
            }

            var myTask = Task.Run(() =>
            {
                Parallel.For(0, DeviceList.Count,
                    new ParallelOptions { MaxDegreeOfParallelism = MaxThreads },
                    (ii, loopState) =>
                    {
                        int thisCurrent = 0;
                        lock (lockCurrent)
                        {
                            thisCurrent = current;
                            current++;
                        }
                        string device = DeviceList[thisCurrent];
                        Device ThisDevice = new Device() { Name = device, Status = "Starting...", ImageSource = "Images\\step01.png", ProcessProgress = 10 };
                        Devices.Add(ThisDevice);
                        int thisIndex = Devices.IndexOf(ThisDevice);
                        RegisterClient(thisIndex);

                        progress.Report(0);
                    });
            });

            await myTask;
        }

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 : Form1.cs
License : MIT License
Project Creator : 1y0n

private void button1_Click(object sender, EventArgs e)
        {
            if (MODE) //极简模式
            {
                if (textBox1.Text.Contains(":"))
                {
                    string ip = textBox1.Text.Split(':')[0];
                    string port = textBox1.Text.Split(':')[1];
                    saveFileDialog1.Filter = "可执行文件|*.exe";
                    if ((saveFileDialog1.ShowDialog() == DialogResult.OK) && (saveFileDialog1.FileName != ""))
                    {
                        string savepath = saveFileDialog1.FileName;
                        if (Core.Generate_1_IP(comboBox3.Text, ip, port, savepath))
                        {
                            if (MessageBox.Show("生成成功,是否复制 metasploit 启动命令到剪贴板?", "成功", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                string msf_cmd = @"msfconsole -x ""use exploit/multi/handler; set payload windows/{{arch}}meterpreter/reverse_tcp; set lhost {{ip}}; set lport {{port}}; run; """;
                                string temp = comboBox3.Text.StartsWith("64") ? "x64/" : "";
                                msf_cmd = msf_cmd.Replace("{{arch}}", temp).Replace("{{ip}}", ip).Replace("{{port}}", port);
                                Clipboard.SetText(msf_cmd);
                            }
                        }
                        else
                        {
                            MessageBox.Show("生成失败,请检查你的输入。");
                        }
                    }
                    else
                    {
                        MessageBox.Show("必须按照 IP:端口 的形式,如 192.168.1.1:4444 ,输入地址。");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("必须按照 IP:端口 的形式,如 192.168.1.1:4444 ,输入地址。");
                    return;
                }
            }
            else
            {
                if (comboBox2.Text.Contains("注入"))
                {
                    if (textBox2.Text.Trim() == "")
                    {
                        MessageBox.Show("漏填了必填项,请检查", "提示");
                        return;
                    }
                    if (comboBox2.Text.Contains("现有"))
                    {
                        try
                        {
                            int temp = int.Parse(textBox2.Text);
                        }
                        catch
                        {
                            MessageBox.Show("注入现有进程时必须填写数字PID号", "提示");
                            return;
                        }
                    }
                }
                saveFileDialog1.Filter = "可执行文件|*.exe";
                if ((saveFileDialog1.ShowDialog() == DialogResult.OK) && (saveFileDialog1.FileName != "") && (richTextBox1.Text.Trim() != ""))
                {
                    bool result = false;
                    if (comboBox1.Text == "C")
                    {
                        result = Core.Gen_C(richTextBox1.Text, saveFileDialog1.FileName, comboBox2.Text, textBox2.Text, comboBox3.Text, comboBox5.Text);
                    }
                    else if (comboBox1.Text == "C#")
                    {
                        result = Core.Gen_CS(richTextBox1.Text, saveFileDialog1.FileName, comboBox2.Text, textBox2.Text, comboBox3.Text, comboBox5.Text);
                    }
                    if (result)
                    {
                        MessageBox.Show("生成成功!不要将生成的程序上传到在线杀毒网站", "成功");
                        return;
                    }
                    else
                    {
                        MessageBox.Show("生成失败!请检查你的输入", "失败");
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }

19 View Source File : SegmentedControlRenderer.cs
License : MIT License
Project Creator : 1iveowl

private void SegmentRadioButtonOnChecked(object sender, RoutedEventArgs e)
        {
            var button = (SegmentRadioButton) sender;

            if (!(button is null))
            {
                Element.SelectedSegment = int.Parse(button.Tag.ToString());
                Element?.RaiseSelectionChanged();
            }
        }

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

private void UpdateClientCount()
        {
            if (null == EndingNumber) { return; }
            if (null == NumberOfClients) { return; }
            if (StartingNumber.Text.Length.Equals(0) || EndingNumber.Text.Length.Equals(0))
            {
                return;
            }
            int StartingNo = Int32.Parse(StartingNumber.Text);
            int EndingNo = Int32.Parse(EndingNumber.Text);
            CalculatedClientsCount = Enumerable.Range(StartingNo, EndingNo).ToList().Count.ToString();

            NumberOfClients.Text = CalculatedClientsCount;

            Console.WriteLine("Generating " + CalculatedClientsCount + " new clients");
        }

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

private void MaximumThreads_TextChanged(object sender, TextChangedEventArgs e)
        {
            MaxThreads = int.Parse(MaximumThreads.Text);
        }

19 View Source File : RedisDate.cs
License : MIT License
Project Creator : 2881099

public override DateTime Parse(RedisReader reader)
            {
                reader.ExpectType(RedisMessage.MultiBulk);
                reader.ExpectSize(2);

                var timestamp = Int32.Parse(reader.ReadBulkString());
                var microseconds = long.Parse(reader.ReadBulkString());

                return FromTimestamp(timestamp, microseconds);
            }

19 View Source File : DDZGamePlayController.cs
License : Apache License 2.0
Project Creator : 2881099

async public static Task StandupStatic(Player player)
        {
            var sitdownKey = redis.HGet("sitdown_player_ht", player.Id.ToString());
            if (!string.IsNullOrEmpty(sitdownKey))
            {
                using (var pipe = redis.StartPipe())
                {
                    pipe.HDel("sitdown_player_ht", player.Id.ToString());
                    pipe.HDel("sitdown_ht", sitdownKey);
                    pipe.EndPipe();
                }
                //通知消息,坐位有用户离开
                var dp = sitdownKey.Split('_');
                var deskId = int.Parse(dp[0]);
                var desk = await Desk.FindAsync(deskId);
                ImHelper.SendChanMessage(Guid.Empty, "ddz_chan", new
                {
                    type = "Standup",
                    deskId = desk.Id,
                    pos = int.Parse(dp[1]),
                    msg = $"{player.Nick} 离开了座位 ({desk.replacedle}, POS:{dp[1]})"
                });
            }
        }

19 View Source File : RedisRoleCommand.cs
License : MIT License
Project Creator : 2881099

static RedisMasterRole ParseMaster(int num, string role, RedisReader reader)
        {
            reader.ExpectSize(3, num);
            long offset = reader.ReadInt();
            reader.ExpectType(RedisMessage.MultiBulk);
            var slaves = new Tuple<string, int, long>[reader.ReadInt(false)];
            for (int i = 0; i < slaves.Length; i++)
            {
                reader.ExpectType(RedisMessage.MultiBulk);
                reader.ExpectSize(3);
                string ip = reader.ReadBulkString();
                int port = Int32.Parse(reader.ReadBulkString());
                long.TryParse(reader.ReadBulkString(), out var slave_offset);
                slaves[i] = new Tuple<string, int, long>(ip, port, slave_offset);
            }
            return new RedisMasterRole(role, offset, slaves);
        }

19 View Source File : RedisString.cs
License : MIT License
Project Creator : 2881099

public override int Parse(RedisReader reader)
            {
                return Int32.Parse(reader.ReadBulkString());
            }

19 View Source File : Test.cs
License : MIT License
Project Creator : 3wz

IEnumerator Start()
    {
        string testWav = "testWav.wav";
        string testMp3 = "testMp3.mp3";
        WWW www = new WWW(GetFileStreamingreplacedetsPath(testWav));
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            string saveWavPath = Path.Combine(Application.persistentDataPath, testWav);
            File.WriteAllBytes(saveWavPath, www.bytes);
            button.onClick.AddListener(() =>
            {
                string saveMp3Path = Path.Combine(Application.persistentDataPath, testMp3);
                var bitRate = string.IsNullOrEmpty(input.text) ? LAMEPreset.ABR_128 : (LAMEPreset)int.Parse(input.text);
                WaveToMP3(saveWavPath, saveMp3Path, bitRate);
                StartCoroutine(PlayMp3(saveMp3Path));
            });
        }
    }

19 View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc

private static object ParseDefaultValue(Type type, object value)
        {
			if(true)
            {
                Type tmp = Helpers.GetUnderlyingType(type);
                if (tmp != null) type = tmp;
            }
            switch (Helpers.GetTypeCode(type))
            {
                case ProtoTypeCode.Boolean:
                case ProtoTypeCode.Byte:
                case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
                case ProtoTypeCode.DateTime:
                case ProtoTypeCode.Decimal:
                case ProtoTypeCode.Double:
                case ProtoTypeCode.Int16:
                case ProtoTypeCode.Int32:
                case ProtoTypeCode.Int64:
                case ProtoTypeCode.SByte:
                case ProtoTypeCode.Single:
                case ProtoTypeCode.String:
                case ProtoTypeCode.UInt16:
                case ProtoTypeCode.UInt32:
                case ProtoTypeCode.UInt64:
                case ProtoTypeCode.TimeSpan:
                case ProtoTypeCode.Uri:
                case ProtoTypeCode.Guid:
                    {
                        value = value + "";
                    }
                    break;
            }
            if (value is string)
            {
                string s = (string)value;
                if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);

                switch (Helpers.GetTypeCode(type))
                {
                    case ProtoTypeCode.Boolean: return bool.Parse(s);
                    case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
                        if (s.Length == 1) return s[0];
                        throw new FormatException("Single character expected: \"" + s + "\"");
                    case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.String: return s;
                    case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
                    case ProtoTypeCode.Uri: return s; // Uri is decorated as string
                    case ProtoTypeCode.Guid: return new Guid(s);
                }
            }
#if FEAT_IKVM
            if (Helpers.IsEnum(type)) return value; // return the underlying type instead
            System.Type convertType = null;
            switch(Helpers.GetTypeCode(type))
            {
                case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
                case ProtoTypeCode.Int16: convertType = typeof(short); break;
                case ProtoTypeCode.Int32: convertType = typeof(int); break;
                case ProtoTypeCode.Int64: convertType = typeof(long); break;
                case ProtoTypeCode.Byte: convertType = typeof(byte); break;
                case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
                case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
                case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
                case ProtoTypeCode.Single: convertType = typeof(float); break;
                case ProtoTypeCode.Double: convertType = typeof(double); break;
                case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
            }
            if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
            throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
#else
            if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
            return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
#endif
        }

19 View Source File : Download.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private int NHGetPageCount(string url)
        {
            HtmlAgilityPack.HtmlDoreplacedent doreplacedent;
            if (url.EndsWith("/"))
            {
                doreplacedent = new HtmlWeb().Load(url.Substring(0, url.Length - 2));
            }
            else
            {
                doreplacedent = new HtmlWeb().Load(url.Substring(0, url.Length - 1));
            }

            int startIndex = doreplacedent.DoreplacedentNode.InnerHtml.IndexOf("\"num_pages\":") + 12;
            int length = doreplacedent.DoreplacedentNode.InnerHtml.IndexOf(",\"num_favorites\"") - startIndex;
            return int.Parse(doreplacedent.DoreplacedentNode.InnerHtml.Substring(startIndex, length));
        }

19 View Source File : FrmGoTo.cs
License : MIT License
Project Creator : A-Tabeshfard

private void BtnGoTo_Click(object sender, EventArgs e)
        {
            if (txtLineNumber.Text.IsEmpty())
            {
                MessageBox.Show(this, "You must enter a value.", "Notepad Clone - Goto Line");
                return;
            }

            int PotentialLineNumber = Int32.Parse(txtLineNumber.Text);

            if (PotentialLineNumber == 0)
            {
                MessageBox.Show(this, "Zero (0) is not a valid line number, line numbers start at 1.", "Notepad Clone - Goto Line");
                return;
            }

            LineNumber = PotentialLineNumber;
            DialogResult = DialogResult.OK;
            Close();
        }

19 View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063

private bool SendStr(String str, bool hexbool)
        {

            byte[] sendData = null;

            if (hexbool)
            {
                try
                {
                    sendData = strToHexByte(str.Trim());
                }
                catch (Exception)
                {
                    //throw;
                    MessageBox.Show("字符串转十六进制有误,请检测输入格式.", "错误!");
                    return false;
                }
            }
            else if (rbtnSendASCII.Checked)
            {
                //sendData = Encoding.ASCII.GetBytes(str);
                sendData = Encoding.GetEncoding("GBK").GetBytes(str);
            }
            else if (rbtnSendUTF8.Checked)
            {
                sendData = Encoding.UTF8.GetBytes(str);
            }
            else if (rbtnSendUnicode.Checked)
            {
                sendData = Encoding.Unicode.GetBytes(str);
            }
            else
            {
                sendData = Encoding.GetEncoding("GBK").GetBytes(str);
            }

            if (this.SendData(sendData))//发送数据成功计数
            {
                lblSendCount.Invoke(new MethodInvoker(delegate
                {
                    lblSendCount.Text = "发送:" + (int.Parse(lblSendCount.Text.Substring(3)) + sendData.Length).ToString();
                }));
                return true;
            }

            return false;
        }

19 View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063

public void AddData(byte[] data)
        {
            if (rbtnHex.Checked)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sb.AppendFormat("{0:x2}" + " ", data[i]);
                }
                AddContent(sb.ToString().ToUpper());
            }
            else if (rbtnUTF8.Checked)
            {
                AddContent(new UTF8Encoding().GetString(data));
            }
            else if (rbtnUnicode.Checked)
            {
                AddContent(new UnicodeEncoding().GetString(data));
            }
            else// if (rbtnASCII.Checked)
            {
                //AddContent(new ASCIIEncoding().GetString(data));
                AddContent(Encoding.GetEncoding("GBK").GetString(data));
            }

            lblRevCount.Invoke(new MethodInvoker(delegate
            {
                lblRevCount.Text = "接收:" + (int.Parse(lblRevCount.Text.Substring(3)) + data.Length).ToString();
            }));
        }

19 View Source File : DatabaseSchemaUpgradeManager.cs
License : Microsoft Public License
Project Creator : AArnott

private static int GetLatestVersion()
	{
		string startsWith = $"{Thisreplacedembly.RootNamespace}.SchemaUpgradeScripts.";
		string endsWith = ".sql";
		int latestVersion = (from name in replacedembly.GetExecutingreplacedembly().GetManifestResourceNames()
							 where name.StartsWith(startsWith, StringComparison.Ordinal) && name.EndsWith(endsWith, StringComparison.Ordinal)
							 let version = int.Parse(name.Substring(startsWith.Length, name.Length - startsWith.Length - endsWith.Length), CultureInfo.InvariantCulture)
							 select version).Max();
		return latestVersion;
	}

19 View Source File : V1Loader.cs
License : MIT License
Project Creator : Abdesol

static HighlightingBrush ParseColor(string c)
		{
			if (c.StartsWith("#", StringComparison.Ordinal)) {
				int a = 255;
				int offset = 0;
				if (c.Length > 7) {
					offset = 2;
					a = Int32.Parse(c.Substring(1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				}

				int r = Int32.Parse(c.Substring(1 + offset, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				int g = Int32.Parse(c.Substring(3 + offset, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				int b = Int32.Parse(c.Substring(5 + offset, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				return new SimpleHighlightingBrush(Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b));
			} else if (c.StartsWith("SystemColors.", StringComparison.Ordinal)) {
				return V2Loader.GetSystemColorBrush(null, c);
			} else {
				return new SimpleHighlightingBrush((Color)V2Loader.ColorConverter.ConvertFromInvariantString(c));
			}
		}

19 View Source File : HttpGetSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

private static HttpWebRequest BuildRequest(string queryString) {
         HttpWebRequest Request;
         Request = (HttpWebRequest)WebRequest.Create(queryString);
         try {
            Request.Timeout = int.Parse(AppSettings.RequestTimeoutInMilliseconds, CultureInfo.CurrentCulture);
         }
         catch {
            Request.Timeout = 100000;
         }
         Request.ContentType = "text/xml; charset=utf-8";
         Request.Proxy = GetWebProxy();
         Request.Method = "GET";
         return (Request);
      }

19 View Source File : SoapSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

private HttpWebRequest BuildRequest(string soapMessage, string soapAction) {
         HttpWebRequest Request;
         Request = (HttpWebRequest)WebRequest.Create(AppSettings.SearchUrl(this.Style));
         try {
            Request.Timeout = int.Parse(AppSettings.RequestTimeoutInMilliseconds, CultureInfo.CurrentCulture);
         }
         catch {
            Request.Timeout = 100000;
         }
         Request.Headers.Add("SoapAction", soapAction);
         Request.ContentType = "text/xml; charset=utf-8";
         Request.ContentLength = soapMessage.Length;
         Request.Proxy = GetWebProxy();
         Request.Method = "POST";
         return (Request);
      }

19 View Source File : DatabaseMigrationEventHandlerBase.cs
License : MIT License
Project Creator : abpframework

private static int GetEventTryCount(EtoBase eventData)
        {
            var tryCountreplacedtring = eventData.Properties.GetOrDefault(TryCountPropertyName);
            if (tryCountreplacedtring.IsNullOrEmpty())
            {
                return 0;
            }
    
            return int.Parse(tryCountreplacedtring);
        }

19 View Source File : OVRNamedArrayPropertyDrawer.cs
License : MIT License
Project Creator : absurd-joy

public override void OnGUI( Rect rect, SerializedProperty property, GUIContent label ) {
        try {
            int pos = int.Parse(property.propertyPath.Split('[', ']')[1]);
            EditorGUI.PropertyField( rect, property,
                new GUIContent( ( (OVRNamedArrayAttribute)attribute ).names[pos] ) );
        } catch {
            EditorGUI.PropertyField( rect, property, label );
        }
    }

19 View Source File : ExportManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public void Print(
        ExportSheet sheet,
        string printerName,
        int scale,
        ExportLog log)
        {
            var startTime = log.StartLoggingIndividualItem(null);
            log.AddMessage(sheet.ToString());

            PrintManager pm = Doc.PrintManager;
            bool printSettingsValid;
            if (!sheet.Verified)
            {
                sheet.UpdateSheetInfo();
            }
            printSettingsValid = false;

            switch (scale)
            {
                case 3:
                    printSettingsValid |= PrintSettings.PrintToDevice(Doc, "A3-FIT", pm, printerName, sheet.ForceRasterPrint, log);
                    break;

                case 2:
                    printSettingsValid |= PrintSettings.PrintToDevice(Doc, "A2-FIT", pm, printerName, sheet.ForceRasterPrint, log);
                    break;

                default:
                    int i = int.Parse(sheet.PageSize.Substring(1, 1), CultureInfo.InvariantCulture);
                    string printerNameTmp = i > 2 ? PrinterNameA3 : PrinterNameLargeFormat;
                    printSettingsValid |= PrintSettings.PrintToDevice(Doc, sheet.PageSize, pm, printerNameTmp, sheet.ForceRasterPrint, log);
                    break;
            }
            if (printSettingsValid)
            {
                pm.SubmitPrint(sheet.Sheet);
            }
            else
            {
                SCaddinsApp.WindowManager.ShowMessageBox("test", "print error");
            }
            log.EndLoggingIndividualItem(startTime, null);
        }

19 View Source File : ExpressionToken.cs
License : MIT License
Project Creator : actions

internal static Boolean IsValidExpression(
            String expression,
            String[] allowedContext,
            out Exception ex)
        {
            // Create dummy named values and functions
            var namedValues = new List<INamedValueInfo>();
            var functions = new List<IFunctionInfo>();
            if (allowedContext?.Length > 0)
            {
                foreach (var contexreplacedem in allowedContext)
                {
                    var match = s_function.Match(contexreplacedem);
                    if (match.Success)
                    {
                        var functionName = match.Groups[1].Value;
                        var minParameters = Int32.Parse(match.Groups[2].Value, NumberStyles.None, CultureInfo.InvariantCulture);
                        var maxParametersRaw = match.Groups[3].Value;
                        var maxParameters = String.Equals(maxParametersRaw, TemplateConstants.MaxConstant, StringComparison.Ordinal)
                            ? Int32.MaxValue
                            : Int32.Parse(maxParametersRaw, NumberStyles.None, CultureInfo.InvariantCulture);
                        functions.Add(new FunctionInfo<DummyFunction>(functionName, minParameters, maxParameters));
                    }
                    else
                    {
                        namedValues.Add(new NamedValueInfo<ContextValueNode>(contexreplacedem));
                    }
                }
            }

            // Parse
            Boolean result;
            ExpressionNode root = null;
            try
            {
                root = new ExpressionParser().CreateTree(expression, null, namedValues, functions) as ExpressionNode;

                result = true;
                ex = null;
            }
            catch (Exception exception)
            {
                result = false;
                ex = exception;
            }

            return result;
        }

public ChapmanKolmogorov Calculate(int id, int stateId, string startDate)
        {
            var hazards = new List<DBHazardPDF>();
            var codes = transitionCodesReader.GetData(id);
            foreach (var code in codes)
            {
                if (code.Substring(0, 1) == stateId.ToString())
                {
                    var hazard = new DBHazardPDF(new StatAIEnreplacedies(), int.Parse(code), id.ToString(), startDate);
                    hazards.Add(hazard);
                }
            }

            return new ChapmanKolmogorov(hazards, id);
        }

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

private static int ExpectedExitCode(string code)
        {
            var exitCode = ExitCodePattern.Match(code).Groups["exitCode"]?.Captures.SingleOrDefault()?.Value ?? "0";
            return int.Parse(exitCode, CultureInfo.InvariantCulture);
        }

19 View Source File : PluralExpressionCompiler.cs
License : MIT License
Project Creator : adams85

private Expression VisitInteger(ASTNode node)
        {
            return Expression.Constant(int.Parse(node.Value, CultureInfo.InvariantCulture));
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

private void btnCreate_Click(object sender, EventArgs e)
		{
			if (!IsWorking)
			{
				SetAsProcessing();

				BigInteger n = N;
				int degree = Degree;
				BigInteger polyBase = Base;
				BigInteger bound = Bound;

				int relationQuanreplacedy = int.Parse(tbRelationQuanreplacedy.Text);
				int relationValueRange = int.Parse(tbRelationValueRange.Text);

				//Logging.OutputFilename = DirectoryLocations.GetUniqueNameFromN(n) + ".LOG.txt";
				//Logging.CreateLogFileIfNotExists();

				Logging.LogMessage($"[New factorization job creation initialization for N = {DirectoryLocations.GetUniqueNameFromN(n)}...]");

				CancellationToken token = _cancellationTokenSource.Token;
				new Thread(() =>
				{
					GNFS localGnfs =
						GnfsUiBridge.CreateGnfs
						(
							token,  // CancellationToken
							n,      // Semi-prime to factor N = P*Q
							polyBase, // Polynomial base (value for x)
							degree, // Polynomial Degree
							bound, //  BigInteger
							relationQuanreplacedy, // Total # of relations to collect before proceeding.
							relationValueRange // 
						);

					SetGnfs(this, localGnfs);
					HaultAllProcessing();
					ControlBridge.SetControlEnabledState(panelFunctions, true);
					Logging.LogMessage($"[New factorization job initialization complete]");
					Logging.LogMessage($"NOTE: You should save your progress now.");
					PrintCurrentCounts();
					RefreshLoadSaveButtonState();
				}).Start();
			}
		}

19 View Source File : IntComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX

public byte[] GetValueData()
        {
            switch (_dataType)
            {
                case DataTypeEnum.RegUwpByte:
                    return FromByte(byte.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpInt16:
                    return FromInt16(short.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpUint16:
                    return FromUInt16(ushort.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpInt32:
                    return FromInt32(int.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpUint32:
                    return FromUInt32(uint.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpInt64:
                    return FromInt64(long.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpUint64:
                    return FromUInt64(ulong.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpSingle:
                    return FromSingle(float.Parse(txBox.Text), _timestamp);
                case DataTypeEnum.RegUwpDouble:
                    return FromDouble(double.Parse(txBox.Text), _timestamp);
                default:
                    return null;
            }
        }

19 View Source File : NumericsForm.cs
License : MIT License
Project Creator : adospace

public override VisualNode Render()
        {
            return new RxStackLayout()
            {
                new RxLabel("Field 3"),
                new RxEntry(State.Field3.ToString())
                    .OnTextChanged((e) => SetState(_=>_.Field3 = int.Parse(e.NewTextValue)))
                    .Keyboard(Keyboard.Numeric),
                new RxLabel("Field 4"),
                new RxEntry(State.Field4.ToString())
                    .OnTextChanged((e) => SetState(_=>_.Field4 = int.Parse(e.NewTextValue)))
                    .Keyboard(Keyboard.Numeric),
                new RxLabel("Field 5"),
                new RxEntry(State.Field5.ToString())
                    .OnTextChanged((e) => SetState(_=>_.Field5 = int.Parse(e.NewTextValue)))
                    .Keyboard(Keyboard.Numeric),
            };
        }

19 View Source File : ChildPageComponent.cs
License : MIT License
Project Creator : adospace

public override VisualNode Render()
        {
            return new RxContentPage()
            {
                new RxStackLayout()
                {
                    new RxEntry(State.Value.ToString())
                        .OnAfterTextChanged(_=>SetState(s => s.Value = int.Parse(_)))
                        .Keyboard(Keyboard.Numeric),
                    new RxButton("Back")
                        .OnClick(GoBack)
                }
                .VCenter()
                .HCenter()
            }
            .replacedle("Child Page");
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static object GetAttribute<T>(this JToken attribute)
		{
			if (attribute == null) return null;
			if (typeof(T).GetUnderlyingType() == typeof(bool)) return bool.Parse(attribute.Value<string>());
			if (typeof(T).GetUnderlyingType() == typeof(int)) return int.Parse(attribute.Value<string>());
			if (typeof(T) == typeof(object)) return attribute.Value<JValue>().Value;

			return null;
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void OpportunityUpdating(object sender, CrmEnreplacedyFormViewUpdatingEventArgs e)
		{
			if (UpdatePipelinePhase.Checked)
			{
				e.Values["stepname"] = PipelinePhase.SelectedItem.Text;
				e.Values["salesstagecode"] = int.Parse(PipelinePhase.SelectedValue);

				//var processCode = PipelinePhase.SelectedValue;
			}
			else if (ReturnToNetwork.Checked)
			{
				e.Values["closeprobability"] = 0;
				e.Values["adx_reasonforreturn"] = ReasonForReturn.SelectedIndex + 100000000;
			}

			e.Values["description"] = OpportunityNotes.Text;

			Guid id;

			if ((replacedignToList != null && !string.IsNullOrEmpty(replacedignToList.SelectedValue)) && Guid.TryParse(replacedignToList.SelectedItem.Value, out id))
			{
				e.Values["msa_partneroppid"] = id;
			}

		}

19 View Source File : ScheduleService.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void FindTimes_Click(object sender, EventArgs args)
		{
			var startTimeInMinutesFromMidnight = int.Parse(StartTime.SelectedValue);

			var startDate = StartDate.SelectedDate.AddMinutes(startTimeInMinutesFromMidnight);

			var endTimeInMinutesFromMidnight = int.Parse(EndTime.SelectedValue);

			var endDate = EndDate.SelectedDate.AddMinutes(endTimeInMinutesFromMidnight);

			if (!SelectedDatesAndTimesAreValid(startDate, endDate, startTimeInMinutesFromMidnight, endTimeInMinutesFromMidnight))
			{
				return;
			}

			// Add the timezone selected to the CRM Contact for next time.
			var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == Contact.Id);

			if (contact == null)
			{
				throw new ApplicationException(string.Format("Couldn't find the user contact where contactid equals {0}.", Contact.Id));
			}

			contact.SetAttributeValue("adx_timezone", int.Parse(TimeZoneSelection.SelectedValue));

			XrmContext.UpdateObject(contact);

			XrmContext.SaveChanges();

			var usersMinutesFromGmt = GetUsersMinutesFromGmt(contact.GetAttributeValue<int?>("adx_timezone"), XrmContext);

			var appointmentRequest = new AppointmentRequest
			{
				AnchorOffset = Service.GetAttributeValue<int?>("anchoroffset").GetValueOrDefault(),
				Direction = SearchDirection.Forward,
				Duration = Service.GetAttributeValue<int?>("duration").GetValueOrDefault(60),
				NumberOfResults = 10,
				RecurrenceDuration = endTimeInMinutesFromMidnight - startTimeInMinutesFromMidnight,
				RecurrenceTimeZoneCode = contact.GetAttributeValue<int?>("adx_timezone").GetValueOrDefault(),
				SearchRecurrenceRule = "FREQ=DAILY;INTERVAL=1",
				SearchRecurrenceStart = new DateTime(startDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc),
				SearchWindowEnd = new DateTime(endDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc),
				ServiceId = Service.GetAttributeValue<Guid>("serviceid")
			};

			var service = XrmContext;

			var searchRequest = new OrganizationRequest("Search");
			searchRequest.Parameters["AppointmentRequest"] = appointmentRequest;

			var searchResults = (SearchResults)service.Execute(searchRequest).Results["SearchResults"];

			var schedules = searchResults.Proposals.Select(proposal => new
			{
				ScheduledStart = proposal.Start.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
				ScheduledStartUniversalTime = proposal.Start.GetValueOrDefault().ToUniversalTime(),
				ScheduledEnd = proposal.End.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
				ScheduledEndUniversalTime = proposal.End.GetValueOrDefault().ToUniversalTime(),
				AvailableResource = proposal.ProposalParties.First().ResourceId
			}).Where(proposal => proposal.ScheduledStartUniversalTime >= DateTime.UtcNow);

			if (!schedules.Any())
			{
				SearchPanel.Visible = true;
				NoTimesMessage.Visible = true;
				ResultsDisplay.Visible = false;

				return;
			}

			AvailableTimes.DataSource = schedules;
			AvailableTimes.DataBind();

			SearchPanel.Visible = false;
			ResultsDisplay.Visible = true;
			ScheduleServiceButton.Enabled = false;
		}

19 View Source File : SimpleAudioRecorderImplementation.cs
License : MIT License
Project Creator : adrianstevens

public Task RecordAsync()
        {
            if (CanRecordAudio == false || audioRecord?.RecordingState == RecordState.Recording)
                return Task.CompletedTask;

            var audioManager = (AudioManager)Application.Context.GetSystemService(Context.AudioService);

            var micSampleRate = Int32.Parse(audioManager.GetProperty(AudioManager.PropertyOutputSampleRate));

            audioRecord = GetAudioRecord(micSampleRate);

            audioRecord.StartRecording();

            return Task.Run(() => WriteAudioDataToFile());
        }

19 View Source File : EnumDeclarationVisitor.cs
License : MIT License
Project Creator : adrianoc

public override int VisitLiteralExpression(LiteralExpressionSyntax node)
            {
                if (node.Kind() != SyntaxKind.NumerireplacederalExpression)
                {
                    throw new InvalidOperationException($"Invalid literal type: {node}");
                }

                var value = node.ToString();
                if (value.StartsWith("0x"))
                {
                    return Convert.ToInt32(value.Substring(2), 16);
                }

                return int.Parse(value);
            }

19 View Source File : AduPage.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
      {
         if (!(e.OriginalSource is RadioButton button)) return;
         if (button.IsChecked == false) return;
         PageIndex = int.Parse(button.Tag.ToString());
      }

19 View Source File : Notifiaction.xaml.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void NoticeGrid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Height != 0.0)
                return;
            var element = sender as Grid;
            RemoveNotification(NotifiactionList.First(n => n.Id == Int32.Parse(element.Tag.ToString())));
        }

See More Examples