Here are the examples of the csharp api System.Convert.ToInt32(string, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
5134 Examples
19
View Source File : DiscordWebhook.cs
License : MIT License
Project Creator : 1-EXON
License : MIT License
Project Creator : 1-EXON
private void Send_click()
{
if (content.Text == string.Empty)
{
MessageBox.Show("메세지를 입력하세요");
Console.WriteLine("Empty");
}
else
{
using (DcWebHook dcWeb = new DcWebHook())
{
dcWeb.ProfilePicture = image.Text;
dcWeb.UserName = name.Text;
dcWeb.WebHook = Data.discordLink;
#region Embed Test
//Embed TEST
//NameValueCollection embed = new NameValueCollection
//{
// {
// "replacedle",
// this.content.Text
// },
// {
// "description",
// "안녕"
// },
// {
// "color",
// "#ffffff"
// }
//};
// NameValueCollection msg = new NameValueCollection
// {
// {
// "username",
// this.name.Text
// },
// {
// "avatar_url",
// this.image.Text
// },
// {
// "content",
// this.content.Text
// },
// {
// "embeds",
// {
// {
// "replacedle",
// this.content.Text
// },
// {
// "description",
// "안녕"
// },
// {
// "color",
// "#ffffff"
// },
// }
// }
// };
#endregion
if (repeat.Text == "")
{
MessageBox.Show("숫자를 입력하세요");
return;
}
else if (Convert.ToInt32(repeat.Text) < 6)
{
for (int i = 0; i < Convert.ToInt32(repeat.Text); i++)
{
dcWeb.SendMessage(content.Text);//
}
}
//서른개 넘어가면 1초도 에러
else if (Convert.ToInt32(repeat.Text) <= 0)
{
MessageBox.Show("0 이하의 수는 입력하실 수 없습니다.");
}
else
{
for (int i = 0; i < Convert.ToInt32(repeat.Text); i++)
{
dcWeb.SendMessage(content.Text);//
Thread.Sleep(1 * 1000);
}
}
}
}
if (resetRepeat.Checked)
{
repeat.Text = "1";
}
if (resetContent.Checked)
{
content.Text = string.Empty;
}
}
19
View Source File : LoadBalancing.WeightedPolling.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task<ServiceNodeInfo> GetNextNode(string serviceName, string serviceRoute, IReadOnlyList<object> serviceArgs, IReadOnlyDictionary<string, string> serviceMeta)
{
var nodes = await ServiceDiscovery.GetServiceNodes(serviceName);
if (!nodes.Any())
throw new NotFoundNodeException(serviceName);
if (nodes.Count == 1)
return nodes.First();
lock (LockObject)
{
var index = -1;
var total = 0;
for (var i = 0; i < nodes.Count; i++)
{
nodes[i].Attach.AddOrUpdate(Key, nodes[i].Weight, (key, old) => Convert.ToInt32(old) + nodes[i].Weight);
total += nodes[i].Weight;
if (index == -1 || GetCurrentWeightValue(nodes[index]) < GetCurrentWeightValue(nodes[i]))
{
index = i;
}
}
nodes[index].Attach.AddOrUpdate(Key, -total, (k, old) => Convert.ToInt32(old) - total);
var node= nodes[index];
if (Logger.IsEnabled(LogLevel.Trace))
Logger.LogTrace($"Load to node {node.ServiceId}.");
return node;
}
}
19
View Source File : LoadBalancing.WeightedPolling.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static int GetCurrentWeightValue(ServiceNodeInfo node)
{
return !node.Attach.TryGetValue(Key, out var val) ? 0 : Convert.ToInt32(val);
}
19
View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static byte[] Hex2Bytes(this string s)
{
if (s.IsNull())
return null;
var bytes = new byte[s.Length / 2];
for (int x = 0; x < s.Length / 2; x++)
{
int i = (Convert.ToInt32(s.Substring(x * 2, 2), 16));
bytes[x] = (byte)i;
}
return bytes;
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
Global_Var.delay = Convert.ToInt32(numericUpDown1.Value);
numericUpDown1.Enabled = true;
}
else
{
Global_Var.delay = 0;
numericUpDown1.Enabled = false;
}
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
Global_Var.delay = Convert.ToInt32(numericUpDown1.Value);
}
}
19
View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan
License : MIT License
Project Creator : 20chan
public static byte[] CompileToMachineCode(string asmcode)
{
var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
var asmfile = $"{path}.s";
var objfile = $"{path}.o";
File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var gcc = Process.Start(psi);
gcc.WaitForExit();
if (gcc.ExitCode == 0)
{
psi.FileName = "objdump";
psi.Arguments = $"-z -M intel -d {objfile}";
var objdump = Process.Start(psi);
objdump.WaitForExit();
if (objdump.ExitCode == 0)
{
var output = objdump.StandardOutput.ReadToEnd();
var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
var result = new List<byte>();
foreach (Match match in matches)
{
result.Add((byte)Convert.ToInt32(match.Value, 16));
}
return result.TakeWhile(b => b != 0x90).ToArray();
}
}
else
{
var err = gcc.StandardError.ReadToEnd();
}
throw new ArgumentException();
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
private void button1_Click(object sender, EventArgs e)
{
if ((textBox2.Enabled) && (textBox2.Text.Trim() == ""))
{
MessageBox.Show("注入进程时应按照要求填写进程名或 pid", "警告");
return;
}
string file_type = comboBox1.Text;
string target_arch = null;
Compiler compiler = new Compiler();
target_arch = " /platform:x86 /optimize ";
switch (file_type)
{
case ".exe":
saveFileDialog1.Filter = "可执行文件|*.exe";
break;
case ".js":
saveFileDialog1.Filter = "js脚本|*.js";
break;
case ".xsl":
saveFileDialog1.Filter = "xsl文件|*.xsl";
break;
}
DialogResult dr = saveFileDialog1.ShowDialog();
if (dr == DialogResult.OK && saveFileDialog1.FileName.Length > 0)
{
switch (file_type)
{
case ".exe":
if (radioButton2.Checked)
{
target_arch = " /platform:x64 /optimize";
}
if (checkBox2.Checked)
{
target_arch += "/target:winexe ";
}
if (ico_filename != null)
{
target_arch += " /win32icon:" + ico_filename;
}
KEY = Random_Key();
List<string> temp_list = new List<string>();
foreach (byte i in KEY)
{
temp_list.Add("0x" + i.ToString("X2"));
}
KEY_String = string.Join(",", temp_list); //生成key的字符串形式,用于写入到文件
switch (comboBox4.Text)
{
case "直接执行(VirtualAlloc)":
TP_VirtualAlloc va = new TP_VirtualAlloc(KEY_String, Handle_Payload());
compiler.compileToExe(va.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
case "直接执行(VirtualProtect)":
TP_VirtualProtect vp = new TP_VirtualProtect(KEY_String, Handle_Payload());
compiler.compileToExe(vp.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
case "[x64]新进程注入(SYSCALL)":
TP_Syscall_New scn = new TP_Syscall_New(KEY_String, Handle_Payload(), textBox2.Text.Trim());
target_arch += " /unsafe"; //必需,因为包含了不安全代码
compiler.compileToExe(scn.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
case "新进程注入(VirtualAllocEx)":
TP_VirtualAllocEx vaex = new TP_VirtualAllocEx(KEY_String, Handle_Payload(), textBox2.Text);
compiler.compileToExe(vaex.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
case "注入现有进程(VirtualAllocEx)":
TP_VirtualAllocEx_Exist vaee = new TP_VirtualAllocEx_Exist(KEY_String, Handle_Payload(), Convert.ToInt32(textBox2.Text.Trim()));
compiler.compileToExe(vaee.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
case "[x64]注入现有进程(SYSCALL)":
TP_Syscall_Exist sce = new TP_Syscall_Exist(KEY_String, Handle_Payload(), Convert.ToInt32(textBox2.Text.Trim()));
target_arch += " /unsafe"; //必需,因为包含了不安全代码
compiler.compileToExe(sce.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
case "进程镂空(Process Hollowing)":
TP_Process_Hollowing ph = new TP_Process_Hollowing(KEY_String, Handle_Payload(), textBox2.Text);
target_arch += " /unsafe"; //必需,因为包含了不安全代码
compiler.compileToExe(ph.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
break;
}
break;
default:
string temp = Generate_JS_XSL(file_type);
System.IO.File.WriteAllText(saveFileDialog1.FileName, temp);
break;
}
MessageBox.Show("All seems fine. Lets Hack the Plant!\r\n\r\nWARNING: 不要将生成的程序上传到在线杀毒网站!", "ALL SUCCESS!");
}
}
19
View Source File : SshSettingForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void btn_Ok_Click(object sender, EventArgs e)
{
// 保存
if (config == null)
{
config = new SessionConfig();
config.Index = AppConfig.Instance.SessionConfigDict.Count + 1;
config.SessionId = "S" + YSTools.YSDateTime.ConvertDateTimeToLong();
config.Name = string.IsNullOrWhiteSpace(tb_name.Text) ? "New Session" + config.Index : tb_name.Text;
config.Host = tb_host.Text;
config.Port = (int) nud_port.Value;
config.Protocol = cb_protocol.SelectedItem.ToString();
config.Method = cb_method.SelectedItem.ToString();
config.RemenberPwd = cb_remenber_pwd.Checked;
config.UserName = tb_userName.Text;
config.Preplacedword = YSEncrypt.EncryptA(tb_preplacedword.Text, KeysUtil.PreplacedKey);
ColorTheme theme = new ColorTheme();
theme.ColorScheme = cb_scheme.SelectedItem.ToString();
theme.FontName = cb_fontName.SelectedItem.ToString();
theme.FontSize = Convert.ToInt32(cb_fontSize.SelectedItem.ToString());
config.Theme = theme;
AppConfig.Instance.SessionConfigDict.Add(config.Index + config.Name, config);
}
else
{
config.Name = string.IsNullOrWhiteSpace(tb_name.Text) ? "New Session" + config.Index : tb_name.Text;
config.Host = tb_host.Text;
config.Port = (int)nud_port.Value;
config.Protocol = cb_protocol.SelectedItem.ToString();
config.Method = cb_method.SelectedItem.ToString();
config.RemenberPwd = cb_remenber_pwd.Checked;
config.UserName = tb_userName.Text;
config.Preplacedword = YSEncrypt.EncryptA(tb_preplacedword.Text, KeysUtil.PreplacedKey);
config.Theme.ColorScheme = cb_scheme.SelectedItem.ToString();
config.Theme.FontName = cb_fontName.SelectedItem.ToString();
config.Theme.FontSize = Convert.ToInt32(cb_fontSize.SelectedItem.ToString());
if (AppConfig.Instance.SessionConfigDict.ContainsKey(config.SessionId))
{
AppConfig.Instance.SessionConfigDict.Remove(config.SessionId);
}
AppConfig.Instance.SessionConfigDict.Add(config.SessionId, config);
}
// 保存
AppConfig.Instance.SaveConfig();
this.Close();
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private List<string> getTreeNodeContent(TreeListViewItemCollection items)
{
List<string> list = new List<string>();
string line = "";
int level = 0;
foreach (TreeListViewItem treeNode in items)
{
line = treeNode.Text;
if (!line.TrimStart().StartsWith("#"))
{
line += ": ";
level = Convert.ToInt32(treeNode.SubItems[2].Text);
line = YmlFormatUtil.GetSpace(level * 4) + line;
line += treeNode.SubItems[1].Text;
line += treeNode.SubItems[3].Text;
}
if (!string.IsNullOrWhiteSpace(line))
{
list.Add(line);
}
list.AddRange(getTreeNodeContent(treeNode.Items));
}
return list;
}
19
View Source File : NAudioPlayer.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
private static MemoryStream AudioMemStream(WaveStream waveStream)
{
MemoryStream outputStream = new MemoryStream();
using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
{
byte[] bytes = new byte[waveStream.Length];
waveStream.Position = 0;
waveStream.Read(bytes, 0, Convert.ToInt32(waveStream.Length));
waveFileWriter.Write(bytes, 0, bytes.Length);
waveFileWriter.Flush();
}
return outputStream;
}
19
View Source File : Converter.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
public static byte[] FromHex(this string value)
{
byte[] result = new byte[value.Length / 2];
for (int i = 0; i < result.Length; i++)
{
result[i] = (byte)Convert.ToInt32(value.Substring(i * 2, 2), 16);
}
return result;
}
19
View Source File : EnumAppservice.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
private List<KeyValuePair<string, int>> GetEnumTypeForIntList<T>()
{
var items = new List<KeyValuePair<string, int>>();
typeof(T).Each(
(name, value, description) => { items.Add(new KeyValuePair<string, int>(description, Convert.ToInt32(value))); });
return items;
}
19
View Source File : dlgSettings.cs
License : MIT License
Project Creator : 86Box
License : MIT License
Project Creator : 86Box
private bool SaveSettings()
{
if (cbxLogging.Checked && string.IsNullOrWhiteSpace(txtLogPath.Text))
{
DialogResult result = MessageBox.Show("Using an empty or whitespace string for the log path will prevent 86Box from logging anything. Are you sure you want to use this path?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
return false;
}
}
if (!File.Exists(txtEXEdir.Text + "86Box.exe") && !File.Exists(txtEXEdir.Text + @"\86Box.exe"))
{
DialogResult result = MessageBox.Show("86Box.exe could not be found in the directory you specified, so you won't be able to use any virtual machines. Are you sure you want to use this path?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
return false;
}
}
try
{
RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true); //Try to open the key first (in read-write mode) to see if it already exists
if (regkey == null) //Regkey doesn't exist yet, must be created first and then reopened
{
Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
regkey.CreateSubKey("Virtual Machines");
}
//Store the new values, close the key, changes are saved
regkey.SetValue("EXEdir", txtEXEdir.Text, RegistryValueKind.String);
regkey.SetValue("CFGdir", txtCFGdir.Text, RegistryValueKind.String);
regkey.SetValue("MinimizeOnVMStart", cbxMinimize.Checked, RegistryValueKind.DWord);
regkey.SetValue("ShowConsole", cbxShowConsole.Checked, RegistryValueKind.DWord);
regkey.SetValue("MinimizeToTray", cbxMinimizeTray.Checked, RegistryValueKind.DWord);
regkey.SetValue("CloseToTray", cbxCloseTray.Checked, RegistryValueKind.DWord);
regkey.SetValue("LaunchTimeout", Convert.ToInt32(txtLaunchTimeout.Text), RegistryValueKind.DWord);
regkey.SetValue("EnableLogging", cbxLogging.Checked, RegistryValueKind.DWord);
regkey.SetValue("LogPath", txtLogPath.Text, RegistryValueKind.String);
regkey.SetValue("EnableGridLines", cbxGrid.Checked, RegistryValueKind.DWord);
regkey.Close();
settingsChanged = CheckForChanges();
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred. Please provide the following information to the developer:\n" + ex.Message + "\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
Get86BoxVersion(); //Get the new exe version in any case
}
return true;
}
19
View Source File : AuthController.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
[HttpPost]
public IActionResult Login([FromBody] LoginDto parm)
{
var captchaCode = RedisServer.Cache.Get($"Captcha:{parm.Uuid}");
RedisServer.Cache.Del($"Captcha:{parm.Uuid}");
if (parm.Code.ToUpper() != captchaCode)
{
return toResponse(StatusCodeType.Error, "输入验证码无效");
}
var userInfo = _userService.GetFirst(o => o.UserID == parm.UserName.Trim());
if (userInfo == null)
{
return toResponse(StatusCodeType.Error, "用户名或密码错误");
}
if (!PreplacedwordUtil.ComparePreplacedwords(userInfo.UserID, userInfo.Preplacedword, parm.PreplacedWord.Trim()))
{
return toResponse(StatusCodeType.Error, "用户名或密码错误");
}
if (!userInfo.Enabled)
{
return toResponse(StatusCodeType.Error, "用户未启用,请联系管理员!");
}
var userToken = _tokenManager.CreateSession(userInfo, SourceType.Web, Convert.ToInt32(AppSettings.Configuration["AppSettings:WebSessionExpire"]));
return toResponse(userToken);
}
19
View Source File : AuthController.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
[HttpPost]
public IActionResult LoginMiniProgram([FromBody] LoginMiniProgramDto parm)
{
var userInfo = _userService.GetFirst(o => o.UserID == parm.UserName.Trim());
if (userInfo == null)
{
return toResponse(StatusCodeType.Error, "用户名或密码错误");
}
if (!PreplacedwordUtil.ComparePreplacedwords(userInfo.UserID, userInfo.Preplacedword, parm.PreplacedWord.Trim()))
{
return toResponse(StatusCodeType.Error, "用户名或密码错误");
}
if (!userInfo.Enabled)
{
return toResponse(StatusCodeType.Error, "用户未启用,请联系管理员!");
}
var userToken = _tokenManager.CreateSession(userInfo, SourceType.MiniProgram, Convert.ToInt32(AppSettings.Configuration["AppSettings:MiniProgramSessionExpire"]));
return toResponse(userToken);
}
19
View Source File : SetupSqlSugar.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static void AddSqlsugarSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddScoped<ISqlSugarClient>(x =>
{
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = AppSettings.Configuration["DbConnection:ConnectionString"],
DbType = (DbType)Convert.ToInt32(AppSettings.Configuration["DbConnection:DbType"]),
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new RedisCache()
},
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
}
});
});
}
19
View Source File : Job1TimedService.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
private void Execute()
{
try
{
RemoveExpiredSession(SourceType.Web.ToString(), Convert.ToInt32(AppSettings.Configuration["AppSettings:WebSessionExpire"]));
RemoveExpiredSession(SourceType.MiniProgram.ToString(), Convert.ToInt32(AppSettings.Configuration["AppSettings:MiniProgramSessionExpire"]));
_logger.LogInformation("Run RemoveExpiredSession Succeed.");
}
catch (Exception ex)
{
_logger.LogError($"Run RemoveExpiredSession Fail. Message : {ex.Message}.");
}
}
19
View Source File : SetupCap.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static void AddCapSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddTransient<ISubscriberService, SubscriberService>();
services.AddCap(x =>
{
//如果你使用的ADO.NET,根据数据库选择进行配置:
x.UseSqlServer(AppSettings.Configuration["DbConnection:ConnectionString"]);
//CAP支持 RabbitMQ、Kafka、AzureServiceBus 等作为MQ,根据使用选择配置:
x.UseRabbitMQ(o =>
{
o.HostName = AppSettings.Configuration["RabbitMQ:HostName"];
o.UserName = AppSettings.Configuration["RabbitMQ:UserName"];
o.Preplacedword = AppSettings.Configuration["RabbitMQ:Preplacedword"];
o.VirtualHost = AppSettings.Configuration["RabbitMQ:VirtualHost"];
o.Port = Convert.ToInt32(AppSettings.Configuration["RabbitMQ:Port"]);
});
//设置处理成功的数据在数据库中保存的时间(秒),为保证系统新能,数据会定期清理。
x.SucceedMessageExpiredAfter = 24 * 3600;
//设置失败重试次数
x.FailedRetryCount = 100;
//设置失败重试间隔
x.FailedRetryInterval = 20 * 60;
// 注册 Dashboard
x.UseDashboard();
});
}
19
View Source File : MicroVM.Assembler.cs
License : MIT License
Project Creator : a-downing
License : MIT License
Project Creator : a-downing
bool TryParseIntegerLiteral(string str, out int value) {
Match decimalMatch = decimalRegex.Match(str);
Match hexMatch = hexRegex.Match(str);
Match binMatch = binRegex.Match(str);
if(decimalMatch.Success) {
value = Convert.ToInt32(decimalMatch.Groups[0].ToString(), 10);
return true;
} else if(hexMatch.Success) {
str = hexMatch.Groups[0].ToString();
value = Convert.ToInt32(hexMatch.Groups[2].ToString(), 16);
if(hexMatch.Groups[1].ToString() == "-") {
value *= -1;
}
return true;
} else if(binMatch.Success) {
str = binMatch.Groups[0].ToString();
value = Convert.ToInt32(binMatch.Groups[2].ToString(), 2);
if(binMatch.Groups[1].ToString() == "-") {
value *= -1;
}
return true;
}
value = 0;
return false;
}
19
View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063
License : MIT License
Project Creator : a2633063
private void btnOpen_Click(object sender, EventArgs e)
{
if (cbbComList.Items.Count <= 0)
{
//MessageBox.Show("没有发现串口,请检查线路!");
Log.Text = "没有发现串口,请检查线路!";
return;
}
try
{
//if (ComDevice.IsOpen == false)
if (btnOpen.Text == "打开串口")
{
ComDevice.PortName = cbbComList.Text.ToString();
ComDevice.BaudRate = Convert.ToInt32(cbbBaudRate.Text.ToString());
ComDevice.Parity = (Parity)Convert.ToInt32(cbbParity.SelectedIndex.ToString());
ComDevice.DataBits = Convert.ToInt32(cbbDataBits.Text.ToString());
ComDevice.StopBits = (StopBits)Convert.ToInt32(cbbStopBits.Text.ToString());
ComDevice.Open();
}
else
{
ComDevice.Close();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
AddContent("串口打开错误:" + ex.Message + "\r\n");
}
finally
{
if (ComDevice.IsOpen == false)
{
btnSend.Enabled = false;
btnOpen.Text = "打开串口";
btnOpen.Image = Properties.Resources.close;
Log.Text = "串口已关闭";
timerIcon.Enabled = false;
this.Icon = Properties.Resources.zuart;
}
else
{
btnSend.Enabled = true;
btnOpen.Text = "关闭串口";
btnOpen.Image = Properties.Resources.open;
// 串口号,波特率,数据位,停止位.校验位
Log.Text = "串口已开启:" + cbbComList.Text + "," + cbbBaudRate.Text + "," + cbbDataBits.Text + "," + cbbStopBits.Text + "," + cbbParity.Text;
timerIcon.Enabled = true;
}
}
}
19
View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063
License : MIT License
Project Creator : a2633063
private void btnSend_Click(object sender, EventArgs e)
{
if (chkAutoSend.Checked)
{
if (txtSendData.Text.Length < 1)
{
MessageBox.Show("发送数据为空!", "错误");
return;
}
if (txtAutoSendms.Text.Length < 1) txtAutoSendms.Text = "500";
timerAutoSend.Interval = Convert.ToInt32(txtAutoSendms.Text);
if (timerAutoSend.Enabled)
{
timerAutoSend.Enabled = false;
groupBoxComSetting.Enabled = true;
groupboxSendSetting.Enabled = true;
btnSend.Text = "发送";
}
else
{
timerAutoSend.Enabled = true;
groupBoxComSetting.Enabled = false;
groupboxSendSetting.Enabled = false;
btnSend.Text = "停止发送";
}
}
else
{
if (SendStr(txtSendData.Text))
{
if (chkAutoCleanSend.Checked)
{
txtSendData.Text = "";
}
}
}
}
19
View Source File : DynamicCharacterAvatarEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void OnInspectorGUI()
{
serializedObject.Update();
Editor.DrawPropertiesExcluding(serializedObject, new string[] { "hide", "loadBlendShapes","activeRace","defaultChangeRaceOptions","cacheCurrentState", "rebuildSkeleton", "preloadWardrobeRecipes", "raceAnimationControllers",
"characterColors","BoundsOffset","_buildCharacterEnabled",
/*LoadOtions fields*/ "defaultLoadOptions", "loadPathType", "loadPath", "loadFilename", "loadString", "loadFileOnStart", "waitForBundles", /*"buildAfterLoad",*/
/*SaveOptions fields*/ "defaultSaveOptions", "savePathType","savePath", "saveFilename", "makeUniqueFilename","ensureSharedColors",
/*Moved into AdvancedOptions*/"context","umaData","umaRecipe", "umaAdditionalRecipes","umaGenerator", "animationController",
/*Moved into CharacterEvents*/"CharacterCreated", "CharacterUpdated", "CharacterDestroyed", "CharacterDnaUpdated", "RecipeUpdated",
/*PlaceholderOptions fields*/"showPlaceholder", "previewModel", "customModel", "customRotation", "previewColor"});
//The base DynamicAvatar properties- get these early because changing the race changes someof them
SerializedProperty context = serializedObject.FindProperty("context");
SerializedProperty umaData = serializedObject.FindProperty("umaData");
SerializedProperty umaGenerator = serializedObject.FindProperty("umaGenerator");
SerializedProperty umaRecipe = serializedObject.FindProperty("umaRecipe");
SerializedProperty umaAdditionalRecipes = serializedObject.FindProperty("umaAdditionalRecipes");
SerializedProperty animationController = serializedObject.FindProperty("animationController");
EditorGUI.BeginChangeCheck();
showHelp = EditorGUILayout.Toggle("Show Help", showHelp);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty thisRaceSetter = serializedObject.FindProperty("activeRace");
Rect currentRect = EditorGUILayout.GetControlRect(false, _racePropDrawer.GetPropertyHeight(thisRaceSetter, GUIContent.none));
EditorGUI.BeginChangeCheck();
_racePropDrawer.OnGUI(currentRect, thisRaceSetter, new GUIContent(thisRaceSetter.displayName));
if (EditorGUI.EndChangeCheck())
{
thisDCA.ChangeRace((string)thisRaceSetter.FindPropertyRelative("name").stringValue);
//Changing the race may cause umaRecipe, animationController to change so forcefully update these too
umaRecipe.objectReferenceValue = thisDCA.umaRecipe;
animationController.objectReferenceValue = thisDCA.animationController;
serializedObject.ApplyModifiedProperties();
}
if (showHelp)
{
EditorGUILayout.HelpBox("Active Race: Sets the race of the character, which defines the base recipe to build the character, the available DNA, and the available wardrobe.", MessageType.Info);
}
//the ChangeRaceOptions
SerializedProperty defaultChangeRaceOptions = serializedObject.FindProperty("defaultChangeRaceOptions");
EditorGUI.indentLevel++;
defaultChangeRaceOptions.isExpanded = EditorGUILayout.Foldout(defaultChangeRaceOptions.isExpanded, new GUIContent("Race Change Options", "The default options for when the Race is changed. These can be overidden when calling 'ChangeRace' directly."));
if (defaultChangeRaceOptions.isExpanded)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(defaultChangeRaceOptions, GUIContent.none);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(serializedObject.FindProperty("cacheCurrentState"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("rebuildSkeleton"));
EditorGUI.indentLevel--;
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.indentLevel--;
//Other DCA propertyDrawers
//in order for the "preloadWardrobeRecipes" prop to properly check if it can load the recipies it gets replacedigned to it
//it needs to know that its part of this DCA
GUILayout.Space(2f);
SerializedProperty thisPreloadWardrobeRecipes = serializedObject.FindProperty("preloadWardrobeRecipes");
Rect pwrCurrentRect = EditorGUILayout.GetControlRect(false, _wardrobePropDrawer.GetPropertyHeight(thisPreloadWardrobeRecipes, GUIContent.none));
_wardrobePropDrawer.OnGUI(pwrCurrentRect, thisPreloadWardrobeRecipes, new GUIContent(thisPreloadWardrobeRecipes.displayName));
if (showHelp)
{
EditorGUILayout.HelpBox("Preload Wardrobe: Sets the default wardrobe recipes to use on the Avatar. This is useful when creating specific Avatar prefabs.", MessageType.Info);
}
if (_wardrobePropDrawer.changed)
{
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying)
{
thisDCA.ClearSlots();
thisDCA.LoadDefaultWardrobe();
thisDCA.BuildCharacter(true);
}
}
SerializedProperty thisRaceAnimationControllers = serializedObject.FindProperty("raceAnimationControllers");
Rect racCurrentRect = EditorGUILayout.GetControlRect(false, _animatorPropDrawer.GetPropertyHeight(thisRaceAnimationControllers, GUIContent.none));
EditorGUI.BeginChangeCheck();
_animatorPropDrawer.OnGUI(racCurrentRect, thisRaceAnimationControllers, new GUIContent(thisRaceAnimationControllers.displayName));
if (showHelp)
{
EditorGUILayout.HelpBox("Race Animation Controllers: This sets the animation controllers used for each race. When changing the race, the animation controller for the active race will be used by default.", MessageType.Info);
}
//EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(serializedObject.FindProperty("raceAnimationControllers"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying)
{
thisDCA.SetExpressionSet();//this triggers any expressions to reset.
thisDCA.SetAnimatorController();
}
}
GUILayout.Space(2f);
//NewCharacterColors
SerializedProperty characterColors = serializedObject.FindProperty("characterColors");
SerializedProperty newCharacterColors = characterColors.FindPropertyRelative("_colors");
//for ColorValues as OverlayColorDatas we need to outout something that looks like a list but actully uses a method to add/remove colors because we need the new OverlayColorData to have 3 channels
newCharacterColors.isExpanded = EditorGUILayout.Foldout(newCharacterColors.isExpanded, new GUIContent("Character Colors"));
var n_origArraySize = newCharacterColors.arraySize;
var n_newArraySize = n_origArraySize;
EditorGUI.BeginChangeCheck();
if (newCharacterColors.isExpanded)
{
n_newArraySize = EditorGUILayout.DelayedIntField(new GUIContent("Size"), n_origArraySize);
EditorGUILayout.Space();
EditorGUI.indentLevel++;
if (n_origArraySize > 0)
{
for(int i = 0; i < n_origArraySize; i++)
{
EditorGUILayout.PropertyField(newCharacterColors.GetArrayElementAtIndex(i));
}
}
EditorGUI.indentLevel--;
}
if (showHelp)
{
EditorGUILayout.HelpBox("Character Colors: This lets you set predefined colors to be used when building the Avatar. The colors will be replacedigned to the Shared Colors on the overlays as they are applied to the Avatar.", MessageType.Info);
}
if (EditorGUI.EndChangeCheck())
{
if (n_newArraySize != n_origArraySize)
{
SetNewColorCount(n_newArraySize);//this is not prompting a save so mark the scene dirty...
if (!Application.isPlaying)
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
serializedObject.ApplyModifiedProperties();
if (Application.isPlaying)
thisDCA.UpdateColors(true);
}
GUILayout.Space(2f);
//Load save fields
EditorGUI.BeginChangeCheck();
SerializedProperty loadPathType = serializedObject.FindProperty("loadPathType");
loadPathType.isExpanded = EditorGUILayout.Foldout(loadPathType.isExpanded, "Load/Save Options");
if (loadPathType.isExpanded)
{
SerializedProperty loadString = serializedObject.FindProperty("loadString");
SerializedProperty loadPath = serializedObject.FindProperty("loadPath");
SerializedProperty loadFilename = serializedObject.FindProperty("loadFilename");
SerializedProperty loadFileOnStart = serializedObject.FindProperty("loadFileOnStart");
SerializedProperty savePathType = serializedObject.FindProperty("savePathType");
SerializedProperty savePath = serializedObject.FindProperty("savePath");
SerializedProperty saveFilename = serializedObject.FindProperty("saveFilename");
//LoadSave Flags
SerializedProperty defaultLoadOptions = serializedObject.FindProperty("defaultLoadOptions");
SerializedProperty defaultSaveOptions = serializedObject.FindProperty("defaultSaveOptions");
//extra LoadSave Options in addition to flags
SerializedProperty waitForBundles = serializedObject.FindProperty("waitForBundles");
SerializedProperty makeUniqueFilename = serializedObject.FindProperty("makeUniqueFilename");
SerializedProperty ensureSharedColors = serializedObject.FindProperty("ensureSharedColors");
EditorGUILayout.PropertyField(loadPathType);
if (loadPathType.enumValueIndex == Convert.ToInt32(DynamicCharacterAvatar.loadPathTypes.String))
{
EditorGUILayout.PropertyField(loadString);
}
else
{
if (loadPathType.enumValueIndex <= 1)
{
EditorGUILayout.PropertyField(loadPath);
}
}
EditorGUILayout.PropertyField(loadFilename);
if (loadFilename.stringValue != "")
{
EditorGUILayout.PropertyField(loadFileOnStart);
}
EditorGUI.indentLevel++;
//LoadOptionsFlags
defaultLoadOptions.isExpanded = EditorGUILayout.Foldout(defaultLoadOptions.isExpanded, new GUIContent("Load Options", "The default options for when a character is loaded from an UMATextRecipe replacedet or a recipe string. Can be overidden when calling 'LoadFromRecipe' or 'LoadFromString' directly."));
if (defaultLoadOptions.isExpanded)
{
EditorGUILayout.PropertyField(defaultLoadOptions, GUIContent.none);
EditorGUI.indentLevel++;
//waitForBundles.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(waitForBundles.displayName, waitForBundles.tooltip), waitForBundles.boolValue);
//buildAfterLoad.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(buildAfterLoad.displayName, buildAfterLoad.tooltip), buildAfterLoad.boolValue);
//just drawing these as propertyFields because the toolTip on toggle left doesn't work
EditorGUILayout.PropertyField(waitForBundles);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
if (Application.isPlaying)
{
if (GUILayout.Button("Perform Load"))
{
thisDCA.DoLoad();
}
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(savePathType);
if (savePathType.enumValueIndex <= 2)
{
EditorGUILayout.PropertyField(savePath);
}
EditorGUILayout.PropertyField(saveFilename);
EditorGUI.indentLevel++;
defaultSaveOptions.isExpanded = EditorGUILayout.Foldout(defaultSaveOptions.isExpanded, new GUIContent("Save Options", "The default options for when a character is save to UMATextRecipe replacedet or a txt. Can be overidden when calling 'DoSave' directly."));
if (defaultSaveOptions.isExpanded)
{
EditorGUILayout.PropertyField(defaultSaveOptions, GUIContent.none);
EditorGUI.indentLevel++;
//ensureSharedColors.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(ensureSharedColors.displayName, ensureSharedColors.tooltip), ensureSharedColors.boolValue);
//makeUniqueFilename.boolValue = EditorGUILayout.ToggleLeft(new GUIContent(makeUniqueFilename.displayName, makeUniqueFilename.tooltip), makeUniqueFilename.boolValue);
//just drawing these as propertyFields because the toolTip on toggle left doesn't work
EditorGUILayout.PropertyField(ensureSharedColors);
EditorGUILayout.PropertyField(makeUniqueFilename);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
if (Application.isPlaying)
{
if (GUILayout.Button("Perform Save"))
{
thisDCA.DoSave();
}
}
EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
GUILayout.Space(2f);
//for CharacterEvents
EditorGUI.BeginChangeCheck();
SerializedProperty CharacterCreated = serializedObject.FindProperty("CharacterCreated");
CharacterCreated.isExpanded = EditorGUILayout.Foldout(CharacterCreated.isExpanded, "Character Events");
if (CharacterCreated.isExpanded)
{
SerializedProperty CharacterUpdated = serializedObject.FindProperty("CharacterUpdated");
SerializedProperty CharacterDestroyed= serializedObject.FindProperty("CharacterDestroyed");
SerializedProperty CharacterDnaUpdated = serializedObject.FindProperty ("CharacterDnaUpdated");
SerializedProperty RecipeUpdated = serializedObject.FindProperty("RecipeUpdated");
EditorGUILayout.PropertyField(CharacterCreated);
EditorGUILayout.PropertyField(CharacterUpdated);
EditorGUILayout.PropertyField(CharacterDestroyed);
EditorGUILayout.PropertyField (CharacterDnaUpdated);
EditorGUILayout.PropertyField(RecipeUpdated);
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
GUILayout.Space(2f);
//for AdvancedOptions
EditorGUI.BeginChangeCheck();
context.isExpanded = EditorGUILayout.Foldout(context.isExpanded, "Advanced Options");
if (context.isExpanded)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedObject.FindProperty("hide"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
if (showHelp)
{
EditorGUILayout.HelpBox("Hide: This disables the display of the Avatar without preventing it from being generated. If you want to prevent the character from being generated at all disable the DynamicCharacterAvatar component itself.", MessageType.Info);
}
//for _buildCharacterEnabled we want to set the value using the DCS BuildCharacterEnabled property because this actually triggers BuildCharacter
var buildCharacterEnabled = serializedObject.FindProperty("_buildCharacterEnabled");
var buildCharacterEnabledValue = buildCharacterEnabled.boolValue;
EditorGUI.BeginChangeCheck();
var buildCharacterEnabledNewValue = EditorGUILayout.Toggle(new GUIContent(buildCharacterEnabled.displayName, "Builds the character on recipe load or race changed. If you want to load multiple recipes into a character you can disable this and enable it when you are done. By default this should be true."), buildCharacterEnabledValue);
if (EditorGUI.EndChangeCheck())
{
if (buildCharacterEnabledNewValue != buildCharacterEnabledValue)
thisDCA.BuildCharacterEnabled = buildCharacterEnabledNewValue;
serializedObject.ApplyModifiedProperties();
}
if (showHelp)
{
EditorGUILayout.HelpBox("Build Character Enabled: Builds the character on recipe load or race changed. If you want to load multiple recipes into a character you can disable this and enable it when you are done. By default this should be true.", MessageType.Info);
}
EditorGUILayout.PropertyField(serializedObject.FindProperty("loadBlendShapes"), new GUIContent("Load BlendShapes (experimental)"));
EditorGUILayout.PropertyField(context);
EditorGUILayout.PropertyField(umaData);
EditorGUILayout.PropertyField(umaGenerator);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(umaRecipe);
EditorGUILayout.PropertyField(umaAdditionalRecipes, true);
EditorGUILayout.PropertyField(animationController);
EditorGUILayout.PropertyField(serializedObject.FindProperty("BoundsOffset"));
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
GUILayout.Space(2f);
//for PlaceholderOptions
EditorGUI.BeginChangeCheck();
SerializedProperty gizmo = serializedObject.FindProperty("showPlaceholder");
SerializedProperty enableGizmo = serializedObject.FindProperty("showPlaceholder");
SerializedProperty previewModel = serializedObject.FindProperty("previewModel");
SerializedProperty customModel = serializedObject.FindProperty("customModel");
SerializedProperty customRotation = serializedObject.FindProperty("customRotation");
SerializedProperty previewColor = serializedObject.FindProperty("previewColor");
gizmo.isExpanded = EditorGUILayout.Foldout(gizmo.isExpanded, "Placeholder Options");
if (gizmo.isExpanded)
{
EditorGUILayout.PropertyField(enableGizmo);
EditorGUILayout.PropertyField(previewModel);
if(previewModel.enumValueIndex == 2)
{
EditorGUILayout.PropertyField(customModel);
EditorGUILayout.PropertyField(customRotation);
}
EditorGUILayout.PropertyField(previewColor);
}
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
if (Application.isPlaying)
{
EditorGUILayout.LabelField("replacedetBundles used by Avatar");
string replacedetBundlesUsed = "";
if (thisDCA.replacedetBundlesUsedbyCharacter.Count == 0)
{
replacedetBundlesUsed = "None";
}
else
{
for (int i = 0; i < thisDCA.replacedetBundlesUsedbyCharacter.Count; i++)
{
replacedetBundlesUsed = replacedetBundlesUsed + thisDCA.replacedetBundlesUsedbyCharacter[i];
if (i < (thisDCA.replacedetBundlesUsedbyCharacter.Count - 1))
replacedetBundlesUsed = replacedetBundlesUsed + "\n";
}
}
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.TextArea(replacedetBundlesUsed);
EditorGUI.EndDisabledGroup();
}
}
19
View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void Show()
{
OpLock.Apply();
try
{
Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
if (!cache_prop.ContainsKey(item.GetType()))
{
_reflectProps(item.GetType());
}
if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
{
var insp = new InspectPanel();
currentEdit = insp;
int idx = 0;
foreach (var kv in itemProps)
{
string name = kv.Key;
Type propType = kv.Value.PropertyType;
object value = kv.Value.GetValue(item, null);
value = Convert.ToSingle(value);
ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();
LogProp(propType, name, value);
if(idx == 0)
{
insp.UpdateName(idx,name);
if(con is IntConstraint)
{
//Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
}
else if(con is FloatConstraint)
{
//Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
}
else
{
throw new ArgumentException();
}
//Logger.LogDebug($"Check3 {value}-{value.GetType()}");
insp.UpdateValue(idx, (float)value);
}
else
{
insp.AppendPropPanel(name);
if (con is IntConstraint)
{
insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
}
else if (con is FloatConstraint)
{
insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
}
else
{
throw new ArgumentException();
}
insp.UpdateValue(idx, (float)value);
insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));
}
//insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
insp.AddListener(idx, (v) => {
if (ItemManager.Instance.currentSelect == null)
return;
object val;
try
{
if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
{
val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
}
else
val = Convert.ChangeType(v, kv.Value.PropertyType);
ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
}
catch
{
Logger.LogError("Error occour at Inspect OnValue Chnaged");
Hide();
}
});
idx++;
}
}
else
{
Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
}
}
catch(NullReferenceException e)
{
Logger.LogError($"NulRef Error at Inspector.Show:{e}");
OpLock.Undo();
}
}
19
View Source File : OptionXY.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
public void SetName(string name)
{
Label.Text = name;
//Label.Left = Convert.ToInt32((Fields.XField.Box.Left / 2.0) - (Label.Width / 2.0)); //Centered
Label.Left = Convert.ToInt32(Fields.XField.Box.Left - Label.Width - 10); //Right-aligned
}
19
View Source File : DynamoDBItem.cs
License : MIT License
Project Creator : abelperezok
License : MIT License
Project Creator : abelperezok
public int GetInt32(string key)
{
return Convert.ToInt32(_data.GetValueOrDefault(key)?.N);
}
19
View Source File : EmailSender.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task SendEmailByEmailAsync(string email, Email emailToSend)
{
try
{
#region formatter
string text = emailToSend.Subject + emailToSend.TextBody;
string html = emailToSend.HtmlBody;
#endregion
var emailToSendFrom = _configurations["EmailConfigs:Email"];
var preplacedword = _configurations["EmailConfigs:Preplacedword"];
var host = _configurations["EmailConfigs:Host"];
var port = _configurations["EmailConfigs:Port"];
MailMessage msg = new MailMessage
{
From = new MailAddress(emailToSendFrom),
Subject = emailToSend.Subject,
};
msg.To.Add(new MailAddress(email));
if (!string.IsNullOrEmpty(emailToSend.TextBody))
{
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
}
if (!string.IsNullOrEmpty(emailToSend.HtmlBody))
{
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
msg.IsBodyHtml = true;
}
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(emailToSendFrom, preplacedword);
SmtpClient smtpClient = new SmtpClient(host, Convert.ToInt32(port));
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
await smtpClient.SendMailAsync(msg);
_logger.LogInformation($"A message was sent successfully to {email}",
$"The message subject was: {emailToSend.Subject}",
$"The message html body was: {emailToSend.HtmlBody}",
$"The message text body was: {emailToSend.TextBody}");
}
catch (Exception e)
{
_logger.LogError($"There were an error while sending an email to: {email}, Exception Details {e.ToString()}");
}
}
19
View Source File : NumberParse.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
public static bool TryParse(string str, out int value)
{
value = int.MinValue;
if (str is null)
return false;
var (numStr, @base, negate) = Configure(str);
try
{
value = Convert.ToInt32(numStr, @base);
if (negate)
value = -value;
return true;
}
catch
{
return false;
}
}
19
View Source File : WaterfallChart.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnAxisMarkerAnnotationMove()
{
var doubleSeries = new XyDataSeries<double, double>();
var axisInfo = AxisMarkerAnnotation.AxisInfo;
var dataIndex = 0;
if (axisInfo != null)
{
var position = (double)axisInfo.DataValue;
dataIndex = sciChart.RenderableSeries[0].DataSeries.XValues.FindIndex(true, position, SearchMode.Nearest);
}
else dataIndex = Convert.ToInt32(AxisMarkerAnnotation.X1);
if (_paletteProvider != null)
{
_paletteProvider.SelectedIndex = dataIndex;
}
for (var i = 0; i < sciChart.RenderableSeries.Count; i++)
{
doubleSeries.Append(i, (double)sciChart.RenderableSeries[i].DataSeries.YValues[dataIndex]);
_paletteProvider.OnBeginSeriesDraw(sciChart.RenderableSeries[i]);
}
if (sciChart3 != null && sciChart3.RenderableSeries.Any())
{
sciChart3.RenderableSeries[0].DataSeries = doubleSeries;
sciChart3.ZoomExtents();
}
}
19
View Source File : SurfaceMeshSelectionModifier.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public override void OnModifierMouseUp(ModifierMouseArgs e)
{
base.OnModifierMouseUp(e);
ClearAll();
if (!IsDragging || Viewport3D == null || Viewport3D.RootEnreplacedy == null) return;
var endPoint = e.MousePoint;
var distanceDragged = PointUtil.Distance(StartPoint, endPoint);
var isAreaSelection = distanceDragged > MinDragSensitivity;
IList<EnreplacedyVertexId> hitEnreplacedyVertexIds;
if (isAreaSelection)
{
// Drag select
hitEnreplacedyVertexIds = Viewport3D.PickScene(new Rect(StartPoint, e.MousePoint));
}
else
{
// Point select
var vertexId = Viewport3D.PickScene(e.MousePoint);
hitEnreplacedyVertexIds = vertexId.HasValue ? new[] { vertexId.Value } : new EnreplacedyVertexId[0];
}
if (!hitEnreplacedyVertexIds.IsNullOrEmpty())
{
var hitEnreplacedyGroups = hitEnreplacedyVertexIds
.GroupBy(x => x.EnreplacedyId)
.ToDictionary(x => x.Key, x => x.Select(i => new VertexId { Id = i.VertexId }).ToList());
var xSize = BoundedPaletteProvider.XSize - 1;
//Visit enreplacedies to perform selection or deselection
Viewport3D.RootEnreplacedy.VisitEnreplacedies(enreplacedy =>
{
var enreplacedyId = enreplacedy.EnreplacedyId;
var hitVertexIds = new List<VertexId>();
if (hitEnreplacedyGroups.ContainsKey(enreplacedyId))
{
hitVertexIds = hitEnreplacedyGroups[enreplacedyId];
}
if (hitVertexIds.Any())
{
if (!_selectedVertices.ContainsKey(enreplacedyId))
_selectedVertices.Add(enreplacedyId, new HashSet<ulong>());
var selectedVertices = _selectedVertices[enreplacedyId];
hitVertexIds.ForEach(x => selectedVertices.Add(x.Id));
BoundedPaletteProvider.SelectedIndexes.Clear();
foreach (var hitEnreplacedyVertexId in hitEnreplacedyVertexIds)
{
var id = Convert.ToInt32(hitEnreplacedyVertexId.VertexId) - 1;
var vertexIndexInfo = new SurfaceMeshVertexInfo();
if (id < xSize)
{
vertexIndexInfo.XIndex = id;
}
else
{
vertexIndexInfo.ZIndex = id / xSize;
vertexIndexInfo.XIndex = id - (vertexIndexInfo.ZIndex * xSize);
}
BoundedPaletteProvider.SelectedIndexes.Add(vertexIndexInfo);
}
}
else
{
_selectedVertices.Remove(enreplacedyId);
BoundedPaletteProvider.SelectedIndexes.Clear();
}
});
}
IsDragging = false;
ReleaseMouseCapture();
BoundedPaletteProvider.DataSeries.IsDirty = true;
BoundedPaletteProvider.DataSeries.OnDataSeriesChanged(DataSeriesUpdate.SelectionChanged,
DataSeriesAction.None);
}
19
View Source File : EffectArgument.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public bool ResolveValue(WorldObject item)
{
// type:enum - invalid, double, int32, quality (2 int32s: type and quality), float range (min, max), variable index (int32)
switch (Type)
{
case EffectArgumentType.Double:
case EffectArgumentType.Int:
case EffectArgumentType.Int64:
// these are ok as-is
IsValid = true;
break;
case EffectArgumentType.Quality:
switch (StatType)
{
case StatType.Int:
Type = EffectArgumentType.Int;
var intVal = item.GetProperty((PropertyInt)StatIdx);
if (intVal != null)
{
IntVal = intVal.Value;
IsValid = true;
}
break;
case StatType.Int64:
Type = EffectArgumentType.Int64;
var int64Val = item.GetProperty((PropertyInt64)StatIdx);
if (int64Val != null)
{
LongVal = int64Val.Value;
IsValid = true;
}
break;
case StatType.Bool:
Type = EffectArgumentType.Int;
IntVal = Convert.ToInt32(item.GetProperty((PropertyBool)StatIdx) ?? false);
IsValid = true;
break;
case StatType.Float:
Type = EffectArgumentType.Double;
var doubleVal = item.GetProperty((PropertyFloat)StatIdx);
if (doubleVal != null)
{
DoubleVal = doubleVal.Value;
IsValid = true;
}
break;
case StatType.DID:
Type = EffectArgumentType.Int;
IntVal = (int)(item.GetProperty((PropertyDataId)StatIdx) ?? 0);
IsValid = true;
break;
}
break;
case EffectArgumentType.Random:
DoubleVal = ThreadSafeRandom.Next(MinVal, MaxVal);
Type = EffectArgumentType.Double;
IsValid = true;
break;
case EffectArgumentType.Variable:
/*if (IntVal < 0 || IntVal >= GTVariables.Count)
break;
this = GTVariables[IntVal];
IsValid = true;*/
log.Error($"TODO: EffectArgumentType.Variable");
break;
}
return IsValid;
}
19
View Source File : Creature.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void GenerateNewFace()
{
var cg = DatManager.PortalDat.CharGen;
if (!Heritage.HasValue)
{
if (!string.IsNullOrEmpty(HeritageGroupName) && Enum.TryParse(HeritageGroupName.Replace("'", ""), true, out HeritageGroup heritage))
Heritage = (int)heritage;
}
if (!Gender.HasValue)
{
if (!string.IsNullOrEmpty(Sex) && Enum.TryParse(Sex, true, out Gender gender))
Gender = (int)gender;
}
if (!Heritage.HasValue || !Gender.HasValue)
{
#if DEBUG
//if (!(NpcLooksLikeObject ?? false))
//log.Debug($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data missing or unparsable, Cannot randomize face.");
#endif
return;
}
if (!cg.HeritageGroups.TryGetValue((uint)Heritage, out var heritageGroup) || !heritageGroup.Genders.TryGetValue((int)Gender, out var sex))
{
#if DEBUG
log.Debug($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data invalid, Cannot randomize face.");
#endif
return;
}
PaletteBaseId = sex.BasePalette;
var appearance = new Appearance
{
HairStyle = 1,
HairColor = 1,
HairHue = 1,
EyeColor = 1,
Eyes = 1,
Mouth = 1,
Nose = 1,
SkinHue = 1
};
// Get the hair first, because we need to know if you're bald, and that's the name of that tune!
if (sex.HairStyleList.Count > 1)
{
if (PropertyManager.GetBool("npc_hairstyle_fullrange").Item)
appearance.HairStyle = (uint)ThreadSafeRandom.Next(0, sex.HairStyleList.Count - 1);
else
appearance.HairStyle = (uint)ThreadSafeRandom.Next(0, Math.Min(sex.HairStyleList.Count - 1, 8)); // retail range data compiled by OptimShi
}
else
appearance.HairStyle = 0;
if (sex.HairStyleList.Count < appearance.HairStyle)
{
log.Warn($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - HairStyle = {appearance.HairStyle} | HairStyleList.Count = {sex.HairStyleList.Count} - Data invalid, Cannot randomize face.");
return;
}
var hairstyle = sex.HairStyleList[Convert.ToInt32(appearance.HairStyle)];
appearance.HairColor = (uint)ThreadSafeRandom.Next(0, sex.HairColorList.Count - 1);
appearance.HairHue = ThreadSafeRandom.Next(0.0f, 1.0f);
appearance.EyeColor = (uint)ThreadSafeRandom.Next(0, sex.EyeColorList.Count - 1);
appearance.Eyes = (uint)ThreadSafeRandom.Next(0, sex.EyeStripList.Count - 1);
appearance.Mouth = (uint)ThreadSafeRandom.Next(0, sex.MouthStripList.Count - 1);
appearance.Nose = (uint)ThreadSafeRandom.Next(0, sex.NoseStripList.Count - 1);
appearance.SkinHue = ThreadSafeRandom.Next(0.0f, 1.0f);
//// Certain races (Undead, Tumeroks, Others?) have multiple body styles available. This is controlled via the "hair style".
////if (hairstyle.AlternateSetup > 0)
//// character.SetupTableId = hairstyle.AlternateSetup;
if (!EyesTextureDID.HasValue)
EyesTextureDID = sex.GetEyeTexture(appearance.Eyes, hairstyle.Bald);
if (!DefaultEyesTextureDID.HasValue)
DefaultEyesTextureDID = sex.GetDefaultEyeTexture(appearance.Eyes, hairstyle.Bald);
if (!NoseTextureDID.HasValue)
NoseTextureDID = sex.GetNoseTexture(appearance.Nose);
if (!DefaultNoseTextureDID.HasValue)
DefaultNoseTextureDID = sex.GetDefaultNoseTexture(appearance.Nose);
if (!MouthTextureDID.HasValue)
MouthTextureDID = sex.GetMouthTexture(appearance.Mouth);
if (!DefaultMouthTextureDID.HasValue)
DefaultMouthTextureDID = sex.GetDefaultMouthTexture(appearance.Mouth);
if (!HeadObjectDID.HasValue)
HeadObjectDID = sex.GetHeadObject(appearance.HairStyle);
// Skin is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette
var skinPalSet = DatManager.PortalDat.ReadFromDat<PaletteSet>(sex.SkinPalSet);
if (!SkinPaletteDID.HasValue)
SkinPaletteDID = skinPalSet.GetPaletteID(appearance.SkinHue);
// Hair is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette
var hairPalSet = DatManager.PortalDat.ReadFromDat<PaletteSet>(sex.HairColorList[Convert.ToInt32(appearance.HairColor)]);
if (!HairPaletteDID.HasValue)
HairPaletteDID = hairPalSet.GetPaletteID(appearance.HairHue);
// Eye Color
if (!EyesPaletteDID.HasValue)
EyesPaletteDID = sex.EyeColorList[Convert.ToInt32(appearance.EyeColor)];
}
19
View Source File : YamlObjectReader.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private Boolean MatchInteger(
Scalar scalar,
out NumberToken value)
{
// YAML 1.2 "core" schema https://yaml.org/spec/1.2/spec.html#id2804923
var str = scalar.Value;
if (!String.IsNullOrEmpty(str))
{
// Check for [0-9]+
var firstChar = str[0];
if (firstChar >= '0' && firstChar <= '9' &&
str.Skip(1).All(x => x >= '0' && x <= '9'))
{
// Try parse
if (Double.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out var doubleValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
return true;
}
// Otherwise exceeds range
ThrowInvalidValue(scalar, c_integerTag); // throws
}
// Check for (-|+)[0-9]+
else if ((firstChar == '-' || firstChar == '+') &&
str.Length > 1 &&
str.Skip(1).All(x => x >= '0' && x <= '9'))
{
// Try parse
if (Double.TryParse(str, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var doubleValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
return true;
}
// Otherwise exceeds range
ThrowInvalidValue(scalar, c_integerTag); // throws
}
// Check for 0x[0-9a-fA-F]+
else if (firstChar == '0' &&
str.Length > 2 &&
str[1] == 'x' &&
str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
{
// Try parse
if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integerValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, integerValue);
return true;
}
// Otherwise exceeds range
ThrowInvalidValue(scalar, c_integerTag); // throws
}
// Check for 0o[0-9]+
else if (firstChar == '0' &&
str.Length > 2 &&
str[1] == 'o' &&
str.Skip(2).All(x => x >= '0' && x <= '7'))
{
// Try parse
var integerValue = default(Int32);
try
{
integerValue = Convert.ToInt32(str.Substring(2), 8);
}
// Otherwise exceeds range
catch (Exception)
{
ThrowInvalidValue(scalar, c_integerTag); // throws
}
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, integerValue);
return true;
}
}
value = default;
return false;
}
19
View Source File : UnknownEnumJsonConverter.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Newtonsoft doesn't call CanConvert if you specify the converter using a JsonConverter attribute
// they just replacedume you know what you're doing :)
if (!CanConvert(objectType))
{
// if there's no Unknown value, fall back to the StringEnumConverter behavior
return base.ReadJson(reader, objectType, existingValue, serializer);
}
if (reader.TokenType == JsonToken.Integer)
{
var intValue = Convert.ToInt32(reader.Value);
var values = (int[])Enum.GetValues(objectType);
if (values.Contains(intValue))
{
return Enum.Parse(objectType, intValue.ToString());
}
}
if (reader.TokenType == JsonToken.String)
{
var stringValue = reader.Value.ToString();
return UnknownEnum.Parse(objectType, stringValue);
}
// we know there's an Unknown value because CanConvert returned true
return Enum.Parse(objectType, UnknownName);
}
19
View Source File : ExpressionUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal static Double ParseNumber(String str)
{
// Trim
str = str?.Trim() ?? String.Empty;
// Empty
if (String.IsNullOrEmpty(str))
{
return 0d;
}
// Try parse
else if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var value))
{
return value;
}
// Check for 0x[0-9a-fA-F]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'x' &&
str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
{
// Try parse
if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integer))
{
return (Double)integer;
}
// Otherwise exceeds range
}
// Check for 0o[0-9]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'o' &&
str.Skip(2).All(x => x >= '0' && x <= '7'))
{
// Try parse
var integer = default(Int32?);
try
{
integer = Convert.ToInt32(str.Substring(2), 8);
}
// Otherwise exceeds range
catch (Exception)
{
}
// Success
if (integer != null)
{
return (Double)integer.Value;
}
}
// Infinity
else if (String.Equals(str, ExpressionConstants.Infinity, StringComparison.Ordinal))
{
return Double.PositiveInfinity;
}
// -Infinity
else if (String.Equals(str, ExpressionConstants.NegativeInfinity, StringComparison.Ordinal))
{
return Double.NegativeInfinity;
}
// Otherwise NaN
return Double.NaN;
}
19
View Source File : Lexer.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
private static IEnumerable<IToken> Lex(CodeFile file, Diagnostics diagnostics)
{
var code = file.Code;
var text = code.Text;
var tokenStart = 0;
var tokenEnd = -1; // One past the end position to allow for zero length spans
while (tokenStart < text.Length)
{
var currentChar = text[tokenStart];
switch (currentChar)
{
case '{':
yield return TokenFactory.OpenBrace(SymbolSpan());
break;
case '}':
yield return TokenFactory.CloseBrace(SymbolSpan());
break;
case '(':
yield return TokenFactory.OpenParen(SymbolSpan());
break;
case ')':
yield return TokenFactory.CloseParen(SymbolSpan());
break;
case '[':
case ']':
case '|':
case '&':
case '@':
case '`':
case '$':
yield return NewReservedOperator();
break;
case ';':
yield return TokenFactory.Semicolon(SymbolSpan());
break;
case ',':
yield return TokenFactory.Comma(SymbolSpan());
break;
case '#':
switch (NextChar())
{
case '#':
// it is `##`
yield return NewReservedOperator(2);
break;
case '(':
// it is `#(`
yield return NewReservedOperator(2);
break;
case '[':
// it is `#[`
yield return NewReservedOperator(2);
break;
case '{':
// it is `#{`
yield return NewReservedOperator(2);
break;
default:
// it is `#`
yield return NewReservedOperator();
break;
}
break;
case '.':
if (NextChar() is '.')
{
if (CharAt(2) is '<')
// it is `..<`
yield return TokenFactory.DotDotLessThan(SymbolSpan(3));
else
// it is `..`
yield return TokenFactory.DotDot(SymbolSpan(2));
}
else
yield return TokenFactory.Dot(SymbolSpan());
break;
case ':':
if (NextChar() is ':' && CharAt(2) is '.')
// it is `::.`
yield return TokenFactory.ColonColonDot(SymbolSpan(3));
else
// it is `:`
yield return TokenFactory.Colon(SymbolSpan());
break;
case '?':
switch (NextChar())
{
case '?':
// it is `??`
yield return TokenFactory.QuestionQuestion(SymbolSpan(2));
break;
case '.':
// it is `?.`
yield return TokenFactory.QuestionDot(SymbolSpan(2));
break;
default:
// it is `?`
yield return TokenFactory.Question(SymbolSpan());
break;
}
break;
case '→':
yield return TokenFactory.RightArrow(SymbolSpan());
break;
case '⇒':
yield return TokenFactory.RightDoubleArrow(SymbolSpan());
break;
case '⬿':
yield return TokenFactory.LeftWaveArrow(SymbolSpan());
break;
case '⤳':
yield return TokenFactory.RightWaveArrow(SymbolSpan());
break;
case '^':
if (NextChar() is '.')
// it is `^.`
yield return NewReservedOperator(2);
else
// it is `^`
yield return NewReservedOperator();
break;
case '+':
if (NextChar() is '=')
// it is `+=`
yield return TokenFactory.PlusEquals(SymbolSpan(2));
else
// it is `+`
yield return TokenFactory.Plus(SymbolSpan());
break;
case '-':
switch (NextChar())
{
case '=':
// it is `-=`
yield return TokenFactory.MinusEquals(SymbolSpan(2));
break;
case '>':
// it is `->`
yield return TokenFactory.RightArrow(SymbolSpan(2));
break;
default:
// it is `-`
yield return TokenFactory.Minus(SymbolSpan());
break;
}
break;
case '~':
if (NextChar() is '>')
// it is `~>`
yield return TokenFactory.RightWaveArrow(SymbolSpan(2));
else
{
// it is `~` which isn't allowed
yield return NewUnexpectedCharacter();
}
break;
case '*':
if (NextChar() is '=')
// it is `*=`
yield return TokenFactory.AsteriskEquals(SymbolSpan(2));
else
// it is `*`
yield return TokenFactory.Asterisk(SymbolSpan());
break;
case '/':
switch (NextChar())
{
case '/':
// it is a line comment `//`
tokenEnd = tokenStart + 2;
// Include newline at end
while (tokenEnd < text.Length)
{
currentChar = text[tokenEnd];
tokenEnd += 1;
if (currentChar == '\r' || currentChar == '\n')
break;
}
yield return TokenFactory.Comment(TokenSpan());
break;
case '*':
// it is a block comment `/*`
tokenEnd = tokenStart + 2;
var lastCharWreplacedtar = false;
// Include slash at end
for (; ; )
{
// If we ran into the end of the file, error
if (tokenEnd >= text.Length)
{
diagnostics.Add(LexError.UnclosedBlockComment(file,
TextSpan.FromStartEnd(tokenStart, tokenEnd)));
break;
}
currentChar = text[tokenEnd];
tokenEnd += 1;
if (lastCharWreplacedtar && currentChar == '/')
break;
lastCharWreplacedtar = currentChar == '*';
}
yield return TokenFactory.Comment(TokenSpan());
break;
case '=':
// it is `/=`
yield return TokenFactory.SlashEquals(SymbolSpan(2));
break;
default:
// it is `/`
yield return TokenFactory.Slash(SymbolSpan());
break;
}
break;
case '=':
switch (NextChar())
{
case '>':
// it is `=>`
yield return TokenFactory.RightDoubleArrow(SymbolSpan(2));
break;
case '=':
// it is `==`
yield return TokenFactory.EqualsEquals(SymbolSpan(2));
break;
case '/':
if (CharAt(2) is '=')
// it is `=/=`
yield return TokenFactory.NotEqual(SymbolSpan(3));
else
goto default;
break;
default:
// it is `=`
yield return TokenFactory.Equals(SymbolSpan());
break;
}
break;
case '≠':
yield return TokenFactory.NotEqual(SymbolSpan());
break;
case '>':
if (NextChar() is '=')
// it is `>=`
yield return TokenFactory.GreaterThanOrEqual(SymbolSpan(2));
else
// it is `>`
yield return TokenFactory.GreaterThan(SymbolSpan());
break;
case '≥':
yield return TokenFactory.GreaterThanOrEqual(SymbolSpan());
break;
case '<':
switch (NextChar())
{
case '=':
// it is `<=`
yield return TokenFactory.LessThanOrEqual(SymbolSpan(2));
break;
case ':':
// it is `<:`
yield return TokenFactory.LessThanColon(SymbolSpan(2));
break;
case '~':
// it is `<~`
yield return TokenFactory.LeftWaveArrow(SymbolSpan(2));
break;
case '.':
if (CharAt(2) is '.')
{
if (CharAt(3) is '<')
// it is `<..<`
yield return TokenFactory.LessThanDotDotLessThan(SymbolSpan(4));
else
// it is `<..`
yield return TokenFactory.LessThanDotDot(SymbolSpan(3));
}
else
goto default;
break;
default:
// it is `<`
yield return TokenFactory.LessThan(SymbolSpan());
break;
}
break;
case '≤':
yield return TokenFactory.LessThanOrEqual(SymbolSpan());
break;
case '"':
yield return LexString();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
tokenEnd = tokenStart + 1;
while (tokenEnd < text.Length && IsIntegerCharacter(text[tokenEnd]))
tokenEnd += 1;
var span = TokenSpan();
var value = BigInteger.Parse(code[span], CultureInfo.InvariantCulture);
yield return TokenFactory.IntegerLiteral(span, value);
break;
}
case '\\':
{
tokenEnd = tokenStart + 1;
while (tokenEnd < text.Length && IsIdentifierCharacter(text[tokenEnd]))
tokenEnd += 1;
if (tokenEnd == tokenStart + 1)
yield return NewUnexpectedCharacter();
else
yield return NewEscapedIdentifier();
break;
}
default:
if (char.IsWhiteSpace(currentChar))
{
tokenEnd = tokenStart + 1;
// Include whitespace at end
while (tokenEnd < text.Length && char.IsWhiteSpace(text[tokenEnd]))
tokenEnd += 1;
yield return TokenFactory.Whitespace(TokenSpan());
}
else if (IsIdentifierStartCharacter(currentChar))
{
tokenEnd = tokenStart + 1;
while (tokenEnd < text.Length && IsIdentifierCharacter(text[tokenEnd]))
tokenEnd += 1;
yield return NewIdentifierOrKeywordToken();
}
else if (currentChar == '!' && NextChar() is '=')
{
var span = SymbolSpan(2);
diagnostics.Add(LexError.CStyleNotEquals(file, span));
yield return TokenFactory.NotEqual(span);
}
else
yield return NewUnexpectedCharacter();
break;
}
tokenStart = tokenEnd;
}
// The end of file token provides something to attach any final errors to
yield return TokenFactory.EndOfFile(SymbolSpan(0));
yield break;
TextSpan SymbolSpan(int length = 1)
{
var end = tokenStart + length;
return TokenSpan(end);
}
TextSpan TokenSpan(int? end = null)
{
tokenEnd = end ?? tokenEnd;
return TextSpan.FromStartEnd(tokenStart, tokenEnd);
}
IToken NewIdentifierOrKeywordToken()
{
var span = TokenSpan();
var value = code[span];
if (TokenTypes.KeywordFactories.TryGetValue(value, out var keywordFactory))
return keywordFactory(span);
if (value == "continue")
diagnostics.Add(LexError.ContinueInsteadOfNext(file, span));
else if (TokenTypes.ReservedWords.Contains(value)
|| TokenTypes.IsReservedTypeName(value))
diagnostics.Add(LexError.ReservedWord(file, span, value));
return TokenFactory.BareIdentifier(span, value);
}
IToken NewEscapedIdentifier()
{
var identifierStart = tokenStart + 1;
var span = TokenSpan();
var value = text[identifierStart..tokenEnd];
var isValidToEscape = TokenTypes.Keywords.Contains(value)
|| TokenTypes.ReservedWords.Contains(value)
|| TokenTypes.IsReservedTypeName(value)
|| char.IsDigit(value[0]);
if (!isValidToEscape)
diagnostics.Add(LexError.EscapedIdentifierShouldNotBeEscaped(file, span, value));
return TokenFactory.EscapedIdentifier(span, value);
}
IToken NewUnexpectedCharacter()
{
var span = SymbolSpan();
var value = code[span];
diagnostics.Add(LexError.UnexpectedCharacter(file, span, value[0]));
return TokenFactory.Unexpected(span);
}
IToken NewReservedOperator(int length = 1)
{
var span = SymbolSpan(length);
var value = code[span];
diagnostics.Add(LexError.ReservedOperator(file, span, value));
return TokenFactory.Unexpected(span);
}
char? NextChar()
{
var index = tokenStart + 1;
return index < text.Length ? text[index] : default;
}
char? CharAt(int offset)
{
var index = tokenStart + offset;
return index < text.Length ? text[index] : default;
}
IToken LexString()
{
tokenEnd = tokenStart + 1;
var content = new StringBuilder();
char currentChar;
while (tokenEnd < text.Length && (currentChar = text[tokenEnd]) != '"')
{
tokenEnd += 1;
if (currentChar != '\\')
{
content.Append(currentChar);
continue;
}
// Escape Sequence (i.e. "\\")
// In case of an invalid escape sequence, we just drop the `\` from the value
if (tokenEnd >= text.Length)
{
// Just the slash is invalid
var errorSpan = TextSpan.FromStartEnd(tokenEnd - 1, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
break; // we hit the end of file and need to not add to tokenEnd any more
}
// Escape Sequence with next char (i.e. "\\x")
var escapeStart = tokenEnd - 1;
currentChar = text[tokenEnd];
tokenEnd += 1;
switch (currentChar)
{
case '"':
case '\'':
case '\\':
content.Append(currentChar);
break;
case 'n':
content.Append('\n');
break;
case 'r':
content.Append('\r');
break;
case '0':
content.Append('\0');
break;
case 't':
content.Append('\t');
break;
case 'u':
{
if (tokenEnd < text.Length && text[tokenEnd] == '(')
tokenEnd += 1;
else
{
content.Append('u');
var errorSpan = TextSpan.FromStartEnd(escapeStart, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
break;
}
var codepoint = new StringBuilder(6);
while (tokenEnd < text.Length &&
IsHexDigit(currentChar = text[tokenEnd]))
{
codepoint.Append(currentChar);
tokenEnd += 1;
}
int value;
if (codepoint.Length > 0
&& codepoint.Length <= 6
&& (value = Convert.ToInt32(codepoint.ToString(), 16)) <= 0x10FFFF)
{
// TODO disallow surrogate pairs
content.Append(char.ConvertFromUtf32(value));
}
else
{
content.Append("u(");
content.Append(codepoint);
// Include the closing ')' in the escape sequence if it is present
if (tokenEnd < text.Length && text[tokenEnd] == ')')
{
content.Append(')');
tokenEnd += 1;
}
var errorSpan = TextSpan.FromStartEnd(escapeStart, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
break;
}
if (tokenEnd < text.Length && text[tokenEnd] == ')')
tokenEnd += 1;
else
{
var errorSpan = TextSpan.FromStartEnd(escapeStart, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
}
break;
}
default:
{
// Last two chars form the invalid sequence
var errorSpan = TextSpan.FromStartEnd(tokenEnd - 2, tokenEnd);
diagnostics.Add(LexError.InvalidEscapeSequence(file, errorSpan));
// drop the `/` keep the character after
content.Append(currentChar);
break;
}
}
}
if (tokenEnd < text.Length)
{
// To include the close quote
if (text[tokenEnd] == '"')
tokenEnd += 1;
}
else
diagnostics.Add(LexError.UnclosedStringLiteral(file,
TextSpan.FromStartEnd(tokenStart, tokenEnd)));
return TokenFactory.StringLiteral(TextSpan.FromStartEnd(tokenStart, tokenEnd), content.ToString());
}
}
19
View Source File : MiniJson.cs
License : MIT License
Project Creator : AdamCarballo
License : MIT License
Project Creator : AdamCarballo
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
19
View Source File : AdColonyZone.cs
License : Apache License 2.0
Project Creator : AdColony
License : Apache License 2.0
Project Creator : AdColony
public string toJsonString()
{
Hashtable data = new Hashtable();
data.Add(Constants.ZoneIdentifierKey, Identifier);
data.Add(Constants.ZoneTypeKey, Convert.ToInt32(Type).ToString());
data.Add(Constants.ZoneEnabledKey, Enabled ? "1" : "0");
data.Add(Constants.ZoneRewardedKey, Rewarded ? "1" : "0");
data.Add(Constants.ZoneViewsPerRewardKey, ViewsPerReward.ToString());
data.Add(Constants.ZoneViewsUntilRewardKey, ViewsUntilReward.ToString());
data.Add(Constants.ZoneRewardAmountKey, RewardAmount.ToString());
data.Add(Constants.ZoneRewardNameKey, RewardName);
return AdColonyJson.Encode(data);
}
19
View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public Task<bool> UpdateCategoryAsync(CategoryDTO objCategoryDTO)
{
try
{
int intCategoryId = Convert.ToInt32(objCategoryDTO.CategoryId);
var ExistingCategory =
_context.Categorys
.Where(x => x.CategoryId == intCategoryId)
.FirstOrDefault();
if (ExistingCategory != null)
{
ExistingCategory.replacedle =
objCategoryDTO.replacedle;
ExistingCategory.Description =
objCategoryDTO.Description;
_context.SaveChanges();
}
else
{
return Task.FromResult(false);
}
return Task.FromResult(true);
}
catch
{
DetachAllEnreplacedies();
throw;
}
}
19
View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public Task<bool> DeleteCategoryAsync(CategoryDTO objCategoryDTO)
{
int intCategoryId = Convert.ToInt32(objCategoryDTO.CategoryId);
var ExistingCategory =
_context.Categorys
.Where(x => x.CategoryId == intCategoryId)
.FirstOrDefault();
if (ExistingCategory != null)
{
_context.Categorys.Remove(ExistingCategory);
_context.SaveChanges();
}
else
{
return Task.FromResult(false);
}
return Task.FromResult(true);
}
19
View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public Task<bool> UpdateFilesAsync(FilesDTO objFilesDTO)
{
try
{
int intFilesId = Convert.ToInt32(objFilesDTO.FileId);
var ExistingFiles =
_context.Files
.Where(x => x.FileId == intFilesId)
.FirstOrDefault();
if (ExistingFiles != null)
{
ExistingFiles.DownloadCount =
objFilesDTO.DownloadCount;
ExistingFiles.FileName =
objFilesDTO.FileName;
ExistingFiles.FilePath =
objFilesDTO.FilePath;
_context.SaveChanges();
}
else
{
return Task.FromResult(false);
}
return Task.FromResult(true);
}
catch
{
DetachAllEnreplacedies();
throw;
}
}
19
View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public Task<bool> DeleteFilesAsync(FilesDTO objFilesDTO)
{
int intFilesId = Convert.ToInt32(objFilesDTO.FileId);
var ExistingFiles =
_context.Files
.Where(x => x.FileId == intFilesId)
.FirstOrDefault();
if (ExistingFiles != null)
{
_context.Files.Remove(ExistingFiles);
_context.SaveChanges();
// Delete the file
FileController objFileController = new FileController(_environment);
objFileController.DeleteFile(objFilesDTO.FilePath);
}
else
{
return Task.FromResult(false);
}
return Task.FromResult(true);
}
19
View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public Task<bool> UpdateExternalConnectionsAsync(ExternalConnectionsDTO objExternalConnectionsDTO)
{
try
{
int intExternalConnectionsId = Convert.ToInt32(objExternalConnectionsDTO.Id);
var ExistingExternalConnections =
_context.ExternalConnections
.Where(x => x.Id == intExternalConnectionsId)
.FirstOrDefault();
if (ExistingExternalConnections != null)
{
ExistingExternalConnections.ServerName =
objExternalConnectionsDTO.ServerName;
ExistingExternalConnections.DatabaseName =
objExternalConnectionsDTO.DatabaseName;
ExistingExternalConnections.DatabaseUsername =
objExternalConnectionsDTO.DatabaseUsername;
ExistingExternalConnections.DatabasePreplacedword =
objExternalConnectionsDTO.DatabasePreplacedword;
ExistingExternalConnections.IntegratedSecurity =
objExternalConnectionsDTO.IntegratedSecurity;
_context.SaveChanges();
}
else
{
return Task.FromResult(false);
}
return Task.FromResult(true);
}
catch
{
DetachAllEnreplacedies();
throw;
}
}
19
View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public Task<bool> DeleteExternalConnectionsAsync(ExternalConnectionsDTO objExternalConnectionsDTO)
{
int intExternalConnectionsId = Convert.ToInt32(objExternalConnectionsDTO.Id);
var ExistingExternalConnections =
_context.ExternalConnections
.Where(x => x.Id == intExternalConnectionsId)
.FirstOrDefault();
if (ExistingExternalConnections != null)
{
_context.ExternalConnections.Remove(ExistingExternalConnections);
_context.SaveChanges();
}
else
{
return Task.FromResult(false);
}
return Task.FromResult(true);
}
19
View Source File : TestShortcutsPage.xaml.cs
License : MIT License
Project Creator : adenearnshaw
License : MIT License
Project Creator : adenearnshaw
private async void AddShortcutSet(object sender, System.EventArgs e)
{
var tag = Convert.ToInt32((sender as Button)?.CommandParameter);
await RemoveCurrentShortcuts();
switch (tag)
{
case 1:
await AddShortcut(new AddIcon());
await AddShortcut(new AlarmIcon());
await AddShortcut(new AudioIcon());
await AddShortcut(new BookmarkIcon());
break;
case 2:
await AddShortcut(new CapturePhotoIcon());
await AddShortcut(new CaptureVideoIcon());
await AddShortcut(new CloudIcon());
await AddShortcut(new ComposeIcon());
break;
case 3:
await AddShortcut(new ConfirmationIcon());
await AddShortcut(new ContactIcon());
await AddShortcut(new DateIcon());
await AddShortcut(new FavoriteIcon());
break;
case 4:
await AddShortcut(new HomeIcon());
await AddShortcut(new InvitationIcon());
await AddShortcut(new LocationIcon());
await AddShortcut(new LoveIcon());
break;
case 5:
await AddShortcut(new MailIcon());
await AddShortcut(new MarkLocationIcon());
await AddShortcut(new MessageIcon());
await AddShortcut(new PauseIcon());
break;
case 6:
await AddShortcut(new PlayIcon());
await AddShortcut(new ProhibitIcon());
await AddShortcut(new SearchIcon());
await AddShortcut(new ShareIcon());
break;
case 7:
await AddShortcut(new ShuffleIcon());
await AddShortcut(new TaskIcon());
await AddShortcut(new TaskCompletedIcon());
await AddShortcut(new TimeIcon());
break;
case 8:
await AddShortcut(new UpdateIcon());
await AddShortcut(new DefaultIcon());
await AddCustomShortcut("ic_beach.png");
break;
}
await Navigation.PopAsync();
}
19
View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private void CreateOutputPane()
{
_paneGuid = Guid.NewGuid();
_panereplacedle = "Real Xaml";
IVsOutputWindow output = (IVsOutputWindow)GetService(typeof(SVsOutputWindow));
output.CreatePane(ref _paneGuid, _panereplacedle, Convert.ToInt32(true), Convert.ToInt32(true));
output.GetPane(ref _paneGuid, out _outputPane);
}
19
View Source File : Job_Creation_Test.cs
License : MIT License
Project Creator : AdemCatamak
License : MIT License
Project Creator : AdemCatamak
[Fact]
public void When_JobCreatedOneAfterAnother__JobIdShouldBeGreaterThanPreviousOne()
{
List<Job> jobs = new List<Job>();
for (var i = 0; i < 100; i++)
{
jobs.Add(new Job(_message, i.ToString()));
Thread.Sleep(1);
}
for (var i = 1; i < jobs.Count; i++)
{
Job job = jobs[i];
Job jobPrevious = jobs[i - 1];
replacedertThat.GreaterThan(Convert.ToInt32(jobPrevious.MessageHandlerTypeName), Convert.ToInt32(job.MessageHandlerTypeName));
replacedertThat.GreaterThan(jobPrevious.CreatedOn, job.CreatedOn);
replacedertThat.GreaterThan(jobPrevious.Id, job.Id);
}
}
19
View Source File : MetadataEntityAttributeUpdate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected object GetValue(JToken token, AttributeTypeCode attributeType)
{
var value = token.ToObject<object>();
if (value == null)
{
return null;
}
if (attributeType == AttributeTypeCode.Customer || attributeType == AttributeTypeCode.Lookup || attributeType == AttributeTypeCode.Owner)
{
EnreplacedyReference enreplacedyReference;
if (TryGetEnreplacedyReference(value, out enreplacedyReference))
{
return enreplacedyReference;
}
throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.LogicalName, typeof(EnreplacedyReference)));
}
// Option set values will be in Int64 form from the JSON deserialization -- convert those to OptionSetValues
// for option set attributes.
if (attributeType == AttributeTypeCode.EnreplacedyName || attributeType == AttributeTypeCode.Picklist || attributeType == AttributeTypeCode.State || attributeType == AttributeTypeCode.Status)
{
return new OptionSetValue(Convert.ToInt32(value));
}
if (attributeType == AttributeTypeCode.Memo || attributeType == AttributeTypeCode.String)
{
return value is string ? value : value.ToString();
}
if (attributeType == AttributeTypeCode.BigInt)
{
return Convert.ToInt64(value);
}
if (attributeType == AttributeTypeCode.Boolean)
{
return Convert.ToBoolean(value);
}
if (attributeType == AttributeTypeCode.DateTime)
{
var dateTimeValue = Convert.ToDateTime(value);
return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
}
if (attributeType == AttributeTypeCode.Decimal)
{
return Convert.ToDecimal(value);
}
if (attributeType == AttributeTypeCode.Double)
{
return Convert.ToDouble(value);
}
if (attributeType == AttributeTypeCode.Integer)
{
return Convert.ToInt32(value);
}
if (attributeType == AttributeTypeCode.Money)
{
return new Money(Convert.ToDecimal(value));
}
if (attributeType == AttributeTypeCode.Uniqueidentifier)
{
return value is Guid ? value : new Guid(value.ToString());
}
return value;
}
19
View Source File : ReflectionEntityAttributeUpdate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected object GetValue(JToken token, Type propertyType)
{
var value = token.ToObject<object>();
if (value == null)
{
return null;
}
if (propertyType == typeof(bool?))
{
return Convert.ToBoolean(value);
}
if (propertyType == typeof(CrmEnreplacedyReference))
{
EnreplacedyReference enreplacedyReference;
if (TryGetEnreplacedyReference(value, out enreplacedyReference))
{
return new CrmEnreplacedyReference(enreplacedyReference.LogicalName, enreplacedyReference.Id);
}
throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
}
if (propertyType == typeof(DateTime?))
{
var dateTimeValue = value is DateTime ? (DateTime)value : Convert.ToDateTime(value);
return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
}
if (propertyType == typeof(double?))
{
return Convert.ToDouble(value);
}
if (propertyType == typeof(decimal))
{
return Convert.ToDecimal(value);
}
if (propertyType == typeof(EnreplacedyReference))
{
EnreplacedyReference enreplacedyReference;
if (TryGetEnreplacedyReference(value, out enreplacedyReference))
{
return enreplacedyReference;
}
throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
}
if (propertyType == typeof(Guid?))
{
return value is Guid ? value : new Guid(value.ToString());
}
if (propertyType == typeof(int?))
{
return Convert.ToInt32(value);
}
if (propertyType == typeof(long?))
{
return Convert.ToInt64(value);
}
if (propertyType == typeof(string))
{
return value is string ? value : value.ToString();
}
if (propertyType.IsreplacedignableFrom(value.GetType()))
{
return value;
}
throw new InvalidOperationException("Unable to convert value of type".FormatWith(value.GetType(), propertyType, Attribute.CrmPropertyAttribute.LogicalName));
}
19
View Source File : BooleanControlTemplate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void AddSpecialBindingAndHiddenFieldsToPersistDisabledRadioButtons(Control container, ListControl radioButtonList)
{
radioButtonList.CssClreplaced = "{0} readonly".FormatWith(CssClreplaced);
radioButtonList.Enabled = false;
var hiddenValue = new HiddenField
{
ID = "{0}_Value".FormatWith(ControlID),
Value = radioButtonList.SelectedValue
};
container.Controls.Add(hiddenValue);
RegisterClientSideDependencies(container);
Bindings[Metadata.DataFieldName] = new CellBinding
{
Get = () =>
{
int value;
return int.TryParse(hiddenValue.Value, out value) ? (object)(value == 1) : null;
},
Set = obj =>
{
var value = new OptionSetValue(Convert.ToInt32(obj)).Value;
radioButtonList.SelectedValue = "{0}".FormatWith(value);
hiddenValue.Value = radioButtonList.SelectedValue;
}
};
}
See More Examples