System.Convert.ToInt32(object)

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

2928 Examples 7

19 View Source File : MySqlTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string FileUpdateSql(string field, object value, IList<DbParameter> parameters)
        {
            field = FieldDictionary[field];
            if (value == null)
                return $"`{field}` = NULL";
            if (value is string || value is DateTime || value is byte[])
            {
                var name = "v_" + field;
                parameters.Add(CreateFieldParameter(name, GetDbType(field), value));
                return $"`{field}` = ?{name}";
            }
            if (value is bool)
                value = (bool)value ? 1 : 0;
            else if (value is Enum)
                value = Convert.ToInt32(value);
            return $"`{field}` = {value}";
        }

19 View Source File : Collection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public void Remove(object index)
        {
            if (index is int)
            {
                M_Collection.Remove(checked(Convert.ToInt32(index) + 1));
            }
            else if (index is string)
            {
                M_Collection.Remove(checked(Convert.ToString(index)));
            }
        }

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

internal static dynamic TryConvertAttributeValue(OrganizationServiceContext context, string enreplacedyName, string attributeName, object value, Dictionary<string, AttributeTypeCode?> AttributeTypeCodeDictionary)
		{

			if (context == null || string.IsNullOrWhiteSpace(enreplacedyName) || string.IsNullOrWhiteSpace(attributeName)) return null;

			if (AttributeTypeCodeDictionary == null || !AttributeTypeCodeDictionary.Any())
			{
				AttributeTypeCodeDictionary = MetadataHelper.BuildAttributeTypeCodeDictionary(context, enreplacedyName);
			}

			object newValue = null;
			var attributeTypeCode = AttributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;

			if (attributeTypeCode == null)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Unable to recognize the attribute '{0}' specified.", attributeName));
				return null;
			}

			try
			{
				switch (attributeTypeCode)
				{
					case AttributeTypeCode.BigInt:
						newValue = value == null ? (object)null : Convert.ToInt64(value);
						break;
					case AttributeTypeCode.Boolean:
						newValue = value == null ? (object)null : Convert.ToBoolean(value);
						break;
					case AttributeTypeCode.Customer:
						if (value is EnreplacedyReference)
						{
							newValue = value as EnreplacedyReference;
						}
						else if (value is Guid)
						{
							var metadata = MetadataHelper.GetEnreplacedyMetadata(context, enreplacedyName);
							var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
							if (attribute != null)
							{
								var lookupAttribute = attribute as LookupAttributeMetadata;
								if (lookupAttribute != null && lookupAttribute.Targets.Length == 1)
								{
									var lookupEnreplacedyType = lookupAttribute.Targets[0];
									newValue = new EnreplacedyReference(lookupEnreplacedyType, (Guid)value);
								}
							}
						}
						break;
					case AttributeTypeCode.DateTime:
						newValue = value == null ? (object)null : Convert.ToDateTime(value).ToUniversalTime();
						break;
					case AttributeTypeCode.Decimal:
						newValue = value == null ? (object)null : Convert.ToDecimal(value);
						break;
					case AttributeTypeCode.Double:
						newValue = value == null ? (object)null : Convert.ToDouble(value);
						break;
					case AttributeTypeCode.Integer:
						newValue = value == null ? (object)null : Convert.ToInt32(value);
						break;
					case AttributeTypeCode.Lookup:
						if (value is EnreplacedyReference)
						{
							newValue = value as EnreplacedyReference;
						}
						else if (value is Guid)
						{
							var metadata = MetadataHelper.GetEnreplacedyMetadata(context, enreplacedyName);
							var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
							if (attribute != null)
							{
								var lookupAttribute = attribute as LookupAttributeMetadata;
								if (lookupAttribute != null && lookupAttribute.Targets.Length == 1)
								{
									var lookupEnreplacedyType = lookupAttribute.Targets[0];
									newValue = new EnreplacedyReference(lookupEnreplacedyType, (Guid)value);
								}
							}
						}
						break;
					case AttributeTypeCode.Memo:
						newValue = value as string;
						break;
					case AttributeTypeCode.Money:
						newValue = value == null ? (object)null : Convert.ToDecimal(value);
						break;
					case AttributeTypeCode.Picklist:
						var plMetadata = MetadataHelper.GetEnreplacedyMetadata(context, enreplacedyName);
						var plAttribute = plMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
						if (plAttribute != null)
						{
							var picklistAttribute = plAttribute as PicklistAttributeMetadata;
							if (picklistAttribute != null)
							{
								int picklistInt;
								OptionMetadata picklistValue;
								if (int.TryParse(string.Empty + value, out picklistInt))
								{
									picklistValue = picklistAttribute.OptionSet.Options.FirstOrDefault(o => o.Value == picklistInt);
								}
								else
								{
									picklistValue = picklistAttribute.OptionSet.Options.FirstOrDefault(o => o.Label.GetLocalizedLabelString() == string.Empty + value);
								}

								if (picklistValue != null && picklistValue.Value.HasValue)
								{
									newValue = value == null ? null : new OptionSetValue(picklistValue.Value.Value);
								}
							}
						}
						break;
					case AttributeTypeCode.State:
						ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute '{0}' type '{1}' is unsupported. The state attribute is created automatically when the enreplacedy is created. The options available for this attribute are read-only.", attributeName, attributeTypeCode));
						break;
					case AttributeTypeCode.Status:
						if (value == null)
						{
							return false;
						}
						var optionSetValue = new OptionSetValue(Convert.ToInt32(value));
						newValue = optionSetValue;
						break;
					case AttributeTypeCode.String:
						newValue = value as string;
						break;
					default:
						ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute '{0}' type '{1}' is unsupported.", attributeName, attributeTypeCode));
						break;
				}
			}
			catch (Exception ex)
			{
				WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute '{0}' specified is expecting a {1}. The value provided is not valid.", attributeName, attributeTypeCode));
			}
			return newValue;
		}

