Here are the examples of the csharp api System.Convert.ToString(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
706 Examples
19
View Source File : DBHelperMySQL.cs
License : Apache License 2.0
Project Creator : 0nise
License : Apache License 2.0
Project Creator : 0nise
public static string Top30Money()
{
// 未提取存款
Hashtable userMoney = new Hashtable();
Hashtable userInfo = new Hashtable();
// 已经提取存款
Hashtable userBlank = new Hashtable();
// 财富榜前20
Hashtable userData = new Hashtable();
string resultMsg = "";
MySqlConnection connection = null;
try
{
connection = ConnectionPool.getPool().getConnection();
// 链接为null就执行等待
while (connection == null)
{
}
string sql = "SELECT bbs_nick_name,user_money,user_qq FROM ichunqiu_blank";
using (MySqlCommand cmd = new MySqlCommand(sql,connection))
{
using (MySqlDataReader myDataReader = cmd.ExecuteReader())
{
while (myDataReader.Read() == true)
{
userMoney.Add(myDataReader["bbs_nick_name"], myDataReader["user_money"]);
userInfo.Add(myDataReader["user_qq"], myDataReader["bbs_nick_name"]);
}
}
}
// 提取历史提取总金额
userBlank = getAllHistorySumMoney(userInfo);
// ArrayList allMoney = new ArrayList();
List<Decimal> allMoney = new List<decimal>();
foreach (DictionaryEntry item in userMoney)
{
decimal blance = Convert.ToDecimal(item.Value);
decimal historyBlance = Convert.ToDecimal(userBlank[item.Key]);
userData.Add(item.Key, historyBlance + blance);
allMoney.Add(historyBlance + blance);
}
/*
List<decimal> allMoney = new List<decimal>();
foreach (string item in userData.Values)
{
allMoney.Add(Convert.ToDecimal(item));
}*/
// 降序
allMoney.Sort((x, y) => -x.CompareTo(y));
int i = 0;
foreach (decimal money in allMoney)
{
foreach (DictionaryEntry item in userData)
{
if (Convert.ToDecimal(item.Value) == money)
{
resultMsg += string.Format("NO【{0}】:{1}身价{2},已提取存款{3},未提取存款{4}\n", (i + 1).ToString(), Convert.ToString(item.Key), Convert.ToString(money), Convert.ToString(userBlank[item.Key]), Convert.ToString(userMoney[item.Key]));
// 删除用户避免出现重复的情况
userData.Remove(item.Key);
break;
}
}
i++;
if (i > 29)
{
break;
}
}
}
catch (Exception)
{
throw;
}
finally {
if (connection != null) {
connection.Close();
}
// 关闭数据库链接
ConnectionPool.getPool().closeConnection(connection);
}
return resultMsg;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void bgwScan_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
ShowForm();
string result = Convert.ToString(e.UserState);
if (Utils.IsNullOrEmpty(result))
{
UI.ShowWarning(UIRes.I18N("NoValidQRcodeFound"));
}
else
{
int ret = MainFormHandler.Instance.AddBatchServers(config, result);
if (ret > 0)
{
RefreshServers();
UI.Show(UIRes.I18N("SuccessfullyImportedServerViaScan"));
}
}
}
19
View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
public static void HandleException(Exception ex, int index, IDataReader reader, object value)
{
Exception toThrow;
try
{
string name = "(n/a)", formattedValue = "(n/a)";
if (reader != null && index >= 0 && index < reader.FieldCount)
{
name = reader.GetName(index);
try
{
if (value == null || value is DBNull)
{
formattedValue = "<null>";
}
else
{
formattedValue = Convert.ToString(value) + " - " + value.GetType().Name;
}
}
catch (Exception valEx)
{
formattedValue = valEx.Message;
}
}
toThrow = new DataException($"Error parsing column {index} ({name}={formattedValue})", ex);
}
catch
{ // throw the **original** exception, wrapped as DataException
toThrow = new DataException(ex.Message, ex);
}
throw toThrow;
}
19
View Source File : RepositoryBase.cs
License : MIT License
Project Creator : abelperezok
License : MIT License
Project Creator : abelperezok
protected string PKValue(object id)
{
return string.Format(PKPattern, Convert.ToString(id));
}
19
View Source File : RepositoryBase.cs
License : MIT License
Project Creator : abelperezok
License : MIT License
Project Creator : abelperezok
protected string SKValue(object id)
{
return string.Format(SKPattern, Convert.ToString(id));
}
19
View Source File : RepositoryBase.cs
License : MIT License
Project Creator : abelperezok
License : MIT License
Project Creator : abelperezok
protected string GSI1Value(object id)
{
return string.Format(GSI1Pattern, Convert.ToString(id));
}
19
View Source File : ResourceProperties.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static Object ToObject(JToken token)
{
switch (token.Type)
{
case JTokenType.Boolean:
return Convert.ToString((Boolean)token);
case JTokenType.Date:
return Convert.ToString((DateTime)token);
case JTokenType.Float:
return Convert.ToString((Single)token);
case JTokenType.Guid:
return Convert.ToString((Guid)token);
case JTokenType.Integer:
return Convert.ToString((Int32)token);
case JTokenType.TimeSpan:
return Convert.ToString((TimeSpan)token);
case JTokenType.Uri:
return Convert.ToString((Uri)token);
case JTokenType.String:
return (String)token;
case JTokenType.Array:
var array = token as JArray;
return array.Select(x => ToObject(x)).ToList();
case JTokenType.Object:
return ToDictionary(token as JObject);
}
return null;
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private void toggleContextualTabGroupCommand_Execute(object sender, ExecutedRoutedEventArgs e) {
RibbonControls.ContextualTabGroup contextualTabGroup = null;
ICheckableCommandParameter parameter = e.Parameter as ICheckableCommandParameter;
if (parameter != null)
contextualTabGroup = ribbon.ContextualTabGroups[Convert.ToString(parameter.Tag)];
else if (e.Parameter is string)
contextualTabGroup = ribbon.ContextualTabGroups[Convert.ToString(e.Parameter)];
if (contextualTabGroup != null) {
contextualTabGroup.IsActive = !contextualTabGroup.IsActive;
// If making active, select the first tab in it
// if ((contextualTabGroup.IsActive) && (contextualTabGroup.Items.Count > 0))
// ribbon.SelectedTab = (RibbonControls.Tab)contextualTabGroup.Items[0];
}
}
19
View Source File : HookInterceptor.cs
License : MIT License
Project Creator : AdamCarballo
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 : SearchFilterOptionFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static object SearchFilterOptions(object input)
{
var inputToString = Convert.ToString(input);
if (string.IsNullOrEmpty(inputToString))
{
return null;
}
var splitedOptions = Html.SettingExtensions.SplitSearchFilterOptions(inputToString);
return splitedOptions.Any() ? splitedOptions.Select(parsedOption => new SearchFilterOptionDrop(Extensions.LocalizeRecordTypeName(parsedOption.Value.Split(',')[0]), parsedOption.Value)) : null;
}
19
View Source File : TypeFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string String(object input)
{
return Convert.ToString(input);
}
19
View Source File : AduNumericUpDown.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private void MoveCursorToEnd()
{
this.SelectionStart = Convert.ToString(this.Value).Length;
}
19
View Source File : RatingBar.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private static object ValueCoerce(DependencyObject d, object baseValue)
{
RatingBar ratingBar = d as RatingBar;
double value = 0.0;
if (double.TryParse(Convert.ToString(baseValue), out value))
{
if (value < ratingBar.Minimum)
{
value = 0;
}
else if (value > ratingBar.Maximum)
{
value = ratingBar.Maximum;
}
}
return value;
}
19
View Source File : StringIsEmptyConverter.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return string.IsNullOrEmpty(System.Convert.ToString(value));
}
19
View Source File : ListViewItemCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public new osf.ListViewItem Add(object item)
{
if (item is ListViewItem)
{
M_ListViewItemCollection.Add((ListViewItemEx)((ListViewItem)item).M_ListViewItem);
System.Windows.Forms.Application.DoEvents();
return (ListViewItem)item;
}
ListViewItem ListViewItem1 = new ListViewItem("", -1);
ListViewItem1.Text = Convert.ToString(item);
M_ListViewItemCollection.Add((ListViewItemEx)ListViewItem1.M_ListViewItem);
System.Windows.Forms.Application.DoEvents();
return (ListViewItem)ListViewItem1;
}
19
View Source File : ListViewColumnHeaderCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public new osf.ColumnHeader Add(object column = null)
{
if (column is ColumnHeader)
{
M_ColumnHeaderCollection.Add((ColumnHeaderEx)((ColumnHeader)column).M_ColumnHeader);
System.Windows.Forms.Application.DoEvents();
return (ColumnHeader)column;
}
ColumnHeader ColumnHeader1 = new ColumnHeader();
if (column is string)
{
ColumnHeader1.Text = Convert.ToString(column);
}
M_ColumnHeaderCollection.Add((ColumnHeaderEx)ColumnHeader1.M_ColumnHeader);
System.Windows.Forms.Application.DoEvents();
return ColumnHeader1;
}
19
View Source File : ListViewSubItemCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public new osf.ListViewSubItem Add(object item)
{
if (item is ListViewSubItem)
{
M_ListViewSubItemCollection.Add((((ListViewSubItem)item).M_ListViewSubItem));
System.Windows.Forms.Application.DoEvents();
return (ListViewSubItem)item;
}
ListViewSubItem ListViewSubItem1 = new ListViewSubItem("");
ListViewSubItem1.Text = Convert.ToString(item);
M_ListViewSubItemCollection.Add(ListViewSubItem1.M_ListViewSubItem);
System.Windows.Forms.Application.DoEvents();
return (ListViewSubItem)ListViewSubItem1;
}
19
View Source File : TreeNodeCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public new osf.TreeNode Add(object p1)
{
if (p1 is TreeNode)
{
M_TreeNodeCollection.Add((System.Windows.Forms.TreeNode)((TreeNode)p1).M_TreeNode);
System.Windows.Forms.Application.DoEvents();
return (TreeNode)p1;
}
TreeNode TreeNode1 = new TreeNode();
TreeNode1.Text = Convert.ToString(p1);
M_TreeNodeCollection.Add((System.Windows.Forms.TreeNode)((TreeNode)TreeNode1).M_TreeNode);
System.Windows.Forms.Application.DoEvents();
return TreeNode1;
}
19
View Source File : DataTable.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
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 : DataTableCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public void Remove(object p1)
{
if (p1 is DataTable)
{
M_DataTableCollection.Remove(((DataTable)p1).M_DataTable);
}
else
{
M_DataTableCollection.Remove(Convert.ToString(p1));
}
System.Windows.Forms.Application.DoEvents();
}
19
View Source File : TabPageCollection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public osf.TabPage Insert(int index, object page)
{
if (page is TabPage)
{
M_TabPageCollection.Insert(index, ((dynamic)page).M_TabPage);
System.Windows.Forms.Application.DoEvents();
return (TabPage)page;
}
if (!(page is string))
{
return null;
}
TabPage TabPage1 = new TabPage((string)null);
TabPage1.Text = Convert.ToString(page);
M_TabPageCollection.Insert(index, (System.Windows.Forms.TabPage)TabPage1.M_TabPage);
return TabPage1;
}
19
View Source File : Collection.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
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 : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static string Serilize(object val)
{
string result = null;
if (val != null)
{
Type type = val.GetType();
if (type == typeof(string[]))
{
result = string.Join(",", val as string[]);
}
else
{
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
if (fields.Length > 0)
{
//Array.Sort(fields);
string[] vals = Array.ConvertAll(fields,
f => System.Convert.ToString(f.GetValue(val))
);
result = string.Join(":", vals);
}
else
{
result = val.ToString();
}
}
}
return result;
}
19
View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static string ToXml(object obj, string rootElement = null)
{
System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
doc.LoadXml(string.Format(@"<{0}></{0}>", obj.GetType().Name));
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var p in props)
{
var node = doc.CreateElement(p.Name);
node.InnerText = Convert.ToString(p.GetValue(obj, null));
doc.DoreplacedentElement.AppendChild(node);
}
return doc.OuterXml;
}
19
View Source File : ApplicationAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public ApplicationInfo[] GetInstalledApplications()
{
List<ApplicationInfo> apps = new List<ApplicationInfo>();
try
{
string wql = @"SELECT * FROM Win32_Product WHERE InstallLocation IS NOT NULL";
using (var searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
{
foreach (var mo in searcher.Get())
{
var app = new ApplicationInfo()
{
Name = Convert.ToString(mo["Name"]),
Version = Convert.ToString(mo["Version"]),
Description = Convert.ToString(mo["Description"]),
Location = Convert.ToString(mo["InstallLocation"]),
InstallDate = DateTime.ParseExact(Convert.ToString(mo["InstallDate"]),"yyyyMMdd", null)
};
apps.Add(app);
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return apps.ToArray();
}
19
View Source File : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal
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 : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public LocalGroup[] GetGroups()
{
List<LocalGroup> groups = new List<LocalGroup>();
using (DirectoryEntry entry = new DirectoryEntry("WinNT://" + Environment.MachineName))
{
foreach (DirectoryEntry child in entry.Children)
{
if (child.SchemaClreplacedName == "Group")
{
groups.Add(new LocalGroup()
{
Name = child.Name,
Description = Convert.ToString(child.Properties["Description"].Value)
});
}
}
}
return groups.ToArray();
}
19
View Source File : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
[Obsolete]
public string[] GetUserGroupsByWMI(string userName)
{
List<string> groups = new List<string>();
try
{
Regex regGroupName = new Regex(",Name=\"(?<group>.+)\"");
string wql = string.Format("SELECT * FROM Win32_GroupUser WHERE PartComponent=\"Win32_UserAccount.Domain='{0}',Name='{1}'\"", Environment.UserDomainName, userName);
using (var searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
{
foreach (var mo in searcher.Get())
{
string val = Convert.ToString(mo["GroupComponent"]);
var mc = regGroupName.Match(val);
if (mc.Success)
groups.Add(mc.Groups["group"].Value);
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return groups.ToArray();
}
19
View Source File : ChangeType.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
public static T ChangeType<T>(this object @this, T defaultValue = default(T))
{
try
{
if (@this == null)
{
return defaultValue;
}
if (@this is T)
{
return (T)@this;
}
Type conversionType = typeof(T);
// Nullables
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
conversionType = (new NullableConverter(conversionType)).UnderlyingType;
}
if (conversionType.IsEnum)
{
var enumStr = @this.ToString();
// Clean the input string before attempting to convert.
if (!string.IsNullOrWhiteSpace(enumStr))
{
enumStr = InvalidEnumValueChars.Replace(enumStr, string.Empty);
}
return (T)Enum.Parse(conversionType, enumStr, ignoreCase: true);
}
// String
if (conversionType.Equals(typeof(string)))
{
return (T)((object)Convert.ToString(@this));
}
// Guid
if (conversionType.Equals(typeof(Guid)))
{
var input = @this.ToString();
if (string.IsNullOrWhiteSpace(input))
{
return defaultValue;
}
Guid output;
if (Guid.TryParse(input, out output))
{
return (T)((object)output);
}
}
// Bool
if (conversionType.Equals(typeof(bool)))
{
return (T)((object)Convert.ToBoolean(@this));
}
// Datetime
if (conversionType.Equals(typeof(DateTime)))
{
return (T)((object)DateTime.Parse(@this.ToString(), CultureInfo.CurrentCulture));
}
// TimeSpan
if (conversionType.Equals(typeof(TimeSpan)))
{
return (T)((object)TimeSpan.Parse(@this.ToString(), CultureInfo.CurrentCulture));
}
// General
return (T)Convert.ChangeType(@this, conversionType);
}
catch
{
return defaultValue;
}
}
19
View Source File : NumericValidationRule.cs
License : Apache License 2.0
Project Creator : AKruimink
License : Apache License 2.0
Project Creator : AKruimink
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var strValue = Convert.ToString(value);
if (string.IsNullOrEmpty(strValue))
{
if (AllowNull)
{
return new ValidationResult(true, null);
}
return new ValidationResult(false, $"Value cannot be converted to string");
}
var canConvert = (ValidationType?.Name) switch
{
nameof(Boolean) => bool.TryParse(strValue, out var boolValue),
nameof(Double) => double.TryParse(strValue, out var doubleValue),
nameof(Int32) => int.TryParse(strValue, out var intValue),
nameof(Int64) => long.TryParse(strValue, out var longValue),
_ => throw new InvalidCastException($"{ValidationType?.Name} is not a supported type"),
};
19
View Source File : IbContractStorageUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void SaveSecFromTable()
{
if (SecToSubscrible == null ||
SecToSubscrible.Count == 0)
{
return;
}
for (int i = 0; i < _grid.Rows.Count; i++)
{
SecurityIb security = SecToSubscrible[i];
security.Symbol = Convert.ToString(_grid.Rows[i].Cells[0].Value);
security.Exchange = Convert.ToString(_grid.Rows[i].Cells[1].Value);
security.SecType = Convert.ToString(_grid.Rows[i].Cells[2].Value);
security.LocalSymbol = Convert.ToString(_grid.Rows[i].Cells[3].Value);
security.PrimaryExch = Convert.ToString(_grid.Rows[i].Cells[4].Value);
security.Currency = Convert.ToString(_grid.Rows[i].Cells[5].Value);
security.CreateMarketDepthFromTrades = Convert.ToBoolean(_grid.Rows[i].Cells[6].Value);
}
}
19
View Source File : TradeValues.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static TradeValues CreateFromJArray(JArray tradeValueTokens)
{
return new TradeValues
{
Price = Convert.ToDecimal(tradeValueTokens[0]),
Volume = Convert.ToDecimal(tradeValueTokens[1]),
Time = Convert.ToDecimal(tradeValueTokens[2]),
Side = Convert.ToString(tradeValueTokens[3]),
OrderType = Convert.ToString(tradeValueTokens[4]),
Misc = Convert.ToString(tradeValueTokens[5]),
};
}
19
View Source File : QuikDde.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private decimal ToDecimal(object str)
{
decimal result;
decimal.TryParse(Convert.ToString(str), NumberStyles.Any, new CultureInfo("ru-RU"), out result);
if (result == 0)
{
decimal.TryParse(Convert.ToString(str), NumberStyles.Any, new CultureInfo("en-US"), out result);
}
return result;
}
19
View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : Altevir
License : MIT License
Project Creator : Altevir
public static string DefaultString(this object value)
{
if (string.IsNullOrEmpty(Convert.ToString(value)))
{
return string.Empty;
}
return Convert.ToString(value).Trim();
}
19
View Source File : ApiClient.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public string ParameterToString(object obj)
{
if (obj is DateTime)
{
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString(Configuration.DateTimeFormat);
}
else if (obj is DateTimeOffset)
{
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTimeOffset)obj).ToString(Configuration.DateTimeFormat);
}
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
{
flattenedString.Append(",");
}
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else
{
return Convert.ToString(obj);
}
}
19
View Source File : ModConfig.cs
License : MIT License
Project Creator : amazingalek
License : MIT License
Project Creator : amazingalek
private T ConvertToEnum<T>(object value)
{
if (value is float || value is double)
{
var floatValue = Convert.ToDouble(value);
return (T)(object)(long)Math.Round(floatValue);
}
if (value is int || value is long)
{
return (T)value;
}
var valueString = Convert.ToString(value);
try
{
return (T)Enum.Parse(typeof(T), valueString, true);
}
catch (ArgumentException ex)
{
Debug.LogError($"Can't convert {valueString} to enum {typeof(T)}: {ex.Message}");
return default;
}
}
19
View Source File : ModData.cs
License : MIT License
Project Creator : amazingalek
License : MIT License
Project Creator : amazingalek
private bool UpdateSelector(string key, object userSetting, JObject modSetting)
{
var options = modSetting["options"].ToObject<List<string>>();
var userString = userSetting is JObject objectValue ? (string)objectValue["value"] : Convert.ToString(userSetting);
Config.Settings[key] = modSetting;
var isInOptions = options.Contains(userString);
if (isInOptions)
{
Config.SetSettingsValue(key, userString);
}
return isInOptions;
}
19
View Source File : MainForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko
License : GNU General Public License v2.0
Project Creator : AmanoTooko
private void DateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
if (!e.Alt && !e.Shift && e.Control && e.KeyCode == Keys.V)
{
var targetTime = Convert.ToString(Clipboard.GetDataObject().GetData(DataFormats.Text));
try
{
var dt = DateTime.ParseExact(targetTime, "HH:mm:ss", CultureInfo.CurrentCulture);
dtpSyncTime.Value = dt;
}
catch (Exception)
{
}
}
else if (!e.Alt && !e.Shift && e.Control && e.KeyCode == Keys.C)
{
var targetTime = dtpSyncTime.Value.ToString("HH:mm:ss");
Clipboard.SetDataObject(targetTime);
}
}
19
View Source File : SettingsKey.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public string GetString(string strName, string strDefault)
{
return Convert.ToString(m_Key.GetValue(strName, strDefault));
}
19
View Source File : PriorityToColor.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var priority = System.Convert.ToString(value);
switch (priority)
{
case "VERY HIGH":
return new SolidColorBrush(Colors.DodgerBlue);
case "HIGH":
return new SolidColorBrush(Colors.RoyalBlue);
case "COMMON":
return new SolidColorBrush(Colors.MediumBlue);
case "QUITE LOW":
return new SolidColorBrush(Colors.Gray);
case "LOW":
return new SolidColorBrush(Colors.Gray);
default:
return new SolidColorBrush(Colors.Gray);
}
}
19
View Source File : ExcelWorksheet.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
private void UpdateRowCellData(StreamWriter sw)
{
ExcelStyleCollection<ExcelXfs> cellXfs = _package.Workbook.Styles.CellXfs;
int row = -1;
StringBuilder sbXml = new StringBuilder();
var ss = _package.Workbook._sharedStrings;
var styles = _package.Workbook.Styles;
var cache = new StringBuilder();
cache.Append("<sheetData>");
FixSharedFormulas(); //Fixes Issue #32
columnStyles = new Dictionary<int, int>();
var cse = new CellsStoreEnumerator<ExcelCoreValue>(_values, 1, 0, ExcelPackage.MaxRows, ExcelPackage.MaxColumns);
while (cse.Next())
{
if (cse.Column > 0)
{
var val = cse.Value;
//int styleID = cellXfs[styles.GetStyleId(this, cse.Row, cse.Column)].newID;
int styleID = cellXfs[(val._styleId == 0 ? GetStyleIdDefaultWithMemo(cse.Row, cse.Column) : val._styleId)].newID;
//Add the row element if it's a new row
if (cse.Row != row)
{
WriteRow(cache, cellXfs, row, cse.Row);
row = cse.Row;
}
object v = val._value;
object formula = _formulas.GetValue(cse.Row, cse.Column);
if (formula is int)
{
int sfId = (int)formula;
var f = _sharedFormulas[(int)sfId];
if (f.Address.IndexOf(':') > 0)
{
if (f.StartCol == cse.Column && f.StartRow == cse.Row)
{
if (f.IsArray)
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{5}><f ref=\"{2}\" t=\"array\">{3}</f>{4}</c>", cse.CellAddress, styleID < 0 ? 0 : styleID, f.Address, ConvertUtil.ExcelEscapeString(f.Formula), GetFormulaValue(v), GetCellType(v, true));
}
else
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{6}><f ref=\"{2}\" t=\"shared\" si=\"{3}\">{4}</f>{5}</c>", cse.CellAddress, styleID < 0 ? 0 : styleID, f.Address, sfId, ConvertUtil.ExcelEscapeString(f.Formula), GetFormulaValue(v), GetCellType(v, true));
}
}
else if (f.IsArray)
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"/>", cse.CellAddress, styleID < 0 ? 0 : styleID);
}
else
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{4}><f t=\"shared\" si=\"{2}\"/>{3}</c>", cse.CellAddress, styleID < 0 ? 0 : styleID, sfId, GetFormulaValue(v), GetCellType(v, true));
}
}
else
{
// We can also have a single cell array formula
if (f.IsArray)
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{5}><f ref=\"{2}\" t=\"array\">{3}</f>{4}</c>", cse.CellAddress, styleID < 0 ? 0 : styleID, string.Format("{0}:{1}", f.Address, f.Address), ConvertUtil.ExcelEscapeString(f.Formula), GetFormulaValue(v), GetCellType(v, true));
}
else
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{2}>", f.Address, styleID < 0 ? 0 : styleID, GetCellType(v, true));
cache.AppendFormat("<f>{0}</f>{1}</c>", ConvertUtil.ExcelEscapeString(f.Formula), GetFormulaValue(v));
}
}
}
else if (formula != null && formula.ToString() != "")
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{2}>", cse.CellAddress, styleID < 0 ? 0 : styleID, GetCellType(v, true));
cache.AppendFormat("<f>{0}</f>{1}</c>", ConvertUtil.ExcelEscapeString(formula.ToString()), GetFormulaValue(v));
}
else
{
if (v == null && styleID > 0)
{
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"/>", cse.CellAddress, styleID < 0 ? 0 : styleID);
}
else if (v != null)
{
// Fix for issue 15460
var enumerableResult = v as System.Collections.IEnumerable;
if (enumerableResult != null && !(v is string))
{
var enumerator = enumerableResult.GetEnumerator();
if (enumerator.MoveNext() && enumerator.Current != null)
v = enumerator.Current;
else
v = string.Empty;
}
if ((TypeCompat.IsPrimitive(v) || v is double || v is decimal || v is DateTime || v is TimeSpan))
{
//string sv = GetValueForXml(v);
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\"{2}>", cse.CellAddress, styleID < 0 ? 0 : styleID, GetCellType(v));
cache.AppendFormat("{0}</c>", GetFormulaValue(v));
}
else
{
var vString = Convert.ToString(v);
int ix;
if (!ss.ContainsKey(vString))
{
ix = ss.Count;
ss.Add(vString, new ExcelWorkbook.SharedStringItem() { isRichText = _flags.GetFlagValue(cse.Row, cse.Column, CellFlags.RichText), pos = ix });
}
else
{
ix = ss[vString].pos;
}
cache.AppendFormat("<c r=\"{0}\" s=\"{1}\" t=\"s\">", cse.CellAddress, styleID < 0 ? 0 : styleID);
cache.AppendFormat("<v>{0}</v></c>", ix);
}
}
}
////Update hyperlinks.
//if (cell.Hyperlink != null)
//{
// _hyperLinkCells.Add(cell.CellID);
//}
}
else //ExcelRow
{
//int newRow=((ExcelRow)cse.Value).Row;
WriteRow(cache, cellXfs, row, cse.Row);
row = cse.Row;
}
if (cache.Length > 0x600000)
{
sw.Write(cache.ToString());
sw.Flush();
cache.Length = 0;
}
}
columnStyles = null;
if (row != -1) cache.Append("</row>");
cache.Append("</sheetData>");
sw.Write(cache.ToString());
sw.Flush();
}
19
View Source File : MockDbDataReader.cs
License : MIT License
Project Creator : Apps72
License : MIT License
Project Creator : Apps72
public override Guid GetGuid(int ordinal)
{
object value = GetValue(ordinal);
if (value.GetType() == typeof(string))
{
return new Guid(Convert.ToString(value));
}
else
{
return (Guid)value;
}
}
19
View Source File : MssqlSchema.cs
License : MIT License
Project Creator : aquilahkj
License : MIT License
Project Creator : aquilahkj
public List<Table> GetTables()
{
const string tableCommandText = @"SELECT A.name as TableName,A.object_id as TableCode, C.value as CommentText FROM sys.tables A left JOIN sys.extended_properties C ON C.major_id = A.object_id and minor_id=0 WHERE A.name = N'{0}'";
const string columnCommandText = @"
with indexcte as(
select
ic.column_id,
ic.index_column_id,
ic.object_id
from
{0}.sys.indexes idx
inner join {0}.sys.index_columns ic on idx.index_id = ic.index_id
and idx.object_id = ic.object_id
where
idx.object_id = object_id('{0}.dbo.{1}')
and idx.is_primary_key = 1
) select
colm.column_id ColumnId,
cast(
case
when indexcte.column_id is null then
0
else
1
end as bit
) ColumnKey,
cast(colm.max_length as int) bytelength,
(
case
when systype.name = 'nvarchar'
and colm.max_length > 0 then
colm.max_length / 2
when systype.name = 'nchar'
and colm.max_length > 0 then
colm.max_length / 2
when systype.name = 'ntext'
and colm.max_length > 0 then
colm.max_length / 2
else
colm.max_length
end
) MaxLength,
colm.name ColumnName,
systype.name DataType,
colm.is_idenreplacedy IsIdenreplacedy,
colm.is_nullable AllowNull,
cast(colm.precision as int) Precision,
cast(colm.scale as int) Scale,
prop.value ColumnComment
from
{0}.sys.columns colm
inner join {0}.sys.types systype on colm.system_type_id = systype.system_type_id
and colm.user_type_id = systype.user_type_id
left join {0}.sys.extended_properties prop on colm.object_id = prop.major_id
and colm.column_id = prop.minor_id
left join indexcte on colm.column_id = indexcte.column_id
and colm.object_id = indexcte.object_id
where
colm.object_id = object_id('{0}.dbo.{1}')
order by
colm.column_id";
List<Table> tables = new List<Table>();
foreach (TableNameSet tableNameSet in DbSetting.GetTables()) {
string tableCommandStr = String.Format(tableCommandText, tableNameSet.TableName);
SqlConnection tableConn = new SqlConnection(_connectionString);
tableConn.Open();
SqlCommand tableCommand = new SqlCommand(tableCommandStr, tableConn);
SqlDataAdapter tableAd = new SqlDataAdapter(tableCommand);
DataSet tableDs = new DataSet();
tableAd.Fill(tableDs);
DataTable tableColumns = tableDs.Tables[0];
tableConn.Close();
if (tableColumns.Rows.Count == 0) {
continue;
}
string tableComment = Convert.ToString(tableColumns.Rows[0]["CommentText"]);
string tableCode = Convert.ToString(tableColumns.Rows[0]["TableCode"]);
string columnCommandStr = String.Format(columnCommandText, this._dataBaseName, tableNameSet.TableName);
SqlConnection columnConn = new SqlConnection(_connectionString);
columnConn.Open();
SqlCommand columnCommand = new SqlCommand(columnCommandStr, tableConn);
SqlDataAdapter columnAd = new SqlDataAdapter(columnCommand);
DataSet columnDs = new DataSet();
columnAd.Fill(columnDs);
DataTable columnColumns = columnDs.Tables[0];
tableConn.Close();
Table table = new Table(tableNameSet.AliasName, tableNameSet.TableName);
if (String.IsNullOrEmpty(tableComment)) {
tableComment = tableNameSet.TableName;
}
table.CommentText = tableComment;
foreach (DataRow item in columnColumns.Rows) {
Column column = CreateColumn(table, item);
if (column != null) {
table.SetColumn(column);
}
}
tables.Add(table);
}
return tables;
}
19
View Source File : PostgreSchema.cs
License : MIT License
Project Creator : aquilahkj
License : MIT License
Project Creator : aquilahkj
public List<Table> GetTables()
{
const string tableCommandText = @"select relname as ""TableName"",relfilenode as ""TableCode"",col_description(relfilenode,0) as ""CommentText"" from pg_clreplaced where relname = '{0}'";
const string columnCommandText = @"select
a.ordinal_position as ""ColumnId"",
(case when b.constraint_type='PRIMARY KEY' then 1 else 0 end)::BOOLEAN as ""ColumnKey"",
a.character_maximum_length as ""MaxLength"",
a.column_name as ""ColumnName"",
a.udt_name as ""DataType"",
(case when a.column_default like 'nextval%' then 1 else 0 end)::BOOLEAN as ""IsIdenreplacedy"",
(case when a.is_nullable='YES' then 1 else 0 end)::BOOLEAN as ""AllowNull"",
a.numeric_precision as ""Precision"",
a.numeric_scale as ""Scale"",
a.column_comment as ""ColumnComment""
from
(
select table_name,
ordinal_position,
column_name,
column_default,
is_nullable,
udt_name,
character_maximum_length,
numeric_precision,
numeric_scale,
col_description({2},ordinal_position) as column_comment
from information_schema.columns
where table_name='{1}' and table_catalog='{0}'
) as a
left join
(
SELECT kcu.table_name,kcu.column_name,tc.constraint_type
FROM information_schema.key_column_usage kcu
JOIN information_schema.table_constraints tc
ON kcu.constraint_name=tc.constraint_name
where kcu.table_name='{1}' and kcu.table_catalog='{0}'
and tc.table_name='{1}' and tc.table_catalog='{0}'
) as b
on a.table_name=b.table_name and a.column_name=b.column_name
";
List<Table> tables = new List<Table>();
foreach (TableNameSet tableNameSet in DbSetting.GetTables()) {
string tableCommandStr = String.Format(tableCommandText, tableNameSet.TableName);
NpgsqlConnection tableConn = new NpgsqlConnection(_connectionString);
tableConn.Open();
NpgsqlCommand tableCommand = new NpgsqlCommand(tableCommandStr, tableConn);
NpgsqlDataAdapter tableAd = new NpgsqlDataAdapter(tableCommand);
DataSet tableDs = new DataSet();
tableAd.Fill(tableDs);
DataTable tableColumns = tableDs.Tables[0];
tableConn.Close();
if (tableColumns.Rows.Count == 0) {
continue;
}
string tableComment = Convert.ToString(tableColumns.Rows[0]["CommentText"]);
string tableCode = Convert.ToString(tableColumns.Rows[0]["TableCode"]);
string columnCommandStr = String.Format(columnCommandText, this._dataBaseName, tableNameSet.TableName, tableCode);
NpgsqlConnection columnConn = new NpgsqlConnection(_connectionString);
columnConn.Open();
NpgsqlCommand columnCommand = new NpgsqlCommand(columnCommandStr, tableConn);
NpgsqlDataAdapter columnAd = new NpgsqlDataAdapter(columnCommand);
DataSet columnDs = new DataSet();
columnAd.Fill(columnDs);
DataTable columnColumns = columnDs.Tables[0];
tableConn.Close();
Table table = new Table(tableNameSet.AliasName, tableNameSet.TableName);
if (String.IsNullOrEmpty(tableComment)) {
tableComment = tableNameSet.TableName;
}
table.CommentText = tableComment;
foreach (DataRow item in columnColumns.Rows) {
Column column = CreateColumn(table, item);
if (column != null) {
table.SetColumn(column);
}
}
tables.Add(table);
}
return tables;
}
19
View Source File : MysqlSchema.cs
License : MIT License
Project Creator : aquilahkj
License : MIT License
Project Creator : aquilahkj
public List<Table> GetTables()
{
const string tableCommandText = @"select TABLE_NAME as TableName,TABLE_COMMENT as CommentText from information_schema.TABLES where TABLE_SCHEMA='{0}' and TABLE_NAME='{1}'";
const string columnCommandText = @"
select
ORDINAL_POSITION as 'ColumnId',
case when COLUMN_KEY='PRI' then 1 else 0 end as 'ColumnKey',
CHARACTER_MAXIMUM_LENGTH AS 'MaxLength',
COLUMN_NAME AS 'ColumnName',
DATA_TYPE AS 'DataType',
case when EXTRA='auto_increment' then 1 else 0 end as 'IsIdenreplacedy',
case when IS_NULLABLE='YES' then 1 else 0 end as 'AllowNull',
NUMERIC_PRECISION as 'Precision',
NUMERIC_SCALE as 'Scale',
COLUMN_COMMENT as 'ColumnComment',
COLUMN_TYPE AS 'ColumnType'
from information_schema.COLUMNS where TABLE_SCHEMA='{0}' and TABLE_NAME='{1}'
order by ORDINAL_POSITION";
List<Table> tables = new List<Table>();
foreach (TableNameSet tableNameSet in DbSetting.GetTables()) {
string tableCommandStr = String.Format(tableCommandText, this._dataBaseName, tableNameSet.TableName);
MySqlConnection tableConn = new MySqlConnection(_connectionString);
tableConn.Open();
MySqlCommand tableCommand = new MySqlCommand(tableCommandStr, tableConn);
MySqlDataAdapter tableAd = new MySqlDataAdapter(tableCommand);
DataSet tableDs = new DataSet();
tableAd.Fill(tableDs);
DataTable tableColumns = tableDs.Tables[0];
tableConn.Close();
if (tableColumns.Rows.Count == 0) {
continue;
}
string tableComment = Convert.ToString(tableColumns.Rows[0]["CommentText"]);
string columnCommandStr = String.Format(columnCommandText, this._dataBaseName, tableNameSet.TableName);
MySqlConnection columnConn = new MySqlConnection(_connectionString);
columnConn.Open();
MySqlCommand columnCommand = new MySqlCommand(columnCommandStr, tableConn);
MySqlDataAdapter columnAd = new MySqlDataAdapter(columnCommand);
DataSet columnDs = new DataSet();
columnAd.Fill(columnDs);
DataTable columnColumns = columnDs.Tables[0];
tableConn.Close();
Table table = new Table(tableNameSet.AliasName, tableNameSet.TableName);
if (String.IsNullOrEmpty(tableComment)) {
tableComment = tableNameSet.TableName;
}
table.CommentText = tableComment;
foreach (DataRow item in columnColumns.Rows) {
Column column = CreateColumn(table, item);
if (column != null) {
table.SetColumn(column);
}
}
tables.Add(table);
}
return tables;
}
19
View Source File : JObjectFieldResolver.cs
License : GNU General Public License v3.0
Project Creator : arduosoft
License : GNU General Public License v3.0
Project Creator : arduosoft
private string BuildMongoQuery(Dictionary<string, object> arguments)
{
string query = null;
if (arguments != null)
{
JsonSerializerSettings jSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
if (arguments.ContainsKey("rawQuery"))
{
query = Convert.ToString(arguments["rawQuery"]);
}
else if (arguments.ContainsKey("_id"))
{
query = "{_id: ObjectId(\"" + Convert.ToString(arguments["_id"]) + "\")}";
}
else
{
jSettings.ContractResolver = new DefaultContractResolver();
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (string key in arguments.Keys)
{
if (arguments[key] is string)
{
JObject reg = new JObject
{
["$regex"] = $"/*{arguments[key]}/*",
["$options"] = "si"
};
dictionary[key.ToPascalCase().Replace("_", ".")] = reg;
}
else
{
dictionary[key.ToPascalCase().Replace("_", ".")] = arguments[key];
}
}
query = JsonConvert.SerializeObject(dictionary, jSettings);
}
}
return query;
}
19
View Source File : AsposePdfMetadataController.cs
License : MIT License
Project Creator : aspose-pdf
License : MIT License
Project Creator : aspose-pdf
private void SetBuiltInProperties(Doreplacedent doc, List<DocProperty> pars)
{
var builtin = doc.Info;
foreach (var par in pars)
{
if (par.Name != null &&
!par.Name.Equals("Creator", StringComparison.InvariantCultureIgnoreCase) &&
!par.Name.Equals("Producer", StringComparison.InvariantCultureIgnoreCase))
{
var parName = par.Name.ToLower();
switch (parName)
{
case "author":
builtin.Author = Convert.ToString(par.Value);
break;
case "keywords":
builtin.Keywords = Convert.ToString(par.Value);
break;
case "subject":
builtin.Subject = Convert.ToString(par.Value);
break;
case "replacedle":
builtin.replacedle = Convert.ToString(par.Value);
break;
case "trapped":
var resParse = Boolean.TryParse(Convert.ToString(par.Value), out bool valTr);
if (resParse)
builtin.Trapped = valTr.ToString();
break;
case "CreationDate":
DateTime.TryParse(par.Value.ToString(), out DateTime val2);
builtin.CreationDate = val2;
break;
case "ModDate":
DateTime.TryParse(par.Value.ToString(), out DateTime val1);
builtin.ModDate = val1;
break;
}
}
}
}
19
View Source File : AsposePdfMetadataController.cs
License : MIT License
Project Creator : aspose-pdf
License : MIT License
Project Creator : aspose-pdf
private void SetCustomProperties(Doreplacedent doc, List<DocProperty> pars)
{
var custom = doc.Info;
custom.ClearCustomData();
foreach (var par in pars)
switch (par.Type)
{
case PropertyType.String:
custom.Add(par.Name, Convert.ToString(par.Value));
break;
}
}
19
View Source File : ClusterNaming.cs
License : MIT License
Project Creator : ASStoredProcedures
License : MIT License
Project Creator : ASStoredProcedures
[SafeToPrepare(true)]
public static DataTable DistinguishingCharacteristicsForClusters(string ModelName, bool MentionAttributeName)
{
Microsoft.replacedysisServices.AdomdServer.MiningModel model = Context.MiningModels[ModelName];
if (model == null) throw new Exception("Model not found");
if (model.Content.Count == 0) throw new Exception("Model not processed");
DataTable tableReturn = new DataTable();
tableReturn.Columns.Add("ID");
tableReturn.Columns.Add("DistinguishingCharacteristics");
tableReturn.Columns.Add("FullDescription");
if (Context.ExecuteForPrepare) return tableReturn;
DataTable tableAll = GetClusterCharacteristics(ModelName, "", 0.0005); //get the characteristics of the entire population
int iMiscNodesCount = 0;
DataTable[] tables = new DataTable[model.Content[0].Children.Count];
int[] extraAttributes = new int[model.Content[0].Children.Count];
Dictionary<string, int> dictDistinguishers = new Dictionary<string, int>();
for (int i = 0; i< model.Content[0].Children.Count; i++)
{
int iExtraAttributesAdded = 0;
MiningContentNode node = model.Content[0].Children[i];
object[] row = new object[3];
row[0] = node.Name;
DataTable tableNode = (tables[i] ?? GetClusterCharacteristics(ModelName, node.Name, 0.0005));
tables[i] = tableNode;
StringBuilder sDistinguishers = new StringBuilder();
foreach (DataRow dr in tableNode.Rows)
{
if (MIN_PROBABILITY >= Convert.ToDouble(dr["Frequency "]) && iExtraAttributesAdded == extraAttributes[i]) break;
//find matching row and continue if this cluster is distinguished by this attribute/value pair
foreach (DataRow dr2 in tableAll.Rows)
{
if (Convert.ToString(dr2["Attributes"]) == Convert.ToString(dr["Attributes"]) && Convert.ToString(dr2["Values"]) == Convert.ToString(dr["Values"])) {
if (Convert.ToDouble(dr2["Frequency "]) + MIN_PERCENT_DIFFERENT_THAN_WHOLE < Convert.ToDouble(dr["Frequency "])) //the column name actually ends in a space!
{
if (sDistinguishers.Length > 0) sDistinguishers.Append("; ");
if (MentionAttributeName) sDistinguishers.Append(dr["Attributes"]).Append(" = ");
sDistinguishers.Append(dr["Values"]);
if (MIN_PROBABILITY >= Convert.ToDouble(dr["Frequency "])) iExtraAttributesAdded++;
}
break;
}
}
}
Context.CheckCancelled(); //could be a bit long running, so allow user to cancel
if (sDistinguishers.Length == 0) sDistinguishers.Append("Miscellaneous ").Append(++iMiscNodesCount);
if (dictDistinguishers.ContainsKey(sDistinguishers.ToString()) && extraAttributes[i] < tableAll.Rows.Count)
{
//a cluster with the exact same description already exists, so add another attribute to it and to the current cluster
extraAttributes[dictDistinguishers[sDistinguishers.ToString()]]++;
extraAttributes[i]++;
tableReturn.Rows.Clear();
dictDistinguishers.Clear();
i = -1; //reset loop
}
else
{
row[1] = sDistinguishers.ToString();
row[2] = node.Description;
tableReturn.Rows.Add(row);
}
}
return tableReturn;
}
19
View Source File : CurrentCommand.cs
License : MIT License
Project Creator : ASStoredProcedures
License : MIT License
Project Creator : ASStoredProcedures
public static string GetCurrentCommand()
{
AdomdClient.AdomdConnection conn = TimeoutUtility.ConnectAdomdClient("Data Source=" + Context.CurrentServerID + ";Initial Catalog=" + Context.CurrentDatabaseName + ";Application Name=replacedP");
try
{
AdomdClient.AdomdRestrictionCollection restrictions = new AdomdClient.AdomdRestrictionCollection();
//a restriction on SESSION_ID causes it to return no rows: http://msdn.microsoft.com/en-us/library/ee301976(v=sql.105).aspx#id253
string sSessionID = Context.CurrentConnection.SessionID;
System.Data.DataSet dataSet = TimeoutUtility.GetSchemaDataSet(conn, "DISCOVER_SESSIONS", restrictions);
if (dataSet != null
&& dataSet.Tables.Count > 0
&& dataSet.Tables[0].Rows.Count > 0)
{
foreach (System.Data.DataRow row in dataSet.Tables[0].Rows)
{
if (string.Compare(sSessionID, Convert.ToString(row["SESSION_ID"]), true) == 0)
{
return Convert.ToString(row["SESSION_LAST_COMMAND"]);
}
}
throw new Exception("Can't find the current command");
}
else
{
throw new Exception("Can't get the current command");
}
}
finally
{
conn.Close();
}
}
See More Examples