//Checks to see if a key is present based on the passed-in value public virtual bool ItemContainsKey(string key, ExpandoObject item) { var dc = ItemAsDictionary(item); return dc.ContainsKey(key); }
public void AddDup() { IDictionary<string, object> eo = new ExpandoObject(); eo.Add("The test key to add.", "value"); var ae = Assert.Throws<ArgumentException>("key", () => eo.Add("The test key to add.", "value")); Assert.Contains("The test key to add.", ae.Message); }
public void PropertyNotify() { var eo = new ExpandoObject(); IDictionary<string, object> dict = eo; INotifyPropertyChanged note = eo; int changeCount = 0; string lastKey = null; note.PropertyChanged += (sender, args) => { Assert.Same(eo, sender); ++changeCount; lastKey = args.PropertyName; }; Assert.Equal(0, changeCount); dict.Add("X", 1); Assert.Equal(1, changeCount); Assert.Equal(lastKey, "X"); dict["Y"] = 2; Assert.Equal(2, changeCount); Assert.Equal(lastKey, "Y"); object boxed = 0; dict["Z"] = boxed; Assert.Equal(3, changeCount); Assert.Equal("Z", lastKey); dict["Z"] = boxed; // exact same object. Assert.Equal(3, changeCount); dict["Z"] = 0; // same value but different instance. Assert.Equal(4, changeCount); dict.Remove("Not there"); Assert.Equal(4, changeCount); dict.Remove("Z"); Assert.Equal(5, changeCount); dict.Clear(); Assert.Equal(7, changeCount); // trigger for each key. }
public static dynamic RecordToExpando(this IDataReader rdr) { dynamic e = new ExpandoObject(); var d = e as IDictionary<string, object>; for (int i = 0; i < rdr.FieldCount; i++) d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]); return e; }
public void Default() { dynamic project = new ExpandoObject(); project.Name = "Shake"; project.Desc = "simple build tool"; project.Like = "Rake"; Console.WriteLine("{0} is a {1}, inspired by {2}.", project.Name, project.Desc, project.Like); }
void OnConnected(DataEventArgs data) { Log("Connected successfully"); // trying to send request ExpandoObject parameters = new ExpandoObject(); parameters["name"] = "testname"; parameters["password"] = ""; mClient.SendRequest("user.login", parameters); }
public void DeleteAndReInsert() { IDictionary<string, object> eo = new ExpandoObject(); eo.Add("key", 1); Assert.Equal(Enumerable.Repeat(new KeyValuePair<string, object>("key", 1), 1), eo); eo.Remove("key"); Assert.Empty(eo); eo.Add("key", 2); Assert.Equal(Enumerable.Repeat(new KeyValuePair<string, object>("key", 2), 1), eo); }
public void DictionaryMatchesProperties() { dynamic eo = new ExpandoObject(); IDictionary<string, object> dict = eo; eo.X = 1; eo.Y = 2; Assert.Equal(2, dict.Count); Assert.Equal(1, dict["X"]); Assert.Equal(2, dict["Y"]); }
public void DispatchEvent(Delegate handler, string text) { if (text != null && text != "") { ExpandoObject data = new ExpandoObject(); data["text"] = text; DispatchEvent(handler, data); } DispatchEvent(handler); }
public void ShouldBeAbleToAddNewMethodByAssigningADelegateToAPropertySetter() { var target = new DynamicObject(); dynamic expando = new ExpandoObject(target); Func<int, int, int> addition = (a, b) => a + b; expando.Add = addition; var result = expando.Add(2, 2); Assert.AreEqual(4, result); }
public void ShouldBeAbleToImplicitlyCastAnExpandoObjectToADuckTypeIfExpandoLooksLikeDuckType() { var mock = new MockClass(); var target = new DynamicObject(mock); dynamic expando = new ExpandoObject(target); ITest test = expando; test.TargetMethod(); Assert.AreEqual(1, mock.CallCount); }
public void DispatchEvent(Delegate handler, ExpandoObject data = null) { Delegate event_handler = handler; // local variable for thread safety if (event_handler != null) { //event_handler.DynamicInvoke(new DataEventArgs(data)); foreach (var h in event_handler.GetInvocationList()) { h.DynamicInvoke(new DataEventArgs(data)); } } }
public void ShouldOnlyExecuteReplacementMethodAfterReplacingExpandoMethod() { var target = new DynamicObject(); dynamic expando = new ExpandoObject(target); Func<int, int, int> addition = (a, b) => a + b; Func<int, int, int> subtraction = (a, b) => a - b; expando.Operation = addition; expando.Operation = subtraction; int result = expando.Operation(2, 2); Assert.AreEqual(0, result); }
public List<dynamic> GetData(DataTable dt) { List<dynamic> bendinamigim = new List<dynamic>(); foreach (var item in dt.AsEnumerable()) { IDictionary<string, object> dn = new ExpandoObject(); foreach (var column in dt.Columns.Cast<DataColumn>()) dn[column.ColumnName] = item[column]; bendinamigim.Add(dn); } return bendinamigim; }
public void ShouldBeAbleToCallCovariantPropertySetterOnExpandoObject() { var expectedValue = 12345; Func<object[], object> setterBody = args => { var value = args[0]; Assert.AreEqual(value, expectedValue); return null; }; var target = new DynamicObject(); target.AddMethod("set_TargetProperty", setterBody, typeof(void), typeof(object)); dynamic expando = new ExpandoObject(target); expando.TargetProperty = expectedValue; }
public void TestDynamic() { dynamic d = new ExpandoObject(); d.DynProp = "Hello Dynamic!\n"; Console.WriteLine(d.DynProp); dynamic msb = new MsBuildTask("dummy.sln"); msb.Targets.Add("Rebuild"); msb.Properties.Configuration = "Release"; msb.Properties.WarningLevel = 0; msb.Properties.OutPUtPaTh = @"c:\build"; // msb.Build(); Console.WriteLine(msb); Console.WriteLine(msb.Properties.outputPath); }
public void Indexer() { // Deliberately using keys that the C# syntax won't use, to check they're covered too. var boxedInts = Enumerable.Range(0, 10).Select(i => (object)i).ToArray(); IDictionary<string, object> eo = new ExpandoObject(); foreach (var boxed in boxedInts) eo[boxed.ToString()] = boxed; Assert.Equal(10, eo.Count); foreach (var boxed in boxedInts) Assert.Same(boxed, eo[boxed.ToString()]); var knfe = Assert.Throws<KeyNotFoundException>(() => eo["A string that's a key"]); Assert.Contains("A string that's a key", knfe.Message); Assert.Throws<KeyNotFoundException>(() => eo[null]); Assert.Throws<ArgumentNullException>("key", () => eo[null] = 0); // Can overwrite eo["1"] = 1; }
public void DispatchEvent(string event_name, ExpandoObject data) { // http://stackoverflow.com/questions/198543/how-do-i-raise-an-event-via-reflection-in-net-c //EventInfo event_info = this.GetType().GetEvent(event_name); //Type t = this.GetType(); //FieldInfo[] f = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field = this.GetType().GetField(event_name, BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { var event_delegate = (MulticastDelegate)field.GetValue(this); if (event_delegate != null) { foreach (var handler in event_delegate.GetInvocationList()) { handler.DynamicInvoke(new DataEventArgs(data)); // .Method.Invoke(handler.Target, new object[] { this, new DataEventArgs(data) }); } } } }
public void InitialState() { IDictionary<string, object> eo = new ExpandoObject(); Assert.Equal(0, eo.Count); Assert.False(eo.IsReadOnly); }
/// <summary> /// This will return an Expando as a Dictionary /// </summary> public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) { return (IDictionary<string, object>)item; }
public void KeyCollection() { IDictionary<string, object> dict = new ExpandoObject(); dict["X"] = 1; dict["Z"] = 3; dict["Y"] = 2; dict.Remove("Z"); var keys = dict.Keys; Assert.Equal(2, keys.Count); Assert.True(keys.IsReadOnly); Assert.Equal(new[] {"X", "Y"}, keys.OrderBy(k => k)); // OrderBy because order is not guaranteed. Assert.Throws<NotSupportedException>(() => keys.Add("Z")); Assert.Throws<NotSupportedException>(() => keys.Clear()); Assert.Throws<NotSupportedException>(() => keys.Remove("X")); Assert.True(keys.Contains("X")); Assert.False(keys.Contains("x")); string[] array = new string[3]; keys.CopyTo(array, 1); Assert.Null(array[0]); Array.Sort(array); // Because order is not guaranteed. Assert.Equal(new[] {null, "X", "Y"}, array); var keysEnumerated = new List<object>(); foreach (var key in (IEnumerable)keys) // going through non-generic to test delegation to generic { keysEnumerated.Add(key); } Assert.Equal(new[] {"X", "Y"}, keysEnumerated.OrderBy(k => k)); using (var en = keys.GetEnumerator()) { en.MoveNext(); dict["Z"] = 3; Assert.Throws<InvalidOperationException>(() => en.MoveNext()); } }
public void ValueCollection() { IDictionary<string, object> dict = new ExpandoObject(); dict["X"] = 1; dict["Z"] = 3; dict["Y"] = 2; dict.Remove("Z"); var values = dict.Values; Assert.Equal(2, values.Count); Assert.True(values.IsReadOnly); Assert.Equal(new object[] {1, 2}, values.OrderBy(k => k)); // OrderBy because order is not guaranteed. Assert.Throws<NotSupportedException>(() => values.Add(3)); Assert.Throws<NotSupportedException>(() => values.Clear()); Assert.Throws<NotSupportedException>(() => values.Remove(1)); Assert.True(values.Contains(1)); Assert.False(values.Contains(1.0)); object[] array = new object[3]; values.CopyTo(array, 1); Assert.Null(array[0]); Array.Sort(array); // Because order is not guaranteed. Assert.Equal(new object[] {null, 1, 2}, array); var valuesEnumerated = new List<object>(); foreach (var value in (IEnumerable)values) // going through non-generic to test delegation to generic { valuesEnumerated.Add(value); } Assert.Equal(new object[] {1, 2}, valuesEnumerated.OrderBy(k => k)); using (var en = values.GetEnumerator()) { en.MoveNext(); dict["Z"] = 3; Assert.Throws<InvalidOperationException>(() => en.MoveNext()); } }
/// <summary> /// Gets the index at which the value should be stored for the specified name, /// the method is only used in the case-insensitive case. /// </summary> /// <param name="name">the name of the member</param> /// <param name="obj">The ExpandoObject associated with the class /// that is used to check if a member has been deleted.</param> /// <returns> /// the exact match if there is one /// if there is exactly one member with case insensitive match, return it /// otherwise we throw AmbiguousMatchException. /// </returns> private int GetValueIndexCaseInsensitive(string name, ExpandoObject obj) { int caseInsensitiveMatch = ExpandoObject.NoMatch; //the location of the case-insensitive matching member lock (obj.LockObject) { for (int i = _keys.Length - 1; i >= 0; i--) { if (string.Equals( _keys[i], name, StringComparison.OrdinalIgnoreCase)) { //if the matching member is deleted, continue searching if (!obj.IsDeletedMember(i)) { if (caseInsensitiveMatch == ExpandoObject.NoMatch) { caseInsensitiveMatch = i; } else { //Ambigous match, stop searching return ExpandoObject.AmbiguousMatchFound; } } } } } //There is exactly one member with case insensitive match. return caseInsensitiveMatch; }
dynamic GetHours(DateTime start, DateTime end, DateTime current, dynamic constants) { dynamic archive = new ExpandoObject(); archive.success = true; archive.error = string.Empty; archive.errorcode = DeviceError.NO_ERROR; var recs = new List <dynamic>(); int maxProfiles = ((string)constants.aType).Contains("СЭТ-4ТМ.03М") ? 3 : 2; dynamic arr = GetArray(maxProfiles); if (!arr.success) { return(arr); } log(string.Format("Наиболее подходящий массив профилей мощности с номером:{0} и периодом интегрирования:{1} минут.", arr.select, arr.TimeInterval)); /* * Как сейчас? * Поиск подходящего профиля мощности - 30 или 60 минут * Для каждой даты: * Поиск адреса по дате * Ожидание * Запрос по адресу одной записи * Конец * * * Надо * * Для каждой даты * Если адрес неизвестен * Поиск адреса по дате * Ожидание * Конец * Запрос по адресу трёх записей * * Конец */ if (arr.select < maxProfiles) { //2.4.3.6 Расширенное чтение текущего указателя массива профиля мощности var requestCurrent = MakeRequestParameters(0x04, new byte[] { arr.select }); var rspCurrent = Send(requestCurrent); if (!rspCurrent.success) { return(rspCurrent); } var dtCurrent = dtCurrentMemory(rspCurrent.Body, 0); // OnSendMessage(string.Format(" Время начала текущего среза: {0:dd.MM.yyyy HH:mm}", dtCurrent)); uint currAddr = Helper.ToUInt16(rspCurrent.Body, 5); byte addrHigh = rspCurrent.Body[5]; byte addrLow = rspCurrent.Body[6]; // OnSendMessage(string.Format(" Адрес текущего среза:{0:X} и {1:X} => {2:X}", addrHigh,addrLow,currAddr)); //Ограничение на одновременное считывание часовых данных - устанавливаем 10 суток * 24 = 240 часов int countMax = 240; //Считывание профилей мощности var step = 1; UInt16 addrMemory = 0; for (var date0 = start.Date.AddHours(start.Hour); date0 < end; date0 = date0.AddHours(step)) { step = 0; log($"-----------------------------------{date0}"); if (cancel()) { archive.success = false; archive.errorcode = DeviceError.NO_ERROR; archive.error = "опрос отменен"; break; } if (date0 >= current) { log(string.Format("данные за {0:dd.MM.yyyy HH:mm} еще не собраны", date0)); break; } if (date0 >= dtCurrent) { log(string.Format("данные за {0:dd.MM.yyyy HH:mm} еще не собраны", date0)); break; } if (countMax == 0) { log(string.Format("Прерывание опроса по причине превышения числа одновременно считываемых данных. Последнее прочитанное за {0:dd.MM.yyyy HH:mm}. Считано {1} значений", date0, 240 - countMax)); break; } countMax--; for (var i = 0; i < 3; i++) { if (_j != null) { var date = date0.AddHours(i); if (isInJournal(date)) { log(string.Format("Данных за {0:dd.MM.yyyy HH:mm} нет по причине выключения счетчика ", date)); // !!! continue; } } } var readCount = (byte)(arr.TimeInterval == 30 ? 0x18 : 0x10); //log(string.Format("чтение часовых данных за {0:dd.MM.yyyy HH:mm} ", date)); byte[] aMemory = new byte[] { 0x02, 0x03, 0x08, 0x09 }; if (addrMemory == 0) { step = 1; //2.3.1.23 Поиск адреса заголовка массива профиля мощности var request = MakeRequestOnWriteParameters(0x28, new byte[] { arr.select, 0xFF, 0xFF, Helper.IntToBinDec(date0.Hour), Helper.IntToBinDec(date0.Day), Helper.IntToBinDec(date0.Month), Helper.IntToBinDec(date0.Year - 2000), 0xFF, arr.TimeInterval }); var rspAddrRequest = Send(request); if (!rspAddrRequest.success) { return(rspAddrRequest); } dynamic rspAddress; var inProcess = true; do { rspAddress = Send(MakeRequestParameters(0x18, new byte[] { 0x00 })); // 2.4.3.31.1 Чтение слова состояния задачи поиска адреса заголовка массива профиля if (!rspAddress.success) { return(rspAddress); } if (rspAddress.Body[0] == 0) { inProcess = false; } else if (rspAddress.Body[0] > 1) { rspAddress.errorcode = DeviceError.DEVICE_EXCEPTION; rspAddress.success = false; switch ((byte)rspAddress.Body[0]) { case 0x2: rspAddress.error = "Запрошенный заголовок не найден"; break; case 0x3: rspAddress.error = "Внутренняя аппаратная ошибка счетчика. Не отвечает память указателя поиска"; break; case 0x4: rspAddress.error = "Внутренняя логическая ошибка счетчика. Ошибка контрольной суммы указателя поиска"; break; case 0x5: rspAddress.error = "Внутренняя логическая ошибка счетчика. Ошибка контрольной суммы дескриптора поиска"; break; case 0x6: rspAddress.error = "Внутренняя аппаратная ошибка счетчика. Не отвечает память массива профиля"; break; case 0x7: rspAddress.error = "Внутренняя логическая ошибка счетчика. Ошибка контрольной суммы заголовка в массиве профиля"; break; case 0x8: rspAddress.error = "Внутренняя логическая ошибка счетчика. Заголовок находится по адресу, где должна быть запись среза"; break; case 0x9: rspAddress.error = "Недопустимый номер массива поиска"; break; case 0xA: rspAddress.error = "Недопустимое время интегрирования профиля мощности в дескрипторе запроса (не соответствует времени интегрирования счетчика)"; break; default: rspAddress.error = string.Format("Неизвестная ошибка {0:X}h", rspAddress.Body[0]); break; } inProcess = false; } }while (inProcess); if (!rspAddress.success) { log(string.Format("Ошибка.Данные за {0:dd.MM.yyyy HH:mm} не найдены в профилях мощности счетчика.", date0)); if (isInJournal(date0)) { log(string.Format("Данных за {0:dd.MM.yyyy HH:mm} нет по причине выключения счетчика ", date0)); } } else { addrMemory = (UInt16)(((UInt16)rspAddress.Body[3] << 8) | rspAddress.Body[4]); } } // 2.4.4.2 Расширенный запрос на чтение информации по физическим адресам физиче-ской памяти var rsp = Send(MakeRequestProfiles(0x00, aMemory[arr.select + 1], (byte)(addrMemory >> 8), (byte)(addrMemory & 0xFF), (byte)(readCount * 3))); //var rsp = ReadProfiles(arr.select, date, readCount, arr.TimeInterval); if (rsp.success) { // DateTime dateReaded0 = dtfromCounter(rsp.Body, 1); DateTime dateReadedi = dtfromCounter(rsp.Body, 1); int count = 0; for (var i = 0; i < 3; i++) { //var dateReaded = dateReaded0.AddHours(i); var dateReaded = dtfromCounter(rsp.Body, (byte)(1 + i * (8 + 8 * 60 / arr.TimeInterval))); var date = date0.AddHours(i); log($"{date0}-----------------------------------{i}"); if (date >= current) { break; } if (date >= dtCurrent) { break; } log($"dateReaded:{dateReaded} date:{ date}"); if (dateReaded == date) { var currec = new List <dynamic>(); //стр 109 2.4.3.17 if (arr.TimeInterval == 30) { var offset = i * 0x18; currec.Add(MakeHourRecord("P+", (PQ(rsp.Body, offset + 9, constants.constA, arr.TimeInterval) + PQ(rsp.Body, offset + 17, constants.constA, arr.TimeInterval)) / 2.0, "кВт", date)); currec.Add(MakeHourRecord("P-", (PQ(rsp.Body, offset + 11, constants.constA, arr.TimeInterval) + PQ(rsp.Body, offset + 19, constants.constA, arr.TimeInterval)) / 2.0, "кВт", date)); currec.Add(MakeHourRecord("Q+", (PQ(rsp.Body, offset + 13, constants.constA, arr.TimeInterval) + PQ(rsp.Body, offset + 21, constants.constA, arr.TimeInterval)) / 2.0, "кВт", date)); currec.Add(MakeHourRecord("Q-", (PQ(rsp.Body, offset + 15, constants.constA, arr.TimeInterval) + PQ(rsp.Body, offset + 23, constants.constA, arr.TimeInterval)) / 2.0, "кВт", date)); } else { var offset = i * 0x10; currec.Add(MakeHourRecord("P+", PQ(rsp.Body, offset + 9, constants.constA, arr.TimeInterval), "кВт", date)); currec.Add(MakeHourRecord("P-", PQ(rsp.Body, offset + 11, constants.constA, arr.TimeInterval), "кВт", date)); currec.Add(MakeHourRecord("Q+", PQ(rsp.Body, offset + 13, constants.constA, arr.TimeInterval), "кВт", date)); currec.Add(MakeHourRecord("Q-", PQ(rsp.Body, offset + 15, constants.constA, arr.TimeInterval), "кВт", date)); } currec.Add(MakeHourRecord("Статус", 0, "", date)); records(currec); log(string.Format("часовые данные за {0:dd.MM.yyyy HH:mm} P+={1:0.000} P-={2:0.000} Q+={3:0.000} Q-={4:0.000}", date, currec[0].d1, currec[1].d1, currec[2].d1, currec[3].d1)); recs.AddRange(currec); count++; } else { log(string.Format("Ошибка.Прочитаны данные за {0:dd.MM.yyyy HH:mm} вместо ожидаемых за {1:dd.MM.yyyy HH:mm}", dateReaded, date)); if (isInJournal(date)) { log(string.Format("Данных за {0:dd.MM.yyyy HH:mm} нет по причине выключения счетчика ", date)); var currec = new List <dynamic>(); currec.Add(MakeHourRecord("Статус", 1, "", date)); records(currec); } else { } } log($"{date0}+++++++++++++++++++++++++++++++++++++++++++{i}"); } if (count > 0) { step = count; } } else { log(string.Format("Ошибка.Данные за {0:dd.MM.yyyy HH:mm} не найдены в профилях мощности счетчика.", date0)); if (isInJournal(date0)) { log(string.Format("Данных за {0:dd.MM.yyyy HH:mm} нет по причине выключения счетчика ", date0)); } } if (step == 0) { addrMemory = 0; } else { addrMemory += (UInt16)(step * readCount); } } } //log(string.Format("Часовые Q+ ({0}):", hours.Count)); //foreach (var data in hours) //{ // if (data.s1 == "Q+") // { // log(string.Format("{0:dd.MM.yyyy HH:mm} {1} = {2} {3}", data.date, data.s1, data.d1, data.s2)); // } //} archive.records = recs; return(archive); }
/// <summary> /// Formats the log event to various JSON fields that are to be shown in Loggly. /// </summary> /// <param name="loggingEvent"></param> /// <returns></returns> private string PreParse(LoggingEvent loggingEvent) { //formating base logging info dynamic _loggingInfo = new ExpandoObject(); _loggingInfo.timestamp = loggingEvent.TimeStamp.ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffzzz"); _loggingInfo.level = loggingEvent.Level.DisplayName; _loggingInfo.hostName = Environment.MachineName; _loggingInfo.process = _currentProcess.ProcessName; _loggingInfo.threadName = loggingEvent.ThreadName; _loggingInfo.loggerName = loggingEvent.LoggerName; //handling messages object _loggedObject = null; string _message = GetMessageAndObjectInfo(loggingEvent, out _loggedObject); if (_message != string.Empty) { _loggingInfo.message = _message; } //handling exceptions dynamic _exceptionInfo = GetExceptionInfo(loggingEvent); if (_exceptionInfo != null) { _loggingInfo.exception = _exceptionInfo; } //handling threadcontext properties string[] _threadContextProperties = ThreadContext.Properties.GetKeys(); if (_threadContextProperties != null && _threadContextProperties.Any()) { var p = _loggingInfo as IDictionary <string, object>; foreach (string key in _threadContextProperties) { if ((ThreadContext.Properties[key] as IFixingRequired) != null && (ThreadContext.Properties[key] as IFixingRequired).GetFixedObject() != null) { p[key] = (ThreadContext.Properties[key] as IFixingRequired).GetFixedObject(); } else { p[key] = ThreadContext.Properties[key].ToString(); } } } //handling logicalthreadcontext properties if (this._config.LogicalThreadContextKeys != null) { var ltp = _loggingInfo as IDictionary <string, object>; string[] _LogicalThreadContextProperties = this._config.LogicalThreadContextKeys.Split(','); foreach (string key in _LogicalThreadContextProperties) { if (LogicalThreadContext.Properties[key] != null) { if ((LogicalThreadContext.Properties[key] as IFixingRequired) != null && (LogicalThreadContext.Properties[key] as IFixingRequired).GetFixedObject() != null) { ltp[key] = (LogicalThreadContext.Properties[key] as IFixingRequired).GetFixedObject(); } else { ltp[key] = LogicalThreadContext.Properties[key].ToString(); } } } } //handling globalcontext properties if (this._config.GlobalContextKeys != null) { var gcp = _loggingInfo as IDictionary <string, object>; string[] _globalContextProperties = this._config.GlobalContextKeys.Split(','); foreach (string key in _globalContextProperties) { if (GlobalContext.Properties[key] != null) { if ((GlobalContext.Properties[key] as IFixingRequired) != null && (GlobalContext.Properties[key] as IFixingRequired).GetFixedObject() != null) { gcp[key] = (GlobalContext.Properties[key] as IFixingRequired).GetFixedObject(); } else { gcp[key] = GlobalContext.Properties[key].ToString(); } } } } string jsonMessage = string.Empty; if (TryGetParsedJsonFromLog(_loggingInfo, _loggedObject, out jsonMessage)) { return(jsonMessage); } else { //converting event info to Json string return(JsonConvert.SerializeObject(_loggingInfo, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, })); } }
private CreateJobApplicationResponse CreateJobApplication( SocialMediaProcessedResponse result, JobDetailsModel jobDetails, ApplicantInfo applicantInfo, string overrideEmail) { // Gather Attachments Guid identifier = Guid.NewGuid(); JobApplicationAttachmentUploadItem uploadItem = new JobApplicationAttachmentUploadItem() { Id = identifier.ToString(), AttachmentType = JobApplicationAttachmentType.Resume, FileName = result.FileName, FileStream = result.FileStream, PathToAttachment = identifier.ToString() + "_" + result.FileName, Status = "Ready" }; // End code for fetch job details Log.Write("overrideEmail uploadItem object created", ConfigurationPolicy.ErrorLog); List <JobApplicationAttachmentUploadItem> attachments = new List <JobApplicationAttachmentUploadItem>(); attachments.Add(uploadItem); Log.Write("overrideEmail uploadItem attachment added", ConfigurationPolicy.ErrorLog); string resumeAttachmentPath = JobApplicationAttachmentUploadItem.GetAttachmentPath(attachments, JobApplicationAttachmentType.Resume); Log.Write("After resume GetAttachmentPath", ConfigurationPolicy.ErrorLog); string coverletterAttachmentPath = JobApplicationAttachmentUploadItem.GetAttachmentPath(attachments, JobApplicationAttachmentType.Coverletter); Log.Write("After cover letter GetAttachmentPath", ConfigurationPolicy.ErrorLog); string htmlEmailContent = this.GetEmailHtmlContent(this.EmailTemplateId); string htmlEmailSubject = this.GetEmailSubject(this.EmailTemplateId); string htmlAdvertiserEmailContent = this.GetEmailHtmlContent(this.AdvertiserEmailTemplateId); string htmlAdvertiserEmailSubject = this.GetEmailSubject(this.AdvertiserEmailTemplateId); Log.Write("After GetHtmlEmailContent", ConfigurationPolicy.ErrorLog); // Email notification settings List <dynamic> emailAttachments = new List <dynamic>(); foreach (var item in attachments) { dynamic emailAttachment = new ExpandoObject(); emailAttachment.FileStream = item.FileStream; emailAttachment.FileName = item.FileName; emailAttachments.Add(emailAttachment); } EmailNotificationSettings advertiserEmailNotificationSettings = (this.AdvertiserEmailTemplateId != null) ? _createAdvertiserEmailTemplate( new JobApplicationEmailTemplateModel() { FromFirstName = result.FirstName, FromLastName = result.LastName, FromEmail = overrideEmail, ToFirstName = jobDetails.ContactDetails.GetFirstName(), ToLastName = jobDetails.ContactDetails.GetLastName(), ToEmail = jobDetails.ApplicationEmail, Subject = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.AdvertiserEmailTemplateId), HtmlContent = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.AdvertiserEmailTemplateId), Attachments = emailAttachments }) : null; EmailNotificationSettings emailNotificationSettings = (this.EmailTemplateId != null) ? _createApplicantEmailTemplate( new JobApplicationEmailTemplateModel() { FromFirstName = this.EmailTemplateSenderName, FromLastName = null, FromEmail = this.EmailTemplateSenderEmailAddress, ToFirstName = SitefinityHelper.GetUserFirstNameById(SitefinityHelper.GetUserByEmail(overrideEmail).Id), ToLastName = null, ToEmail = overrideEmail, Subject = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.EmailTemplateId), HtmlContent = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.EmailTemplateId), Attachments = null }) : null; EmailNotificationSettings registrationNotificationsSettings = (applicantInfo.IsNewUser && this.RegistrationEmailTemplateId != null) ? _createRegistrationEmailTemplate( new JobApplicationEmailTemplateModel() { FromFirstName = this.EmailTemplateSenderName, FromLastName = null, FromEmail = this.EmailTemplateSenderEmailAddress, ToFirstName = applicantInfo.FirstName, ToLastName = null, ToEmail = applicantInfo.Email, Subject = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.RegistrationEmailTemplateId), HtmlContent = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.RegistrationEmailTemplateId), Attachments = null }) : null; Log.Write("emailNotificationSettings after: ", ConfigurationPolicy.ErrorLog); Log.Write("BL response before: ", ConfigurationPolicy.ErrorLog); //Create Application var response = _blConnector.MemberCreateJobApplication( new JXTNext_MemberApplicationRequest { ApplyResourceID = result.JobId.Value, MemberID = 2, ResumePath = resumeAttachmentPath, CoverletterPath = coverletterAttachmentPath, EmailNotification = emailNotificationSettings, AdvertiserEmailNotification = advertiserEmailNotificationSettings, AdvertiserName = jobDetails.ContactDetails, CompanyName = jobDetails.CompanyName, UrlReferral = result.UrlReferral, RegistrationEmailNotification = registrationNotificationsSettings }, overrideEmail); Log.Write("BL response after: ", ConfigurationPolicy.ErrorLog); var createJobApplicationResponse = new CreateJobApplicationResponse { MemberApplicationResponse = response }; if (response.Success && response.ApplicationID.HasValue) { Log.Write("BL response in: ", ConfigurationPolicy.ErrorLog); var hasFailedUpload = _jobApplicationService.UploadFiles(attachments); Log.Write("file upload is : " + hasFailedUpload, ConfigurationPolicy.ErrorLog); if (hasFailedUpload) { createJobApplicationResponse.FilesUploaded = false; createJobApplicationResponse.Status = JobApplicationStatus.Technical_Issue; // Unable to attach files createJobApplicationResponse.Message = "Unable to attach files to application"; } else { createJobApplicationResponse.FilesUploaded = true; createJobApplicationResponse.Status = JobApplicationStatus.Applied_Successful; createJobApplicationResponse.Message = "Your application was successfully processed."; } } else { if (response.Errors.FirstOrDefault().ToLower().Contains("already exists")) { createJobApplicationResponse.Status = JobApplicationStatus.Already_Applied; createJobApplicationResponse.Message = "You have already applied to this job."; } else { createJobApplicationResponse.Status = JobApplicationStatus.Technical_Issue; createJobApplicationResponse.Message = response.Errors.FirstOrDefault(); } } return(createJobApplicationResponse); }
public ExpandoTypeDescriptor(ExpandoObject expando) { _expando = expando; }
internal string GetTextBody(EmailType emailType, BookingModel bookingModel) { var sb = new StringBuilder(File.ReadAllText($"EmailTemplate/Text/{emailType}.txt")); dynamic expando = new ExpandoObject(); var dictionary = (IDictionary <string, object>)expando; foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(BookingModel))) { try { if (property.PropertyType != typeof(List <string>)) { dictionary.Add(property.Name, Convert.ToString(property.GetValue(bookingModel))); } } catch (Exception ex) { throw; } } expando.ReaderTicket = bookingModel.ReaderTicket < 0 ? $"T{bookingModel.ReaderTicket*-1}" : $"{bookingModel.ReaderTicket}"; expando.HomeURL = Environment.GetEnvironmentVariable("HomeURL"); expando.ReturnURL = $"{expando.HomeURL}/return-to-booking"; expando.VisitType = bookingModel.BookingType == BookingTypes.StandardOrderVisit ? "Standard visit" : "Bulk order visit"; expando.Name = $"{bookingModel.FirstName} {bookingModel.LastName}"; expando.VisitStartDateDisplay = bookingModel.VisitStartDate.ToShortDateString(); expando.AdditionalRequirements = bookingModel.AdditionalRequirements ?? "None entered."; expando.Phone = bookingModel.Phone ?? "None entered."; if (bookingModel.BookingType == BookingTypes.StandardOrderVisit) { expando.ReadingRoom = bookingModel.SeatType == SeatTypes.StdRRSeat ? "Document reading room" : "Map and large document reading room"; } foreach (KeyValuePair <string, object> kv in dictionary) { sb = sb.Replace("{" + kv.Key + "}", (kv.Value != null ? kv.Value.ToString() : string.Empty)); } if (emailType == EmailType.BookingConfirmation || emailType == EmailType.DSDBookingConfirmation || emailType == EmailType.ValidOrderReminder) { var orderDocuments = new StringBuilder(); var documentCount = 0; foreach (var document in bookingModel.OrderDocuments.Where(d => !d.IsReserve).ToList()) { documentCount += 1; if (emailType == EmailType.DSDBookingConfirmation) { orderDocuments.AppendFormat("Document {0}: {1}", documentCount, document.DocumentReference); } else { orderDocuments.AppendFormat("Document {0}: {1}: {2}", documentCount, document.DocumentReference, document.Description); } } var reserveDocumentCount = 0; foreach (var document in bookingModel.OrderDocuments.Where(d => d.IsReserve).ToList()) { reserveDocumentCount += 1; if (emailType == EmailType.DSDBookingConfirmation) { orderDocuments.AppendFormat("Reserve document {0}: {1}", reserveDocumentCount, document.DocumentReference); } else { orderDocuments.AppendFormat("Reserve document {0}: {1}: {2}", reserveDocumentCount, document.DocumentReference, document.Description); } } sb = sb.Replace("{Order-Documents}", orderDocuments.ToString()); } return(sb.ToString()); }
private IDictionary <string, PayloadSchema> LoadPayloads() { if (_options.Modules is null) { return(new Dictionary <string, PayloadSchema>()); } var payloads = new Dictionary <string, PayloadSchema>(); var modulesPath = _options.ModulesPath; modulesPath = string.IsNullOrWhiteSpace(modulesPath) ? string.Empty : (modulesPath.EndsWith("/") ? modulesPath : $"{modulesPath}/"); foreach (var module in _options.Modules) { foreach (var route in module.Value.Routes) { if (string.IsNullOrWhiteSpace(route.Payload)) { continue; } var payloadsFolder = _options.PayloadsFolder; var fullPath = $"{modulesPath}{module.Value.Name}/{payloadsFolder}/{route.Payload}"; var fullJsonPath = fullPath.EndsWith(".json") ? fullPath : $"{fullPath}.json"; if (!File.Exists(fullJsonPath)) { continue; } var schemaPath = $"{modulesPath}{module.Value.Name}/{payloadsFolder}/{route.Schema}"; var fullSchemaPath = schemaPath.EndsWith(".json") ? schemaPath : $"{schemaPath}.json"; var schema = string.Empty; if (File.Exists(fullSchemaPath)) { schema = File.ReadAllText(fullSchemaPath); } var json = File.ReadAllText(fullJsonPath); dynamic expandoObject = new ExpandoObject(); JsonConvert.PopulateObject(json, expandoObject); var upstream = string.IsNullOrWhiteSpace(route.Upstream) ? string.Empty : route.Upstream; if (!string.IsNullOrWhiteSpace(module.Value.Path)) { var modulePath = module.Value.Path.EndsWith("/") ? module.Value.Path : $"{module.Value.Path}/"; if (upstream.StartsWith("/")) { upstream = upstream.Substring(1, upstream.Length - 1); } if (upstream.EndsWith("/")) { upstream = upstream.Substring(0, upstream.Length - 1); } upstream = $"{modulePath}{upstream}"; } if (string.IsNullOrWhiteSpace(upstream)) { upstream = "/"; } payloads.Add(GetKey(route.Method, upstream), new PayloadSchema(expandoObject, schema)); } } return(payloads); }
private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { dynamic result = new ExpandoObject(); var countSQL = ""; if (!string.IsNullOrEmpty(sql)) countSQL = string.Format("SELECT COUNT({0}) FROM ({1}) AS PagedTable", primaryKeyField, sql); else countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName); if (String.IsNullOrEmpty(orderBy)) { orderBy = string.IsNullOrEmpty(primaryKeyField) ? PrimaryKeyField : primaryKeyField; } if (!string.IsNullOrEmpty(where)) { if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase)) { where = " WHERE " + where; } } var query = ""; if (!string.IsNullOrEmpty(sql)) query = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM ({3}) AS PagedTable {4}) AS Paged ", columns, pageSize, orderBy, sql, where); else query = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where); var pageStart = (currentPage - 1) * pageSize; query += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize)); countSQL += where; result.TotalRecords = Scalar(countSQL, args); result.TotalPages = result.TotalRecords / pageSize; if (result.TotalRecords % pageSize > 0) result.TotalPages += 1; result.Items = Query(string.Format(query, columns, TableName), args); return result; }
/// <summary> /// Creates a new Expando from a Form POST - white listed against the columns in the DB /// </summary> public dynamic CreateFrom(NameValueCollection coll) { dynamic result = new ExpandoObject(); var dc = (IDictionary<string, object>)result; var schema = Schema; //loop the collection, setting only what's in the Schema foreach (var item in coll.Keys) { var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower()); if (exists) { var key = item.ToString(); var val = coll[key]; dc.Add(key, val); } } return result; }
protected void SerializeStruct(ExpandoObject obj) { this.mResultStringBuilder.Append("o"); foreach (string key in obj.GetDynamicMemberNames()) { SerializeString(key); Serialize(obj[key]); } this.mResultStringBuilder.Append("g"); }
private void btnMoveRight_Click(object sender, RoutedEventArgs e) { if (currentSelectedProduct != null && !allProductList.Contains(currentSelectedProduct)) { try { OptionProduct optionToMove = new OptionProduct(selectedOptionGuid, currentSelectedProduct.GUID); optionToMove.removeProductFromOption(); productList.Remove(currentSelectedProduct); allProductList.Add(currentSelectedProduct); lvAllProducts.ItemsSource = null; List <ExpandoObject> productListViewAll = new List <ExpandoObject>(); foreach (Product product in allProductList) { if (!productList.Contains(product)) { dynamic javascript = new ExpandoObject(); javascript.Name = product.Name; javascript.InStock = product.InStock ? "Yes" : "No"; javascript.Guid = product.GUID; productListViewAll.Add(javascript); } } lvAllProducts.ItemsSource = productListViewAll; lvOptionProducts.ItemsSource = null; List <ExpandoObject> productListView = new List <ExpandoObject>(); foreach (Product product in productList) { dynamic javascript = new ExpandoObject(); javascript.Name = product.Name; javascript.InStock = product.InStock ? "Yes" : "No"; javascript.Guid = product.GUID; productListView.Add(javascript); } lvOptionProducts.ItemsSource = productListView; if (productList.Count != 0) { lvOptionProducts.SelectedIndex = 0; currentSelectedProduct = productList.ElementAt(0); updateInnerView(productList.ElementAt(0)); } updateOptionCost(); EventBus.EventBus.Instance.PostEvent(new CustomEvent("OptionInserted")); // do SQL query on specificProduct; } catch (InvalidOperationException exception) { ErrorHandler.ErrorHandle error = ErrorHandler.ErrorHandle.getInstance(); error.handle(exception, false, true); } } }
public void Handle(IEnumerable <Domain.Entities.DataRecord> records, Guid userId) { //var userId = StructureGraph.Instance.GetRootUser(); //группируем по объектам var objGroups = records.GroupBy(r => r.ObjectId); foreach (var objGroup in objGroups) { var cache = CacheRepository.Instance.GetCache(objGroup.Key); if (cache == null) { cache = new ExpandoObject(); } var dcache = cache as IDictionary <string, object>; //группируем по типам var typeGroups = objGroup.GroupBy(r => r.Type); foreach (var typeGroup in typeGroups) { if (typeGroup.Key != "LogMessage") { ; } foreach (var record in typeGroup) { switch (typeGroup.Key) { case "Day": { record.Date = record.Date.Date; dynamic dayCurrent = null; if (dcache.ContainsKey("dayCurrent")) { dayCurrent = cache.dayCurrent; } dynamic dayPreview = null; if (dcache.ContainsKey("dayPreview")) { dayPreview = cache.dayPreview; } //DateTime dt = ((DateTime)dayCurrent.date).ToLocalTime(); //long ticks = dt.Date.Ticks; if (dayCurrent == null || record.Date > dayCurrent.date.ToLocalTime().Date) { dayPreview = dayCurrent; dayCurrent = new ExpandoObject(); dayCurrent.date = record.Date; dayCurrent.records = new List <dynamic>() { record.ToDynamic() }; cache.Day = new List <dynamic>(); } if (dayPreview != null && record.Date < dayPreview.date) { continue; } if (dayCurrent != null && dayCurrent.date == record.Date) { var duplicate = (dayCurrent.records as IEnumerable <dynamic>).FirstOrDefault(r => r.s1 == record.S1); if (duplicate != null) { dayCurrent.records.Remove(duplicate); } dayCurrent.records.Add(record.ToDynamic()); } if (dayPreview != null && dayPreview.date == record.Date) { var duplicate = (dayPreview.records as IEnumerable <dynamic>).FirstOrDefault(r => r.s1 == record.S1); if (duplicate != null) { dayPreview.records.Remove(duplicate); } dayPreview.records.Add(record.ToDynamic()); } cache.dayCurrent = dayCurrent; cache.dayPreview = dayPreview; var parameters = CacheRepository.Instance.GetParameters(record.ObjectId); foreach (var parameter in parameters) { var rec = (dayCurrent.records as IEnumerable <dynamic>).FirstOrDefault(r => r.s1 == (string)parameter.name); if (rec == null) { continue; } var dparameter = parameter as IDictionary <string, object>; if (!dparameter.ContainsKey("tag")) { continue; } dynamic day = new ExpandoObject(); var calc = "normal"; if (dparameter.ContainsKey("calc")) { calc = (string)parameter.calc; } if (calc == "total") { if (dayPreview == null) { continue; } var recPrv = (dayPreview.records as IEnumerable <dynamic>).FirstOrDefault(r => r.s1 == rec.s1); if (recPrv == null) { continue; } day.d1 = rec.d1 - recPrv.d1; } else { day.d1 = rec.d1; } day.s1 = parameter.tag; day.s2 = rec.s2; day.date = rec.date; var duplicates = (cache.Day as IEnumerable <dynamic>).Where(r => r.s1 == day.s1).ToArray(); foreach (var dublicate in duplicates) { cache.Day.Remove(dublicate); } cache.Day.Add(day); } break; } case "Current": { if (!dcache.ContainsKey("Current") || !(cache.Current is List <dynamic>)) { cache.Current = new List <dynamic>(); } cache.Current.Add(record.ToDynamic()); var dates = (cache.Current as IEnumerable <dynamic>).Select(d => (DateTime)d.date).Distinct().OrderBy(d => d); if (dates.Count() > 1) { var border = dates.ElementAt(1); cache.Current = (cache.Current as IEnumerable <dynamic>).Where(r => r.date > border).ToArray(); } break; } case "Constant": { if (!dcache.ContainsKey("Constant") || !(cache.Constant is List <dynamic>)) { cache.Constant = new List <dynamic>(); } var drec = record.ToDynamic(); if (!(cache.Constant as List <dynamic>).Any(c => c.s1 == drec.s1)) { cache.Constant.Add(drec); } break; } case "Abnormal": { if (!dcache.ContainsKey("Abnormal") || !(cache.Abnormal is List <dynamic>)) { cache.Abnormal = new List <dynamic>(); } cache.Abnormal.Add(record.ToDynamic()); var dates = (cache.Abnormal as IEnumerable <dynamic>).Select(d => (DateTime)d.date).Distinct().OrderBy(d => d); if (dates.Count() > ABNORMAL_LIMIT) { var border = dates.ElementAt(ABNORMAL_LIMIT); cache.Abnormal = (cache.Abnormal as IEnumerable <dynamic>).Where(r => r.date > border).ToArray(); } break; } case "MatrixSignal": { if (!dcache.ContainsKey("Signal")) { cache.Signal = new ExpandoObject(); } cache.Signal.date = record.Date; cache.Signal.value = record.D1; //related tube? break; } default: break; } } } CacheRepository.Instance.SaveCache(objGroup.Key, cache); Carantine.Instance.Push(objGroup.Key); } }
/// <summary> /// IDataReader转换为T集合的集合 /// </summary> /// <typeparam name="T">泛型类型</typeparam> /// <param name="this">IDataReader数据源</param> /// <returns>T类型集合的集合</returns> public static List <List <T> > ToLists <T>(this IDataReader @this) { var result = new List <List <T> >(); if (@this?.IsClosed == false) { using (@this) { var type = typeof(T); do { #region IDictionary if (type.IsDictionaryType()) { var list = new List <Dictionary <string, object> >(); while (@this.Read()) { var dic = new Dictionary <string, object>(); for (var i = 0; i < @this.FieldCount; i++) { dic[@this.GetName(i)] = @this.GetValue(i); } list.Add(dic); } if (!type.AssignableTo(typeof(Dictionary <,>))) { result.Add(list.Select(o => o as IDictionary <string, object>).ToList() as List <T>); } else { result.Add(list as List <T>); } } #endregion #region Class T else if (type.IsClass && !type.IsDynamicOrObjectType() && !type.IsStringType()) { var list = new List <T>(); var fields = new List <string>(); for (int i = 0; i < @this.FieldCount; i++) { fields.Add(@this.GetName(i)); } while (@this.Read()) { var instance = Activator.CreateInstance <T>(); var props = instance.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); foreach (var p in props) { if (!p.CanWrite) { continue; } var field = fields.Where(o => o.EqualIgnoreCase(p.Name)).FirstOrDefault(); if (!field.IsNullOrEmpty() && !@this[field].IsNull()) { p.SetValue(instance, @this[field].ToSafeValue(p.PropertyType), null); } } list.Add(instance); } result.Add(list); } #endregion #region dynamic else { var list = new List <dynamic>(); while (@this.Read()) { var row = new ExpandoObject() as IDictionary <string, object>; for (var i = 0; i < @this.FieldCount; i++) { row.Add(@this.GetName(i), @this.GetValue(i)); } list.Add(row); } var item = list as List <T>; if (item == null && (type.IsStringType() || type.IsValueType())) { //适合查询单个字段的结果集 item = list.Select(o => (T)(o as IDictionary <string, object>).Select(x => x.Value).FirstOrDefault()).ToList(); } result.Add(item); } #endregion } while (@this.NextResult()); } } return(result); }
public Tuple <bool, List <object> > UploadValidate(List <UnitViewModel> Data, List <KeyValuePair <string, StringValues> > Body) { List <object> ErrorList = new List <object>(); string ErrorMessage; bool Valid = true; Division division = null; foreach (UnitViewModel unitVM in Data) { ErrorMessage = ""; if (string.IsNullOrWhiteSpace(unitVM.Code)) { ErrorMessage = string.Concat(ErrorMessage, "Kode tidak boleh kosong, "); } else if (Data.Any(d => d != unitVM && d.Code.Equals(unitVM.Code))) { ErrorMessage = string.Concat(ErrorMessage, "Kode tidak boleh duplikat, "); } if (string.IsNullOrWhiteSpace(unitVM.Name)) { ErrorMessage = string.Concat(ErrorMessage, "Nama tidak boleh kosong, "); } else if (Data.Any(d => d != unitVM && d.Name.Equals(unitVM.Name))) { ErrorMessage = string.Concat(ErrorMessage, "Nama tidak boleh duplikat, "); } if (string.IsNullOrWhiteSpace(unitVM.Division.Name)) { ErrorMessage = string.Concat(ErrorMessage, "Divisi tidak boleh kosong, "); } if (string.IsNullOrEmpty(ErrorMessage)) { /* Service Validation */ division = this.DbContext.Set <Division>().FirstOrDefault(d => d._IsDeleted.Equals(false) && d.Name.Equals(unitVM.Division.Name)); if (this.DbSet.Any(d => d._IsDeleted.Equals(false) && d.Code.Equals(unitVM.Code))) { ErrorMessage = string.Concat(ErrorMessage, "Kode tidak boleh duplikat, "); } if (this.DbSet.Any(d => d._IsDeleted.Equals(false) && d.Name.Equals(unitVM.Name))) { ErrorMessage = string.Concat(ErrorMessage, "Nama tidak boleh duplikat, "); } if (division == null) { ErrorMessage = string.Concat(ErrorMessage, "Divisi tidak terdaftar di Master Divisi, "); } } if (string.IsNullOrEmpty(ErrorMessage)) { unitVM.Division.Id = division.Id; unitVM.Division.Code = division.Code; } else { ErrorMessage = ErrorMessage.Remove(ErrorMessage.Length - 2); var Error = new ExpandoObject() as IDictionary <string, object>; Error.Add("Kode Unit", unitVM.Code); Error.Add("Divisi", unitVM.Name); Error.Add("Nama", unitVM.Name); Error.Add("Deskripsi", unitVM.Description); Error.Add("Error", ErrorMessage); ErrorList.Add(Error); } } if (ErrorList.Count > 0) { Valid = false; } return(Tuple.Create(Valid, ErrorList)); }
public object Unserialize() { switch ((int)mString[mPosition++]) { case 110: // 'n' return null; //break; case 116: // 't' return true; //break; case 102: // 'f' return false; //break; case 122: // 'z' return 0; //break; case 105: // 'i' return ReadDigits(); //break; case 100: // 'd' int p1 = mPosition; while(true) { int c = mString[mPosition]; if ((c >= 43 && c < 58) || c == 101 || c == 69) mPosition++; else break; } return Convert.ToSingle(mString.Substring(p1,mPosition - p1)); //break; case 121: // 'y' int len = ReadDigits(); if (mString[mPosition++] != ':' || mString.Length - mPosition < len) throw new Exception("Invalid string length"); string s = mString.Substring(mPosition, len); mPosition += len; s = System.Uri.UnescapeDataString(s); mStringsCache.Add(s); return s; //break; case 107: // 'k' return float.NaN; //break; case 109: // 'm' return float.NegativeInfinity;; //break; case 112: // 'p' return float.PositiveInfinity; //break; case 97: // 'a' ArrayList a = new ArrayList(); this.mCache.Add(a); while(true) { int c2 = mString[mPosition]; if (c2 == 104) { mPosition++; break; } if (c2 == 117) { mPosition++; int n = ReadDigits(); a[a.Count + n - 1] = null; } else { a.Add(Unserialize()); } } return a; //break; case 111: // 'o' ExpandoObject o = new ExpandoObject(); mCache.Add(o); UnserializeObject(ref o); return o; //break; case 114: // 'r' int n2 = ReadDigits(); if (n2 < 0 || n2 >= mCache.Count) throw new Exception("Invalid reference"); return mCache[n2]; //break; case 82: // 'R' int n3 = ReadDigits(); if (n3 < 0 || n3 >= mStringsCache.Count) throw new Exception("Invalid string reference"); return mStringsCache[n3]; //break; case 120: // 'x' throw (Exception) Unserialize(); //break; case 99: // 'c' // string name = this.Unserialize(); // var cl : Class = this.resolver.resolveClass(name); // if(cl == null) throw "Class not found " + name; // var o2 : * = Type.createEmptyInstance(cl); // this.cache.push(o2); // this.unserializeObject(o2); // return o2; break; case 119: // 'w' // string name2 = Unserialize(); // var edecl : Class = this.resolver.resolveEnum(name2); // if(edecl == null) throw "Enum not found " + name2; // return this.unserializeEnum(edecl,this.unserialize()); break; case 106: // 'j' // var name3 : String = this.unserialize(); // var edecl2 : Class = this.resolver.resolveEnum(name3); // if(edecl2 == null) throw "Enum not found " + name3; // this.pos++; // var index : int = this.readDigits(); // var tag : String = Type.getEnumConstructs(edecl2)[index]; // if(tag == null) throw "Unknown enum index " + name3 + "@" + index; // return this.unserializeEnum(edecl2,tag); break; case 108: // 'l' ArrayList l = new ArrayList(); mCache.Add(l); while (mString[mPosition] != 104) l.Add(Unserialize()); mPosition++; return l; //break; case 98: // 'b' Hashtable h = new Hashtable(); mCache.Add(h); while(mString[mPosition] != 104) // 'h' = 104 { string s2 = (string)Unserialize(); h[s2] = Unserialize(); } mPosition++; return h; //break; case 113: // 'q' Hashtable h2 = new Hashtable(); mCache.Add(h2); int c3 = mString[mPosition++]; while (c3 == 58) // ':' { int i = ReadDigits(); h2[i] = Unserialize(); c3 = mString[mPosition++]; } if (c3 != 104) // 'h' throw new Exception("Invalid IntHash format"); return h2; //break; case 118: // 'v' DateTime d = Convert.ToDateTime(mString.Substring(mPosition,19)); mCache.Add(d); mPosition += 19; return d; //break; case 115: // 's' - base64 encoded bytes int len2 = ReadDigits(); if (mString[mPosition++] != ':' || mString.Length - mPosition < len2) throw new Exception("Invalid bytes length"); byte[] bytes = Convert.FromBase64String(mString.Substring(mPosition, len2)); mPosition += len2; mCache.Add(bytes); return bytes; //break; // default: // break; } mPosition--; throw new Exception("Invalid char " + mString[mPosition] + " at position " + mPosition); }
void OnPlayerKilled(int killerServerIndex, ExpandoObject info) { Debug.WriteLine($"killer: {killerServerIndex}"); TriggerServerEvent("sth:sendserverkillerserverindex", killerServerIndex); }
/// <summary> /// Save content /// </summary> /// <param name="model">The edit model</param> public async Task SaveAsync(ContentEditModel model) { var contentType = App.ContentTypes.GetById(model.TypeId); if (contentType != null) { if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } var content = await _api.Content.GetByIdAsync(model.Id, model.LanguageId); if (content == null) { content = await _factory.CreateAsync <DynamicContent>(contentType); content.Id = model.Id; } content.TypeId = model.TypeId; content.Title = model.Title; content.Excerpt = model.Excerpt; content.PrimaryImage = model.PrimaryImage; // Save regions foreach (var region in contentType.Regions) { var modelRegion = model.Regions .FirstOrDefault(r => r.Meta.Id == region.Id); if (region.Collection) { var listRegion = (IRegionList)((IDictionary <string, object>)content.Regions)[region.Id]; listRegion.Clear(); foreach (var item in modelRegion.Items) { if (region.Fields.Count == 1) { listRegion.Add(item.Fields[0].Model); } else { var postRegion = new ExpandoObject(); foreach (var field in region.Fields) { var modelField = item.Fields .FirstOrDefault(f => f.Meta.Id == field.Id); ((IDictionary <string, object>)postRegion)[field.Id] = modelField.Model; } listRegion.Add(postRegion); } } } else { var postRegion = ((IDictionary <string, object>)content.Regions)[region.Id]; if (region.Fields.Count == 1) { ((IDictionary <string, object>)content.Regions)[region.Id] = modelRegion.Items[0].Fields[0].Model; } else { foreach (var field in region.Fields) { var modelField = modelRegion.Items[0].Fields .FirstOrDefault(f => f.Meta.Id == field.Id); ((IDictionary <string, object>)postRegion)[field.Id] = modelField.Model; } } } } // Save content await _api.Content.SaveAsync(content, model.LanguageId); } else { throw new ValidationException("Invalid Content Type."); } }
//Checks to see if a key is present based on the passed-in value public virtual bool ItemContainsKey(string key, ExpandoObject item) { var dc = ItemAsDictionary(item); return(dc.ContainsKey(key)); }
public static void OtherInterestingFeatures() { // OPTIONAL PARAMETERS MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones // BY REF AND OUT PARAMETERS int maxCount = 0, count; // ref params must have value MethodSignatures(ref maxCount, out count); // EXTENSION METHODS int i = 3; i.Print(); // Defined below // NULLABLE TYPES - great for database interaction / return values // any value type (i.e. not a class) can be made nullable by suffixing a ? // <type>? <var name> = <value> int?nullable = null; // short hand for Nullable<int> Console.WriteLine("Nullable variable: " + nullable); bool hasValue = nullable.HasValue; // true if not null // ?? is syntactic sugar for specifying default value (coalesce) // in case variable is null int notNullable = nullable ?? 0; // 0 // ?. is an operator for null-propagation - a shorthand way of checking for null nullable?.Print(); // Use the Print() extension method if nullable isn't null // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: var magic = "magic is a string, at compile time, so you still get type safety"; // magic = 9; will not work as magic is a string, not an int // GENERICS // var phonebook = new Dictionary <string, string>() { { "Sarah", "212 555 5555" } // Add some entries to the phone book }; // Calling SETDEFAULT defined as a generic above Console.WriteLine(SetDefault <string, string>(phonebook, "Shaun", "No Phone")); // No Phone // nb, you don't need to specify the TKey and TValue since they can be // derived implicitly Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 // LAMBDA EXPRESSIONS - allow you to write code in line Func <int, int> square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 // ERROR HANDLING - coping with an uncertain world try { var funBike = PennyFarthing.CreateWithGears(6); // will no longer execute because CreateWithGears throws an exception string some = ""; if (true) { some = null; } some.ToLower(); // throws a NullReferenceException } catch (NotSupportedException) { Console.WriteLine("Not so much fun now!"); } catch (Exception ex) // catch all other exceptions { throw new ApplicationException("It hit the fan", ex); // throw; // A rethrow that preserves the callstack } // catch { } // catch-all without capturing the Exception finally { // executes after try or catch } // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); // At the end of scope, resources will be released. // Even if an exception is thrown. } // PARALLEL FRAMEWORK // https://devblogs.microsoft.com/csharpfaq/parallel-programming-in-net-framework-4-getting-started/ var words = new List <string> { "dog", "cat", "horse", "pony" }; Parallel.ForEach(words, new ParallelOptions() { MaxDegreeOfParallelism = 4 }, word => { Console.WriteLine(word); } ); // Running this will produce different outputs // since each thread finishes at different times. // Some example outputs are: // cat dog horse pony // dog horse pony cat // DYNAMIC OBJECTS (great for working with other languages) dynamic student = new ExpandoObject(); student.FirstName = "First Name"; // No need to define class first! // You can even add methods (returns a string, and takes in a string) student.Introduce = new Func <string, string>( (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of // very useful Map / Filter / Reduce style methods var bikes = new List <Bicycle>(); bikes.Sort(); // Sorts the array bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels var result = bikes .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) .Where(b => b.IsBroken && b.HasTassles) .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable<string> var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection // Create a list of IMPLICIT objects based on some parameters of the bike var bikeSummaries = bikes.Select(b => new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); // Hard to show here, but you get type ahead completion since the compiler can implicitly work // out the types above! foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) { Console.WriteLine(bikeSummary.Name); } // ASPARALLEL // And this is where things get wicked - combine linq and parallel operations var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); // this will happen in parallel! Threads will automagically be spun up and the // results divvied amongst them! Amazing for large datasets when you have lots of // cores // LINQ - maps a store to IQueryable<T> objects, with delayed execution // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document var db = new BikeRepository(); // execution is delayed, which is great when querying a database var filter = db.Bikes.Where(b => b.HasTassles); // no query run if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality { filter = filter.Where(b => b.IsBroken); // no query run } var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) .Select(b => b.Name); // still no query run // Now the query runs, but opens a reader, so only populates as you iterate through foreach (string bike in query) { Console.WriteLine(result); } }
//2.4.3.10 Расширенное чтение времени интегрирования мощности для массива профиля dynamic GetArray(int maxProfile) { dynamic answer = new ExpandoObject(); answer.success = true; answer.error = string.Empty; answer.errorcode = DeviceError.NO_ERROR; answer.select = maxProfile; //нет такого массива профиля //2.4.3.10 Расширенное чтение времени интегрирования мощности для массива профиля byte[] aTimeInterval = new byte[maxProfile]; byte maxN = 0; byte maxTI = 0; for (byte nArray = 0; nArray < maxProfile; nArray++) { var rsp = Send(MakeRequestParameters(0x06, new byte[] { nArray })); if (!rsp.success) { return(rsp); } aTimeInterval[nArray] = rsp.Body[1]; if (aTimeInterval[nArray] <= 60 && aTimeInterval[nArray] > maxTI) { maxN = nArray; maxTI = aTimeInterval[nArray]; } } //выбираем массив профилей не большее часа и менее отличаюшейся от часа /*for (byte nArray = 0; nArray < maxProfile; nArray++) * if (aTimeInterval[nArray] <= 60) * { * answer.select = nArray; * answer.TimeInterval = aTimeInterval[answer.select]; * }*/ if (maxTI > 0) { answer.select = maxN; answer.TimeInterval = maxTI; } if (answer.select >= maxProfile) //{ // byte minTime = (byte)(60 - aTimeInterval[answer.select]); // for (byte nArray = 0; nArray < maxProfile; nArray++) // { // if ((minTime > aTimeInterval[nArray]) && (aTimeInterval[nArray] <= 60)) // { // answer.select = nArray; // minTime = (byte)(60 - aTimeInterval[answer.select]); // answer.TimeInterval = aTimeInterval[answer.select]; // } // } //} //else { answer.success = false; answer.error = string.Format("Нет профилей мощности с периодои интегрирования менее или равно 60 минут. Чтение часовых профилей невозможно."); answer.errorcode = DeviceError.NO_ERROR; } return(answer); }
/// <summary> /// Turns the object into an ExpandoObject /// </summary> public static dynamic ToExpando(this object o) { var result = new ExpandoObject(); var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i)); } else { var props = o.GetType().GetProperties(); foreach (var item in props) { d.Add(item.Name, item.GetValue(o, null)); } } return result; }
protected void UnserializeObject(ref ExpandoObject o) { while(true) { if (mPosition >= mString.Length) throw new Exception("Invalid object"); if (mString[mPosition] == 'g') break; string k = (string)Unserialize(); //if (! k is string) // throw "Invalid object key"; object v = Unserialize(); o[k] = v; } mPosition++; }
/// <summary> /// Gets the index at which the value should be stored for the specified name. /// </summary> internal int GetValueIndex(string name, bool caseInsensitive, ExpandoObject obj) { if (caseInsensitive) { return GetValueIndexCaseInsensitive(name, obj); } else { return GetValueIndexCaseSensitive(name); } }
/// <summary> /// This will return an Expando as a Dictionary /// </summary> public virtual IDictionary <string, object> ItemAsDictionary(ExpandoObject item) { return((IDictionary <string, object>)item); }
public static ExpandoObject ShapeData <TSource>(this TSource source, string fields) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var dataShapedObject = new ExpandoObject(); if (string.IsNullOrWhiteSpace(fields)) { // all public properties should be in the ExpandoObject var propertyInfos = typeof(TSource) .GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); foreach (var propertyInfo in propertyInfos) { // get the value of the property on the source object var propertyValue = propertyInfo.GetValue(source); // add the field to the ExpandoObject ((IDictionary <string, object>)dataShapedObject) .Add(propertyInfo.Name, propertyValue); } return(dataShapedObject); } // the field are separated by ",", so we split it. var fieldsAfterSplit = fields.Split(','); foreach (var field in fieldsAfterSplit) { // trim each field, as it might contain leading // or trailing spaces. Can't trim the var in foreach, // so use another var. var propertyName = field.Trim(); // use reflection to get the property on the source object // we need to include public and instance, b/c specifying a // binding flag overwrites the already-existing binding flags. var propertyInfo = typeof(TSource) .GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo == null) { throw new Exception($"Property {propertyName} wasn't found " + $"on {typeof(TSource)}"); } // get the value of the property on the source object var propertyValue = propertyInfo.GetValue(source); // add the field to the ExpandoObject ((IDictionary <string, object>)dataShapedObject) .Add(propertyInfo.Name, propertyValue); } // return the list return(dataShapedObject); }