public void CanCreateJsonNetResultUsingOverloadedConstructors() { JsonNetResult result; result = new JsonNetResult(); Assert.That(result.SerializerSettings, Is.Not.Null); // This is the most typical scenario result = new JsonNetResult("data to be serialized"); Assert.That(result.SerializerSettings, Is.Not.Null); Assert.That(result.Data, Is.Not.Null); // Not used very often, if ever result = new JsonNetResult("hi", "whatever"); Assert.That(result.SerializerSettings, Is.Not.Null); Assert.That(result.Data, Is.Not.Null); Assert.That(result.ContentType, Is.Not.Null); // Not used very often, if ever result = new JsonNetResult("hi", "whatever", Encoding.UTF8); Assert.That(result.SerializerSettings, Is.Not.Null); Assert.That(result.Data, Is.Not.Null); Assert.That(result.ContentType, Is.Not.Null); Assert.That(result.ContentEncoding, Is.EqualTo(Encoding.UTF8)); }
public JsonNetResult LoadData(int configurationID) { //Data return wrapper JsonNetResult result = new JsonNetResult() { }; //Load Configuration ConfigurationService _configurationService = new ConfigurationService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.Configuration configuration = _configurationService.GetByID(configurationID); //Load Model ModelService _modelService = new ModelService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.Model model = _modelService.GetByID(configuration.ModelID); //Load UITemplate UITemplateService _uiTemplatesService = new UITemplateService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.UITemplate template = _uiTemplatesService.GetByID(configuration.UITemplateID); //Initialize the ConfiguratorSession ConfiguratorSession newSession = new ConfiguratorSession(model, configuration, SolverService.CreateNewContext(model)); SetupFeatureSelections(ref newSession); SessionData.ConfiguratorSessions[configurationID] = newSession; //Return the data var innerObj = new { ConfigurationObj = configuration, ModelObj = model, TemplateObj = template }; result.Data = innerObj; return result; }
protected new JsonResult Json(Object obj) { JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.Data = obj; return jsonNetResult; }
public JsonNetResult Geo() { var result = new JsonNetResult { Data = Service.DataWorkSpace.GetGeoChina(),//JsonConvert.DeserializeObject(testData), }; return result; }
public JsonNetResult LoadData(int uiTemplateID) { //Data return controlTagElem JsonNetResult result = new JsonNetResult(); //Get the UITemplate UITemplateService _uiTemplatesService = new UITemplateService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.UITemplate template = _uiTemplatesService.GetByID(uiTemplateID); result.Data = template; return result; }
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { var jsonNetResult = new JsonNetResult(data) { ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; return jsonNetResult; }
public JsonNetResult LoadData(int modelID) { //Data return controlTagElem JsonNetResult result = new JsonNetResult(); //Model ModelService _modelService = new ModelService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.Model model = _modelService.GetByID(modelID); result.Data = model; return result; }
public JsonNetResult GetControlResources(string ControlType) { //Data return controlTagElem JsonNetResult result = new JsonNetResult(); //Create service UIControlTypes controltype = (UIControlTypes)Enum.Parse(typeof(UIControlTypes), ControlType, true); result.Data = UIControlsService.GetUIControlResources(controltype); // return result; }
public JsonNetResult GetModels() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Retreive Models belonging to the current User ModelService _modelService = new ModelService(SessionData.LoggedInUser.ID); List<BLL.BusinessObjects.Model> models = _modelService.GetByUserID_Shallow(SessionData.LoggedInUser.ID); result.Data = models; // return result; }
public JsonNetResult GetUITemplates() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Retreive UITemplates belonging to the current User UITemplateService _uiTemplatesService = new UITemplateService(SessionData.LoggedInUser.ID); List<BLL.BusinessObjects.UITemplate> uitemplates = _uiTemplatesService.GetByUserID(SessionData.LoggedInUser.ID, true); result.Data = uitemplates; // return result; }
public ActionResult Categories(int vn0_en1 = 0) { var categories = db.Categories.Where(a => a.IsActive); JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Formatting.Indented; jsonNetResult.Data = from a in categories select new { a.CategoryID, a.CategoryName }; if (vn0_en1 == 1) jsonNetResult.Data = from a in categories select new { a.CategoryID, CategoryName = a.CategoryName_EN }; return jsonNetResult; }
public JsonNetResult GetRelationTypes() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Get a dictionary of standard RelationTypes RelationService relationService = new RelationService(SessionData.LoggedInUser.ID); Dictionary<int, string> relationTypes = relationService.GetRelationTypes(); result.Data = relationTypes; // return result; }
public JsonNetResult EvalDatabindExpression(int configurationID, string expression) { //Data return controlTagElem JsonNetResult result = new JsonNetResult(); //Get the ConfiguratorSession ConfiguratorSession configSession = SessionData.ConfiguratorSessions[configurationID]; SolverService solverService = new SolverService(); //Get the implicit selections for the other features result.Data = solverService.EvalExpression(ref configSession, expression); return result; }
public JsonNetResult AddNewModel() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Add a new Model ModelService modelService = new ModelService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.Model newModel = (BLL.BusinessObjects.Model) modelService.CreateDefault(); modelService.Add(newModel); // result.Data = newModel; return result; }
public JsonNetResult AddNewUITemplate() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Add a new UITemplate UITemplateService _uiTemplatesService = new UITemplateService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.UITemplate newUITemplate = (BLL.BusinessObjects.UITemplate)_uiTemplatesService.CreateDefault(); _uiTemplatesService.Add(newUITemplate); // result.Data = newUITemplate; return result; }
protected JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior, JsonSerializerSettings settings) { var result = new JsonNetResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; if (settings != null) result.JsonSerializerSettings = settings; return result; }
public JsonNetResult GetCommonResources() { //Data return controlTagElem JsonNetResult result = new JsonNetResult(); //Get resources var commonResources = new { GenericControlTag = UIControlsService.GetGenericControlTag(), }; result.Data = commonResources; // return result; }
public JsonNetResult CallLogin(string email, string password) { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Verify the user credentials bool validUser = WebSecurity.AuthenticateUser(email, password); if (validUser) { result.Data = new JObject() { new JProperty("Redirect", Url.Action("Models", "Models")) }; } // return result; }
public ActionResult GetKeyword4Autocomplete(string StringInput) { var items = db.BrandItems.Where(a => a.Keyword.Length > 0); List<string> list = new List<string>(); foreach (var item in items) { foreach (var key in item.Keyword.Split(';')) { if (key != null && key.ToLower().StartsWith(StringInput.ToLower())) if (!list.Contains(key.ToLower().Trim())) list.Add(key.ToLower().Trim()); } } JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Formatting.Indented; jsonNetResult.Data = from a in list select a; return jsonNetResult; }
public JsonNetResult Search(string keyWord) { var contentGetter = new ContentGetter(); try { StatisticsHandler.HandleExpresion(keyWord); var content = contentGetter.GetResult(keyWord); var search = new JsonNetResult(content, JsonNetSettings.Default); return search; } catch (ModelException exception) { throw new HttpException(httpCode: (int) HttpStatusCode.InternalServerError, message:exception.Message, innerException:exception.InnerException); } catch (Exception) { throw new HttpException(httpCode:(int) HttpStatusCode.InternalServerError, message:"Unknown error."); } }
public JsonNetResult Edit(CreateEmployeeViewModel createEmployeeViewModel) { this.employeeTasks.RiaCreateOrUpdate(createEmployeeViewModel.Employee, createEmployeeViewModel.TerritoriesString); var serializer = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new NHibernateContractResolver(), }; var jsonNetResult = new JsonNetResult { Data = createEmployeeViewModel.Employee, SerializerSettings = serializer }; return jsonNetResult; }
public ActionResult Interest(string input) { //TODO: put this in a view model query IList<InterestKeywordDto> matchingKeywords = _interestTasks.GetMatchingKeywords(input); if (!matchingKeywords.Any(x => x.Name.ToLower() == input.ToLower())) { string formattedName = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()); matchingKeywords.Insert(0, new InterestKeywordDto { Name = formattedName, Slug = "-1" + input.ToLower() }); } var retVal = new JsonNetResult(matchingKeywords) { SerializerSettings = { NullValueHandling = NullValueHandling.Include } }; return retVal; }
public JsonNetResult GetNews() { var json = new JsonNetResult(); var cachedNews = this.HttpContext.Cache.Get("news"); if (cachedNews == null) { json.Data = GetNewsCollection(); if (!Debugger.IsAttached) { this.HttpContext.Cache.Add("news", json.Data, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } } else { json.Data = cachedNews; } return json; }
public ActionResult Login365() { ActionResult result = null; var db = ConfigurationManager.AppSettings["enova365Db"]; var key = ConfigurationManager.AppSettings["enova365Key"]; var user = ConfigurationManager.AppSettings["enova365User"]; var url = ConfigurationManager.AppSettings["enova365Service"]; try { var tokenInfo = new ServiceReference1.GenerateTokenInfo { User = user, DbName = db, Key = key }; var binding = new BasicHttpBinding(BasicHttpSecurityMode.None); var endpoint = new EndpointAddress(url + "/Business/TokenService.svc"); var bus = new ServiceReference1.TokenServiceClient(binding, endpoint); var tokenResult = bus.GenerateToken(tokenInfo); if (tokenResult.IsAuthenticated) { return new JsonNetResult(new { Token = tokenResult.Token, Db = db }); } result = new JsonNetResult(new { ErrorHandle = !String.IsNullOrEmpty(tokenResult.ExceptionMessage) ? tokenResult.ExceptionMessage : "Niepoprawne dane logowania" }); } catch (Exception exc) { result = new JsonNetResult(new { ErrorHandle = exc.Message }); } return result; }
public async Task SendTextMessage(int dialogId, string message, string dialogType) { var connection = _connections.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId); var baseMessage = new ConferenceMessage() { Date = DateTime.Now, IsNew = true, TextMessage = message, FromId = connection.Id }; using (var uofw = _unitOfWorkFactory.CreateSystem()) { var serv = (ISimpleMessageService)GetService<IBaseObjectCRUDService>(dialogType); var messageResult = await serv.CreateMessage(uofw, baseMessage, dialogId); var result = new JsonNetResult(messageResult.Message).ToString(); await _sendTextMessage(messageResult.Targets, result, dialogType); } }
public JsonNetResult NewDefaultCompositionRule() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Get a new default CompositionRule CompositionRuleService _compositionRuleService = new CompositionRuleService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.CompositionRule newCompositionRule = (BLL.BusinessObjects.CompositionRule)_compositionRuleService.CreateDefault(); result.Data = newCompositionRule; // return result; }
public JsonNetResult NewDefaultAttribute() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Get a new default Attribute AttributeService _attributeService = new AttributeService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.Attribute newAttribute = (BLL.BusinessObjects.Attribute)_attributeService.CreateDefault(); result.Data = newAttribute; // return result; }
public void GetList() { JsonNetResult result = (JsonNetResult)_controller.QueryPager(null); Assert.True(result.Data != null); }
public override void ProcessAjaxRequest(ExceptionContext filterContext) { filterContext.HttpContext.Response.StatusCode = 401; filterContext.Result = JsonNetResult.Fail(filterContext.Exception); }
public JsonNetResult SaveBusinessObjects(int modelID, string businessObjectsString, string businessObjectsType) { //Setup variables & types JsonNetResult result = new JsonNetResult(); Assembly BLLAssembly = Assembly.GetAssembly(typeof(BLL.BusinessObjects.IBusinessObject)); Type businessObjectType = BLLAssembly.GetType("BLL.BusinessObjects." + businessObjectsType, false, true); //Create a corresponding service Type specificServiceType = BLLAssembly.GetType("BLL.Services." + businessObjectsType + "Service", false, true); IDataService service = (IDataService)Activator.CreateInstance(specificServiceType, (object)SessionData.LoggedInUser.ID); //Handle BusinessObjects Dictionary<int, JObject> businessObjectsCollection = (Dictionary<int, JObject>)Newtonsoft.Json.JsonConvert.DeserializeObject(businessObjectsString, typeof(Dictionary<int, JObject>)); Dictionary<int, IBusinessObject> updatedObjects = new Dictionary<int, IBusinessObject>(); foreach (KeyValuePair<int, JObject> entry in businessObjectsCollection) { JObject jObj = (JObject)entry.Value; IBusinessObject businessObj = (IBusinessObject)Newtonsoft.Json.JsonConvert.DeserializeObject(jObj.ToString(), businessObjectType); //Delete if (businessObj.ToBeDeleted == true && businessObj.ID != 0) { service.Delete(businessObj); } //Add else if (businessObj.ToBeDeleted == false && businessObj.ID == 0) { service.Add(businessObj); } //Update else if (businessObj.ToBeDeleted == false && businessObj.ID != 0) { service.Update(businessObj); } updatedObjects.Add((int)entry.Key, businessObj); } //Return result.Data = updatedObjects; return result; }
public JsonNetResult NewDefaultRelation() { //Default return variable JsonNetResult result = new JsonNetResult() { Data = null }; //Get a new default Feature RelationService _relationService = new RelationService(SessionData.LoggedInUser.ID); BLL.BusinessObjects.Relation newRelation = (BLL.BusinessObjects.Relation)_relationService.CreateDefault(); result.Data = newRelation; // return result; }
public JsonNetResult GetSalesLeads(string label, int take, string lastPartitionKey = null, string lastRowKey = null) { var authCookie = AuthenticationCookieManager.GetAuthenticationCookie(); //var accountNameKey = authCookie.AccountNameKey; //var accountId = authCookie.AccountID; var account = Common.GetAccountObject(authCookie.AccountNameKey); var userId = authCookie.Id.ToString(); //<-- For future logging purposes List <SalesLeadTableEntity> salesLeads = null; #region Make sure account plan allow for sales leads if (account.PaymentPlan.AllowSalesLeads == false) { JsonNetResult jsonNetResultRestricted = new JsonNetResult(); jsonNetResultRestricted.Formatting = Formatting.Indented; jsonNetResultRestricted.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultRestricted.Data = salesLeads; return(jsonNetResultRestricted); } #endregion #region Connect to table storage and retreive sales leads #region Generate Leads Table Name var leadsTableName = "acc" + account.AccountID.ToString().Replace("-", "").ToLower() + "Leads" + label.Replace("-", "").Replace(" ", ""); #endregion #region Connect to table storage (Legacy) /* * CloudStorageAccount storageAccount; * // Credentials are from centralized CoreServiceSettings * StorageCredentials storageCredentials = new StorageCredentials(CoreServices.PlatformSettings.Storage.AccountName, CoreServices.PlatformSettings.Storage.AccountKey); * storageAccount = new CloudStorageAccount(storageCredentials, false); * CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); * * //Create and set retry policy for logging * //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); * IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); * cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; * * CloudTable cloudTable = cloudTableClient.GetTableReference(leadsTableName); * * cloudTable.CreateIfNotExists(); */ #endregion #region Connect to table storage partition & Set Retry Policy #region Get Storage Partition if (CoreServices.PlatformSettings.StorageParitions == null || CoreServices.PlatformSettings.StorageParitions.ToList().Count == 0) { //No Storage Partitions Available in Static List, refresh list from Core Services Common.RefreshPlatformSettings(); } //Get the storage partition for this account var storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); if (storagePartition == null) { //May be a new partition, refresh platform setting and try again Common.RefreshPlatformSettings(); storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); } #endregion CloudStorageAccount storageAccount; StorageCredentials storageCredentials = new StorageCredentials(storagePartition.Name, storagePartition.Key); storageAccount = new CloudStorageAccount(storageCredentials, false); CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); //Create and set retry policy for logging //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; CloudTable cloudTable = cloudTableClient.GetTableReference(leadsTableName); cloudTable.CreateIfNotExists(); #endregion var continuationToken = new TableContinuationToken(); continuationToken.NextPartitionKey = lastPartitionKey; continuationToken.NextRowKey = lastRowKey; if (lastPartitionKey != null && lastRowKey != null) { take = take + 1; //<-- we add 1 if using continuation since the first row will be a duplicate of the last } TableQuery <SalesLeadTableEntity> query = new TableQuery <SalesLeadTableEntity>().Take(take); salesLeads = cloudTable.ExecuteQuerySegmented(query, continuationToken).ToList(); #endregion if (lastPartitionKey != null && lastRowKey != null) { salesLeads.RemoveAt(0); //<-- we remove the first item if using continuation since the first row will be a duplicate of the last } JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = salesLeads; return(jsonNetResult); }
public JsonNetResult MoveSalesLead(string partitionKey, string rowKey, string fromLabel, string toLabel) { var authCookie = AuthenticationCookieManager.GetAuthenticationCookie(); //var accountNameKey = authCookie.AccountNameKey; //var accountId = authCookie.AccountID; var account = Common.GetAccountObject(authCookie.AccountNameKey); var userId = authCookie.Id.ToString(); //<-- For future logging purposes #region Make sure account plan allow for sales leads if (account.PaymentPlan.AllowSalesLeads == false) { JsonNetResult jsonNetResultRestricted = new JsonNetResult(); jsonNetResultRestricted.Formatting = Formatting.Indented; jsonNetResultRestricted.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultRestricted.Data = new AccountManagementService.DataAccessResponseType { isSuccess = false, ErrorMessage = "Account plan does not allow for sales leads" }; return(jsonNetResultRestricted); } #endregion SalesLeadTableEntity salesLeadToMoveAndDelete = null; AccountManagementService.DataAccessResponseType response = new AccountManagementService.DataAccessResponseType(); #region Connect to table storage and retreive sales lead to move and delete from origin #region Generate BOTH Leads Table Name var leadsFromTableName = "acc" + account.AccountID.ToString().Replace("-", "").ToLower() + "Leads" + fromLabel.Replace("-", "").Replace(" ", ""); var leadsToTableName = "acc" + account.AccountID.ToString().Replace("-", "").ToLower() + "Leads" + toLabel.Replace("-", "").Replace(" ", ""); #endregion #region Connect to table storage (Legacy) /* * CloudStorageAccount storageAccount; * // Credentials are from centralized CoreServiceSettings * StorageCredentials storageCredentials = new StorageCredentials(CoreServices.PlatformSettings.Storage.AccountName, CoreServices.PlatformSettings.Storage.AccountKey); * storageAccount = new CloudStorageAccount(storageCredentials, false); * CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); * * //Create and set retry policy for logging * //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); * IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); * cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; */ #endregion #region Connect to table storage partition & Set Retry Policy #region Get Storage Partition if (CoreServices.PlatformSettings.StorageParitions == null || CoreServices.PlatformSettings.StorageParitions.ToList().Count == 0) { //No Storage Partitions Available in Static List, refresh list from Core Services Common.RefreshPlatformSettings(); } //Get the storage partition for this account var storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); if (storagePartition == null) { //May be a new partition, refresh platform setting and try again Common.RefreshPlatformSettings(); storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); } #endregion CloudStorageAccount storageAccount; StorageCredentials storageCredentials = new StorageCredentials(storagePartition.Name, storagePartition.Key); storageAccount = new CloudStorageAccount(storageCredentials, false); CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); //Create and set retry policy for logging //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; #endregion CloudTable cloudTable = cloudTableClient.GetTableReference(leadsFromTableName); cloudTable.CreateIfNotExists(); TableQuery <SalesLeadTableEntity> query = new TableQuery <SalesLeadTableEntity>().Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey), TableOperators.And, TableQuery.GenerateFilterCondition( "RowKey", QueryComparisons.Equal, rowKey) ) ); try { salesLeadToMoveAndDelete = cloudTable.ExecuteQuery(query).FirstOrDefault(); } catch (Exception e) { response.isSuccess = false; response.ErrorMessage = e.Message; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } if (salesLeadToMoveAndDelete == null) { response.isSuccess = false; response.ErrorMessage = "Could not locate source lead"; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } #endregion #region Move source lead (then delete origin) try { cloudTable = cloudTableClient.GetTableReference(leadsToTableName); cloudTable.CreateIfNotExists(); //Create copy for insert //var salesLeadToMoveAndDeleteCopy = salesLeadToMoveAndDelete; //create an insert operation for each entity, assign to designated CloudTable, and add to our list of tasks: TableOperation insertOperation = TableOperation.Insert(salesLeadToMoveAndDelete); var tableResultMove = cloudTable.Execute(insertOperation); if (tableResultMove.HttpStatusCode == 204) { #region Delete From Origin try { cloudTable = cloudTableClient.GetTableReference(leadsFromTableName); cloudTable.CreateIfNotExists(); //Geta fresh copy from org table (so we don't get an issue with changing ETag) salesLeadToMoveAndDelete = cloudTable.ExecuteQuery(query).FirstOrDefault(); //create an insert operation for each entity, assign to designated CloudTable, and add to our list of tasks: TableOperation deleteOperation = TableOperation.Delete(salesLeadToMoveAndDelete); var tableResultDelete = cloudTable.Execute(deleteOperation); if (tableResultDelete.HttpStatusCode == 204) { //Both leads were moved successfully: response.isSuccess = true; } else { response.isSuccess = false; response.ErrorMessage = "Lead duplicated, but could not delete from origin for an unknown reason"; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } } catch (Exception e) { response.isSuccess = false; response.ErrorMessage = "Lead duplicated, but could not delete from origin: " + e.Message; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } #endregion } } catch (Exception e) { response.isSuccess = false; response.ErrorMessage = "Could not move lead to new label: " + e.Message; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } #endregion JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = response; return(jsonNetResult); }
public JsonNetResult UpdateSalesLead(string partitionKey, string rowKey, string label, string field, string value) { var authCookie = AuthenticationCookieManager.GetAuthenticationCookie(); //var accountNameKey = authCookie.AccountNameKey; //var accountId = authCookie.AccountID; var account = Common.GetAccountObject(authCookie.AccountNameKey); var userId = authCookie.Id.ToString(); //<-- For future logging purposes #region Make sure account plan allow for sales leads if (account.PaymentPlan.AllowSalesLeads == false) { JsonNetResult jsonNetResultRestricted = new JsonNetResult(); jsonNetResultRestricted.Formatting = Formatting.Indented; jsonNetResultRestricted.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultRestricted.Data = new AccountManagementService.DataAccessResponseType { isSuccess = false, ErrorMessage = "Account plan does not allow for sales leads" }; return(jsonNetResultRestricted); } #endregion SalesLeadTableEntity salesLeadToUpdate = null; AccountManagementService.DataAccessResponseType response = new AccountManagementService.DataAccessResponseType(); #region Connect to table storage, retreive sales lead and make the update #region Generate Leads Table Name var leadsTableName = "acc" + account.AccountID.ToString().Replace("-", "").ToLower() + "Leads" + label.Replace("-", "").Replace(" ", ""); #endregion #region Connect to table storage (Legacy) /* * CloudStorageAccount storageAccount; * // Credentials are from centralized CoreServiceSettings * StorageCredentials storageCredentials = new StorageCredentials(CoreServices.PlatformSettings.Storage.AccountName, CoreServices.PlatformSettings.Storage.AccountKey); * storageAccount = new CloudStorageAccount(storageCredentials, false); * CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); * * //Create and set retry policy for logging * //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); * IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); * cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; */ #endregion #region Connect to table storage partition & Set Retry Policy #region Get Storage Partition if (CoreServices.PlatformSettings.StorageParitions == null || CoreServices.PlatformSettings.StorageParitions.ToList().Count == 0) { //No Storage Partitions Available in Static List, refresh list from Core Services Common.RefreshPlatformSettings(); } //Get the storage partition for this account var storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); if (storagePartition == null) { //May be a new partition, refresh platform setting and try again Common.RefreshPlatformSettings(); storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); } #endregion CloudStorageAccount storageAccount; StorageCredentials storageCredentials = new StorageCredentials(storagePartition.Name, storagePartition.Key); storageAccount = new CloudStorageAccount(storageCredentials, false); CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); //Create and set retry policy for logging //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; #endregion #region Select the Entity to update CloudTable cloudTable = cloudTableClient.GetTableReference(leadsTableName); cloudTable.CreateIfNotExists(); TableQuery <SalesLeadTableEntity> query = new TableQuery <SalesLeadTableEntity>().Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey), TableOperators.And, TableQuery.GenerateFilterCondition( "RowKey", QueryComparisons.Equal, rowKey) ) ); try { salesLeadToUpdate = cloudTable.ExecuteQuery(query).FirstOrDefault(); } catch (Exception e) { response.isSuccess = false; response.ErrorMessage = e.Message; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } if (salesLeadToUpdate == null) { response.isSuccess = false; response.ErrorMessage = "Could not locate lead to update"; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } #endregion #endregion #region Make the updates (on allowed fields) switch (field) { case "FirstName": #region Manage Update if (value.Length > 35) { #region Too long (Truncate) value = value.Substring(0, 35); #endregion } salesLeadToUpdate.FirstName = value; #endregion break; case "LastName": #region Manage Update if (value.Length > 35) { #region Too long (Truncate) value = value.Substring(0, 35); #endregion } salesLeadToUpdate.LastName = value; #endregion break; case "CompanyName": #region Manage Update if (value.Length > 60) { #region Too long (Truncate) value = value.Substring(0, 60); #endregion } salesLeadToUpdate.CompanyName = value; #endregion break; case "Comments": #region Manage Update if (value.Length > 600) { #region Too long (Truncate) value = value.Substring(0, 600); #endregion } salesLeadToUpdate.Comments = value; #endregion break; case "Notes": #region Manage Update if (value.Length > 600) { #region Too long (Truncate) value = value.Substring(0, 600); #endregion } salesLeadToUpdate.Notes = value; #endregion break; case "Phone": #region Manage Update if (value.Length > 40) { #region Too long (Truncate) value = value.Substring(0, 40); #endregion } salesLeadToUpdate.Phone = value; #endregion break; case "Email": #region Manage Update if (value.Length > 40) { #region Too long (Truncate) value = value.Substring(0, 40); #endregion } salesLeadToUpdate.Email = value; #endregion break; case "LocationPath": #region Manage Update if (value.Length > 300) { #region Too long (Truncate) value = value.Substring(0, 300); #endregion } salesLeadToUpdate.LocationPath = value; #endregion break; case "FullyQualifiedName": #region Manage Update if (value.Length > 400) { #region Too long (Truncate) value = value.Substring(0, 400); #endregion } salesLeadToUpdate.FullyQualifiedName = value; #endregion break; case "Origin": #region Manage Update if (value.Length > 35) { #region Too long (Truncate) value = value.Substring(0, 35); #endregion } salesLeadToUpdate.Origin = value; #endregion break; case "IPAddress": #region Manage Update if (value.Length > 120) { #region Too long (Truncate) value = value.Substring(0, 120); #endregion } salesLeadToUpdate.IPAddress = value; #endregion break; case "ProductName": #region Manage Update if (value.Length > 240) { #region Too long (Truncate) value = value.Substring(0, 240); #endregion } salesLeadToUpdate.ProductName = value; #endregion break; case "ProductID": #region Manage Update if (value.Length > 120) { #region Too long (Truncate) value = value.Substring(0, 120); #endregion } salesLeadToUpdate.ProductID = value; #endregion break; case "Object": #region Manage Update if (value.Length > 10000) { #region Too long (Truncate) value = value.Substring(0, 10000); #endregion } salesLeadToUpdate.Object = value; #endregion break; default: #region Not allowed, return result response.isSuccess = false; response.ErrorMessage = "Can not make updates to fields titled " + field; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); #endregion } #endregion try { TableOperation updateOperation = TableOperation.Replace(salesLeadToUpdate); var tableResultUpdate = cloudTable.Execute(updateOperation); if (tableResultUpdate.HttpStatusCode == 204) { response.isSuccess = true; } else { response.isSuccess = false; response.ErrorMessage = "Could not make update. HttpStatusCode:" + tableResultUpdate.HttpStatusCode; } } catch (Exception e) { response.isSuccess = false; response.ErrorMessage = "Could not make update: " + e.Message; JsonNetResult jsonNetResultError = new JsonNetResult(); jsonNetResultError.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResultError.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultError.Data = response; return(jsonNetResultError); } JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = response; return(jsonNetResult); }
public JsonNetResult SubmitSalesLead(string label = "New", string firstName = "", string lastName = "", string companyName = "", string phone = "", string email = "", string comments = "", string notes = "", string productName = "", string productId = "", string fullyQualifiedName = "", string locationPath = "", string origin = "", string ipAddress = "", string userId = "", string userName = "") { var response = new AccountManagementService.DataAccessResponseType(); var authCookie = AuthenticationCookieManager.GetAuthenticationCookie(); //var accountNameKey = authCookie.AccountNameKey; //var accountId = authCookie.AccountID; var account = Common.GetAccountObject(authCookie.AccountNameKey); #region Make sure account plan allow for sales leads if (account.PaymentPlan.AllowSalesLeads == false) { JsonNetResult jsonNetResultRestricted = new JsonNetResult(); jsonNetResultRestricted.Formatting = Formatting.Indented; jsonNetResultRestricted.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResultRestricted.Data = new AccountManagementService.DataAccessResponseType { isSuccess = false, ErrorMessage = "Account plan does not allow for sales leads" }; return(jsonNetResultRestricted); } #endregion if (label == "" || label == null) { label = "New"; } if (userId == "" || userId == null) { userId = authCookie.Id.ToString(); } if (userName == "" || userName == null) { userName = authCookie.FirstName + " " + authCookie.LastName; } #region Generate Leads Table Name var newLeadsTableName = "acc" + account.AccountID.ToString().Replace("-", "").ToLower() + "Leads" + label; #endregion #region Connect to table storage (Legacy) /* * CloudStorageAccount storageAccount; * // Credentials are from centralized CoreServiceSettings * StorageCredentials storageCredentials = new StorageCredentials(CoreServices.PlatformSettings.Storage.AccountName, CoreServices.PlatformSettings.Storage.AccountKey); * storageAccount = new CloudStorageAccount(storageCredentials, false); * CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); * * //Create and set retry policy for logging * //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); * IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); * cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; */ #endregion #region Connect to table storage partition & Set Retry Policy #region Get Storage Partition if (CoreServices.PlatformSettings.StorageParitions == null || CoreServices.PlatformSettings.StorageParitions.ToList().Count == 0) { //No Storage Partitions Available in Static List, refresh list from Core Services Common.RefreshPlatformSettings(); } //Get the storage partition for this account var storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); if (storagePartition == null) { //May be a new partition, refresh platform setting and try again Common.RefreshPlatformSettings(); storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition); } #endregion CloudStorageAccount storageAccount; StorageCredentials storageCredentials = new StorageCredentials(storagePartition.Name, storagePartition.Key); storageAccount = new CloudStorageAccount(storageCredentials, false); CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient(); //Create and set retry policy for logging //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; #endregion #region Create TableEntity for Lead SalesLeadTableEntity salesLead = new SalesLeadTableEntity(cloudTableClient, newLeadsTableName); salesLead.FirstName = firstName; salesLead.LastName = lastName; salesLead.CompanyName = companyName; salesLead.Origin = origin; salesLead.Phone = phone; salesLead.Email = email; salesLead.Comments = comments; salesLead.Notes = notes; salesLead.ProductID = productId; salesLead.ProductName = productName; salesLead.IPAddress = ipAddress; salesLead.FullyQualifiedName = fullyQualifiedName; salesLead.LocationPath = locationPath; salesLead.UserID = userId; salesLead.UserName = userName; #endregion #region Insert Entity try { //create an insert operation for each entity, assign to designated CloudTable, and add to our list of tasks: TableOperation operation = TableOperation.Insert(salesLead); var tableResult = salesLead.cloudTable.Execute(operation); if (tableResult.HttpStatusCode == 204) { response.isSuccess = true; } else { response.isSuccess = false; response.ErrorMessage = "Could not insert lead. HttpStatusCode: " + tableResult.HttpStatusCode; } } catch (Exception e) { response.isSuccess = false; response.ErrorMessage = "Could not insert lead: " + e.Message; } #endregion #region Send email alerts (If ON) using BackgroundTask (We don't do this on the ADMIN side - just on the site //if (isSuccess) //{ //BackgroundTasks.SalesAlerts.SendSalesAlerts(accountNameKey, firstName, lastName, companyName, phone, email, comments, productName, productId, fullyQualifiedName, locationPath, origin, ipAddress); //} #endregion JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = response; return(jsonNetResult); }
public JsonNetResult GetPayment(string chargeId) { var user = AuthenticationCookieManager.GetAuthenticationCookie(); Charge charge = null; #region (Plan A) Get data from Redis Cache /* * try * { * IDatabase cache = CoreServiceSettings.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase(); * * string hashKey = "accountbyid:" + accountId.ToString().Replace("-", ""); * string hashField = "creditcard"; * * var redisValue = cache.HashGet(hashKey, hashField); * * if (redisValue.HasValue) * { * accountCreditCardInfo = JsonConvert.DeserializeObject<AccountCreditCardInfo>(redisValue); * } * } * catch (Exception e) * { * var error = e.Message; * //TODO: Log: error message for Redis call * }*/ #endregion if (charge == null) { #region (Plan B) Get data from WCF var accountBillingServiceClient = new AccountBillingService.AccountBillingServiceClient(); try { accountBillingServiceClient.Open(); charge = accountBillingServiceClient.GetPayment( chargeId, Common.SharedClientKey );//, //user.Id, //PlatformAdminSite.AccountManagementService.RequesterType.PlatformUser).ToList(); //Close the connection WCFManager.CloseConnection(accountBillingServiceClient); } catch (Exception e) { #region Manage Exception string exceptionMessage = e.Message.ToString(); var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name; // Abort the connection & manage the exception WCFManager.CloseConnection(accountBillingServiceClient, exceptionMessage, currentMethodString); #endregion } #endregion } JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = charge; return(jsonNetResult); }
/// <summary> /// Check for presence of valid trip. /// </summary> /// <remarks> /// NOTE: Assumes that model binder has already worked it's magic on the /// request pipeline. /// </remarks> /// <param name="filterContext">Current action context</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { // If the parameter doesn't exist in the collection of params, assume that the // filter was incorrectly applied and drive on. if (!filterContext.ActionParameters.ContainsKey(Parameter)) { base.OnActionExecuting(filterContext); return; } var trip = filterContext.ActionParameters[Parameter]; bool isPresent = null != trip; bool isCorrectType = isPresent && this.TripType.IsAssignableFrom(trip.GetType()); // Trip exists and is of the correct type. if (isPresent && isCorrectType) { base.OnActionExecuting(filterContext); return; } // Push to our custom 404 page called 'NoSuchTripResult' if (!IsApiRequest(filterContext)) { filterContext.Result = new NoSuchTripResult(); return; } // At this point, we know that the trip is missing (or wrong type) // and need to send an appropriate result. filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; var result = new JsonNetResult() { Data = isPresent ? INVALID_TRIP_MESSAGE : MISSING_TRIP_MESSAGE, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.Result = result; }
public JsonNetResult GetAccount() { //Account account = null; List <ApiKeyModel> keys = null; //var accountId = AuthenticationCookieManager.GetAuthenticationCookie().AccountID.ToString(); var accountNameKey = Common.GetSubDomain(Request.Url); #region (Plan A) Get data from Redis Cache try { //First we attempt to get the apikeys from the Redis Cache IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase(); string hashKey = accountNameKey + ":apikeys"; string hashField = "list"; try { var redisValue = cache.HashGet(hashKey, hashField); if (redisValue.HasValue) { keys = JsonConvert.DeserializeObject <List <ApiKeyModel> >(redisValue); } } catch { } } catch (Exception e) { var error = e.Message; //Log error message for Redis call } #endregion if (keys == null) { #region (Plan B) Get data from WCF var applicationApiKeysServiceClient = new ApplicationApiKeysService.ApplicationApiKeysServiceClient(); try { applicationApiKeysServiceClient.Open(); keys = applicationApiKeysServiceClient.GetApiKeys(accountNameKey, Common.SharedClientKey).ToList(); //Close the connection WCFManager.CloseConnection(applicationApiKeysServiceClient); } catch (Exception e) { #region Manage Exception string exceptionMessage = e.Message.ToString(); var currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name; // Abort the connection & manage the exception WCFManager.CloseConnection(applicationApiKeysServiceClient, exceptionMessage, currentMethodString); #endregion } #endregion } JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.Formatting = Formatting.Indented; jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime jsonNetResult.Data = keys; return(jsonNetResult); }