19 View Source File : MySqlDataBase_.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static MySqlParameter CreateParameter(string csharpType, string parameterName, object value)
        {
            if (value is Enum)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Int32)
                {
                    Value = Convert.ToInt32(value)
                };
            }
            if (value is bool b)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Byte)
                {
                    Value = b ? (byte)1 : (byte)0
                };
            }
            return CreateParameter(parameterName, value, ToSqlDbType(csharpType));
        }

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

protected int RenderTypeNumeric(IEnumerable dataSource)
		{
			var count = 0;
			var progressIndex = 0;
			var clreplacedName = "progress-numeric";
			
			var e = dataSource.GetEnumerator();

			if (string.IsNullOrWhiteSpace(Position))
			{
				CssClreplaced = string.Join(" ", CssClreplaced, clreplacedName);
			}
			else
			{
				switch (Position.ToLowerInvariant())
				{
					case "top":
						clreplacedName += " top";
						break;
					case "bottom":
						clreplacedName += " bottom";
						break;
					case "left":
						clreplacedName += " left";
						CssClreplaced += " col-sm-3 col-md-2";
						break;
					case "right":
						clreplacedName += " right";
						CssClreplaced += " col-sm-3 col-sm-push-9 col-md-2 col-md-push-10";
						break;
				}

				CssClreplaced = string.Join(" ", CssClreplaced, clreplacedName);
			}

			while (e.MoveNext())
			{
				if (e.Current == null)
				{
					continue;
				}

				var indexValue = DataBinder.GetPropertyValue(e.Current, IndexDataPropertyName);
				var activeValue = DataBinder.GetPropertyValue(e.Current, ActiveDataPropertyName);
				var index = Convert.ToInt32(indexValue);
				var active = Convert.ToBoolean(activeValue);

				if (active)
				{
					progressIndex = ZeroBasedIndex ? index + 1 : index;
				}

				count++;
			}

			var literal = new LiteralControl { Text = string.Format("{0} <span clreplaced='number'>{1}</span> of <span clreplaced='number total'>{2}</span>", NumericPrefix, progressIndex, count) };
			
			Controls.Add(literal);

			return count;
		}

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

public void _OnRewardGranted(string paramJson)
        {
            string zoneId = null;
            bool success = false;
            string productId = null;
            int amount = 0;

            Hashtable values = (AdColonyJson.Decode(paramJson) as Hashtable);
            if (values == null)
            {
                Debug.LogError("Unable to parse parameters in _OnRewardGranted, " + (paramJson ?? "null"));
                return;
            }

            if (values != null)
            {
                if (values.ContainsKey(Constants.OnRewardGrantedZoneIdKey))
                {
                    zoneId = values[Constants.OnRewardGrantedZoneIdKey] as string;
                }
                if (values.ContainsKey(Constants.OnRewardGrantedSuccessKey))
                {
                    success = Convert.ToBoolean(Convert.ToInt32(values[Constants.OnRewardGrantedSuccessKey]));
                }
                if (values.ContainsKey(Constants.OnRewardGrantedNameKey))
                {
                    productId = values[Constants.OnRewardGrantedNameKey] as string;
                }
                if (values.ContainsKey(Constants.OnRewardGrantedAmountKey))
                {
                    amount = Convert.ToInt32(values[Constants.OnRewardGrantedAmountKey]);
                }
            }

            if (Ads.OnRewardGranted != null)
            {
                Ads.OnRewardGranted(zoneId, success, productId, amount);
            }
        }

19 View Source File : AuthorizedToken.razor.cs
License : Apache License 2.0
Project Creator : Aguafrommars

protected override void OnInitialized()
        {
            Localizer.OnResourceReady = () => InvokeAsync(StateHasChanged);
            if (Value != null)
            {
                var timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(Value));
                _token = new Token
                {
                    ValueString = timeSpan.ToString(DISPLAY_FORMAT)
                };
            }
            else
            {
                _token = new Token();
            }

            _token.PropertyChanged += (s, e) =>
            {
                if (_updatingValue)
                {
                    return;
                }

                var match = _regex.Match(_token.ValueString);
                if (!match.Success)
                {
                    return;
                }

                var groups = match.Groups;
                if (groups["DaysTime"].Success || groups["Time"].Success)
                {
                    var newTimeSpan = TimeSpan.Parse(_token.ValueString);
                    SetValue(newTimeSpan);
                }
                else if (groups["MinutesSecondes"].Success)
                {
                    var newTimeSpan = TimeSpan.Parse($"00:{_token.ValueString}");
                    SetValue(newTimeSpan);
                }
                else if (groups["Days"].Success)
                {
                    var newTimeSpan = TimeSpan.FromDays(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (groups["Hours"].Success)
                {
                    var newTimeSpan = TimeSpan.FromHours(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (groups["Minutes"].Success)
                {
                    var newTimeSpan = TimeSpan.FromMinutes(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (_token.ValueString.EndsWith("s"))
                {
                    var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else
                {
                    var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString));
                    SetValue(newTimeSpan);
                }
            };
            base.OnInitialized();
        }

19 View Source File : HeatMapWithTextInCellsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
            {
                try
                {
                    switch (Convert.ToInt32(dataValue))
                    {
                        case 0: return "Mon";
                        case 1: return "Tue";
                        case 2: return "Wed";
                        case 3: return "Thu";
                        case 4: return "Fri";
                        case 5: return "Sat";
                        case 6: return "Sun";

                        default: return string.Empty;
                    }
                }
                catch
                {
                    return string.Empty;
                }
            }

19 View Source File : EnumType.cs
License : Apache License 2.0
Project Creator : ajuna-network

public void Create(T t)
        {
            //var byteArray = BitConverter.GetBytes(Convert.ToInt32(t));
            //if (byteArray.Length < Size())
            //{
            //    var newByteArray = new byte[Size()];
            //    byteArray.CopyTo(newByteArray, 0);
            //    byteArray = newByteArray;
            //}
            //Bytes = byteArray;
            Bytes = BitConverter.GetBytes(Convert.ToInt32(t));
            Value = t;
        }

19 View Source File : MonthLabelConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
		#endif
			int intValue = System.Convert.ToInt32(value);
			if(intValue == 1)
				return string.Format("{0} month", intValue);

			return string.Format("{0} months", intValue);
		}

19 View Source File : MySqlDataBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static MySqlParameter CreateParameter(string parameterName, object value, MySqlDbType type)
        {
            if (value == null)
            {
                return new MySqlParameter(parameterName, MySqlDbType.VarChar)
                {
                    Value = DBNull.Value
                };
            }
            var s = value as string;
            if (s != null)
            {
                return CreateParameter(parameterName, s);
            }
            if (value is Enum)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Int32)
                {
                    Value = Convert.ToInt32(value)
                };
            }
            if (value is bool)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Byte)
                {
                    Value = (bool)value ? (byte)1 : (byte)0
                };
            }
            return new MySqlParameter(parameterName, type)
            {
                Value = value
            };
        }

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

