public string GetNec([FromBody] ICollection <Filter> searchParams) { string jsonString = string.Empty; using (var db = new EverestPortalContext()) { if (searchParams == null || searchParams.Count == 0) { var query = db.ReportParameters.Select(nec1 => new { NEC_Code = nec1.NEC1_Code, NEC_Desc = nec1.NEC1_Desc }) .Union(db.ReportParameters.Select(nec2 => new { NEC_Code = nec2.NEC2_Code, NEC_Desc = nec2.NEC2_desc })) .Union(db.ReportParameters.Select(nec3 => new { NEC_Code = nec3.NEC3_Code, NEC_Desc = nec3.NEC3_Desc })) .Where(nec => !string.IsNullOrEmpty(nec.NEC_Code) && !string.IsNullOrEmpty(nec.NEC_Desc)) .Distinct().OrderBy(x => x.NEC_Code).Take(numberOfItems).ToList(); jsonString = JsonConvert.SerializeObject(query, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }); } else { var value = searchParams.ToArray()[0].Value; var query = db.ReportParameters.Select(nec1 => new { NEC_Code = nec1.NEC1_Code, NEC_Desc = nec1.NEC1_Desc }) .Union(db.ReportParameters.Select(nec2 => new { NEC_Code = nec2.NEC2_Code, NEC_Desc = nec2.NEC2_desc })) .Union(db.ReportParameters.Select(nec3 => new { NEC_Code = nec3.NEC3_Code, NEC_Desc = nec3.NEC3_Desc })) .Where(nec => (nec.NEC_Code.Contains(value) || nec.NEC_Desc.Contains(value)) && !string.IsNullOrEmpty(nec.NEC_Code) && !string.IsNullOrEmpty(nec.NEC_Desc)) .Distinct().OrderBy(x => x.NEC_Code).Take(numberOfItems).ToList(); jsonString = JsonConvert.SerializeObject(query, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }); } } return(jsonString); }
public HttpResponseMessage GetECPClients() { HttpResponseMessage message; using (EverestPortalContext context = new EverestPortalContext()) { var clients = (from client in context.Clients select new { clientId = client.Id, clientName = client.Name, }).ToList(); var result = new { data = clients }; message = Request.CreateResponse(HttpStatusCode.OK, result); return(message); } }
public string GetCADPagesString() { HttpResponseMessage message; string jsonString = string.Empty; using (EverestPortalContext context = new EverestPortalContext()) { //var lstCADPages = context.CADPages.OrderBy(cp => cp.cadPageCreatedOn).Take(2).ToList() // .Select(cpItem => new { // cadPageId = cpItem.cadPageId, // cadPageTitle = cpItem.cadPageTitle, // cadPageDescription = cpItem.cadPageDescription }); var lstCADPages = (from cpItem in context.CADPages select new CADPageViewModel { CADPageId = cpItem.cadPageId, CADPageTitle = cpItem.cadPageTitle, CADPageDescription = cpItem.cadPageDescription, CadPageModifiedOn = cpItem.cadPageModifiedOn }).OrderByDescending(x => x.CadPageModifiedOn).Take(2).ToList <CADPageViewModel>(); if (lstCADPages == null) { // message = new HttpResponseMessage(HttpStatusCode.InternalServerError); } else if (lstCADPages.Count() == 0) { //message = new HttpResponseMessage(HttpStatusCode.NotFound); } else { //message = Request.CreateResponse(HttpStatusCode.OK, lstCADPages); jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(lstCADPages); } //return message; return(jsonString); } }
public HttpResponseMessage GetToReallocateClients([FromBody] RequestAllocation request) { var users = request.ReallocatedUsers; using (EverestPortalContext context = new EverestPortalContext()) { var clientUsers = (from client in context.Clients join clUser in context.userClient on client.Id equals clUser.ClientID into gCUsers from clUser in gCUsers.DefaultIfEmpty() where clUser.user.userType.UserTypeName != "External users" select new { clientId = client.Id, clientName = client.Name, userID = clUser.UserID == null ? 0 : clUser.UserID }).ToList(); var toReallocationClient = clientUsers.GroupBy(x => x.clientId) .Where(g => !g.Any(gi => users.Contains(gi.userID))) .Select(x => new { clientId = x.Key, clientName = x.First().clientName }).OrderBy(x => x.clientName); var response = new { data = toReallocationClient }; return(Request.CreateResponse(HttpStatusCode.OK, response)); } }
public HttpResponseMessage GetReportFiltersByModule(int ModuleId, int UserID) { HttpResponseMessage message; using (var db = new EverestPortalContext()) { //var ReportFilterByModule = db.ReportFilters.Where(m => m.ModuleID == ModuleId).OrderByDescending(f=>f.FilterType).ToList(); var ReportFilterByModule = db.ReportFilters.Where(m => m.ModuleID == ModuleId && (m.CreatedBy == UserID || m.FilterType == "Default")).OrderByDescending(f => f.FilterType).ToList(); var RoleID = GetRoleforUser(); var clientID = GetClientforUser(); bool IsExternalUser = RoleID.Contains("1") || RoleID.Contains("2") || RoleID.Contains("8"); int territoryCount = 0; int indx = -1; if (IsExternalUser) { foreach (string c in clientID) { territoryCount += db.Territories.Where(t => t.IsBrickBased == false && t.Client_Id.ToString() == c).ToList().Count; } if (territoryCount == 0) { indx = ReportFilterByModule.FindIndex(f => f.FilterName.Equals("Default Filter – Outlet") && f.ModuleID == 3); if (indx > 0) { ReportFilterByModule.Remove(ReportFilterByModule[indx]); } } } var result = new { data = ReportFilterByModule }; message = Request.CreateResponse(HttpStatusCode.OK, result); return(message); } }
public string UserLoginCheck(string userName, string pwd) { DataTable dataTable = new DataTable(); dataTable.Columns.Add(new DataColumn("UserID", typeof(Int32))); dataTable.Columns.Add(new DataColumn("RoleID", typeof(Int32))); dataTable.Columns.Add(new DataColumn("RoleName", typeof(String))); dataTable.Columns.Add(new DataColumn("EmailId", typeof(String))); dataTable.Columns.Add(new DataColumn("username", typeof(String))); //Get userid from identity var identity = (ClaimsIdentity)User.Identity; var id = identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString(); var userid = Convert.ToInt32(id); if (userid > 0) { using (var context = new EverestPortalContext()) { var userRole = context.userRole.FirstOrDefault(r => r.UserID == userid); if (userRole != null && userRole.role != null && userRole.user != null) { DataRow dr = dataTable.NewRow(); dr["UserID"] = userRole.UserID; dr["RoleID"] = userRole.role.RoleID; dr["RoleName"] = userRole.role.RoleName; dr["EmailId"] = userRole.user.Email; dr["username"] = userRole.user.FirstName + "." + userRole.user.LastName; dataTable.Rows.Add(dr); } } } string JSONString = string.Empty; JSONString = JsonConvert.SerializeObject(dataTable); return(JSONString); }
public bool EditCustomFilter([FromBody] ReportFilter Filter) { bool blnEdit = false; if (Filter != null) { using (var db = new EverestPortalContext()) { ReportFilter ReportFilterUpdate = db.ReportFilters.Where(m => m.FilterID == Filter.FilterID).SingleOrDefault(); if (ReportFilterUpdate != null) { //ReportFilterUpdate.FilterName = Filter.FilterName; //ReportFilterUpdate.FilterDescription = Filter.FilterDescription; ReportFilterUpdate.SelectedFields = Filter.SelectedFields; ReportFilterUpdate.UpdatedBy = Filter.UpdatedBy; db.Entry(ReportFilterUpdate).State = EntityState.Modified; db.SaveChanges(); blnEdit = true; } } } return(blnEdit); }
public async Task <FilterResult <Manufacturer> > GetManufacturerByMFRsId(int clientID, int currentPage, int pageSize) { List <string> mfrs = new List <string>(); using (EverestPortalContext context = new EverestPortalContext()) { var clientMfrs = context.ClientMFR.Where(x => x.ClientId == clientID).Select(x => x.MFRId).ToList(); mfrs = clientMfrs.Select(x => Convert.ToString(x)).ToList(); } ICollection <Filter> searchFilter = new List <Filter>(); foreach (var item in mfrs) { searchFilter.Add(new Filter { Condition = "Add", Criteria = "OrgCode", Value = item }); } var result = dimProductExpanded.GetManufacturer(searchFilter, currentPage, pageSize); return(result); }
public void GetUserInfo(string UserName, ref string FirstName, ref string LastName, ref string Email, ref string Pwd) { using (EverestPortalContext context = new EverestPortalContext()) { var currrentUser = (from u in context.Users where u.UserName == UserName && u.IsActive == true select new { FirstName = u.FirstName, LastName = u.LastName == null ? "" : u.LastName, Email = u.Email, Pwd = u.Password }).ToList(); if (currrentUser.Count() > 0) { Email = currrentUser[0].Email; FirstName = currrentUser[0].FirstName; LastName = currrentUser[0].LastName; Pwd = currrentUser[0].Pwd; } } }
public HttpResponseMessage GetIRPClients() { HttpResponseMessage message; using (EverestPortalContext context = new EverestPortalContext()) { var clients = (from irpclient in context.IRPClients where irpclient.VersionTo == 32767 select new { clientId = irpclient.ClientID, clientName = irpclient.ClientName, clientNo = irpclient.ClientNo }).ToList(); var result = new { data = clients }; message = Request.CreateResponse(HttpStatusCode.OK, result); return(message); } }
public HttpResponseMessage AddPopularLink([FromBody] PopularLink postedData) { HttpResponseMessage response = null; try { PopularLink newPopLink = new PopularLink(); newPopLink.popularLinkTitle = postedData.popularLinkTitle; newPopLink.popularLinkDescription = postedData.popularLinkDescription; using (EverestPortalContext context = new EverestPortalContext()) { context.PopularLinks.Add(newPopLink); context.SaveChanges(); } response = Request.CreateResponse <PopularLink>(HttpStatusCode.Created, newPopLink); } catch (Exception ex) { } return(response); }
public HttpResponseMessage updateServices([FromBody] requestMasterData request) { var msg = "successfully saved"; var isSuccess = false; HttpResponseMessage message; using (EverestPortalContext context = new EverestPortalContext()) { if (Convert.ToString(request.Action).Equals("delete", StringComparison.InvariantCultureIgnoreCase)) { var deleteEntity = context.Services.FirstOrDefault(c => c.ServiceId == request.ServiceId); context.Services.Remove(deleteEntity); context.SaveChanges(); msg = "Successfully removed"; var deleteResponse = new { msg, isSuccess = true }; message = Request.CreateResponse(HttpStatusCode.OK, deleteResponse); return(message); } if (request.ServiceId != null && request.ServiceId != 0) { if (context.Services.Any(s => s.Name.Equals(request.ServiceName, StringComparison.InvariantCultureIgnoreCase) && s.ServiceId != request.ServiceId)) { msg = "Name already exists"; isSuccess = false; } else { var updateEntity = context.Services.FirstOrDefault(c => c.ServiceId == request.ServiceId); updateEntity.Name = request.ServiceName; isSuccess = true; } } else { if (context.Services.Any(s => s.Name.Equals(request.ServiceName, StringComparison.InvariantCultureIgnoreCase))) { msg = "Name already exists"; isSuccess = false; } else { var newEntity = new Service() { Name = request.ServiceName }; context.Services.Add(newEntity); isSuccess = true; } }; context.SaveChanges(); var response = new { msg, isSuccess }; message = Request.CreateResponse(HttpStatusCode.OK, response); return(message); } }
public HttpResponseMessage CreateDeliverable([FromBody] DeliverableModel request) { try { HttpResponseMessage responseMessage; var message = "deliverable successfully created for the selected subscription"; var isSuccess = false; var validationResult = validateRequest(request); if (!validationResult.isSuccess) { responseMessage = Request.CreateResponse(HttpStatusCode.OK, new { message = validationResult.message, validationResult.isSuccess }); return(responseMessage); } var reportNo = Convert.ToInt32(request.ReportNo); using (EverestPortalContext context = new EverestPortalContext()) { if (!IsDeliverableExists(request)) { //adding the new deliverables to the selected clients var deliverable = new Deliverables() { SubscriptionId = request.SubscriptionId, ReportWriterId = request.ReportWriterId, StartDate = new DateTime(request.StartDate.Year, request.StartDate.Month, 1), //change into first day of the month EndDate = new DateTime(request.EndDate.Year, request.EndDate.Month, DateTime.DaysInMonth(request.EndDate.Year, request.EndDate.Month)), //change into last day of the month FrequencyTypeId = request.FrequencyTypeId, FrequencyId = request.FrequencyId, RestrictionId = request.RestrictionId, PeriodId = request.PeriodId, DeliveryTypeId = request.DeliveryTypeId, LastModified = DateTime.Now, ModifiedBy = 1, }; deliverable = context.deliverables.Add(deliverable); context.SaveChanges(); isSuccess = true; //add reportno. //context.DeliveryReports.Add(new DeliveryReport() { DeliverableId = 218, // ReportNo = reportNo }); //context.SaveChanges(); AddReportNoDeliverable(new DeliveryReport() { DeliverableId = deliverable.DeliverableId, ReportNo = reportNo }); } else { message = "Already same deliverable exists for the selected subscription"; } } var response = new { msg = message, isSuccess }; responseMessage = Request.CreateResponse(HttpStatusCode.OK, response); return(responseMessage); } catch (Exception ex) { throw ex; } }
public string Getclients() { Role userRole = GetRoleforUser(); if (userRole.IsExternal) { List <string> ClientIDList = new List <string>(); var identity = (ClaimsIdentity)User.Identity; //force to use login id, can not pass other value for security reasons. var tid = identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString(); int uid = Convert.ToInt32(tid); using (var db = new EverestPortalContext()) { var Clients = (from u in db.Users join uClient in db.userClient on u.UserID equals uClient.UserID join client in db.Clients on uClient.ClientID equals client.Id where uClient.UserID == uid select new { clientID = client.Id, Name = client.Name, }).Distinct().ToList(); var result = new { data = Clients.OrderBy(o => o.Name) }; var json = JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); } } else { using (EverestPortalContext context = new EverestPortalContext()) { var ClientList = (from client in context.Clients join userClient in context.userClient on client.Id equals userClient.ClientID select new { clientID = client.Id, Name = client.Name, }).Distinct().ToList(); var result = new { data = ClientList.OrderBy(o => o.Name) }; var json = JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); } } }
public HttpResponseMessage ChangePasswordByResetToken([FromBody] UserDetail userdeatil) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.ExpectationFailed); try { using (EverestPortalContext context = new EverestPortalContext()) { var result = context.ResetTokens.FirstOrDefault(x => x.Token == userdeatil.Token); if (result != null && result.user != null) { //if (result.ExpiryDate >= DateTime.Now && result.user.IsPasswordVerified) if (result.ExpiryDate >= DateTime.Now) { AuthController authController = new AuthController(); var passwordHashed = authController.GenerateHashedPassword(userdeatil.Password); var passwordHistoryExist = context.PasswordHistories.Where(x => x.UserID.Equals(result.user.UserID)) .OrderByDescending(x => x.CreatedDate).Take(12).FirstOrDefault(x => x.Password == passwordHashed); if (passwordHistoryExist != null || result.user.Password == passwordHashed) { response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = false, message = " You cannot reuse one of your last 13 passwords" }); } else { context.PasswordHistories.Add( new Models.Security.PasswordHistory { UserID = result.user.UserID, Password = passwordHashed, CreatedDate = DateTime.Now }); result.user.Password = passwordHashed; result.user.FailedPasswordAttempt = 0; result.user.IsPasswordVerified = true; result.user.PasswordCreatedDate = DateTime.Now; result.ExpiryDate = DateTime.Now; context.SaveChanges(); response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = true, message = "" }); } } else if (result.ExpiryDate < DateTime.Now) { response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = false, message = "Your password reset link has been expired." }); } else { response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = false, message = "Your account has not yet been verified. Please contact support." }); } } else { response = Request.CreateResponse(HttpStatusCode.OK, new { isSuccess = false, message = "User inactive or email address invalid." }); } } } catch (Exception ex) { } return(response); }
private void SaveTdwExportHistory(List <int> selectedClients, bool isSelectedAll) { //var Tdw var identity = (ClaimsIdentity)User.Identity; //force to use login id, can not pass other value for security reasons. var actionUserId = identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString(); using (EverestPortalContext context = new EverestPortalContext()) { if (isSelectedAll) { var result = context.Tdw_export_history.OrderByDescending(x => x.versionId) .FirstOrDefault(t => t.ClientId == 0); var version = 1; if (result != null) { version = result.versionId + 1; } var exportHistory = new Tdw_export_history() { versionId = version, ClientId = 0, Deliverable = "All", Market = "All", Territory = "All", //ClientName = "All", SubmittedBy = int.Parse(actionUserId), SubmittedDate = DateTime.Now }; context.Tdw_export_history.Add(exportHistory); context.SaveChanges(); } else { foreach (var clientId in selectedClients) { var result = context.Tdw_export_history.OrderByDescending(x => x.versionId) .FirstOrDefault(t => t.ClientId == clientId); var version = 1; if (result != null) { version = result.versionId + 1; } var exportHistory = new Tdw_export_history() { versionId = version, ClientId = clientId, Deliverable = "All", Market = "All", Territory = "All", //ClientName = "All", SubmittedBy = int.Parse(actionUserId), SubmittedDate = DateTime.Now }; context.Tdw_export_history.Add(exportHistory); context.SaveChanges(); } } }; }
public async Task <FilterResult <ReleasePack> > GetPacksByFCC(int clientID, int currentPage, int pageSize) { string delimiter = " "; var packids = string.Empty; List <ReleasePack> packs = new List <ReleasePack>(); List <ClientPackException> clientPacks = new List <ClientPackException>(); using (EverestPortalContext context = new EverestPortalContext()) { clientPacks = context.ClientPackException.Where(x => x.ClientId == clientID).ToList(); var temp = clientPacks.Select(x => Convert.ToString(x.PackExceptionId)).ToList(); if (temp.Count() > 0) { packids = temp.Aggregate((i, j) => i + delimiter + j); } } var query = string.Format("?q=FCC:({0})&rows=" + pageSize, packids); string resultContent = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri(packsSolrURL); client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); var result = await client.GetAsync(query); resultContent = result.Content.ReadAsStringAsync().Result; } XmlDocument doc = new XmlDocument(); doc.LoadXml(resultContent); foreach (XmlNode node in doc.DocumentElement.SelectNodes("/response/result/doc")) { packs.Add(ParsePack(node)); } int rCount = 0; XmlNodeList nodeList = doc.SelectNodes("/response/result"); foreach (XmlNode node in nodeList) { rCount = Convert.ToInt32(node.Attributes["numFound"].Value); } foreach (var pack in packs) { var aClientPack = clientPacks.FirstOrDefault(x => x.PackExceptionId == pack.Id); pack.ProductLevel = aClientPack.ProductLevel; pack.ExpiryDate = SetExpiryDate(aClientPack.ExpiryDate); } //taking the distinct values var distinct = packs.GroupBy(i => i.Id).Select(i => i.First()).ToList(); return(new FilterResult <ReleasePack> { Data = distinct.OrderBy(x => x.ProductName).ToList(), TotalCount = rCount }); }
public string MarketDefinitionReport(int Id, int startVersion, int endVersion, string reportname) { List <MarketbaseDTO> marketbaseAuditReport = new List <MarketbaseDTO>(); List <MarketDefNameChanges> MarketDefNameChanges = new List <MarketDefNameChanges>(); List <MarketDefPackChanges> MarketDefPackChanges = new List <MarketDefPackChanges>(); List <MarketDefBaseMapChanges> MarketDefBaseMapChanges = new List <MarketDefBaseMapChanges>(); List <MarketDefGroupChanges> MarketDefGroupChanges = new List <MarketDefGroupChanges>(); using (EverestPortalContext context = new EverestPortalContext()) { if (reportname == "Name Changes") { MarketDefNameChanges = context.Database.SqlQuery <MarketDefNameChanges>("exec [AuditMarketDefNameReport] " + startVersion + "," + endVersion + "," + Id + "").ToList(); var json = JsonConvert.SerializeObject(MarketDefNameChanges, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); } else if (reportname == "Market Base Changes") { MarketDefBaseMapChanges = context.Database.SqlQuery <MarketDefBaseMapChanges>("exec [AuditMarketDefBaseMapReport] " + startVersion + "," + endVersion + "," + Id + "").ToList(); var json = JsonConvert.SerializeObject(MarketDefBaseMapChanges, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); } else if (reportname == "Pack Changes") { MarketDefPackChanges = context.Database.SqlQuery <MarketDefPackChanges>("exec [AuditMarketDefPacksReport] " + startVersion + "," + endVersion + "," + Id + "").ToList(); var json = JsonConvert.SerializeObject(MarketDefPackChanges, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); } else if (reportname == "Group Changes") { MarketDefGroupChanges = context.Database.SqlQuery <MarketDefGroupChanges>("exec [AuditMarketDefGroupReport] " + startVersion + "," + endVersion + "," + Id + "").ToList(); var json = JsonConvert.SerializeObject(MarketDefGroupChanges, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(json); } } return(""); }
public HttpResponseMessage ImportDeliverablesAndSubscriptionForClient(RequestImport req) { //var clientid = req.clientId; HttpResponseMessage message; var selectedClientIds = req.selectedClients; var importMessage = string.Empty; try { if (req.selectAll) { return(ImportDeliverablesforAllClients("IRP_Import_Subscription_Deliverables_All", req.EmailId)); } using (EverestPortalContext context = new EverestPortalContext()) { //if (req.selectAll) //{ // return ImportDeliverablesforAllClients("IRP_Import_Subscription_Deliverables_All"); //var clients = context.ClientMaps.ToList(); //selectedClientIds = new List<int>(); //foreach (var ic in clients) //{ // if (ic.ClientId != null) // { // selectedClientIds.Add(Convert.ToInt32(ic.ClientId)); // } //} // } List <DataRow> nonIAMCollection = new List <DataRow>(); List <DataRow> IAMCollection = new List <DataRow>(); List <DataRow> subResponse = new List <DataRow>(); List <DataRow> deliResponse = new List <DataRow>(); foreach (var clientid in selectedClientIds) { List <DataRow> subTempResponse = new List <DataRow>(); List <DataRow> deliTempResponse = new List <DataRow>(); var clientNo = context.ClientMaps.FirstOrDefault(c => c.ClientId == clientid).IRPClientNo; executeDeliverablesIAM(clientNo, ref subTempResponse, ref deliTempResponse); subResponse.AddRange(subTempResponse); deliResponse.AddRange(deliTempResponse); subTempResponse = new List <DataRow>(); deliTempResponse = new List <DataRow>(); executeDeliverablesNonIAM(clientNo, ref subTempResponse, ref deliTempResponse); subResponse.AddRange(subTempResponse); deliResponse.AddRange(deliTempResponse); } var dataDeli = deliResponse.Select(dr => new { SubscriptionId = dr != null ? Convert.ToString(dr["SubscriptionId"]) : "", DeliverableId = dr != null ? Convert.ToString(dr["DeliverableId"]) : "", Frequency = dr != null ? Convert.ToString(dr["Frequency"]) : "", FrequencyType = dr != null ? Convert.ToString(dr["FrequencyType"]) : "", Period = dr != null ? Convert.ToString(dr["Period"]) : "", Status = dr != null ? Convert.ToString(dr["Status"]) : "" }); var dataSub = subResponse.Select(dr => new { SubscriptionId = dr != null ? Convert.ToString(dr["SubscriptionId"]) : "", Country = dr != null ? Convert.ToString(dr["Country"]) : "", Service = dr != null ? Convert.ToString(dr["Service"]) : "", TerritoryBase = dr != null ? Convert.ToString(dr["TerritoryBase"]) : "", DataType = dr != null ? Convert.ToString(dr["DataType"]) : "", ClienId = dr != null ? Convert.ToString(dr["ClientId"]) : "", Status = dr != null ? Convert.ToString(dr["Status"]) : "" }); var result = new { sResponse = dataSub, dResponse = dataDeli, IsSelectAll = false, importMessage }; message = Request.CreateResponse(HttpStatusCode.OK, result); return(message); } } catch (Exception ex) { string exMessage = ex.Message; throw ex; } }
public async Task <HttpResponseMessage> EditMarketBase(int ClientId, int MarketBaseId) { AuthController objAuth = new AuthController(); if (objAuth.CheckUserClients(ClientId) == 0) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "You have no permission to view/edit this marketbase")); } HttpContent requestContent = Request.Content; var jsonContent = requestContent.ReadAsStringAsync().Result; // var marketBase = JsonConvert.DeserializeObject<MarketBase>(jsonContent); var marketBaseDetails = JsonConvert.DeserializeObject <MarketbaseDetails>(jsonContent); List <DimensionBaseMap> Dimension = marketBaseDetails.Dimension; //to get dimension seperatly. List <PxR> PxRCollection = marketBaseDetails.PxR; //to get PxR seperatly. MarketBase marketBase = marketBaseDetails.MarketBase; var identity = (ClaimsIdentity)User.Identity; int uid = Convert.ToInt32(identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString()); Guid Id = Guid.NewGuid(); if (jsonContent.Trim() != string.Empty) { MarketBase MBObj = null; using (var db = new EverestPortalContext()) { var oldBaseFilter = db.BaseFilters.Where(i => i.MarketBaseId == MarketBaseId).ToList(); if (oldBaseFilter != null) { db.BaseFilters.RemoveRange(oldBaseFilter); db.SaveChanges(); } MBObj = db.MarketBases.Where(i => i.Id == MarketBaseId).FirstOrDefault(); if (MBObj != null) { MBObj.BaseType = marketBase.BaseType; MBObj.Description = marketBase.Description; MBObj.DurationFrom = marketBase.DurationFrom; MBObj.DurationTo = marketBase.DurationTo; MBObj.Name = marketBase.Name; MBObj.Suffix = marketBase.Suffix; MBObj.LastSaved = DateTime.Now; foreach (BaseFilter fil in marketBase.Filters) { BaseFilter obj = fil; obj.MarketBaseId = MarketBaseId; MBObj.Filters.Add(obj); } MBObj.LastModified = DateTime.Now; MBObj.ModifiedBy = uid; } else { marketBase.GuiId = Id.ToString(); // marketBase.LastSaved = DateTime.Now; marketBase.LastModified = DateTime.Now; marketBase.ModifiedBy = uid; db.MarketBases.Add(marketBase); } db.SaveChanges(); //to save dimension base map await SaveDimensionBaseMap(MarketBaseId, Dimension); await SavePxRBaseMap(MarketBaseId, PxRCollection); } } var objClient = _db.MarketBases.Where(u => u.Id == MarketBaseId).ToList <MarketBase>().FirstOrDefault(); // place the request in queue var result = _db.Database.SqlQuery <string>("exec PutInMarketBaseQueue " + MarketBaseId + "," + uid).FirstOrDefault(); var json = JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return(Request.CreateResponse(HttpStatusCode.OK, json)); }
public async Task <HttpResponseMessage> saveClientMarketDef(int ID) { HttpContent requestContent = Request.Content; var jsonContent = requestContent.ReadAsStringAsync().Result; Guid Id = Guid.NewGuid(); int MarketDefId; var client = JsonConvert.DeserializeObject <Client[]>(jsonContent); var marketDefinitionPacks = client[0].MarketDefinitions[0].MarketDefinitionPacks;//store Packs //to remove marketdefinition packs from Marketdefinition model client[0].MarketDefinitions[0].MarketDefinitionPacks = null; //to clear market base when client save market base for (var i = 0; i < client[0].MarketDefinitions[0].MarketDefinitionBaseMaps.Count(); i++) { client[0].MarketDefinitions[0].MarketDefinitionBaseMaps[i].MarketBase = null; } client[0].MarketDefinitions[0].GuiId = Id.ToString(); client[0].MarketDefinitions[0].LastModified = DateTime.Now; var identity = (ClaimsIdentity)User.Identity; int uid = Convert.ToInt32(identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString()); client[0].MarketDefinitions[0].ModifiedBy = uid; using (var db = new EverestPortalContext()) { _db.MarketDefinitions.Add(client[0].MarketDefinitions[0]).ClientId = ID; //_db.SaveChanges(); await _db.SaveChangesAsync(); MarketDefId = client[0].MarketDefinitions[0].Id; } var packsDt = new DataTable(); packsDt.Columns.Add("Pack", typeof(string)); packsDt.Columns.Add("MarketBase", typeof(string)); packsDt.Columns.Add("MarketBaseId", typeof(string)); packsDt.Columns.Add("GroupNumber", typeof(string)); packsDt.Columns.Add("GroupName", typeof(string)); packsDt.Columns.Add("Factor", typeof(string)); packsDt.Columns.Add("PFC", typeof(string)); packsDt.Columns.Add("Manufacturer", typeof(string)); packsDt.Columns.Add("ATC4", typeof(string)); packsDt.Columns.Add("NEC4", typeof(string)); packsDt.Columns.Add("DataRefreshType", typeof(string)); packsDt.Columns.Add("StateStatus", typeof(string)); packsDt.Columns.Add("MarketDefinitionId", typeof(int)); packsDt.Columns.Add("Alignment", typeof(string)); packsDt.Columns.Add("Product", typeof(string)); packsDt.Columns.Add("ChangeFlag", typeof(string)); packsDt.Columns.Add("Molecule", typeof(string)); foreach (var item in marketDefinitionPacks) { item.MarketDefinitionId = MarketDefId; packsDt.Rows.Add(item.Pack, item.MarketBase, item.MarketBaseId, item.GroupNumber, item.GroupName, item.Factor, item.PFC, item.Manufacturer, item.ATC4, item.NEC4, item.DataRefreshType, item.StateStatus, MarketDefId, item.Alignment, item.Product, item.ChangeFlag, item.Molecule); } SqlParameter paramMarketDefinitionID = new SqlParameter("@marketdefinitionid", MarketDefId); SqlParameter paramPacks = new SqlParameter("@TVP", packsDt); paramPacks.SqlDbType = System.Data.SqlDbType.Structured; paramPacks.TypeName = "TYP_MarketDefinitionPacks"; //_db.Database.ExecuteSqlCommand("exec EditMarketDefinition @marketdefinitionid,@TVP", paramMarketDefinitionID, paramPacks); await _db.Database.ExecuteSqlCommandAsync("exec EditMarketDefinition @marketdefinitionid,@TVP", paramMarketDefinitionID, paramPacks); var objClient = _db.MarketDefinitions.Where(u => u.ClientId == ID && u.GuiId == Id.ToString()).FirstOrDefault(); /*var json = JsonConvert.SerializeObject(objClient, Formatting.Indented, * new JsonSerializerSettings * { * ReferenceLoopHandling = ReferenceLoopHandling.Ignore * });*/ return(Request.CreateResponse(HttpStatusCode.OK, objClient)); }
public bool SaveSubchannel([FromBody] EntityType entityType) { bool result = false; if (entityType != null) { using (var context = new EverestPortalContext()) { if (entityType.EntityTypeId == 0) //Add a new record { var isExist = context.EntityTypes.FirstOrDefault(e => e.EntityTypeName == entityType.EntityTypeCode.Trim() || e.Abbrev == entityType.Abbrev.Trim() || e.Display == entityType.Display.Trim() || e.Description == entityType.Description.Trim() ); if (isExist != null) { return(false); } var entity = new EntityType() { EntityTypeCode = entityType.EntityTypeCode.Trim(), EntityTypeName = entityType.Display.Trim(), DataTypeId = entityType.DataTypeId, Abbrev = entityType.Abbrev.Trim(), Display = entityType.Display.Trim(), Description = entityType.Description.Trim(), IsActive = entityType.IsActive }; context.EntityTypes.Add(entity); } else //Update existing record { var isExist = context.EntityTypes.FirstOrDefault(e => (e.EntityTypeName == entityType.EntityTypeCode.Trim() || e.Abbrev == entityType.Abbrev.Trim() || e.Display == entityType.Display.Trim() || e.Description == entityType.Description.Trim()) && e.EntityTypeId != entityType.EntityTypeId ); if (isExist != null) { return(false); } var entity = context.EntityTypes.SingleOrDefault(e => e.EntityTypeId == entityType.EntityTypeId); if (entity != null) { entity.EntityTypeCode = entityType.EntityTypeCode.Trim(); entity.EntityTypeName = entityType.EntityTypeName.Trim(); entity.DataTypeId = entityType.DataTypeId; entity.Abbrev = entityType.Abbrev.Trim(); entity.Display = entityType.Display.Trim(); entity.Description = entityType.Description.Trim(); entity.IsActive = entityType.IsActive; } //If enity type is inactive then delete all respective subchannels if (!entityType.IsActive) { var subchannels = context.SubChannels.Where(s => s.EntityTypeId == entityType.EntityTypeId).ToList(); context.SubChannels.RemoveRange(subchannels); } } context.SaveChanges(); result = true; } } return(result); }
public HttpResponseMessage ImportClients([FromBody] RequestImport request) { HttpResponseMessage message; using (EverestPortalContext context = new EverestPortalContext()) { var isSuccess = false; List <int> clientids = request.selectedClients; if (request.selectAll) { var irpclients = context.IRPClients.ToList(); clientids = new List <int>(); foreach (var ic in irpclients) { if (ic.ClientId != null) { clientids.Add(Convert.ToInt32(ic.ClientId)); } } } foreach (var clientid in clientids) { if (!context.ClientMaps.Any(x => x.IRPClientId == clientid)) { var irpClient = context.IRPClients.FirstOrDefault(i => i.ClientId == clientid); if (irpClient != null && !string.IsNullOrEmpty(irpClient.ClientName)) { var newClient = new Client() { Name = irpClient.ClientName, IsMyClient = false }; if (!context.Clients.Any(c => c.Name == newClient.Name)) { context.Clients.Add(newClient); context.SaveChanges(); context.ClientMaps.Add(new ClientMap { ClientId = newClient.Id, IRPClientId = irpClient.ClientId, IRPClientNo = irpClient.ClientNo, }); context.SaveChanges(); } } } isSuccess = true; } var result = new { message = "selected client is successfully imported", isSuccess }; message = Request.CreateResponse(HttpStatusCode.OK, result); return(message); } }
public HttpResponseMessage ImportMarkets(RequestImport req) { try { //var clientid = req.clientId; HttpResponseMessage message; var selectedClients = req.selectedClients; using (EverestPortalContext context = new EverestPortalContext()) { if (req.selectAll) { return(ImportMarketsForAllClients("IRP_Import_Market_All", req.EmailId)); //var importedClients = (from c in context.Clients // join // cm in context.ClientMaps on c.Id equals cm.ClientId // select c.Id).Distinct().ToList(); ////var clients = context.Clients.ToList(); //selectedClients = new List<int>(); //foreach (var ic in importedClients) //{ // if (ic != null) // { // selectedClients.Add(Convert.ToInt32(ic)); // } //} } } var drs = executeImportMarketDefinitions(selectedClients); string msg = "Market definitions imported sucessfully"; if (drs.Count == 0) { msg = "No market definitions are imported"; } var logCollection = drs.Select(row => new { clientId = Convert.ToString(row["ClientId"]), clientName = Convert.ToString(row["ClientName"]), dimensionId = Convert.ToString(row["DimensionId"]), marketDefinition = Convert.ToString(row["MarketDefinition"]), status = Convert.ToString(row["Status"]), timeOfImport = Convert.ToString(row["TimeOfImport"]), username = Convert.ToString(row["UserName"]) }).ToList(); var result = new { message = msg, isSuccess = true, log = logCollection }; message = Request.CreateResponse(HttpStatusCode.OK, result); return(message); } catch (Exception ex) { throw ex; } }
public HttpResponseMessage GetReportSectionListByUserType(int id) { HttpResponseMessage message; var ReportSections = new List <ReportSection>(); var identity = (ClaimsIdentity)User.Identity; //force to use login id, can not pass other value for security reasons. var tid = identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString(); int uid = Convert.ToInt32(tid); using (var db = new EverestPortalContext()) { ReportSections = db.ReportSections.ToList(); //Where( m => m.UserTypeID == id).ToList(); var RoleID = (from u in db.Users join urole in db.userRole on u.UserID equals urole.UserID where urole.UserID == uid select urole.RoleID).ToList(); var UserTypeID = db.Users.FirstOrDefault(u => u.UserID == id).UserTypeID; if (RoleID.Contains(1) || RoleID.Contains(2)) // External User { ReportSections = ReportSections.Where(q => q.UserTypeID == 2).ToList(); } if (RoleID.Contains(8)) { ReportSections = ReportSections.Where(r => r.ReportSectionName == "Territories").ToList(); } } if (ReportSections.Count > 1) { //interchange territories and subscriptions in the section drop down var index = ReportSections.FindIndex(f => string.Equals(f.ReportSectionName, "Territories", StringComparison.InvariantCultureIgnoreCase)); if (index >= 0) { var fItem = ReportSections[index]; ReportSections.RemoveAt(index); ReportSections.Insert(1, fItem); } var newindex = ReportSections.FindIndex(f => string.Equals(f.ReportSectionName, "Allocation", StringComparison.InvariantCultureIgnoreCase)); if (newindex >= 0) { var fAllocationItem = ReportSections[newindex]; ReportSections.RemoveAt(newindex); ReportSections.Insert(ReportSections.Count, fAllocationItem); } } var response = new { data = ReportSections }; message = Request.CreateResponse(HttpStatusCode.OK, response); return(message); }
public HttpResponseMessage GetClientReleaseDetails(string id, string isAllClients) { var identity = (ClaimsIdentity)User.Identity; //force to use login id, can not pass other value for security reasons. var tid = identity.Claims.FirstOrDefault(c => c.Type == "userid").Value.ToString(); var getAllClients = false; if (!string.IsNullOrWhiteSpace(isAllClients)) { getAllClients = Convert.ToBoolean(isAllClients); } HttpResponseMessage message; using (EverestPortalContext context = new EverestPortalContext()) { var clientReleaseDetails = (from client in context.Clients join clRelease in context.ClientRelease on client.Id equals clRelease.ClientId into rClients from r in rClients.DefaultIfEmpty() join cMfr in context.ClientMFR on client.Id equals cMfr.ClientId into mCLients from m in mCLients.DefaultIfEmpty() join pException in context.ClientPackException on client.Id equals pException.ClientId into pClients from p in pClients.DefaultIfEmpty() select new { clientId = client.Id, clientName = client.Name, CapitalChemist = r.CapitalChemist == null ? false : r.CapitalChemist, Census = r.Census == null ? false : r.Census, OneKey = r.OneKey == null ? false : r.OneKey, MfrId = m.MFRId, packExceptionId = p.PackExceptionId }).GroupBy(x => x.clientId).Select(x => new { clientId = x.Key, clientName = x.FirstOrDefault().clientName, OneKey = x.FirstOrDefault().OneKey, CapitalChemist = x.FirstOrDefault().CapitalChemist, Census = x.FirstOrDefault().Census, MfrCount = x.Select(m => m.MfrId).Distinct().Where(w => w != null).Count(), packCount = x.Select(p => p.packExceptionId).Distinct().Where(w => w != null).Count() }). ToList(); var uId = Convert.ToInt32(tid); //force to use login id, not querystring var userClients = context.userClient.Where(u => u.UserID == uId).Select(x => x.ClientID).ToList(); var responseReleaseClients = new List <ReleaseClient>(); foreach (var cr in clientReleaseDetails) { var aClientRelease = new ReleaseClient() { clientId = cr.clientId, clientName = cr.clientName, CapitalChemist = cr.CapitalChemist == null ? false : Convert.ToBoolean(cr.CapitalChemist), Census = cr.Census == null ? false : Convert.ToBoolean(cr.Census), OneKey = cr.OneKey == null ? false : Convert.ToBoolean(cr.OneKey), MfrCount = cr.MfrCount, packCount = cr.packCount, isMyClient = userClients.Contains(cr.clientId) }; if (getAllClients || aClientRelease.isMyClient) { responseReleaseClients.Add(aClientRelease); } } var response = new { //data = clientReleaseDetails.Where(cr => userClients.Contains(cr.clientId)).ToList() data = responseReleaseClients.OrderBy(r => r.clientName).ToList() }; message = Request.CreateResponse(HttpStatusCode.OK, response); return(message); } }