private IWriteHandler CheckBaseTypes(Type type, IEnumerable<Type> baseTypes) { IDictionary<Type, IWriteHandler> possibles = new Dictionary<Type, IWriteHandler>(); foreach (Type item in baseTypes) { // TODO Better way to decide the most appropriate possibility if (possibles.Count < 1) { IWriteHandler h; if (handlers.TryGetValue(item, out h)) { possibles.Add(item, h); } } } switch (possibles.Count) { case 0: return null; case 1: { IWriteHandler h = possibles.First().Value; handlers = handlers.Add(type, h); return h; } default: throw new TransitException("More thane one match for " + type); } }
public static string ToRelativeTime(this DateTime date) { int Minute = 60; int Hour = Minute * 60; int Day = Hour * 24; int Year = Day * 365; var thresholds = new Dictionary<long, Func<TimeSpan, string>> { {2, t => "a second ago"}, {Minute, t => String.Format("{0} seconds ago", (int)t.TotalSeconds)}, {Minute * 2, t => "a minute ago"}, {Hour, t => String.Format("{0} minutes ago", (int)t.TotalMinutes)}, {Hour * 2, t => "an hour ago"}, {Day, t => String.Format("{0} hours ago", (int)t.TotalHours)}, {Day * 2, t => "yesterday"}, {Day * 30, t => String.Format("{0} days ago", (int)t.TotalDays)}, {Day * 60, t => "last month"}, {Year, t => String.Format("{0} months ago", (int)t.TotalDays / 30)}, {Year * 2, t => "last year"}, {Int64.MaxValue, t => String.Format("{0} years ago", (int)t.TotalDays / 365)} }; var difference = DateTime.UtcNow - date.ToUniversalTime(); return thresholds.First(t => difference.TotalSeconds < t.Key).Value(difference); }
/// <summary> /// This helper function parses an RSA private key using the ASN.1 format /// </summary> /// <param name="privateKeyBytes">Byte array containing PEM string of private key.</param> /// <returns>An instance of <see cref="RSACryptoServiceProvider"/> rapresenting the requested private key. /// Null if method fails on retriving the key.</returns> public static RSACryptoServiceProvider DecodeRsaPrivateKey(string privateKey,string password="") { Dictionary<string, string> extras = new Dictionary<string, string>(); byte[] bytes = Helpers.GetBytesFromPEM(privateKey, out extras); if (extras.Any(x => x.Value.Contains("ENCRYPTED")) && extras.Any(x => x.Key.Contains("DEK-Inf"))) { String saltstr = extras.First(x => x.Key.Contains("DEK-Inf")).Value.Split(',')[1].Trim(); byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); SecureString despswd = new SecureString(); // GetSecPswd("Enter password to derive 3DES key==>"); foreach (char c in password) despswd.AppendChar(c); byte[] decoded = DecryptRSAPrivatePEM(bytes, salt, despswd); bytes = decoded; } return DecodeRsaPrivateKey(bytes); }
/// <summary> /// Gets the string of keys used in URI. /// </summary> /// <param name="context">Wrapping context instance.</param> /// <param name="keys">The dictionary containing key pairs.</param> /// <returns>The string of keys.</returns> public static string GetKeyString(DataServiceContext context, Dictionary<string, object> keys) { var requestInfo = new RequestInfo(context); var serializer = new Serializer(requestInfo); if (keys.Count == 1) { return serializer.ConvertToEscapedUriValue(keys.First().Key, keys.First().Value); } else { StringBuilder stringBuilder = new StringBuilder(); foreach (var keyPair in keys) { stringBuilder.Append(keyPair.Key); stringBuilder.Append(UriHelper.EQUALSSIGN); stringBuilder.Append(serializer.ConvertToEscapedUriValue(keyPair.Key, keyPair.Value)); stringBuilder.Append(UriHelper.COMMA); } stringBuilder.Remove(stringBuilder.Length - 1, 1); return stringBuilder.ToString(); } }
public void should_map_non_generic_dictionary_to_generic_enumerable_of_dictionary_entry() { var results = new Dictionary<string, object> {{"oh", 1}, {"hai", 2}}.As<IDictionary>().AsEnumerable(); results.ShouldTotal(2); var result = results.First(); result.ShouldBeType<DictionaryEntry>(); result.Key.ShouldEqual("oh"); result.Value.ShouldEqual(1); result = results.Skip(1).First(); result.ShouldBeType<DictionaryEntry>(); result.Key.ShouldEqual("hai"); result.Value.ShouldEqual(2); }
public void Save() { if (this.ResFiles == null || this.Datas == null) return; Dictionary<string, ResXResourceWriter> writers = new Dictionary<string, ResXResourceWriter>(); foreach (var f in this.ResFiles) { writers.Add(f.Key, new ResXResourceWriter(f.Value)); } foreach (var d in this.Datas) { if (string.IsNullOrEmpty(d.Key)) continue; var writer = writers.First(w => w.Key == "Default"); writer.Value.AddResource(d.Key, (string)d.Default); foreach (var w in writers.Where(ww => !ww.Key.Equals("Default"))) { var k = w.Key.Replace("-", "_"); PropertyInfo p = d.GetType().GetProperty(k); if (p != null) { var value = (string)p.GetValue(d); w.Value.AddResource(d.Key, value); } } d.IsExists = true; } foreach (var w in writers) { w.Value.Dispose(); } }
/// <summary> /// 获取反射点坐标及碰撞线段和碰撞散射体的旋转方向 /// </summary> /// <param name="seg"></param> /// <param name="collision_seg"></param> /// <param name="dir"></param> /// <returns></returns> public Point? GetClosestReflectionPoint(LineSegment seg, out LineSegment collision_seg, out SCATTER_SEG_DIRECTION dir, out double dc) { Dictionary<Point?, object[]> pt_seg_dir_dict = new Dictionary<Point?, object[]>(); foreach (Scatter scatter in this.Scatters) { Point? tmp_pt = null; LineSegment tmp_seg = null; SCATTER_SEG_DIRECTION tmp_dir = scatter.SegDirection; double tmp_dc = scatter.DielectricConstant; tmp_pt = scatter.GetClosestReflectionPoint(seg, out tmp_seg); if (tmp_pt != null) pt_seg_dir_dict.Add(tmp_pt, new object[] { tmp_seg, tmp_dir, tmp_dc }); } if(pt_seg_dir_dict.Count == 0) //没有交点 { collision_seg = null; dir = SCATTER_SEG_DIRECTION.CLOCKWISE; dc = 0; return null; } KeyValuePair<Point?, object[]> tmp_kvp = pt_seg_dir_dict.First(); double min_d2 = double.PositiveInfinity; foreach (KeyValuePair<Point?, object[]> kvp in pt_seg_dir_dict) { double dist2 = Math.Pow(kvp.Key.Value.X - seg.TailPosition.X, 2) + Math.Pow(kvp.Key.Value.Y - seg.TailPosition.Y, 2); if (dist2 > 0 && dist2 < min_d2) { min_d2 = dist2; tmp_kvp = kvp; } } collision_seg = tmp_kvp.Value[0] as LineSegment; dir = (SCATTER_SEG_DIRECTION)tmp_kvp.Value[1]; dc = (double)tmp_kvp.Value[2]; return tmp_kvp.Key; }
public void startDevideVotingProcess(Dictionary<string, ArrayList> solutionTasks) { //创建输入参数 Dictionary<string, object> para = new Dictionary<string, object>(); para.Add("solutionTasks", solutionTasks); //创建实例对象 WorkflowApplication currentWorkflowInstance = new WorkflowApplication(new decomposeVoting(), para); //委托流程结束时候调用的方法 currentWorkflowInstance.Completed = new Action<WorkflowApplicationCompletedEventArgs>(DevideVotingWorkflowCompleted); //启动实例 currentWorkflowInstance.Run(); CrowdTaskService crowdTaskService = new CrowdTaskService(); //分解任务 CrowdTask divideTask = crowdTaskService.findCrowdTaskByWorkflowId(solutionTasks.First().Key); CrowdTask crowdTask = new CrowdTask(); crowdTask.taskName = divideTask.taskName; crowdTask.taskDescription = divideTask.taskDescription; crowdTask.taskType = TaskType.decomposeVotingTask; crowdTask.taskWorkflowId = currentWorkflowInstance.Id.ToString(); crowdTask.taskParentWorkflowId = crowdTaskService.findCrowdTaskByWorkflowId(solutionTasks.Keys.First().ToString()).taskParentWorkflowId; int result = crowdTaskService.insert(crowdTask); //更新每个实例的主工作流Id crowdTaskService.updateCrowdTaskMainTaskIdByWorkflowId(currentWorkflowInstance.Id.ToString()); if (result == 1) { //将当前实例加入到分解任务集合中 MyWorkflowInstance.setDecomposeVotingWorkflowApplication(currentWorkflowInstance.Id.ToString(), currentWorkflowInstance); } }
public static object DictionaryToObj(Dictionary<string, object> dict, Type type) { Object paramObj = Activator.CreateInstance(type); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase))) continue; KeyValuePair<string, object> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)); // Find which property type (int, string, double? etc) the CURRENT property is... Type tPropertyType = paramObj.GetType().GetProperty(property.Name).PropertyType; // Fix nullables... Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType; string paramType = newT.FullName.ToLower(); //checking and handling nullable type if (newT.IsGenericType && newT.GetGenericTypeDefinition() == typeof(Nullable<>)) { paramType = newT.GetGenericArguments()[0].FullName.ToLower(); if (paramType == "system.datetime" || paramType == "system.single" || paramType == "system.boolean" || paramType == "system.string" || paramType == "system.int32" || paramType == "system.int64" || paramType == "system.decimal" || paramType == "system.double") { if (item.Value != null) { object newA = Convert.ChangeType(item.Value, Type.GetType(newT.GetGenericArguments()[0].FullName)); paramObj.GetType().GetProperty(property.Name).SetValue(paramObj, newA, null); } } } //ok for string decimal int not for class object type else if (paramType == "system.datetime" || paramType == "system.single" || paramType == "system.boolean" || paramType == "system.string" || paramType == "system.int32" || paramType == "system.int64" || paramType == "system.decimal" || paramType == "system.double") { if (item.Value != null) { object newA = Convert.ChangeType(item.Value, newT); paramObj.GetType().GetProperty(property.Name).SetValue(paramObj, newA, null); } } else { if (newT.IsClass == true && newT.IsGenericType == true) { Type objectParamType = Type.GetType(newT.FullName); if (objectParamType == null) { if (newT.Assembly.Location != null && newT.Assembly.Location != string.Empty) { Assembly assembly = Assembly.LoadFile(newT.Assembly.Location); objectParamType = assembly.GetType(newT.FullName); } } var obj = DictionaryToList((IList)item.Value, objectParamType); paramObj.GetType().GetProperty(property.Name).SetValue(paramObj, obj, null); } else if (paramType == "system.array") { //value contain arraysvalue Array arrValues = DictionaryToArray((IList)item.Value); paramObj.GetType().GetProperty(property.Name).SetValue(paramObj, arrValues, null); } else if (paramType == "system.collections.arraylist") { //value contains array var x = (IList)item.Value; if (x.Count > 0) { ArrayList arrList = DictionaryToArrayList((IList)item.Value); paramObj.GetType().GetProperty(property.Name).SetValue(paramObj, arrList, null); } } else { Type objectParamType = Type.GetType(newT.FullName); if (objectParamType == null) { if (newT.Assembly.Location != null && newT.Assembly.Location != string.Empty) { Assembly assembly = Assembly.LoadFile(newT.Assembly.Location); objectParamType = assembly.GetType(newT.FullName); } } var obj = DictionaryToObj((Dictionary<string, object>)item.Value, objectParamType); paramObj.GetType().GetProperty(property.Name).SetValue(paramObj, obj, null); } } } return paramObj; }
private FrameworkElement GetInstancesElement(Dictionary<string, IDictionary> instances) { var typeName = instances.First().Value[Key].ToString(); if (ShowInstanceKeys) { var listBox = new ListBox { DataContext = instances }; listBox.SelectionChanged += ListBox_SelectionChanged; return new Expander { Header = typeName, Content = listBox }; } else { return new Label { Content = typeName }; } }