protected int RenderTypeProgressBar(IEnumerable dataSource)
		{
			var count = 0;
			var progressIndex = 0;
			var clreplacedName = "progress";
			var controlContainer = new HtmlGenericControl("div");
			
			var e = dataSource.GetEnumerator();

			if (string.IsNullOrWhiteSpace(Position))
			{
				CssClreplaced = string.Join(" ", CssClreplaced, clreplacedName);
			}
			else
			{
				switch (Position.ToLowerInvariant())
				{
					case "top":
						clreplacedName += " top";
						break;
					case "bottom":
						clreplacedName += " bottom";
						break;
					case "left":
						clreplacedName += " left";
						CssClreplaced += " col-sm-3 col-md-2";
						break;
					case "right":
						clreplacedName += " right";
						CssClreplaced += " col-sm-3 col-sm-push-9 col-md-2 col-md-push-10";
						break;
				}

				CssClreplaced = string.Join(" ", CssClreplaced, clreplacedName);
			}

			while (e.MoveNext())
			{
				if (e.Current == null)
				{
					continue;
				}

				var indexValue = DataBinder.GetPropertyValue(e.Current, IndexDataPropertyName);
				var activeValue = DataBinder.GetPropertyValue(e.Current, ActiveDataPropertyName);
				var index = Convert.ToInt32(indexValue);
				var active = Convert.ToBoolean(activeValue);
				
				if (active)
				{
					if (ZeroBasedIndex)
					{
						index++;
					}

					progressIndex = index > 0 ? index - 1 : 0;
				}
				
				count++;
			}

			controlContainer.Attributes["clreplaced"] = "bar progress-bar";

			double percent = 0;

			if (count > 0)
			{
				if (!CountLastStepInProgress)
				{
					percent = (double)(progressIndex * 100) / (count - 1);
				}
				else
				{
					percent = (double)(progressIndex * 100) / count;
				}
			}

			var progress = Math.Floor(percent);

			controlContainer.Attributes["style"] = string.Format("width: {0}%;", progress);
			controlContainer.Attributes["role"] = "progressbar";
			controlContainer.Attributes["aria-valuemin"] = "0";
			controlContainer.Attributes["aria-valuemax"] = "100";
			controlContainer.Attributes["aria-valuenow"] = progress.ToString(CultureInfo.InvariantCulture);

			if (progress.CompareTo(0) == 0)
			{
				controlContainer.Attributes["clreplaced"] = controlContainer.Attributes["clreplaced"] + " zero";
			}

			controlContainer.InnerHtml = string.Format("{0}%", progress);

			Controls.Add(controlContainer);

			return count;
		}

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

public void _OnIAPOpportunity(string paramJson)
        {
            Hashtable values = (AdColonyJson.Decode(paramJson) as Hashtable);
            if (values == null)
            {
                Debug.LogError("Unable to parse parameters in _OnIAPOpportunity, " + (paramJson ?? "null"));
                return;
            }

            Hashtable valuesAd = null;
            string iapProductId = null;
            AdsIAPEngagementType engagement = AdsIAPEngagementType.AdColonyIAPEngagementEndCard;

            if (values.ContainsKey(Constants.OnIAPOpportunityAdKey))
            {
                valuesAd = (AdColonyJson.Decode(values[Constants.OnIAPOpportunityAdKey] as String)) as Hashtable;
            }
            if (values.ContainsKey(Constants.OnIAPOpportunityEngagementKey))
            {
                engagement = (AdsIAPEngagementType)Convert.ToInt32(values[Constants.OnIAPOpportunityEngagementKey]);
            }
            if (values.ContainsKey(Constants.OnIAPOpportunityIapProductIdKey))
            {
                iapProductId = values[Constants.OnIAPOpportunityIapProductIdKey] as string;
            }

            IntersreplacedialAd ad = GetAdFromHashtable(valuesAd);
            if (ad == null)
            {
                Debug.LogError("Unable to create ad within _OnIAPOpportunity, " + (paramJson ?? "null"));
                return;
            }

            if (Ads.OnIAPOpportunity != null)
            {
                Ads.OnIAPOpportunity(ad, iapProductId, engagement);
            }
        }

19 View Source File : MySqlTable.dml.async.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public async Task<int> SetValueAsync(Expression<Func<TData, Enum>> field, Enum value, string condition,
            params DbParameter[] args)
        {
            return await SetValueByConditionAsync(GetPropertyName(field), Convert.ToInt32(value), condition, args);
        }

19 View Source File : YearsLabelProvider.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            var i = Convert.ToInt32(dataValue);
            string result = "";
            if (i >= 0 && i < 4)
            {
                result = _xLabels[i];
            }
            return result;
        }

