int getNewlyGeneratedId(DatabaseType dbType, CRMDb db) { ObjectContext objectContext = ((IObjectContextAdapter)db).ObjectContext; ObjectSet <DatabaseType> set = objectContext.CreateObjectSet <DatabaseType>(); IEnumerable <string> keyNames = set.EntitySet.ElementType .KeyMembers .Select(k => k.Name); if (keyNames != null && keyNames.Any()) { string idValue = dbType.GetType().GetProperty(keyNames.FirstOrDefault()).GetValue(dbType, null).ToString(); int id = 0; if (!int.TryParse(idValue, out id)) { throw new InvalidOperationException("More than once key configured to the entity: " + dbType.GetType().ToString()); } else { return(id); } } else { throw new InvalidOperationException("More than once key configured to the entity: " + dbType.GetType().ToString()); } }
public static string GetCustomerSegmentation(string customersegmentation, string type) { CRMDb db = new CRMDb(); string custinfo = string.Empty; /* * 101 --> Segementation * 102 --> Membership */ int statustype = "Segmentation".Equals(type) ? 101 : 102; var model = db.statusmapper .Where(x => x.EntityType == 19) .Where(x => x.StatusType == statustype) .Select(x => new { k = x.Key, v = x.Value }); foreach (var item in model) { if (customersegmentation.Contains(item.k)) { custinfo = item.v; break; } } return(custinfo); }
private CustomerInfo RetrieveCustomerByCustomerNumber(string customerNumber) { CRMDb db = new CRMDb(); CustomerInfo customerInfo = new CustomerInfo(); var query = db.customer.Where(x => x.CreditCardCustomerNo == customerNumber); if (query.Count() == 1) { customerInfo.Customer = query.First(); customerInfo.StatusUpdate = 1; } else if (query.Count() > 1) { customerInfo.Customer = null; customerInfo.StatusUpdate = -1; } else { customerInfo.Customer = null; customerInfo.StatusUpdate = 0; } return(customerInfo); }
/// <summary> /// gets data from given multiple sql and executes the action /// </summary> /// <param name="db"></param> /// <param name="sql"></param> /// <param name="parameters"></param> /// <param name="action"></param> /// <param name="getFromCache"></param> public static void GetMultiple (this CRMDb db, string sql, Action <SqlMapper.GridReader> action = null, object parameters = null, bool getFromCache = false, int commandTimeout = 300) { try { var cs = getConnectionString(db); using (var _con = GetSqlConnection(cs)) { _con.Open(); using (var mq = _con.QueryMultiple(sql, parameters, commandTimeout: commandTimeout)) { action(mq); } } } catch (Exception ex) { parameters = (parameters == null) ? new object() : parameters; ex.Data.Clear(); ex.Data.Add("parameters", new JavaScriptSerializer().Serialize(parameters)); ex.Data.Add("sql", sql); Logger.Current.Error("Error while querying using dapper", ex); throw ex; } }
public static IEnumerable <dynamic> Get(this CRMDb db, string sql, object parameters = null, bool getFromCache = false, TimeSpan cacheInterval = default(TimeSpan)) { try { var cache = new MemoryCacheManager(); var key = GetHashedKey(sql + parameters); if (getFromCache && cache.IsExists(key)) { return(cache.Get <IEnumerable <dynamic> >(key)); } var cs = getConnectionString(db); using (var _con = GetSqlConnection(cs)) { _con.Open(); var result = _con.Query(sql, parameters); return(AddToCache(key, result, cache, getFromCache, cacheInterval)); } } catch (Exception ex) { parameters = (parameters == null) ? new object() : parameters; ex.Data.Clear(); ex.Data.Add("parameters", new JavaScriptSerializer().Serialize(parameters)); ex.Data.Add("sql", sql); Logger.Current.Error("Error while querying using dapper", ex); throw ex; } }
//Get all actions list to from selected role and entityname public static List <RootMenuSubmenuEntityAction> getActionButton(Guid roleID, string entityName) { CRMDb db = new CRMDb(); var getCurrentRole = db.securityRole.Find(roleID); Root roleObject = (Root)ParseXMLHelper.DeserializeXml(getCurrentRole.XMLRole, "db");; var ent = ( from menu in roleObject.Menu from submenu in menu.Submenu from entity in submenu.Entity where entity.name == entityName && entity.Action != null //where entity.name == entityName //where action != null && action.check == true select new RootMenuSubmenuEntity { Action = entity.Action } ).ToList(); List <RootMenuSubmenuEntityAction> actionList = ent.SelectMany(x => x.Action).ToList(); return(actionList); }
/// <summary> /// /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <param name="db"></param> /// <param name="sql"></param> /// <param name="map"></param> /// <param name="parameters"></param> /// <param name="splitOn"></param> /// <param name="getFromCache"></param> /// <returns></returns> public static IEnumerable <T1> Get <T1, T2, T3, T4>(this CRMDb db, string sql, Func <T1, T2, T3, T4, T1> map, object parameters = null, string splitOn = "Id", bool getFromCache = false, TimeSpan cacheInterval = default(TimeSpan), CommandType commandType = CommandType.Text, int timeoutSeconds = 30) { try { var cache = new MemoryCacheManager(); var key = GetHashedKey(sql + parameters); if (getFromCache && cache.IsExists(key)) { return(cache.Get <IEnumerable <T1> >(key)); } var cs = getConnectionString(db); using (var _con = GetSqlConnection(cs)) { _con.Open(); var result = _con.Query <T1, T2, T3, T4, T1>(sql, map, parameters, splitOn: splitOn, commandType: commandType, commandTimeout: timeoutSeconds); return(AddToCache(key, result, cache, getFromCache, cacheInterval)); } } catch (Exception ex) { parameters = (parameters == null) ? new object() : parameters; ex.Data.Clear(); ex.Data.Add("parameters", new JavaScriptSerializer().Serialize(parameters)); ex.Data.Add("sql", sql); Logger.Current.Error("Error while querying using dapper", ex); throw ex; } }
/// <summary> /// Persists the user tours. /// </summary> /// <param name="tour">The tour.</param> /// <param name="tourDb">The tour database.</param> /// <param name="db">The database.</param> public void PersistUserTours(Tour tour, TourDb tourDb, CRMDb db) { var userTourDb = new List <UserTourMapDb>(); var dbData = ObjectContextFactory.Create(); var sql = @"SELECT UAM.UserID FROM UserTourMap (NOLOCK) UAM WHERE UAM.TourID = @tourId"; var dbData1 = ObjectContextFactory.Create(); var tourUsers = dbData1.Get <int>(sql, new { tourId = tour.Id }); tourUsers = tour.OwnerIds.Except(tourUsers); foreach (int userId in tourUsers) { userTourDb.Add(new UserTourMapDb() { TourID = tourDb.TourID, UserID = userId, LastUpdatedOn = DateTime.Now.ToUniversalTime(), LastUpdatedBy = tour.CreatedBy, UserEmailGuid = (tour.EmailGuid != null && tour.EmailGuid.Any()) ? tour.EmailGuid.Where(s => s.Key == userId).Select(v => v.Value).FirstOrDefault(): new Guid(), UserTextGuid = (tour.TextGuid != null && tour.TextGuid.Any()) ? tour.TextGuid.Where(s => s.Key == userId).Select(v => v.Value).FirstOrDefault() : new Guid() }); } db.UserTours.AddRange(userTourDb); var UnMapTourUsers = db.UserTours.Where(s => !tour.OwnerIds.Contains(s.UserID) && s.TourID == tour.Id).ToArray(); db.UserTours.RemoveRange(UnMapTourUsers); }
/// <summary> /// Persists the form fields. /// </summary> /// <param name="form">The form.</param> /// <param name="formDb">The form database.</param> /// <param name="db">The database.</param> private void PersistFormFields(Form form, FormsDb formDb, CRMDb db) { if (form.Id > 0) { foreach (FormField formField in form.FormFields.Where(f => f.FormFieldId == 0)) { FormFieldsDb formFieldDb = Mapper.Map <FormField, FormFieldsDb>(formField); db.FormFields.Add(formFieldDb); } } //else //{ // formDb.FormFields = db.FormFields.Where(f => f.FormID == formDb.FormID).ToList(); // foreach (FormField field in form.FormFields) // { // FormFieldsDb formFieldDb = formDb.FormFields.Where(f => f.FieldID == field.Id).FirstOrDefault(); // formFieldDb = Mapper.Map<FormField, FormFieldsDb>(field); // formFieldDb.FormID = form.Id; // if (formFieldDb.FormFieldID == 0) // formDb.FormFields.Add(formFieldDb); // } //} IList <int> formFieldIds = form.FormFields.Where(a => a.FormFieldId > 0).Select(a => a.FormFieldId).ToList(); var unMapFormFields = db.FormFields.Where(a => !formFieldIds.Contains(a.FormFieldID) && a.FormID == form.Id); foreach (FormFieldsDb formFieldMapDb in unMapFormFields) { formFieldMapDb.IsDeleted = true; db.Entry(formFieldMapDb).State = EntityState.Deleted; } }
//Get XML role for writing menu public static Root getRoleObject(Guid roleID) { CRMDb db = new CRMDb(); Root roleObject = new Root(); var getCurrentRole = db.securityRole.Find(roleID); roleObject = (Root)ParseXMLHelper.DeserializeXml(getCurrentRole.XMLRole, "db");; return(roleObject); }
/// <summary> /// Adds the refresh token. /// </summary> /// <param name="token">The token.</param> /// <returns></returns> public bool AddRefreshToken(ClientRefreshToken token) { var dbType = Mapper.Map <ClientRefreshTokensDb>(token); using (var db = new CRMDb()) { db.ClientRefreshTokens.Add(dbType); db.SaveChanges(); } return(true); }
/// <summary> /// Removes the role permissions. /// </summary> /// <param name="accountId">The account identifier.</param> /// <param name="moduleIds">The module ids.</param> /// <param name="db">The database.</param> void removeRolePermissions(int accountId, List <byte> moduleIds, CRMDb db) { Logger.Current.Verbose("Request to remove Role Permissions for removed modules in subscription"); if (moduleIds != null) { Logger.Current.Informational("Removing Role-Access permissions for AccountId " + accountId); var accountRoles = db.Roles.Where(s => s.AccountID == accountId).Select(s => s.RoleID); var roleAccessPermissions = db.RoleModules.Where(s => s.ModuleID != 0 && moduleIds.Contains(s.ModuleID) && accountRoles.Contains(s.RoleID)); db.RoleModules.RemoveRange(roleAccessPermissions); } }
/// <summary> /// Removes the data sharing permissions. /// </summary> /// <param name="accountId">The account identifier.</param> /// <param name="moduleIds">The module ids.</param> /// <param name="db">The database.</param> void removeDataSharingPermissions(int accountId, List <byte> moduleIds, CRMDb db) { Logger.Current.Verbose("Request to remove Data-Sharing permissions"); if (moduleIds != null) { Logger.Current.Informational("Removing Data-Sharing permissions for AccountId " + accountId); Logger.Current.Informational("No of modules for remove :" + moduleIds.Count); var dataAccessPermission = db.DataAccessPermissions.Where(s => s.AccountID == accountId && moduleIds.Contains(s.ModuleID)); db.DataAccessPermissions.RemoveRange(dataAccessPermission); } }
public IEnumerable <Subscription> GetAllSubscriptions() { var procedureName = "[dbo].[Account_Subscriptions_Types]"; var parms = new List <SqlParameter> { }; CRMDb context = new CRMDb(); var objectContext = (context as IObjectContextAdapter).ObjectContext; objectContext.CommandTimeout = 400; return(context.ExecuteStoredProcedure <Subscription>(procedureName, parms)); }
public override AttachmentsDb ConvertToDatabaseType(Attachment domainType, CRMDb db) { Logger.Current.Verbose("Request to convet DomainObjet(Attachment) to DbObject(AttachmentsDb)"); try { return(Mapper.Map <Attachment, AttachmentsDb>(domainType as Attachment)); } catch (Exception ex) { Logger.Current.Error("Exception occurred while conveting DomainObjet(Attachment) to DbObject(AttachmentsDb)", ex); return(null); } }
public static List <Guid?> getBUChild(List <Guid?> BUUpdate, Guid?parentBU) { CRMDb db = new CRMDb(); List <Guid?> buQuery = db.businessunit.Where(x => x.ParentBusinessUnitId == parentBU).Select(x => x.BusinessUnitId).ToList(); foreach (Guid?currentBU in buQuery) { BUUpdate.Add(currentBU); getBUChild(BUUpdate, currentBU); } return(BUUpdate); }
public JsonResult LoadGridWorkflow(string sidx, string sord, int rows, int page = 1) { if (sidx == "Id") { sidx = "SeqNo"; sord = "asc"; } CRMDb db = new CRMDb(); string getVal = Request["_val"]; if (getVal == "" || getVal == null) { getVal = Guid.Empty.ToString(); } Guid serviceLevelID = new Guid(getVal); //Query to workflow by service Level ID var wf = db.Workflow.Where(x => x.SLID == serviceLevelID); var data = wf.ToList() .Select(x => new { ID = x.ID, ServiceLevelID = x.SLID, WgID = x.WgID, WgName = x.WgName, WorkflowSLADays = x.WorkflowSLADays, SeqNo = x.SeqNo, Keterangan = x.Keterangan }); int pageIndex = Convert.ToInt32(page) - 1; int pageSize = rows; int totalRecords = data.Count(); int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize); data = data.AsQueryable().OrderBy(sidx + " " + sord).Skip((page - 1) * pageSize).Take(pageSize); var recordCount = data.Count(); JSONTable jTable = new JSONTable(); jTable.total = totalPages; jTable.page = page; jTable.records = totalRecords; jTable.rows = data.ToArray(); return(Json(jTable, JsonRequestBehavior.AllowGet)); }
public JsonResult LoadGrid(string sidx, string sord, int rows, int page = 1) { CRMDb db = new CRMDb(); string getVal = Request["_val"]; if (getVal == "" || getVal == null) { getVal = Guid.Empty.ToString(); } Guid roleId = new Guid(getVal); //Query to privilege by role id var priv = db.privilegeException.Where(x => x.SecurityRoleID == roleId); var data = priv.ToList() .Select(x => new { Id = x.PrivilegeExceptionID, EntityType = x.EntityType, EntityName = x.EntityName, StatusType = x.StatusType, StatusName = x.StatusName, ExKey = x.Key, ExValue = x.Value, NewKey = x.NewKey, NewValue = x.NewValue, Inclusive = x.Inclusive, InclusiveLabel = x.InclusiveLabel, StatusChangeID = x.StatusChangeID }); int pageIndex = Convert.ToInt32(page) - 1; int pageSize = rows; int totalRecords = data.Count(); int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize); data = data.AsQueryable().OrderBy(sidx + " " + sord).Skip((page - 1) * pageSize).Take(pageSize); var recordCount = data.Count(); JSONTable jTable = new JSONTable(); jTable.total = totalPages; jTable.page = page; jTable.records = totalRecords; jTable.rows = data.ToArray(); return(Json(jTable, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Persists the form tags. /// </summary> /// <param name="form">The form.</param> /// <param name="formDb">The form database.</param> /// <param name="db">The database.</param> private void PersistFormTags(Form form, FormsDb formDb, CRMDb db) { var formTags = db.FormTags.Where(a => a.FormID == form.Id).ToList(); foreach (Tag tag in form.Tags) { var tagexist = db.Tags.Where(p => p.TagID == tag.Id && p.AccountID == tag.AccountID && p.IsDeleted != true).FirstOrDefault(); if (tag.Id == 0 || tagexist == null) { var tagDb = db.Tags.SingleOrDefault(t => t.TagName.Equals(tag.TagName) && t.AccountID.Equals(tag.AccountID) && t.IsDeleted != true); if (tagDb == null) { tagDb = Mapper.Map <Tag, TagsDb>(tag); tagDb.IsDeleted = false; tagDb = db.Tags.Add(tagDb); } var formTag = new FormTagsDb() { Form = formDb, Tag = tagDb }; db.FormTags.Add(formTag); } else if (!formTags.Any(a => a.TagID == tag.Id)) { db.FormTags.Add(new FormTagsDb() { FormID = form.Id, TagID = tag.Id }); db.RefreshAnalytics.Add(new RefreshAnalyticsDb() { EntityID = tag.Id, EntityType = 5, Status = 1, LastModifiedOn = DateTime.Now.ToUniversalTime() }); } } IList <int> tagIds = form.Tags.Where(a => a.Id > 0).Select(a => a.Id).ToList(); var unMapActionTags = formTags.Where(a => !tagIds.Contains(a.TagID)); foreach (FormTagsDb formTagMapDb in unMapActionTags) { db.FormTags.Remove(formTagMapDb); db.RefreshAnalytics.Add(new RefreshAnalyticsDb() { EntityID = formTagMapDb.TagID, EntityType = 5, Status = 1, LastModifiedOn = DateTime.Now.ToUniversalTime() }); } }
public static string GetStatusInfo(string Code) { CRMDb db = new CRMDb(); var text = db.mapping .Where(x => x.AttributeName == "Inquiry Status") .Where(x => x.Code == Code) .Select(x => x.Label); if (text.Count() > 0 && !string.IsNullOrEmpty(text.First())) { return(text.First().ToString()); } return(Code); }
//Check entity by roleid - used on call wrapup function public static bool isEntityChecked(Guid roleID, string entityName) { CRMDb db = new CRMDb(); var getCurrentRole = db.securityRole.Find(roleID); Root roleObject = (Root)ParseXMLHelper.DeserializeXml(getCurrentRole.XMLRole, "db");; if (roleObject.Menu.Any(a => a.Submenu.Any(b => b.Entity.Any(c => c.name == entityName && c.check == true)))) { return(true); } else { return(false); } }
/// <summary> /// Persists the note tags. /// </summary> /// <param name="note">The note.</param> /// <param name="notesDb">The notes database.</param> /// <param name="db">The database.</param> void persistNoteTags(Note note, NotesDb notesDb, CRMDb db) { var noteTags = db.NoteTags.Where(a => a.NoteID == note.Id).ToList(); foreach (Tag tag in note.Tags) { if (tag.Id == 0) { var tagDb = db.Tags.Where(t => t.TagName.Equals(tag.TagName) && t.AccountID == tag.AccountID && t.IsDeleted != true).FirstOrDefault(); if (tagDb == null) { tagDb = Mapper.Map <Tag, TagsDb>(tag); tagDb.IsDeleted = false; tagDb = db.Tags.Add(tagDb); } var noteTag = new NoteTagsMapDb() { Note = notesDb, Tags = tagDb }; db.NoteTags.Add(noteTag); } else if (!noteTags.Any(a => a.TagID == tag.Id)) { db.NoteTags.Add(new NoteTagsMapDb() { NoteID = notesDb.NoteID, TagID = tag.Id }); db.RefreshAnalytics.Add(new RefreshAnalyticsDb() { EntityID = tag.Id, EntityType = 5, Status = 1, LastModifiedOn = DateTime.Now.ToUniversalTime() }); } } IList <int> tagIds = note.Tags.Where(a => a.Id > 0).Select(a => a.Id).ToList(); var unMapNoteTags = noteTags.Where(a => !tagIds.Contains(a.TagID)); foreach (NoteTagsMapDb noteTagMapDb in unMapNoteTags) { db.NoteTags.Remove(noteTagMapDb); db.RefreshAnalytics.Add(new RefreshAnalyticsDb() { EntityID = noteTagMapDb.TagID, EntityType = 5, Status = 1, LastModifiedOn = DateTime.Now.ToUniversalTime() }); } }
public static void BulkInsert <T>(this CRMDb db, IList <T> list) where T : class { string connection = db.Database.Connection.ConnectionString; string tableName = db.GetTableName <T>(); using (var _conn = new SqlConnection(connection)) { _conn.Open(); using (var bulkCopy = new SqlBulkCopy(_conn)) { bulkCopy.BatchSize = list.Count; bulkCopy.DestinationTableName = tableName; bulkCopy.BulkCopyTimeout = 6000; var batchCount = 5000; var table = new DataTable(); var props = TypeDescriptor.GetProperties(typeof(T)) //Dirty hack to make sure we only have system data types //i.e. filter out the relationships/collections .Cast <PropertyDescriptor>() .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System")) .ToArray(); var iteratorCount = Math.Ceiling((float)list.Count() / (float)batchCount); foreach (var propertyInfo in props) { bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name); table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType); } var values = new object[props.Length]; for (var i = 0; i < iteratorCount; i++) { foreach (var item in list.Skip(i * batchCount).Take(batchCount)) { for (var j = 0; j < values.Length; j++) { values[j] = props[j].GetValue(item); } table.Rows.Add(values); } bulkCopy.WriteToServer(table); table.Rows.Clear(); } } } }
//Check action by roleid to decide when the button should be showed or hidden public static bool checkEntityButtonByRoleID(Guid roleID, string entityName, string action) { CRMDb db = new CRMDb(); var getCurrentRole = db.securityRole.Find(roleID); Root roleObject = (Root)ParseXMLHelper.DeserializeXml(getCurrentRole.XMLRole, "db");; if (roleObject.Menu.Any(a => a.Submenu.Any(b => b.Entity.Any(c => c.name == entityName && c.Action != null)))) { bool isCheck = roleObject.Menu.Any(a => a.Submenu.Any(b => b.Entity.Any(c => c.name == entityName && c.Action.Any(d => d.name == action && d.check == true)))); return(isCheck); } else { return(false); } }
public static string GetLabel(string entityName, string attributeName, int attributeValue) { CRMDb db = new CRMDb(); var text = db.pickList .Where(r => r.EntityName == entityName) .Where(r => r.AttributeName == attributeName) .Where(r => r.AttributeValue == attributeValue) .Select(r => r.label); if (text.Count() > 0 && !string.IsNullOrEmpty(text.First())) { return(text.First().ToString()); } return(String.Empty); }
public static string GetStringMap(int entityType, int statusType, string key) { CRMDb db = new CRMDb(); var text = db.statusmapper .Where(x => x.EntityType == entityType) .Where(x => x.StatusType == statusType) .Where(x => x.Key == key) .Select(x => x.Value); if (text.Count() > 0 && !string.IsNullOrEmpty(text.First())) { return(text.First().ToString()); } return(key); }
public static string GetLoanType(string code) { CRMDb db = new CRMDb(); var text = db.mapping .Where(x => x.CategoryName == "LoanType") .Where(x => x.Code == code) .Where(x => x.StateCode == 0) .Select(x => x.Label); if (text.Count() > 0 && !string.IsNullOrEmpty(text.First())) { return(text.First().ToString()); } return(code); }
public static string GetCurrency(string Code) { CRMDb db = new CRMDb(); var text = db.mapping .Where(x => x.CategoryName == "CurrencyCode") .Where(x => x.ObjectName == "Currency") .Where(x => x.AttributeName == "CurrencyCode") .Where(x => x.Code == Code) .Select(x => x.Label); if (text.Count() > 0 && !string.IsNullOrEmpty(text.First())) { return(text.First().ToString()); } return(Code); }
// Validate user through Database public SystemUser validateUserDb(string domainName) { CRMDb db = new CRMDb(); var model = db.systemUser.Where(x => x.DomainName == domainName) .Where(x => x.DeletionStateCode == 0) .Where(x => x.IsDisabled == false) .Select(x => x); //User not found if (model.ToList().Count <= 0) { return(null); } else { return(model.Single()); } }
/// <summary> /// Getting All Invalid Coupons /// </summary> /// <param name="pagenumber"></param> /// <param name="pagesize"></param> /// <returns></returns> public IEnumerable <ReportedCoupons> GetAllReportedCoupons(int pageNumber, int pageSize) { var procedureName = "[dbo].[GetGrabOnInvalidCouponResponses]"; var parms = new List <SqlParameter> { new SqlParameter { ParameterName = "@PageNumber", Value = pageNumber }, new SqlParameter { ParameterName = "@PageSize", Value = pageSize } }; CRMDb context = new CRMDb(); var objectContext = (context as IObjectContextAdapter).ObjectContext; objectContext.CommandTimeout = 400; return(context.ExecuteStoredProcedure <ReportedCoupons>(procedureName, parms)); }