public async Task <ActionResult <StoreResult> > UpdateStore(string id, [FromBody] Store store) { StoreResult result = new StoreResult(); if (id != store.StoreId) { result.IsSuccessful = false; result.ErrorMessages.Add("Id does not mathc with object id"); return(BadRequest(result)); } try { var update = await _storeRepository.UpdateAsync(id, store); result.IsSuccessful = true; result.ResultData.Add(update); } catch (ItemNotFoundException e) { result.IsSuccessful = false; result.ErrorMessages.Add(e.Message); return(NotFound(result)); } catch (ItemAlreadyExistsException e) { result.IsSuccessful = false; result.ErrorMessages.Add(e.Message); return(Conflict(result)); } catch (Exception e) { throw e; } return(Ok(result)); }
public async Task <ActionResult <StoreResult> > CreateStore(Store store) { var user = await _currentUserProvider.GetUserAsync(); store.CreatedAt = DateTime.Now; store.CreatorId = user.Id; StoreResult result = new StoreResult(); try { var created = await _storeRepository.CreateAsync(store); result.IsSuccessful = true; result.ResultData.Add(created); } catch (ItemAlreadyExistsException e) { result.IsSuccessful = false; result.ErrorMessages.Add(e.Message); return(Conflict(result)); } catch (Exception e) { throw e; } return(Ok(result)); }
public StoreResult QueryPersons(StoreParams storeParams) { IStoreProcessDal storeProcess = new StoreProcessDal(); StoreResult result = storeProcess.QueryPersons(storeParams); return(result); }
/// <inheritdoc /> public override async Task <StoreResult> InsertWebHookAsync(string user, WebHook webHook) { if (user == null) { throw new ArgumentNullException("user"); } if (webHook == null) { throw new ArgumentNullException("webHook"); } user = NormalizeKey(user); string id = NormalizeKey(webHook.Id); CloudTable table = await _manager.GetCloudTableAsync(_options.ConnectionString, WebHookTable); DynamicTableEntity tableEntity = ConvertFromWebHook(user, id, webHook); TableOperation operation = TableOperation.Insert(tableEntity, echoContent: false); TableResult tableResult = await _manager.ExecuteAsync(table, operation); StoreResult result = GetStoreResult(tableResult); if (result != StoreResult.Success) { string msg = string.Format(AzureStorageResource.StorageManager_CreateFailed, table.Name, tableResult.HttpStatusCode); _logger.LogError(msg); } return(result); }
public void ValidateStoreResultSerialization() { HashSet <string> storeResultProperties = typeof(StoreResult).GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToHashSet <string>(); string datumKey = "ClientStats"; Trace trace = Trace.GetRootTrace("Test"); ClientSideRequestStatisticsTraceDatum datum = new ClientSideRequestStatisticsTraceDatum(DateTime.UtcNow); trace.AddDatum(datumKey, datum); StoreResult storeResult = new StoreResult( storeResponse: new StoreResponse(), exception: null, partitionKeyRangeId: 42.ToString(), lsn: 1337, quorumAckedLsn: 23, requestCharge: 3.14, currentReplicaSetSize: 4, currentWriteQuorum: 3, isValid: true, storePhysicalAddress: new Uri("http://storephysicaladdress.com"), globalCommittedLSN: 1234, numberOfReadRegions: 13, itemLSN: 15, sessionToken: new SimpleSessionToken(42), usingLocalLSN: true, activityId: Guid.Empty.ToString(), backendRequestDurationInMs: "4.2", retryAfterInMs: "42", transportRequestStats: TraceWriterBaselineTests.CreateTransportRequestStats()); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics( DateTime.MinValue, DateTime.MaxValue, storeResult, ResourceType.Document, OperationType.Query, new Uri("http://someUri1.com")); ((List <StoreResponseStatistics>)datum.GetType().GetField("storeResponseStatistics", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(datum)).Add(storeResponseStatistics); CosmosTraceDiagnostics diagnostics = new CosmosTraceDiagnostics(trace); string json = diagnostics.ToString(); JObject jObject = JObject.Parse(json); JObject storeResultJObject = jObject["data"][datumKey]["StoreResponseStatistics"][0]["StoreResult"].ToObject <JObject>(); List <string> jsonPropertyNames = storeResultJObject.Properties().Select(p => p.Name).ToList(); storeResultProperties.Add("BELatencyInMs"); storeResultProperties.Remove(nameof(storeResult.BackendRequestDurationInMs)); storeResultProperties.Add("TransportException"); storeResultProperties.Remove(nameof(storeResult.Exception)); storeResultProperties.Add("transportRequestTimeline"); storeResultProperties.Remove(nameof(storeResult.TransportRequestStats)); foreach (string key in jsonPropertyNames) { Assert.IsTrue(storeResultProperties.Remove(key), $"Json contains key:{key} not a storeresult property"); } Assert.AreEqual(0, storeResultProperties.Count, $"Json is missing properties: {string.Join(';', storeResultProperties)}"); }
/// <inheritdoc /> public override Task <StoreResult> UpdateWebHookAsync(string user, WebHook webHook) { if (user == null) { throw new ArgumentNullException("user"); } if (webHook == null) { throw new ArgumentNullException("webHook"); } user = NormalizeKey(user); ConcurrentDictionary <string, WebHook> userHooks; StoreResult result = StoreResult.NotFound; if (_store.TryGetValue(user, out userHooks)) { string id = NormalizeKey(webHook.Id); WebHook current; if (userHooks.TryGetValue(id, out current)) { bool updated = userHooks.TryUpdate(id, webHook, current); result = updated ? StoreResult.Success : StoreResult.Conflict; } } return(Task.FromResult(result)); }
public void RecordResponse(DocumentServiceRequest request, StoreResult storeResult) { DateTime responseTime = DateTime.UtcNow; StoreResponseStatistics responseStatistics; responseStatistics.RequestResponseTime = responseTime; responseStatistics.StoreResult = storeResult; responseStatistics.RequestOperationType = request.OperationType; responseStatistics.RequestResourceType = request.ResourceType; Uri locationEndpoint = request.RequestContext.LocationEndpointToRoute; lock (this.lockObject) { if (!this.requestEndTime.HasValue || responseTime > this.requestEndTime) { this.requestEndTime = responseTime; } if (locationEndpoint != null) { this.RegionsContacted.Add(locationEndpoint); } if (responseStatistics.RequestOperationType == OperationType.Head || responseStatistics.RequestOperationType == OperationType.HeadFeed) { this.supplementalResponseStatisticsList.Add(responseStatistics); } else { this.responseStatisticsList.Add(responseStatistics); } } }
public StoreResponseStatistics( DateTime?requestStartTime, DateTime requestResponseTime, StoreResult storeResult, ResourceType resourceType, OperationType operationType, Uri locationEndpoint) { this.RequestStartTime = requestStartTime; this.RequestResponseTime = requestResponseTime; this.RequestResourceType = resourceType; this.RequestOperationType = operationType; this.LocationEndpoint = locationEndpoint; this.IsSupplementalResponse = operationType == OperationType.Head || operationType == OperationType.HeadFeed; if (storeResult != null) { this.StoreResultStatistics = new StoreResultStatistics( exception: storeResult.Exception, statusCode: storeResult.StatusCode, subStatusCode: storeResult.SubStatusCode, partitionKeyRangeId: storeResult.PartitionKeyRangeId, lsn: storeResult.LSN, requestCharge: storeResult.RequestCharge, isValid: storeResult.IsValid, storePhysicalAddress: storeResult.StorePhysicalAddress, globalCommittedLSN: storeResult.GlobalCommittedLSN, itemLSN: storeResult.ItemLSN, sessionToken: storeResult.SessionToken, usingLocalLSN: storeResult.UsingLocalLSN, activityId: storeResult.ActivityId); } }
public StoreResult UpdateDocument(ITransaction transaction, string collection, long rowId, JSONDocument update) { PersistenceManagerTransaction pmTransaction = transaction as PersistenceManagerTransaction; StorageResult <byte[]> storageResult = _storageManager.UpdateDocument(pmTransaction, _metadataIndices[collection].GetFileId(rowId), collection, rowId, SerializeDocument(update)); if (storageResult.Status != StoreResult.Success) { return(storageResult.Status); } lock (_metadataIndices) { _metadataIndices[collection].Add(rowId, storageResult.FileId); } MetaDataIndexOperation operation = new MetaDataIndexOperation() { ActualDocumentSize = update.Size, FileId = storageResult.FileId, OperationType = OperationType.Update, RowId = _metadataIndices[collection].GetRowId(new DocumentKey(update.Key)) }; (pmTransaction.MetadataTransaction as MetaDataIndexTransaction).AddOperation(new DocumentKey(update.Key), operation); StoreResult metadataResult = _metadataIndices[collection].StoreKeyMetadata(pmTransaction.MetadataTransaction.InnerObject as ITransaction, update, rowId); if (metadataResult != StoreResult.Success) //undo data operation { //_storageManager.DeleteDocument(pmTransaction.DataTransaction, storageResult.FileId, _collectionName, rowId); return(metadataResult); } return(StoreResult.Success); }
public async Task <IHttpActionResult> Put(string id, WebHook webHook) { if (webHook == null) { return(BadRequest()); } if (!string.Equals(id, webHook.Id, StringComparison.OrdinalIgnoreCase)) { return(BadRequest()); } string userId = await GetUserId(); await VerifyFilters(webHook); await VerifyWebHook(webHook); try { StoreResult result = await _store.UpdateWebHookAsync(userId, webHook); return(CreateHttpResult(result)); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_UpdateFailure, ex.Message); Configuration.DependencyResolver.GetLogger().Error(msg, ex); HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex); return(ResponseMessage(error)); } }
public async Task <IHttpActionResult> Post(WebHook webHook) { if (webHook == null) { return(BadRequest()); } string userId = await GetUserId(); await VerifyFilters(webHook); await VerifyWebHook(webHook); try { // Validate the provided WebHook ID (or force one to be created on server side) IWebHookIdValidator idValidator = Configuration.DependencyResolver.GetIdValidator(); await idValidator.ValidateIdAsync(Request, webHook); // Add WebHook for this user. StoreResult result = await _store.InsertWebHookAsync(userId, webHook); if (result == StoreResult.Success) { return(CreatedAtRoute(WebHookRouteNames.RegistrationLookupAction, new { id = webHook.Id }, webHook)); } return(CreateHttpResult(result)); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, CustomApiResources.RegistrationController_RegistrationFailure, ex.Message); Configuration.DependencyResolver.GetLogger().Error(msg, ex); HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex); return(ResponseMessage(error)); } }
public void RecordResponse(DocumentServiceRequest request, StoreResult storeResult) { DateTime responseTime = DateTime.UtcNow; Uri locationEndpoint = request.RequestContext.LocationEndpointToRoute; StoreResponseStatistics responseStatistics = new StoreResponseStatistics( responseTime, storeResult, request.ResourceType, request.OperationType, locationEndpoint); if (storeResult?.IsClientCpuOverloaded ?? false) { this.IsCpuOverloaded = true; } lock (this.lockObject) { if (!this.RequestEndTimeUtc.HasValue || responseTime > this.RequestEndTimeUtc) { this.RequestEndTimeUtc = responseTime; } if (locationEndpoint != null) { this.RegionsContacted.Add(locationEndpoint); } this.DiagnosticsContext.AddDiagnosticsInternal(responseStatistics); } }
public async Task <IHttpActionResult> Post(WebHook webHook) { if (webHook == null) { return(BadRequest()); } string userId = await GetUserId(); await VerifyFilters(webHook); await VerifyWebHook(webHook); try { // Ensure we have a normalized ID for the WebHook webHook.Id = null; // Add WebHook for this user. StoreResult result = await _store.InsertWebHookAsync(userId, webHook); if (result == StoreResult.Success) { return(CreatedAtRoute(WebHookRouteNames.RegistrationLookupAction, new { id = webHook.Id }, webHook)); } return(CreateHttpResult(result)); } catch (Exception ex) { string msg = ex.Message; HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex); return(ResponseMessage(error)); } }
public async Task <IHttpActionResult> Post(WebHook webHook) { if (webHook == null) { return(BadRequest()); } string userId = _userId; await VerifyFilters(webHook); try { // Ensure we have a normalized ID for the WebHook webHook.Id = null; // Add WebHook for this user. StoreResult result = await _store.InsertWebHookAsync(userId, webHook); return(CreateHttpResult(result)); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, ex.Message); _logger.Error(msg, ex); HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex); return(ResponseMessage(error)); } }
public async Task <IHttpActionResult> UpdateWebHook(string id, WebHook webHook) { if (webHook == null) { return(BadRequest()); } if (!string.Equals(id, webHook.Id, StringComparison.OrdinalIgnoreCase)) { return(BadRequest()); } string userId = GetUserId(); await VerifyFilters(webHook); await VerifyWebHook(webHook); try { StoreResult result = await _store.UpdateWebHookAsync(userId, webHook); return(CreateHttpResult(result)); } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, _localizationService.GetResource("Api.WebHooks.CouldNotUpdateWebhook"), ex.Message); Configuration.DependencyResolver.GetLogger().Error(msg, ex); HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex); return(ResponseMessage(error)); } }
/// <inheritdoc /> public async Task <StoreResult> UpdateWebHookAsync(string user, WebHook webHook) { if (user == null) { throw new ArgumentNullException("user"); } if (webHook == null) { throw new ArgumentNullException("webHook"); } user = NormalizeKey(user); string id = NormalizeKey(webHook.Id); CloudTable table = _manager.GetCloudTable(_connectionString, WebHookTable); DynamicTableEntity tableEntity = ConvertFromWebHook(user, id, webHook); TableOperation operation = TableOperation.Replace(tableEntity); TableResult tableResult = await _manager.ExecuteAsync(table, operation); StoreResult result = GetStoreResult(tableResult); if (result != StoreResult.Success) { string msg = string.Format(CultureInfo.CurrentCulture, AzureStorageResources.StorageManager_OperationFailed, table.Name, tableResult.HttpStatusCode); _logger.Error(msg); } return(result); }
public async Task CanCreateAndDeleteData() { var dataType = "SqlUnitTestObject"; var utcNow = DateTime.UtcNow; var container = new GenericDataContainer( IdGenerator.FromGuid(), "jdoe", utcNow, "jdoe", utcNow, ApiVersion.Current, BsonDocument.Parse("{ Name : 'Jan', Address : { Street : 'Teglholm Tværvej', Number : 27 }}")); var sut = CreateMssqlRdDataStorage(); StoreResult storeResult = null; Assert.That(async() => storeResult = await sut.StoreAsync(dataType, container, false), Throws.Nothing); Assert.That(storeResult.ModificationType, Is.EqualTo(DataModificationType.Created)); var retrievedContainer = await sut.GetFromIdAsync(dataType, storeResult.Id); Assert.That(retrievedContainer.Submitter, Is.EqualTo(container.Submitter)); Assert.That(retrievedContainer.SubmissionTimeUtc, Is.EqualTo(container.SubmissionTimeUtc).Within(TimeSpan.FromSeconds(1))); Assert.That(retrievedContainer.Data.GetValue("Name").AsString, Is.EqualTo(container.Data.GetValue("Name").AsString)); // Cannot add document a second time Assert.That(async() => storeResult = await sut.StoreAsync(dataType, container, false), Throws.TypeOf <DocumentAlreadyExistsException>()); // Can overwrite document Assert.That(async() => storeResult = await sut.StoreAsync(dataType, container, true), Throws.Nothing); Assert.That(storeResult.ModificationType, Is.EqualTo(DataModificationType.Replaced)); var isDeleted = await sut.DeleteDataContainerAsync(dataType, storeResult.Id); Assert.That(isDeleted, Is.True); }
/// <inheritdoc /> public async Task <StoreResult> DeleteWebHookAsync(string user, string id) { if (user == null) { throw new ArgumentNullException("user"); } if (id == null) { throw new ArgumentNullException("id"); } user = NormalizeKey(user); id = NormalizeKey(id); CloudTable table = _manager.GetCloudTable(_connectionString, WebHookTable); TableEntity tableEntity = new TableEntity(user, id); tableEntity.ETag = "*"; TableOperation operation = TableOperation.Delete(tableEntity); TableResult tableResult = await _manager.ExecuteAsync(table, operation); StoreResult result = GetStoreResult(tableResult); if (result != StoreResult.Success) { string msg = string.Format(CultureInfo.CurrentCulture, AzureStorageResources.StorageManager_OperationFailed, table.Name, tableResult.HttpStatusCode); _logger.Error(msg); } return(result); }
/// <inheritdoc /> public override Task <StoreResult> DeleteWebHookAsync(string user, string id) { if (user == null) { throw new ArgumentNullException("user"); } if (id == null) { throw new ArgumentNullException("id"); } user = NormalizeKey(user); ConcurrentDictionary <string, WebHook> userHooks; StoreResult result = StoreResult.NotFound; if (_store.TryGetValue(user, out userHooks)) { id = NormalizeKey(id); WebHook current; bool deleted = userHooks.TryRemove(id, out current); result = deleted ? StoreResult.Success : StoreResult.NotFound; } return(Task.FromResult(result)); }
public async Task <IHttpActionResult> Put(string id, WebHook webHook) { if (webHook == null) { return(BadRequest()); } if (!string.Equals(id, webHook.Id, StringComparison.OrdinalIgnoreCase)) { return(BadRequest()); } string userId = _userId; await VerifyFilters(webHook); try { StoreResult result = await _store.UpdateWebHookAsync(userId, webHook); return(CreateHttpResult(result)); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, ex.Message); _logger.Error(msg, ex); HttpResponseMessage error = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg, ex); return(ResponseMessage(error)); } }
/// <inheritdoc /> public virtual async Task <StoreResult> DeleteWebHookAsync(IPrincipal user, string id) { string userId = await _userManager.GetUserIdAsync(user); StoreResult result = await _store.DeleteWebHookAsync(userId, id); return(result); }
public async Task <IHttpActionResult> Delete(string id) { string userId = await GetUserId(); StoreResult result = await _store.DeleteWebHookAsync(userId, id); return(CreateHttpResult(result)); }
public static StoreResult Store(int input) { if (input > 5) { return(StoreResult.CreateFailed("out of scope")); } return(StoreResult.Ok); }
public async Task DeleteWebHookAsync_DeletesItem() { // Arrange await Initialize(); // Act StoreResult actual = await _store.DeleteWebHookAsync(TestUser, "0"); // Assert Assert.Equal(StoreResult.Success, actual); }
public StoreLocatorResponse(StoreResult storeResult) : this() { foreach (var store in storeResult.Stores) { if (!store.ShipToStore) { Locations.Add(new Store(store)); } } }
public ActionResult GetData(int start, int limit, int page) { List <VmStock> allData = CreateMockData(); page--; var data = allData.Skip(limit * page).Take(limit); StoreResult result = this.Store(data); result.Total = allData.Count; return(result); }
public async Task <ActionResult <StoreResult> > GetStores() { var stores = await _storeRepository.GetAllAsync(); var result = new StoreResult { IsSuccessful = true, ResultData = stores }; return(Ok(result)); }
public StoreResult QueryPerson(string userID) { IEnumerable <HrEmploy> item = new HrEmployeeDal().LoadEntity(H => H.UserID == userID); if (item != null && item.Count() > 0) { StoreResult result = new StoreResult(); result.root = item.First().ToAjaxResult(); result.total = item.Count(); return(result); } return(null); }
public async Task InsertWebHookAsync_InsertsItem() { // Arrange await Initialize(); WebHook webHook = CreateWebHook(TestUser, TestId); // Act StoreResult actual = await _store.InsertWebHookAsync(TestUser, webHook); // Assert Assert.Equal(StoreResult.Success, actual); }
public async Task UpdateWebHookAsync_DetectsWhenUpdatedItemDoesNotExist() { // Arrange await Initialize(); WebHook webHook = CreateWebHook(TestUser, TestId); // Act StoreResult actual = await _store.UpdateWebHookAsync(TestUser, webHook); // Assert Assert.Equal(StoreResult.NotFound, actual); }
public async Task Put_ReturnsError_IfStoreReturnsNonsuccess(StoreResult result, Type response) { // Arrange WebHook webHook = CreateWebHook(); _storeMock.Setup(s => s.UpdateWebHookAsync(TestUser, webHook)) .ReturnsAsync(result); // Act IHttpActionResult actual = await _controller.Put(TestWebHookId, webHook); // Assert Assert.IsType(response, actual); }
internal static bool StoreResults( int rows, string query, int skip, string serverAssembly, string serverType, string serverMethod, string dataMember, string dataValueField, string dataTextField, string parentAssembly, string parentType, string parentBaseAssembly, string parentBaseType, string pageAssembly, string pageType, string pageBaseAssembly, string pageBaseType, StoreResult StoreResultDel, XmlDocument xmlDoc, XmlNode responseTag, Hashtable clientState, Hashtable serverState, string serverStateString, string serverStateHash, bool upLevel) { bool foundMethod = false; bool attributeMissingException=false; MethodInfo methodInfo = null; #region Find the method - bit messy, could be improved? if (serverAssembly!="")//assembly specified { if (serverType!="")//type specified { foundMethod = GetMethod(serverAssembly, serverType, serverMethod, ref attributeMissingException, ref methodInfo); //try with specified assembly and specified type } } if (serverType!="" &! foundMethod)//type specified { foundMethod = GetMethod(pageAssembly, serverType, serverMethod, ref attributeMissingException, ref methodInfo); //try with page assembly and specified type if(!foundMethod) foundMethod = GetMethod(pageBaseAssembly, serverType, serverMethod, ref attributeMissingException, ref methodInfo); //try with page codebehind assembly and specified type if(!foundMethod) foundMethod = GetMethod(parentAssembly, serverType, serverMethod, ref attributeMissingException, ref methodInfo); //try with parent assembly and specified type if(!foundMethod) foundMethod = GetMethod(parentBaseAssembly, serverType, serverMethod, ref attributeMissingException, ref methodInfo); //try with parent codebehind assembly and specified type } if(!foundMethod) foundMethod = GetMethod(pageAssembly, pageType, serverMethod, ref attributeMissingException, ref methodInfo); //try with page assembly and page type if(!foundMethod) foundMethod = GetMethod(pageBaseAssembly, pageBaseType, serverMethod, ref attributeMissingException, ref methodInfo); //try with page codebehind assembly and page codebehind type if(!foundMethod) foundMethod = GetMethod(parentAssembly, parentType, serverMethod, ref attributeMissingException, ref methodInfo); //try with parent assembly and parent type if(!foundMethod) foundMethod = GetMethod(parentBaseAssembly, parentBaseType, serverMethod, ref attributeMissingException, ref methodInfo); //try with parent codebehind assembly and parent codebehind type if(!foundMethod && attributeMissingException) throw new Exception("ServerMethod is not tagged with '[Cambro.Web.DbCombo.ResultsMethodAttribute(true)]' attribute."); if(!foundMethod) throw new Exception("Can't find ServerMethod."); #endregion #region Convert the method to a GetResults delegate, and throw a nice exception if it doesn't convert DbCombo.GetResults mydel; try { mydel = (DbCombo.GetResults) Delegate.CreateDelegate(typeof(DbCombo.GetResults),methodInfo); } catch(Exception ex) { throw new Exception("Error while getting results - I've found your ServerMethod, but an exception was thrown while converting it to a DbCombo.GetResults delegate. Are you sure your ServerMethod has the signature: public static object YourServerMethodName(Cambro.Web.DbCombo.ServerMethodArgs args)? ",ex); } #endregion #region Populate our Secure Server State hashtable SecureHashtable serverStateSecure = new SecureHashtable(); serverStateSecure.HashHash=serverStateHash; serverStateSecure.Downlevel=!upLevel; serverStateSecure.HashSerial=serverStateString; if (serverState != null) { foreach(object c in serverState.Keys) { serverStateSecure.Add(c,serverState[c]); } } #endregion FieldSecurityClass fieldSecurity = new FieldSecurityClass(); ArrayList fieldSubset = new ArrayList(); DataMemberSecurityClass dataMemberSecurity = new DataMemberSecurityClass(); ArrayList dataMemberSubset = new ArrayList(); #region Build our ServerMethodArgs and execute our delegate ServerMethodArgs a = new ServerMethodArgs( query, skip+rows+2, clientState, serverStateSecure, upLevel, fieldSecurity, fieldSubset, dataMemberSecurity, dataMemberSubset); object result1 = mydel(a); #endregion object result = new object(); object iListObj = new object(); #region Throw an exception if we are trying to use a field that is not alowed by the fieldsecurity. if ( fieldSecurity.Value.Equals(FieldSecurity.Default) ) { if ( dataValueField!="" || dataTextField!="" ) throw new Exception("You have specified either DataValueField or DataTextField, but have not specified FieldSecurity in the ServerMethod. Add 'args.FieldSecurity.Value = FieldSecurity.xxx' to your ServerMethod, where xxx is either 'AllFields' or 'fieldSubset'"); } else if ( fieldSecurity.Value.Equals(FieldSecurity.IncludeFieldSubset) ) { string valueField="DbComboValue"; string textField="DbComboText"; if (dataValueField!="") valueField = dataValueField; if (dataTextField!="") textField = dataTextField; if ( ! fieldSubset.Contains(valueField) ) throw new Exception("You have specified FieldSecurity=IncludeFieldSubset in the ServerMethod, but your DataValueField ('"+valueField+"') does not occur in the ArrayList FieldSubset."); if ( ! fieldSubset.Contains(textField) ) throw new Exception("You have specified FieldSecurity=IncludeFieldSubset in the ServerMethod, but your DataTextField ('"+textField+"') does not occur in the ArrayList FieldSubset."); } else if ( fieldSecurity.Value.Equals(FieldSecurity.ExcludeFieldSubset) ) { string valueField="DbComboValue"; string textField="DbComboText"; if (dataValueField!="") valueField = dataValueField; if (dataTextField!="") textField = dataTextField; if ( fieldSubset.Contains(valueField) ) throw new Exception("You have specified FieldSecurity=ExcludeFieldSubset in the ServerMethod, and your DataValueField ('"+valueField+"') occurs in the ArrayList FieldSubset."); if ( fieldSubset.Contains(textField) ) throw new Exception("You have specified FieldSecurity=ExcludeFieldSubset in the ServerMethod, and your DataTextField ('"+textField+"') occurs in the ArrayList FieldSubset."); } if (dataValueField=="") dataValueField = "DbComboValue"; if (dataTextField=="") dataTextField = "DbComboText"; #endregion #region Throw an exception if we are trying to use a DataMember that is not alowed by the DataMemberSecurity. if (dataMemberSecurity.Equals(DataMemberSecurity.Default)) { if (dataMember!="") throw new Exception("You have specified a DataMember, but DataMemberSecurity is still set on Default. In your ServerMethod, please choose a diferent value for DataMemberSecurity."); } else if (dataMemberSecurity.Equals(DataMemberSecurity.IncludeDataMemberSubset)) { if (!dataMemberSubset.Contains(dataMember)) throw new Exception("You have specified a DataMember, and you have chosed DataMemberSecurity.IncludeDataMemberSubset. Your chosen DataMember does not occur in the ArrayList DataMemberSubset."); } else if (dataMemberSecurity.Equals(DataMemberSecurity.ExcludeDataMemberSubset)) { if (dataMemberSubset.Contains(dataMember)) throw new Exception("You have specified a DataMember, and you have chosed DataMemberSecurity.ExcludeDataMemberSubset. Your chosen DataMember occurs in the ArrayList DataMemberSubset."); } #endregion bool moreRowsAvailable=false; int counter=0; #region Extract an IList (if we can) bool useIList = true; if (result1 is DataSet) { if (dataMember.Length>0) iListObj = ((IListSource)(object)((DataSet)result1).Tables[dataMember]).GetList(); else iListObj = ((IListSource)(object)((DataSet)result1).Tables[0]).GetList(); } else if (result1 is IListSource) iListObj = ((IListSource)result1).GetList(); else if (result1 is IList) iListObj = (IList)result1; else useIList = false; #endregion if (useIList) { #region This is the new DataBinding code (>=v4.1) - it handles custom objects, but not DataReaders. IList iList = (IList)iListObj; int maxVar = rows+skip; if (rows+skip>iList.Count) maxVar = iList.Count; for(int i=skip;i<maxVar;i++) { string thisValue = GetField(iList[i],dataValueField); string thisText = GetField(iList[i],dataTextField); StoreResultDel(xmlDoc,responseTag,thisValue,thisText); } if (iList.Count>rows+skip) return true; else return false; #endregion } else { #region This is the old DataDinding code (<v4.1) - it handles DataReaders. if (result1 is DataSet) { result = (object)((DataSet)result1).Tables[0].DefaultView; } else { result = result1; } if (result is IEnumerable) { IEnumerator iEnumerator = ((IEnumerable)result).GetEnumerator(); while (counter<skip && iEnumerator.MoveNext()) { counter++; } while (counter<(rows+skip) && iEnumerator.MoveNext()) { string val = GetField(iEnumerator.Current,dataValueField); string text = GetField(iEnumerator.Current,dataTextField); StoreResultDel(xmlDoc,responseTag,val,text); counter++; } try { moreRowsAvailable=iEnumerator.MoveNext(); } catch { moreRowsAvailable=false; } } else { throw new Exception("Returned object is not DataSet or IListSource or IList or IEnumerable"); } if (result is IDisposable) { IDisposable dis = (IDisposable)result; dis.Dispose(); } #endregion } #region Old DataBinding code (removed) /* if (result1 is DataSet) { result = (object)((DataSet)result1).Tables[0].DefaultView; } else { result = result1; } if (result is IEnumerable) { IEnumerator iEnumerator = ((IEnumerable)result).GetEnumerator(); while (counter<skip && iEnumerator.MoveNext()) { counter++; } while (counter<(rows+skip) && iEnumerator.MoveNext()) { string val; string text; #region extract the data record if (iEnumerator.Current is IDataRecord) { IDataRecord current = (IDataRecord)iEnumerator.Current; val = current[dataValueField].ToString(); text = current[dataTextField].ToString(); } else if (iEnumerator.Current is DataRowView) { DataRowView current = (DataRowView)iEnumerator.Current; val = current[dataValueField].ToString(); text = current[dataTextField].ToString(); } else if (iEnumerator.Current is IDictionary) { IDictionary current = (IDictionary)iEnumerator.Current; val = current[dataValueField].ToString(); text = current[dataTextField].ToString(); } else if (iEnumerator.Current is IEnumerable) { IEnumerator ie = ((IEnumerable)iEnumerator.Current).GetEnumerator(); ie.MoveNext(); val = ie.Current.ToString(); ie.MoveNext(); text = ie.Current.ToString(); } else { throw new Exception("Returned Object's IEnumerator.Current is not IDataRecord, DataRowView, IDictionary or IEnumerable"); } #endregion StoreResultDel(xmlDoc,responseTag,val,text); counter++; } try { moreRowsAvailable=iEnumerator.MoveNext(); } catch { moreRowsAvailable=false; } } else { throw new Exception("returned object is not IEnumerable"); } if (result is IDisposable) { IDisposable dis = (IDisposable)result; dis.Dispose(); } */ #endregion return moreRowsAvailable; }
/// <summary> /// Creates an <see cref="IHttpActionResult"/> based on the provided <paramref name="result"/>. /// </summary> /// <param name="result">The result to use when creating the <see cref="IHttpActionResult"/>.</param> /// <returns>An initialized <see cref="IHttpActionResult"/>.</returns> protected IHttpActionResult CreateHttpResult(StoreResult result) { switch (result) { case StoreResult.Success: return Ok(); case StoreResult.Conflict: return Conflict(); case StoreResult.NotFound: return NotFound(); case StoreResult.OperationError: return BadRequest(); default: return InternalServerError(); } }