19 View Source File : SqlServerDataBase_.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static SqlParameter CreateParameter(string parameterName, object value, SqlDbType type)
        {
            switch (value)
            {
                case string s:
                    return CreateParameter(parameterName, s);
                case Enum _:
                    return new SqlParameter(parameterName, SqlDbType.Int)
                    {
                        Value = Convert.ToInt32(value)
                    };
                case bool _:
                    return new SqlParameter(parameterName, SqlDbType.Bit)
                    {
                        Value = (bool)value ? (byte)1 : (byte)0
                    };
                case null:
                    return new SqlParameter(parameterName, type)
                    {
                        Value = DBNull.Value
                    };
                default:
                    return new SqlParameter(parameterName, type)
                    {
                        Value = value
                    };
            }

        }

19 View Source File : EmailService.cs
License : MIT License
Project Creator : ADefWebserver

private async Task<string> SendMailAsync(bool SendAsync, string MailFrom, string MailTo, string MailToDisplayName, string Cc, string Bcc, string ReplyTo, System.Net.Mail.MailPriority Priority,
            string Subject, Encoding BodyEncoding, string Body, string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPreplacedword, bool SMTPEnableSSL)
        {
            string strSendMail = "";
            GeneralSettings GeneralSettings = await _generalSettingsService.GetGeneralSettingsAsync();

            // SMTP server configuration
            if (SMTPServer == "")
            {
                SMTPServer = GeneralSettings.SMTPServer;

                if (SMTPServer.Trim().Length == 0)
                {
                    return "Error: Cannot send email - SMTPServer not set";
                }
            }

            if (SMTPAuthentication == "")
            {
                SMTPAuthentication = GeneralSettings.SMTPAuthendication;
            }

            if (SMTPUsername == "")
            {
                SMTPUsername = GeneralSettings.SMTPUserName;
            }

            if (SMTPPreplacedword == "")
            {
                SMTPPreplacedword = GeneralSettings.SMTPPreplacedword;
            }

            MailTo = MailTo.Replace(";", ",");
            Cc = Cc.Replace(";", ",");
            Bcc = Bcc.Replace(";", ",");

            System.Net.Mail.MailMessage objMail = null;
            try
            {
                System.Net.Mail.MailAddress SenderMailAddress = new System.Net.Mail.MailAddress(MailFrom, MailFrom);
                System.Net.Mail.MailAddress RecipientMailAddress = new System.Net.Mail.MailAddress(MailTo, MailToDisplayName);

                objMail = new System.Net.Mail.MailMessage(SenderMailAddress, RecipientMailAddress);

                if (Cc != "")
                {
                    objMail.CC.Add(Cc);
                }
                if (Bcc != "")
                {
                    objMail.Bcc.Add(Bcc);
                }

                if (ReplyTo != string.Empty)
                {
                    objMail.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo));
                }

                objMail.Priority = (System.Net.Mail.MailPriority)Priority;
                objMail.IsBodyHtml = IsHTMLMail(Body);

                foreach (string myAtt in Attachment)
                {
                    if (myAtt != "") objMail.Attachments.Add(new System.Net.Mail.Attachment(myAtt));
                }

                // message
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject = Subject.Trim();
                objMail.BodyEncoding = BodyEncoding;

                System.Net.Mail.AlternateView PlainView =
                    System.Net.Mail.AlternateView.CreateAlternateViewFromString(Utility.ConvertToText(Body),
                    null, "text/plain");

                objMail.AlternateViews.Add(PlainView);

                //if body contains html, add html part
                if (IsHTMLMail(Body))
                {
                    System.Net.Mail.AlternateView HTMLView =
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

                    objMail.AlternateViews.Add(HTMLView);
                }
            }
            catch (Exception objException)
            {
                // Problem creating Mail Object
                strSendMail = MailTo + ": " + objException.Message;

                // Log Error 
                BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs();
                objLog.LogDate = DateTime.Now;
                objLog.LogAction = $"{Constants.EmailError} - Error: {strSendMail}";
                objLog.LogUserName = MailTo;
                objLog.LogIpaddress = "127.0.0.1";
            }

            if (objMail != null)
            {
                // external SMTP server alternate port
                int? SmtpPort = null;
                int portPos = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                if (SMTPServer != "")
                {
                    smtpClient.Host = SMTPServer;
                    smtpClient.Port = (SmtpPort == null) ? (int)25 : (Convert.ToInt32(SmtpPort));

                    switch (SMTPAuthentication)
                    {
                        case "":
                        case "0":
                            // anonymous
                            break;
                        case "1":
                            // basic
                            if (SMTPUsername != "" & SMTPPreplacedword != "")
                            {
                                smtpClient.UseDefaultCredentials = false;
                                smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPreplacedword);
                            }

                            break;
                        case "2":
                            // NTLM
                            smtpClient.UseDefaultCredentials = true;
                            break;
                    }
                }
                smtpClient.EnableSsl = SMTPEnableSSL;

                try
                {
                    if (SendAsync) // Send Email using SendAsync
                    {
                        // Set the method that is called back when the send operation ends.
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;

                        // Send the email
                        MailMessage objMailMessage = new MailMessage();
                        objMailMessage = objMail;

                        smtpClient.SendAsync(objMail, objMailMessage);
                        strSendMail = "";
                    }
                    else // Send email and wait for response
                    {
                        smtpClient.Send(objMail);
                        strSendMail = "";

                        // Log the Email
                        LogEmail(objMail);

                        objMail.Dispose();
                        smtpClient.Dispose();
                    }
                }
                catch (Exception objException)
                {
                    // mail configuration problem
                    if (!(objException.InnerException == null))
                    {
                        strSendMail = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message);
                    }
                    else
                    {
                        strSendMail = objException.Message;
                    }

                    // Log Error 
                    BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs();
                    objLog.LogDate = DateTime.Now;
                    objLog.LogAction = $"{Constants.EmailError} - Error: {strSendMail}";
                    objLog.LogUserName = null;
                    objLog.LogIpaddress = "127.0.0.1";

                    _context.Logs.Add(objLog);
                    _context.SaveChanges();
                }
            }

            return strSendMail;
        }

19 View Source File : ListBoxSelectedIndexCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public override bool Contains(object value)
        {
            return M_ListBoxSelectedIndexCollection.Contains(Convert.ToInt32(value));
        }

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

public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<BookListMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
                {
                    var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
                    
                    if (_quietMode)
                    {
                        // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
                        var exitCode = Convert.ToInt32(!migrationSucceeded);
                        Environment.Exit(exitCode);
                    }
                    else
                    {
                        Console.WriteLine("Press ENTER to exit...");
                        Console.ReadLine();
                    }
                }
            }
        }

19 View Source File : SystemEventsCenter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

void watcher_EventArrived(object sender, EventArrivedEventArgs e)
		{
			ManagementBaseObject obj = e.NewEvent;
			string clsName = obj.ClreplacedPath.ClreplacedName;
			switch (clsName)
			{
				case "Win32_ProcessStartTrace":
				case "Win32_ProcessStopTrace":
					{
						ProcessEventArgs arg = new ProcessEventArgs()
						{
							SessionId = Convert.ToInt32(obj["SessionID"]),
							ProcessId = Convert.ToInt32(obj["ProcessID"]),
							ProcessName = obj["ProcessName"] as string,
							TimeCreated = DateTime.FromFileTimeUtc(Convert.ToInt64(obj["TIME_CREATED"])).AddHours(UtcOffsetHours),
						};
						if (clsName == "Win32_ProcessStartTrace" && this.ProcessStart != null)
							this.ProcessStart(this, arg);
						if (clsName == "Win32_ProcessStopTrace" && this.ProcessExit != null)
							this.ProcessExit(this, arg);
					}
					break;
				default:
					break;

			}
		}

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

public static int? Integer(object input)
		{
			if (input == null)
			{
				return null;
			}

			try
			{
				return Convert.ToInt32(input);
			}
			catch (FormatException) { }
			catch (InvalidCastException) { }

			return null;
		}

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

protected void AddStep(object dataItem, Control container)
		{
			if (dataItem == null)
			{
				return;
			}

			var replacedle = DataBinder.GetPropertyValue(dataItem, replacedleDataPropertyName, null);
			var indexValue = DataBinder.GetPropertyValue(dataItem, IndexDataPropertyName);
			var activeValue = DataBinder.GetPropertyValue(dataItem, ActiveDataPropertyName);
			var completedValue = DataBinder.GetPropertyValue(dataItem, CompletedDataPropertyName);
			var index = Convert.ToInt32(indexValue);
			var active = Convert.ToBoolean(activeValue);
			var completed = Convert.ToBoolean(completedValue);
			var step = new ProgressStep(index, replacedle, active, completed);
			var item = new HtmlGenericControl("li");
			item.AddClreplaced("list-group-item");

			item.InnerHtml = PrependStepIndexToreplacedle ? string.Format("<span clreplaced='number'>{0}</span>{1}", ZeroBasedIndex ? (step.Index + 1) : step.Index, step.replacedle) : step.replacedle;
			
			if (step.IsActive)
			{
				item.AddClreplaced("active");
			} 
			else if (step.IsCompleted)
			{
				item.AddClreplaced("text-muted list-group-item-success");
				item.InnerHtml += "<span clreplaced='glyphicon glyphicon-ok'></span>";
			}
			else
			{
				item.AddClreplaced("incomplete");
			}

			container.Controls.Add(item);
		}

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

public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<PhoneBookMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
                {
                    var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
                    
                    if (_quietMode)
                    {
                        // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
                        var exitCode = Convert.ToInt32(!migrationSucceeded);
                        Environment.Exit(exitCode);
                    }
                    else
                    {
                        Console.WriteLine("Press ENTER to exit...");
                        Console.ReadLine();
                    }
                }
            }
        }

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

