/// <summary> /// Connects the ucs. /// </summary> /// <param name="configObject">The configuration object.</param> /// <param name="contactAppName">Name of the application.</param> /// <returns></returns> public OutputValues ConnectUCS(ConfService configObject, NullableInt tenantDBID, string contactAppName, Func <bool, bool> contactServerNotification) { OutputValues output = null; ReadConfigObjects readConfigObjects = new ReadConfigObjects(); try { Settings.comObject = configObject; Settings.tenantDBID = tenantDBID; readConfigObjects.ReadApplicationObject(contactAppName); ContactConnectionManager createProtocol = new ContactConnectionManager(); createProtocol.ContactServerNotificationHandler += new NotifyContactServerState(contactServerNotification); output = createProtocol.ConnectContactServer(Settings.PrimaryApplication, Settings.SecondaryApplication); if (output.MessageCode == "200") { messageToClient.NotifyContactProtocol(Settings.UCSProtocol); } else { messageToClient.NotifyContactProtocol(Settings.UCSProtocol); } } catch (Exception commonException) { logger.Error("ContactLibrary:ConnectUCS:" + commonException.ToString()); } return(output); }
public void Test() { const int testValue = 0; NullableInt ni = new NullableInt(); ni.I = testValue; ni.II = testValue; using (DbManager db = new DbManager()) { IDbDataParameter[] ps = db.CreateParameters(ni); foreach (IDbDataParameter p in ps) { switch (p.ParameterName) { case "@I": Assert.AreEqual(testValue, p.Value); break; case "@II": Assert.AreEqual(testValue, p.Value); break; } } } }
public override int GetHashCode() { if (Id != 0) { return(Id.GetHashCode()); } return(AnInt.GetHashCode() + (AString?.GetHashCode() ?? 0) + (NullableInt?.GetHashCode() ?? 0) + (OfficialName?.GetHashCode() ?? 0)); }
public void TestRoundtripNullableInt([ValueSource(nameof(NullableIntValues))] int?value) { var obj = new NullableInt { Value = value }; var actualObj = Roundtrip(obj); actualObj.Should().NotBeNull(); actualObj.Value.Should().Be(value); }
public override int GetHashCode() { unchecked { int hashCode = Date.GetHashCode(); hashCode = (hashCode * 397) ^ NullableInt.GetHashCode(); hashCode = (hashCode * 397) ^ (InterfaceHolder != null ? InterfaceHolder.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ObjectHolder != null ? ObjectHolder.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (BaseType != null ? BaseType.GetHashCode() : 0); return(hashCode); } }
public override int GetHashCode() { unchecked { int hashCode = (BaseType != null ? BaseType.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Date.GetHashCode(); hashCode = (hashCode * 397) ^ (InterfaceHolder != null ? InterfaceHolder.GetHashCode() : 0); hashCode = (hashCode * 397) ^ NullableInt.GetHashCode(); hashCode = (hashCode * 397) ^ (PolymorphicHolder != null ? PolymorphicHolder.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Array != null ? Array.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (GuidCollection != null ? GuidCollection.GetHashCode() : 0); return(hashCode); } }
private static void ApplyLabel(ReadOnlyBlockadeState state, Grid <NullableInt> labels, Location location, int label) { Throw.If(labels[location].HasValue); labels[location] = new NullableInt(label); GetD1Neighbors(state, location, distance: 1) .ToList() .ForEach(newLocation => { // not using Where() because we need to evaluate condition immediately before recursing if (!labels[newLocation].HasValue && state.GetCell(newLocation).IsEmpty()) { ApplyLabel(state, labels, newLocation, label); } }); }
/// <summary> /// Gets the agent favorite response. /// </summary> /// <param name="agentId">The agent identifier.</param> /// <returns></returns> public static OutputValues GetAgentFavoriteResponse(NullableInt agentId) { Pointel.Logger.Core.ILog logger = Pointel.Logger.Core.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "AID"); OutputValues output = OutputValues.GetInstance(); try { RequestGetAgentStdRespFavorites requestGetAgentStdRespFavorites = new RequestGetAgentStdRespFavorites(); requestGetAgentStdRespFavorites.AgentId = agentId; if (Settings.UCSProtocol != null && Settings.UCSProtocol.State == ChannelState.Opened) { logger.Info("--------GetAgentFavoriteResponse---------"); logger.Info("AgentId :" + agentId); logger.Info("------------------------------------------"); IMessage response = Settings.UCSProtocol.Request(requestGetAgentStdRespFavorites); if (response != null) { logger.Trace(response.ToString()); output.IContactMessage = response; output.MessageCode = "200"; output.Message = "Get Agent Standard Response Favorites Successful"; } else { output.IContactMessage = null; output.MessageCode = "2001"; output.Message = "Don't Get Agent Standard Response Favorites Successful"; } } else { output.IContactMessage = null; output.MessageCode = "2001"; output.Message = "Universal Contact Server protocol is Null or Closed"; logger.Warn("GetAgentFavoriteResponse() : Universal Contact Server Protocol is Null"); } } catch (Exception generalException) { logger.Error("Error Occurred while Get Agent Standard Response Favorites request" + generalException.ToString()); output.IContactMessage = null; output.MessageCode = "2001"; output.Message = generalException.Message; } return(output); }
public void TestQueryNullableValue() { foreach (IDataService dataService in DataServices) { if (dataService is OracleDataService && typeof(SQLDataService).Assembly.ImageRuntimeVersion.StartsWith("v2")) { ///TODO: Исправить конвертацию для OracleDataService decimal в char, если используется System.Data.OracleClient (в Net3.5). ///Для версии Net4.0 и выше используется Oracle.ManagedDataAccess.Client, для которого исправление не требуется. continue; } var ds = (SQLDataService)dataService; NullableDateTime date = new NullableDateTime(); date.Value = DateTime.Now; NullableDecimal dec = new NullableDecimal(); dec.Value = new decimal(77.111); NullableDecimal decGreater = new NullableDecimal(); decGreater.Value = dec.Value + new decimal(0.001); NullableInt i = new NullableInt(); i.Value = 77; FullTypesMaster1 fullTypes = new FullTypesMaster1() { PoleNullableDateTime = date, PoleNullableDecimal = dec, PoleNullableInt = i }; // Сохранение данных. var updateObjectsArray = new ICSSoft.STORMNET.DataObject[] { fullTypes }; ds.UpdateObjects(ref updateObjectsArray); // Выбор представления. var view = FullTypesMaster1.Views.FullMasterView; List <FullTypesMaster1> list; // Проверка поиска NullableDateTime. list = ds.Query <FullTypesMaster1>(view).Where(d => d.PoleNullableDateTime.Value <= date.Value).ToList(); Assert.Equal(1, list.Count); // Проверка поиска NullableDecimal. list = ds.Query <FullTypesMaster1>(view).Where(d => d.PoleNullableDecimal.Value < decGreater.Value).ToList(); Assert.Equal(1, list.Count); // Проверка поиска NullableInt. list = ds.Query <FullTypesMaster1>(view).Where(d => d.PoleNullableInt.Value == i.Value).ToList(); Assert.Equal(1, list.Count); } }
internal void WriteInheritedOptionInfo() { Console.WriteLine("Int:{0},BoolValue:{1},EnumValue:{2},NullableInt:{3},NullableBoolValue:{4},NullableEnum:{5}", Int, BoolValue, EnumValue, NullableInt.HasValue ? NullableInt.ToString() : "null", NullableBoolValue.HasValue ? NullableBoolValue.ToString() : "null", NullableEnum.HasValue ? NullableEnum.ToString() : "null", StringValue); Console.WriteLine($"StringValue:{StringValue}"); Console.WriteLine($"MutiIntValues{MutiIntValues.Length}:"); for (int i = 0; i < MutiIntValues.Length; i++) { Console.WriteLine($"\t[{i}]:{MutiIntValues[i]}"); } }
protected void SubmitButton_Click(object sender, EventArgs e) { string szMessage = null; bool boTransactionSuccessful = false; StringBuilder sbString; int nCount = 0; int nTemp; CardDetailsTransaction cdtCardDetailsTransaction; RequestGatewayEntryPointList lrgepRequestGatewayEntryPoints; GatewayOutput goGatewayOutput; TransactionOutputMessage tomTransactionOutputMessage; TransactionControl tcTransactionControl; CardDetails cdCardDetails; CreditCardDate ccdExpiryDate = null; CreditCardDate ccdStartDate = null; CustomerDetails cdCustomerDetails = null; NullableInt nCountryCode = null; NullableInt nExpiryDateMonth = null; NullableInt nExpiryDateYear = null; NullableInt nStartDateMonth = null; NullableInt nStartDateYear = null; string szPreviousTransactionMessage = null; bool boDuplicateTransaction = false; lrgepRequestGatewayEntryPoints = new RequestGatewayEntryPointList(); // you need to put the correct gateway entry point urls in here // contact support to get the correct urls // The actual values to use for the entry points can be established in a number of ways // 1) By periodically issuing a call to GetGatewayEntryPoints // 2) By storing the values for the entry points returned with each transaction // 3) Speculatively firing transactions at https://gw1.xxx followed by gw2, gw3, gw4.... // The lower the metric (2nd parameter) means that entry point will be attempted first, // EXCEPT if it is -1 - in this case that entry point will be skipped // NOTE: You do NOT have to add the entry points in any particular order - the list is sorted // by metric value before the transaction sumbitting process begins // The 3rd parameter is a retry attempt, so it is possible to try that entry point that number of times // before failing over onto the next entry point in the list lrgepRequestGatewayEntryPoints.Add(new RequestGatewayEntryPoint("https://gw1." + Global.PaymentProcessorFullDomain, 100, 2)); lrgepRequestGatewayEntryPoints.Add(new RequestGatewayEntryPoint("https://gw2." + Global.PaymentProcessorFullDomain, 200, 2)); lrgepRequestGatewayEntryPoints.Add(new RequestGatewayEntryPoint("https://gw3." + Global.PaymentProcessorFullDomain, 300, 2)); tcTransactionControl = new TransactionControl(new NullableBool(true), new NullableBool(true), new NullableBool(true), new NullableBool(true), new NullableInt(60), null, null, null, null, null, null); if (!String.IsNullOrEmpty(ddExpiryDateMonth.SelectedValue)) { nExpiryDateMonth = new NullableInt(System.Convert.ToInt32(ddExpiryDateMonth.SelectedValue)); } if (!String.IsNullOrEmpty(ddExpiryDateYear.SelectedValue)) { nExpiryDateYear = new NullableInt(System.Convert.ToInt32(ddExpiryDateYear.SelectedValue)); } ccdExpiryDate = new CreditCardDate(nExpiryDateMonth, nExpiryDateYear); if (!String.IsNullOrEmpty(ddStartDateMonth.SelectedValue)) { nStartDateMonth = new NullableInt(System.Convert.ToInt32(ddStartDateMonth.SelectedValue)); } if (!String.IsNullOrEmpty(ddStartDateYear.SelectedValue)) { nStartDateYear = new NullableInt(System.Convert.ToInt32(ddStartDateYear.SelectedValue)); } ccdStartDate = new CreditCardDate(nStartDateMonth, nStartDateYear); cdCardDetails = new CardDetails(tbCardName.Text, tbCardNumber.Text, ccdExpiryDate, ccdStartDate, tbIssueNumber.Text, tbCV2.Text); if (!String.IsNullOrEmpty(ddCountries.SelectedValue)) { nTemp = System.Convert.ToInt32(ddCountries.SelectedValue); if (nTemp != -1) { nCountryCode = new NullableInt(nTemp); } } cdCustomerDetails = new CustomerDetails(new AddressDetails(tbAddress1.Text, tbAddress2.Text, tbAddress3.Text, tbAddress4.Text, tbCity.Text, tbState.Text, tbPostCode.Text, nCountryCode), "*****@*****.**", "123456789", Request.UserHostAddress); cdtCardDetailsTransaction = new CardDetailsTransaction(lrgepRequestGatewayEntryPoints, new MerchantDetails(Global.MerchantID, Global.Password), new TransactionDetails(TRANSACTION_TYPE.SALE, new NullableInt(System.Convert.ToInt32(hfAmount.Value)), new NullableInt(System.Convert.ToInt32(hfCurrencyISOCode.Value)), hfOrderID.Value, hfOrderDescription.Value, tcTransactionControl, new ThreeDSecureBrowserDetails(new NullableInt(0), "*/*", Request.UserAgent)), cdCardDetails, cdCustomerDetails, null); // send the SOAP request if (!cdtCardDetailsTransaction.ProcessTransaction(out goGatewayOutput, out tomTransactionOutputMessage)) { szMessage = "Couldn't communicate with payment gateway"; boTransactionSuccessful = false; } else { switch (goGatewayOutput.StatusCode) { case 0: // status code of 0 - means transaction successful boTransactionSuccessful = true; m_fmFormMode = FORM_MODE.RESULTS; szMessage = goGatewayOutput.Message; break; case 3: // status code of 3 - means 3D Secure authentication required m_fmFormMode = FORM_MODE.THREE_D_SECURE; m_szTermURL = Global.SiteSecureBaseURL + "ThreeDSecureLandingPage.aspx"; m_szPaREQ = tomTransactionOutputMessage.ThreeDSecureOutputData.PaREQ; m_szACSURL = tomTransactionOutputMessage.ThreeDSecureOutputData.ACSURL; m_szCrossReference = tomTransactionOutputMessage.CrossReference; break; case 5: // status code of 5 - means transaction declined boTransactionSuccessful = false; m_fmFormMode = FORM_MODE.RESULTS; szMessage = goGatewayOutput.Message; break; case 20: // status code of 20 - means duplicate transaction m_fmFormMode = FORM_MODE.RESULTS; szMessage = goGatewayOutput.Message; if (goGatewayOutput.PreviousTransactionResult.StatusCode.Value == 0) { boTransactionSuccessful = true; } else { boTransactionSuccessful = false; } szPreviousTransactionMessage = goGatewayOutput.PreviousTransactionResult.Message; boDuplicateTransaction = true; break; case 30: // status code of 30 - means an error occurred boTransactionSuccessful = false; m_fmFormMode = FORM_MODE.PAYMENT_FORM; sbString = new StringBuilder(); // get any additional messages if (goGatewayOutput.ErrorMessages.Count > 0) { sbString.Append("<br /><ul>"); for (nCount = 0; nCount < goGatewayOutput.ErrorMessages.Count; nCount++) { sbString.AppendFormat("<li>{0}</li>", goGatewayOutput.ErrorMessages[nCount]); } sbString.Append("</ul>"); } szMessage = goGatewayOutput.Message + sbString.ToString(); break; default: // unhandled status code boTransactionSuccessful = false; m_fmFormMode = FORM_MODE.PAYMENT_FORM; szMessage = goGatewayOutput.Message; break; } } if (m_fmFormMode == FORM_MODE.PAYMENT_FORM) { pnMessagePanel.CssClass = "ErrorMessage"; pnMessagePanel.Visible = true; lbMessageLabel.Text = szMessage; pnTransactionResultsPanel.Visible = false; } else { pnTransactionResultsPanel.Visible = true; pnMessagePanel.Visible = false; if (!boTransactionSuccessful) { pnTransactionResultsPanel.CssClass = "ErrorMessage"; } else { pnTransactionResultsPanel.CssClass = "SuccessMessage"; } lbGatewayResponse.Text = szMessage; // sort out the duplicate transaction reporting if (boDuplicateTransaction) { pnDuplicateTransactionPanel.Visible = true; lbPreviousTransactionMessage.Text = szPreviousTransactionMessage; } // the process another link if (boTransactionSuccessful == true) { Response.Redirect("Thankyou.aspx?id=" + szMessage); } else { hlProcessAnother.NavigateUrl = Global.SiteSecureBaseURL + "PaymentForm.aspx"; } } }
/// <summary> /// Получить объект на заданную дату. /// </summary> /// <param name="date">Дата на которую следует откатить состояние объекта</param> /// <param name="obj">Объект, который откатываем на заданную дату.</param> /// <param name="onlySelfObj">Откатывать только сам объект, т.е. в обратное состояния вернутся все собственные поля объекта и все собственные ссылочные объекты(мастра и детейлы) только ключи</param> /// <param name="forceNullAgregator">Объект вернётся в состояние сразу после заданной даты. /// Если откатываем создание объекта, то возвращаем путой объект с первичным ключом. /// Если объект был удалён и ведётся аудит удаления, то он будет восстановлен со всеми своими собственными полями, иначе если аудит удаления отключен, у удаленного объекта будет проинициализирован только первичный ключ. /// </param> public static void GetObjForDate(DateTime date, ref DataObject obj, bool onlySelfObj = true, bool forceNullAgregator = false) { if (obj != null) { var objType = obj.GetType(); try { obj.DisableInitDataCopy(); // Не кидается исключение о не существовании объекта, если объект был удалён и ведётся аудит удаления, то он будет восстановлен со всеми своими собственными полями, иначе если аудит удаления отключен, у удаленного объекта будет проинициализирован только первичный ключ. DataServiceFactory.AppDataService.LoadObject(new View(objType, View.ReadType.WithRelated), obj, true, false); } catch (Exception ex) { throw new Exception($"Ошибка при попытке вычитать изменнённый объект из БД. {ex.Message}"); } List <AuditEntity> changedAuditEntity; try { var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(AuditEntity), AuditEntity.Views.AuditEntityE); lcs.LimitFunction = FunctionBuilder.BuildAnd( #pragma warning disable CS0618 // Используем не дженерик вариант, иначе не работает вычитка FunctionBuilder.BuildEquals(nameof(AuditEntity.ObjectPrimaryKey), obj.__PrimaryKey), #pragma warning restore CS0618 // Тип или член устарел FunctionBuilder.BuildGreater <AuditEntity>(x => x.OperationTime, date)); // Загружаем изменения строго больше даты на которую хотим откатить => получаем объект в состоянии сразу после этой даты. lcs.ColumnsSort = new[] { new ColumnsSortDef(nameof(AuditEntity.OperationTime), SortOrder.Desc) }; changedAuditEntity = DataServiceFactory.AppDataService.LoadObjects(lcs).Cast <AuditEntity>().ToList(); } catch (Exception ex) { throw new Exception( $"Ошибка при попытке загрузить операции изменения {nameof(AuditEntity)} для объекта({obj.__PrimaryKey}). {ex.Message}"); } var auditFieldsLcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(AuditField), ViewForField); foreach (var changeEntity in changedAuditEntity) { if (changeEntity.OperationType != OperationCreateType) { List <AuditField> changedFields; try { // Загружаем набор изменившихся полей из аудита auditFieldsLcs.LimitFunction = FunctionBuilder.BuildEquals <AuditField>(x => x.AuditEntity, changeEntity); changedFields = DataServiceFactory.AppDataService.LoadObjects(auditFieldsLcs) .Cast <AuditField>().ToList(); } catch (Exception ex) { throw new Exception( $"Произошла ошибка при попытке получить набор изменений полей для операции аудита:{PKHelper.GetGuidByObject(changeEntity)}. {ex.Message}"); } //Берём только изменения, вспомогательные объекты LinkedPrimaryKey остаются в основном списке. var onlySelfChangedFields = changedFields.Where(y => y.MainChange == null); foreach (var changedField in onlySelfChangedFields) { var mainChange = changedFields.FirstOrDefault(x => PKHelper.EQPK(x.MainChange, changedField)); if (mainChange == null) { //Если основного изменения нет, то это обычное поле var propertyInfo = objType.GetProperty(changedField.Field); if (propertyInfo != null) { var typeprop = propertyInfo.PropertyType; object value = null; try { if (changedField.OldValue != null) { if (typeprop.IsEnum) { value = EnumCaption.GetValueFor(changedField.OldValue, typeprop); } else if (typeprop == typeof(NullableDateTime)) { value = NullableDateTime.Parse(changedField.OldValue); } else if (typeprop == typeof(NullableInt)) { value = NullableInt.Parse(changedField.OldValue); } else { value = Convert.ChangeType(changedField.OldValue, typeprop, CultureInfo.InvariantCulture); } } propertyInfo.SetValue(obj, value); } catch (Exception ex) { var errorText = value != null ? $"AuditField:{PKHelper.GetGuidByObject(changedField)} Ошибка при попытке установить значение поля {value} в объект {objType.Name}:{PKHelper.GetGuidByObject(obj)} поле {changedField.Field}" : $"AuditField:{PKHelper.GetGuidByObject(changedField)} Ошибка при попытке преобразовать значение поля {changedField.OldValue} в тип {typeprop.Name}"; throw new Exception($"{errorText}. {ex.Message}"); } } else { throw new Exception( $"Ошибка - не найдено поле {changedField.Field} в объекте {objType.Name}."); } } else { // Есть основное изменение, значит это изменение ссылочного объекта. // Только если изменилась ссылка if (mainChange.OldValue != mainChange.NewValue) { // В аудите детейл отличается от мастера тем, что у него приписывается в скобках позиция if (Regex.IsMatch(changedField.Field, "[ ][(][0-9]+[)]$")) { // Это изменение детейла объекта. var separateIndex = changedField.Field.IndexOf(" ", StringComparison.Ordinal); var detailNameFromField = changedField.Field.Substring(0, separateIndex); var propertyInfo = objType.GetProperty(detailNameFromField); if (propertyInfo != null) { if (propertyInfo.GetValue(obj) is DetailArray detailValue) { if (changedField.OldValue == "-NULL-") { var key = new KeyGuid(mainChange.NewValue); try { detailValue.RemoveByKey(key); } catch (Exception ex) { throw new Exception( $"Ошибка при попытке удалить объект с ключом {key} из детейла {detailNameFromField} в объекте {objType.Name}. {ex.Message}"); } } else { var detailItemType = detailValue.ItemType; var oldDetailObj = Helper.CreateDataObject(detailItemType, mainChange.OldValue); try { detailValue.AddObject(oldDetailObj); } catch (Exception ex) { throw new Exception( $"Ошибка при добавить объект с ключом {PKHelper.GetGuidByObject(oldDetailObj)} в детейл {detailNameFromField} в объекте {objType.Name}. {ex.Message}"); } } } } else { throw new Exception( $"Ошибка - не найден детейл {detailNameFromField} в объекте {objType.Name}."); } } else { // Это изменение мастера объекта. var propertyInfo = objType.GetProperty(changedField.Field); if (propertyInfo != null) { //Это свойство является агрегатором, для детейла var itIsAgregator = propertyInfo.GetCustomAttribute <AgregatorAttribute>() != null; if (changedField.OldValue == "-NULL-" || forceNullAgregator && itIsAgregator) { //Если свойство является агрегатором для детейла, то в последующих витках рекурсии всегда возвращаем нулл для такого поля, во избежание циклических ссылок. propertyInfo.SetValue(obj, null); } else { var typeprop = propertyInfo.PropertyType; var oldMasterObj = Helper.CreateDataObject(typeprop, mainChange.OldValue); try { propertyInfo.SetValue(obj, oldMasterObj); } catch (Exception ex) { throw new Exception( $"Ошибка при попытке установить свойство мастера {changedField.Field} в объекте {objType.Name}. {ex.Message}"); } } } else { throw new Exception( $"Ошибка - не найден мастер {changedField.Field} в объекте {objType.Name}."); } } } } } } else { // Если откатываем создание объекта, то возвращаем путой объект с первичным ключом. obj = Helper.CreateDataObject(objType, obj.__PrimaryKey); } } // На этом этапе основной объект и все его собственные поля и зависимые сущности возвращены на дату // Получаем мастера и откатываем их поля, рекурсивно вызывая этот метод // Получаем детейлы объекта и откатываем их поля, рекурсивно вызывая этот метод if (!onlySelfObj && changedAuditEntity.Any()) { var objProperties = objType.GetProperties(); foreach (var property in objProperties) { var typeprop = property.PropertyType; if (typeprop.IsSubclassOf(typeof(DataObject))) { //Перебираем все мастера var masterValue = property.GetValue(obj) as DataObject; GetObjForDate(date, ref masterValue, false, true); } else if (typeprop.IsSubclassOf(typeof(DetailArray))) { //Перебираем все детейлы if (property.GetValue(obj) is DetailArray detailValue) { var detailObjects = detailValue.GetAllObjects(); foreach (var dataObject in detailObjects) { var currentObj = dataObject; GetObjForDate(date, ref currentObj, false, true); } } } } } } }
public void TestFilterNullable() { ActODataService(args => { NullableDateTime date = new NullableDateTime(); date.Value = new DateTimeOffset(DateTime.Now).UtcDateTime; NullableInt i = new NullableInt(); i.Value = 7; NullableDecimal d = new NullableDecimal(); d.Value = new decimal(777.777); string prevDecimal = (d.Value - 1).ToString().Replace(",", "."); string nextDecimal = (d.Value + 1).ToString().Replace(",", "."); string prevDate = $"{date.Value.AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ss.fff")}%2B05:00"; string nextDate = $"{date.Value.AddDays(1).ToString("yyyy-MM-ddTHH:mm:ss.fff")}%2B05:00"; КлассСМножествомТипов класс = new КлассСМножествомТипов() { PropertyStormnetNullableInt = i, PropertyStormnetNullableDecimal = d, PropertyStormnetNullableDateTime = date, PropertyDateTime = date.Value }; var objs = new DataObject[] { класс }; args.DataService.UpdateObjects(ref objs); string requestUrl; /* * // Проверка использования фильтрации для типа ICSSoft.STORMNET.UserDataTypes.NullableDateTime. * requestUrl = $"http://localhost/odata/КлассСМножествомТиповs?$filter=(PropertyStormnetNullableDateTime gt {prevDate}) and (PropertyStormnetNullableDateTime lt {nextDate})"; * * // Обращаемся к OData-сервису и обрабатываем ответ. * using (HttpResponseMessage response = args.HttpClient.GetAsync(requestUrl).Result) * { * // Убедимся, что запрос завершился успешно. * Assert.Equal(HttpStatusCode.OK, response.StatusCode); * * // Получим строку с ответом. * string receivedStr = response.Content.ReadAsStringAsync().Result.Beautify(); * * // Преобразуем полученный объект в словарь. * Dictionary<string, object> receivedDict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(receivedStr); * * Assert.Equal(1, ((ArrayList)receivedDict["value"]).Count); * } * * // Проверка использования фильтрации для типа ICSSoft.STORMNET.UserDataTypes.NullableDecimal. * requestUrl = $"http://localhost/odata/КлассСМножествомТиповs?$filter=(PropertyStormnetNullableDecimal gt {prevDecimal}M) and (PropertyStormnetNullableDecimal lt {nextDecimal})"; * * // Обращаемся к OData-сервису и обрабатываем ответ. * using (HttpResponseMessage response = args.HttpClient.GetAsync(requestUrl).Result) * { * // Убедимся, что запрос завершился успешно. * Assert.Equal(HttpStatusCode.OK, response.StatusCode); * * // Получим строку с ответом. * string receivedStr = response.Content.ReadAsStringAsync().Result.Beautify(); * * // Преобразуем полученный объект в словарь. * Dictionary<string, object> receivedDict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(receivedStr); * * Assert.Equal(1, ((ArrayList)receivedDict["value"]).Count); * } */ // Проверка использования фильтрации для типа ICSSoft.STORMNET.UserDataTypes.NullableInt. requestUrl = $"http://localhost/odata/КлассСМножествомТиповs?$filter=PropertyStormnetNullableInt eq {i.Value.ToString()}"; // Обращаемся к OData-сервису и обрабатываем ответ. using (HttpResponseMessage response = args.HttpClient.GetAsync(requestUrl).Result) { // Убедимся, что запрос завершился успешно. Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Получим строку с ответом. string receivedStr = response.Content.ReadAsStringAsync().Result.Beautify(); // Преобразуем полученный объект в словарь. Dictionary <string, object> receivedDict = new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(receivedStr); Assert.Equal(1, ((ArrayList)receivedDict["value"]).Count); } }); }