protected bool Evaluate(Expression left, Expression right, Func<object, object, bool> compare, Func<object, Type, object> convert)
		{
			object testValue;
			var attributeName = ((LeftLiteralExpression)left).Value as string;
			var expressionValue = ((RightLiteralExpression)right).Value;

			if (EvaluateEnreplacedy == null)
			{
				throw new NullReferenceException("EvaluateEnreplacedy is null.");
			}
			
			if (string.IsNullOrWhiteSpace(attributeName))
			{
				throw new InvalidOperationException(string.Format("Unable to recognize the attribute {0} specified in the expression.", attributeName));
			}

			var attributeTypeCode = AttributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;

			if (attributeTypeCode == null)
			{
				throw new InvalidOperationException(string.Format("Unable to recognize the attribute {0} specified in the expression.", attributeName));
			}

			var attributeValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? EvaluateEnreplacedy.Attributes[attributeName] : null;

			switch (attributeTypeCode)
			{
				case AttributeTypeCode.BigInt:
					if (expressionValue != null && !(expressionValue is long | expressionValue is double))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToInt64(expressionValue);
					break;
				case AttributeTypeCode.Boolean:
					if (expressionValue != null && !(expressionValue is bool))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : (bool)expressionValue;
					break;
				case AttributeTypeCode.Customer:
					var enreplacedyReference = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (EnreplacedyReference)EvaluateEnreplacedy.Attributes[attributeName] : null;
					attributeValue = enreplacedyReference != null ? (object)enreplacedyReference.Id : null;
					if (expressionValue != null && !(expressionValue is Guid))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : (Guid)expressionValue;
					break;
				case AttributeTypeCode.DateTime:
					if (expressionValue != null && !(expressionValue is DateTime))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : ((DateTime)expressionValue).ToUniversalTime();
					break;
				case AttributeTypeCode.Decimal:
					if (expressionValue != null && !(expressionValue is int | expressionValue is double | expressionValue is decimal))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToDecimal(expressionValue);
					break;
				case AttributeTypeCode.Double:
					if (expressionValue != null && !(expressionValue is int | expressionValue is double))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToDouble(expressionValue);
					break;
				case AttributeTypeCode.Integer:
					if (expressionValue != null && !(expressionValue is int | expressionValue is double))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
					break;
				case AttributeTypeCode.Lookup:
					var lookupEnreplacedyReference = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (EnreplacedyReference)EvaluateEnreplacedy.Attributes[attributeName] : null;
					attributeValue = lookupEnreplacedyReference != null ? (object)lookupEnreplacedyReference.Id : null;
					if (expressionValue != null && !(expressionValue is Guid))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : (Guid)expressionValue;
					break;
				case AttributeTypeCode.Memo:
					if (expressionValue != null && !(expressionValue is string))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue as string;
					break;
				case AttributeTypeCode.Money:
					var money = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (Money)EvaluateEnreplacedy.Attributes[attributeName] : null;
					attributeValue = money != null ? (object)Convert.ToDecimal(money.Value) : null;
					if (expressionValue != null && !(expressionValue is int | expressionValue is double | expressionValue is decimal))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToDecimal(expressionValue);
					break;
				case AttributeTypeCode.Picklist:
					var optionSetValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEnreplacedy.Attributes[attributeName] : null;
					attributeValue = optionSetValue != null ? (object)optionSetValue.Value : null;
					if (expressionValue != null && !(expressionValue is int | expressionValue is double))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
					break;
				case AttributeTypeCode.State:
					var stateOptionSetValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEnreplacedy.Attributes[attributeName] : null;
					attributeValue = stateOptionSetValue != null ? (object)stateOptionSetValue.Value : null;
					if (expressionValue != null && !(expressionValue is int | expressionValue is double))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
					break;
				case AttributeTypeCode.Status:
					var statusOptionSetValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEnreplacedy.Attributes[attributeName] : null;
					attributeValue = statusOptionSetValue != null ? (object)statusOptionSetValue.Value : null;
					if (expressionValue != null && !(expressionValue is int | expressionValue is double))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
					break;
				case AttributeTypeCode.String:
					if (expressionValue != null && !(expressionValue is string))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue as string;
					break;
				case AttributeTypeCode.Uniqueidentifier:
					if (expressionValue != null && !(expressionValue is Guid))
					{
						throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
					}
					testValue = expressionValue == null ? (object)null : (Guid)expressionValue;
					break;
				default:
					throw new InvalidOperationException(string.Format("Unsupported type of attribute {0} specified in the expression.", attributeName));
			}

			return compare(attributeValue, testValue);
		}

19 View Source File : HookInterceptor.cs
License : MIT License
Project Creator : AdamCarballo

public static object GetParsedParameter(Type type, object param) {
			object parsedParam = null;

			// Ignore object as it doesn't need parsing
			if (type == typeof(bool)) {
				parsedParam = Convert.ToBoolean(param);
			} else if (type == typeof(int)) {
				parsedParam = Convert.ToInt32(param);
			} else if (type == typeof(float)) {
				parsedParam = Convert.ToSingle(param);
			} else if (type == typeof(string)) {
				parsedParam = Convert.ToString(param);
			}

			return parsedParam;
		}

19 View Source File : MySqlDataBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static MySqlParameter CreateParameter(string csharpType, string parameterName, object value)
        {
            if (value is Enum)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Int32)
                {
                    Value = Convert.ToInt32(value)
                };
            }
            if (value is bool)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Byte)
                {
                    Value = (bool)value ? (byte)1 : (byte)0
                };
            }
            return CreateParameter(parameterName, value, ToSqlDbType(csharpType));
        }

19 View Source File : MapManager.cs
License : MIT License
Project Creator : Adsito

public static List<int> GetEnumSelection<T>(T enumGroup)
    {
        var selectedEnums = new List<int>();
        for (int i = 0; i < Enum.GetValues(typeof(T)).Length; i++)
        {
            int layer = 1 << i;
            if ((Convert.ToInt32(enumGroup) & layer) != 0)
                selectedEnums.Add(i);
        }
        return selectedEnums;
    }

19 View Source File : AdColonyUserMetadata.cs
License : Apache License 2.0
Project Creator : AdColony

[Obsolete("GetBoolMetadata is deprecated")]
        public bool GetBoolMetadata(string key)
        {
            return _data.ContainsKey(key) ? Convert.ToBoolean(Convert.ToInt32(_data[key])) : false;
        }

19 View Source File : MySqlDataBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static MySqlParameter CreateParameter<T>(string parameterName, T value)
            where T : struct
        {
            if (value is Enum)
            {
                return new MySqlParameter(parameterName, MySqlDbType.Int32)
                {
                    Value = Convert.ToInt32(value)
                };
            }
            return new MySqlParameter(parameterName, ToSqlDbType(typeof(T).Name))
            {
                Value = value
            };
        }

19 View Source File : InspectorUIUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static Enum DrawEnumSerializedProperty(Rect position, SerializedProperty prop, GUIContent label, Enum propValue)
        {
            Enum result = propValue;
            EditorGUI.BeginProperty(position, label, prop);
            {
                result = EditorGUI.EnumPopup(position, label, propValue);
                prop.enumValueIndex = Convert.ToInt32(result);
            }
            EditorGUI.EndProperty();

            return result;
        }

19 View Source File : MySqlDataBase_.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static MySqlParameter CreateParameter(string parameterName, object value, MySqlDbType type)
        {
            object val;
            switch (value)
            {
                case null:
                case DBNull _:
                    val = DBNull.Value;
                    break;
                case Enum _:
                    val = Convert.ToInt32(value);
                    break;
                case bool b:
                    val = b ? (byte)1 : (byte)0;
                    break;
                default:
                    val = value;
                    break;
                case string s:
                    return CreateParameter(parameterName, s);
            }

            return new MySqlParameter(parameterName, type)
            {
                Value = val
            };
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : ADefWebserver

public static int CastNullableIntegerToPossibleNegativeOneInteger(int? intInteger)
        {
            int dtFinalInteger = -1;
            if (intInteger != null)
            {
                dtFinalInteger = Convert.ToInt32(intInteger);
            }

            return dtFinalInteger;
        }

19 View Source File : MySqlTable.dml.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public int SetValue(Expression<Func<TData, Enum>> field, Enum value, string condition,
            params DbParameter[] args)
        {
            return SetValueByCondition(GetPropertyName(field), Convert.ToInt32(value), condition, args);
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static int ToInt(object obj)
        {
            try
            {
                return Convert.ToInt32(obj);
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
                return 0;
            }
        }

19 View Source File : SqlServerTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string FileUpdateSql(string field, object value, IList<DbParameter> parameters)
        {
            field = FieldDictionary[field];
            if (value == null)
                return $"[{field}] = NULL";
            if (value is string || value is DateTime || value is byte[])
            {
                var name = "v_" + field;
                parameters.Add(CreateFieldParameter(name, GetDbType(field), value));
                return $"[{field}] = @{name}";
            }
            if (value is bool b)
                value = b ? 1 : 0;
            else if (value is Enum)
                value = Convert.ToInt32(value);
            return $"[{field}] = {value}";
        }

19 View Source File : AdColonyOptions.cs
License : Apache License 2.0
Project Creator : AdColony

public int GetIntOption(string key)
        {
            return _data.ContainsKey(key) ? Convert.ToInt32(_data[key]) : 0;
        }

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

void IsGameInstalled()
        {
            string lePath = Path.Combine(ProgramFilesx86(), @"Steam\" + gameMode.GetValue("c_exeDirectory") + @"\" + gameMode.GetValue("c_exe") + ".exe");
            TryPath(lePath);
            if (!gameFound)
            {
                RegistryKey steamSubKey = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam\Apps\" + gameMode.GetValue("c_gameID"));
                if (steamSubKey != null)
                {
                    object installed = steamSubKey.GetValue("Installed");
                    if (installed != null && Convert.ToInt32(installed) > 0)
                    {
                        gameFound = true;
                    }
                }
            }
        }

19 View Source File : YearsLabelProvider.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatCursorLabel(IComparable dataValue)
        {
            var i = Convert.ToInt32(dataValue);
            string result = "";
            if (i >= 0 && i < 4)
            {
                result = _xLabels[i];
            }
            else if (i < 0)
            {
                result = _xLabels[0];
            }
            else
            {
                result = _xLabels[3];
            }
            return result;
        }

19 View Source File : DataTable.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public osf.DataColumn get_Column(object p1)
        {
            if (p1 is int)
            {
                return ((DataColumnEx)(M_DataTable.Columns[Convert.ToInt32(p1)])).M_Object;
            }
            else
            {
                return ((DataColumnEx)(M_DataTable.Columns[Convert.ToString(p1)])).M_Object;
            }
        }

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

internal static string TryConvertAttributeValueToString(OrganizationServiceContext context, Dictionary<string, AttributeTypeCode?> attributeTypeCodeDictionary, string enreplacedyName, string attributeName, object value)
		{
			if (context == null || string.IsNullOrWhiteSpace(enreplacedyName) || string.IsNullOrWhiteSpace(attributeName))
			{
				return string.Empty;
			}

			var newValue = string.Empty;
			var attributeTypeCode = attributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;

			if (attributeTypeCode == null)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Unable to recognize the attribute specified.");
				return string.Empty;
			}

			try
			{
				switch (attributeTypeCode)
				{
					case AttributeTypeCode.BigInt:
						newValue = value == null ? string.Empty : Convert.ToInt64(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Boolean:
						newValue = value == null ? string.Empty : Convert.ToBoolean(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Customer:
						if (value is EnreplacedyReference)
						{
							var enreplacedyref = value as EnreplacedyReference;
							newValue = enreplacedyref.Id.ToString();
						}
						break;
					case AttributeTypeCode.DateTime:
						newValue = value == null ? string.Empty : Convert.ToDateTime(value).ToUniversalTime().ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Decimal:
						newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Double:
						newValue = value == null ? string.Empty : Convert.ToDouble(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Integer:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Lookup:
						if (value is EnreplacedyReference)
						{
							var enreplacedyref = value as EnreplacedyReference;
							newValue = enreplacedyref.Id.ToString();
						}
						break;
					case AttributeTypeCode.Memo:
						newValue = value as string;
						break;
					case AttributeTypeCode.Money:
						newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Picklist:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.State:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Status:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.String:
						newValue = value as string;
						break;
					case AttributeTypeCode.Uniqueidentifier:
						if (value is Guid)
						{
							var id = (Guid)value;
							newValue = id.ToString();
						}
						break;
					default:
						ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute type '{0}' is unsupported.", attributeTypeCode));
						break;
				}
			}
			catch (Exception ex)
			{
				WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute specified is expecting a {0}. The value provided is not valid.", attributeTypeCode));
			}
			return newValue;
		}

19 View Source File : ListBoxSelectedIndexCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public override int IndexOf(object value)
        {
            return M_ListBoxSelectedIndexCollection.IndexOf(Convert.ToInt32(value));
        }

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

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

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

19 View Source File : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public DomainUser[] GetUsers()
		{
			List<DomainUser> users = new List<DomainUser>();
			using (DirectoryEntry entry = new DirectoryEntry("WinNT://" + Environment.MachineName))
			{
				foreach (DirectoryEntry child in entry.Children)
				{
					if (child.SchemaClreplacedName == "User")
					{
						int flag = Convert.ToInt32(child.Properties["UserFlags"].Value);
						if ((flag & util.UF_ACCOUNTDISABLE) == 0)
						{
							users.Add(new DomainUser()
							{
								UserName = child.Name,
								FullName = Convert.ToString(child.Properties["FullName"].Value),
								Description = Convert.ToString(child.Properties["Description"].Value.ToString()),
								Domain = Environment.MachineName
							});
						}
						//foreach (var pn in child.Properties.PropertyNames)
						//{
						//    System.Diagnostics.Debug.WriteLine(pn.ToString());
						//}
					}
				}
			}
			return users.ToArray();
		}

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

private static object Deserialize(object value)
		{
			// convert from surrogate type to actual type

			if (value is long)
			{
				// for object references, the default json numeric type is long but the end result should be int

				return Convert.ToInt32(value);
			}

			if (value is JsonGuid)
			{
				return new Guid(((JsonGuid)value).Value);
			}

			if (value is JsonEnreplacedyFilters)
			{
				return (EnreplacedyFilters)((JsonEnreplacedyFilters)value).Value;
			}

			if (value is JsonList<KeyValuePair<Relationship, QueryBase>>)
			{
				var dictionary = new RelationshipQueryCollection();
				dictionary.AddRange(((JsonList<KeyValuePair<Relationship, QueryBase>>)value).Value);
				return dictionary;
			}

			return value;
		}

19 View Source File : PositiveInt32ValidationRule.cs
License : MIT License
Project Creator : Actipro

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
			try {
				int i = Convert.ToInt32(value);
				if (i >= 0)
					return new ValidationResult(true, null);
				else
					return new ValidationResult(false, "Value is not positive");
			}
			catch (Exception) {
				return new ValidationResult(false, string.Format("{0} is not a valid value for Int32.", value));
			}
		}

19 View Source File : PInvokeHooks.cs
License : zlib License
Project Creator : 0x0ade

public static IntPtr CallHookChain(HookType hookType, IntPtr wParam, IntPtr lParam, ref Message lParamMsg) {
            List<Delegate> hooks = Hooks[hookType];
            if (hooks.Count == 0)
                return IntPtr.Zero;
            CurrentHookChain.Value = hooks;
            for (int i = 0; i < hooks.Count; i++) {
                Delegate hook = hooks[i];
                // Find the first non-null (still registered) hook.
                if (hook == null)
                    continue;
                CurrentHookIndex.Value = i;
                // HookProc expects HC_ACTION (0; take action) or < 0 (preplaced to next hook).
                object[] args = { 0, wParam, lParamMsg };
                object result = hook.DynamicInvoke(args);
                lParamMsg = (Message) args[2];
                return result != null ? (IntPtr) Convert.ToInt32(result) : IntPtr.Zero;
            }
            return IntPtr.Zero;
        }

19 View Source File : JcApiHelper_InitParam.cs
License : MIT License
Project Creator : 279328316

private static ParamModel GetParam(FieldInfo fi, int index = 0)
        {
            PTypeModel ptype = GetPType(fi.FieldType);
            int? value = null;
            if (fi.FieldType.IsEnum)
            {
                try
                {
                    value = Convert.ToInt32(Enum.Parse(fi.FieldType, fi.Name));
                }
                catch
                {   //如转换失败,忽略不做处理
                }
            }

            string fiId = null;
            if (fi.DeclaringType != null)
            {
                fiId = $"F:{fi.DeclaringType.ToString()}.{fi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = fi.Name,
                Id = fiId,
                PType = ptype,
                ParamValue = value,
                CustomAttrList = fi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };

            if (fi.CustomAttributes.Count() > 0)
            {

            }
            return param;
        }

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

private bool CheckField(PlayerEnreplacedy player, string field, string strValue, string strRelation)
        {
            try
            {
                var relations = GetRelations(strRelation);// 1 大于,0 等于 ,-1 小于

                var fieldProp = GetFieldPropertyInfo(player, field);
                if (fieldProp == null)
                {
                    return false;
                }

                var objectValue = fieldProp.GetValue(player);
                var typeCode = Type.GetTypeCode(fieldProp.GetType());
                switch (typeCode)
                {
                    case TypeCode.Int32:
                        return relations.Contains(Convert.ToInt32(strValue).CompareTo(Convert.ToInt32(objectValue)));

                    case TypeCode.Int64:
                        return relations.Contains(Convert.ToInt64(strValue).CompareTo(Convert.ToInt64(objectValue)));

                    case TypeCode.Decimal:
                        return relations.Contains(Convert.ToDecimal(strValue).CompareTo(Convert.ToDecimal(objectValue)));

                    case TypeCode.Double:
                        return relations.Contains(Convert.ToDouble(strValue).CompareTo(Convert.ToDouble(objectValue)));

                    case TypeCode.Boolean:
                        return relations.Contains(Convert.ToBoolean(strValue).CompareTo(Convert.ToBoolean(objectValue)));

                    case TypeCode.DateTime:
                        return relations.Contains(Convert.ToDateTime(strValue).CompareTo(Convert.ToDateTime(objectValue)));

                    case TypeCode.String:
                        return relations.Contains(strValue.CompareTo(objectValue));

                    default:
                        throw new Exception($"不支持的数据类型: {typeCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"CheckField Exception:{ex}");
                return false;
            }
        }

19 View Source File : AdColonyUserMetadata.cs
License : Apache License 2.0
Project Creator : AdColony

[Obsolete("GetIntMetadata is deprecated")]
        public int GetIntMetadata(string key)
        {
            return _data.ContainsKey(key) ? Convert.ToInt32(_data[key]) : 0;
        }

19 View Source File : ConditionItem.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public string AddParameter(object value)
        {
            if (value is Enum)
            {
                value = Convert.ToInt32(value);
            }
            var name = string.Format("p_{0}", _parameters.Count + 1);
            _parameters.Add(name, SqlServerDataBase.CreateParameter(name, value));
            return name;
        }

See More Examples