public void ImportPendingRecords() { string where = " [EntityStateId] = 1 "; int pTotalRows = 0; SaveStatus status = new SaveStatus(); List <OrganizationSummary> list = OrganizationManager.MainSearch(where, "", 1, 500, ref pTotalRows); LoggingHelper.DoTrace(1, string.Format(thisClassName + " - ImportPendingRecords(). Processing {0} records =================", pTotalRows)); foreach (OrganizationSummary item in list) { status = new SaveStatus(); //SWP contains the resource url if (!ImportByResourceUrl(item.SubjectWebpage, status)) { //check for 404 LoggingHelper.DoTrace(1, string.Format(" - (). Failed to import pending credential: {0}, message(s): {1}", item.Id, status.GetErrorsAsString())); } else { LoggingHelper.DoTrace(1, string.Format(" - (). Successfully imported pending credential: {0}", item.Id)); } } }
public ActionResult ByEnvelopeId(string envelopeId) { if (!IsAuthorized()) { msg.Title = "ERROR - you are not authorized for this action."; msg.Message = "<a href='/Account/Login'>Please log in</a> with an account that has sufficient authority."; Session["siteMessage"] = msg.Message; return(RedirectToAction("About", "Home")); } ImportRequest mgr = new ImportRequest(); SaveStatus status = new SaveStatus(); if (!string.IsNullOrWhiteSpace(envelopeId)) { LoggingHelper.DoTrace(4, "ImportController. Starting ByEnvelopeId: " + envelopeId); status = mgr.ImportByEnvelopeId(envelopeId); // if ( !status.HasErrors ) ElasticServices.UpdateElastic(false); } else { SetPopupErrorMessage("ERROR - provide a valid envelopeId "); msg.Title = "ERROR - provide a valid CTID or envelopeId"; msg.Message = "Either a valid CTID, or a valid registry envelope identifier must be provided."; Session["siteMessage"] = msg; return(View()); //return RedirectToAction( "Index", "Home" ); } return(View("Index", status)); }
public static bool IsConditionProfileAvailableFromCache(int id, ref ConditionProfile entity) { //use same as lopp for now int cacheMinutes = UtilityManager.GetAppKeyValue("learningOppCacheMinutes", 0); DateTime maxTime = DateTime.Now.AddMinutes(cacheMinutes * -1); string key = "ConditionProfile_" + id.ToString(); if (HttpRuntime.Cache[key] != null && cacheMinutes > 0) { var cache = ( CachedConditionProfile )HttpRuntime.Cache[key]; try { if (cache.lastUpdated > maxTime) { LoggingHelper.DoTrace(7, string.Format("===CacheManager.IsConditionProfileAvailableFromCache === Using cached version of ConditionProfile, Id: {0}, {1}", cache.Item.Id, cache.Item.ProfileName)); //check if user can update the object //string status = ""; //if ( !CanUserUpdateCredential( id, user, ref status ) ) // cache.Item.CanEditRecord = false; entity = cache.Item; return(true); } } catch (Exception ex) { LoggingHelper.DoTrace(6, "===CacheManager.IsConditionProfileAvailableFromCache === exception " + ex.Message); } } return(false); }
public static void AddConditionProfileToCache(ConditionProfile entity) { int cacheMinutes = UtilityManager.GetAppKeyValue("learningOppCacheMinutes", 0); string key = "ConditionProfile_" + entity.Id.ToString(); if (cacheMinutes > 0) { var newCache = new CachedConditionProfile() { Item = entity, lastUpdated = DateTime.Now }; if (HttpContext.Current != null) { if (HttpContext.Current.Cache[key] != null) { HttpRuntime.Cache.Remove(key); HttpRuntime.Cache.Insert(key, newCache); LoggingHelper.DoTrace(7, string.Format("===CacheManager.AddConditionProfileToCache $$$ Updating cached version of ConditionProfile, Id: {0}, {1}", entity.Id, entity.ProfileName)); } else { LoggingHelper.DoTrace(7, string.Format("===CacheManager.AddConditionProfileToCache ****** Inserting new cached version of ConditionProfile, Id: {0}, {1}", entity.Id, entity.ProfileName)); System.Web.HttpRuntime.Cache.Insert(key, newCache, null, DateTime.Now.AddHours(cacheMinutes), TimeSpan.Zero); } } } //return entity; }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="key">The key could vary if for detail, compare, etc</param> /// <param name="?"></param> /// <returns></returns> public static bool IsCredentialAvailableFromCache(int id, string key, ref Credential credential) { int cacheMinutes = UtilityManager.GetAppKeyValue("credentialCacheMinutes", 60); DateTime maxTime = DateTime.Now.AddMinutes(cacheMinutes * -1); //string key = "credential_" + id.ToString(); if (HttpRuntime.Cache[key] != null && cacheMinutes > 0) { var cache = ( CachedCredential )HttpRuntime.Cache[key]; try { if (cache.lastUpdated > maxTime) { LoggingHelper.DoTrace(7, string.Format("===CacheManager.IsCredentialAvailableFromCache === Using cached version of Credential, Id: {0}, {1}, key: {2}", cache.Item.Id, cache.Item.Name, key)); //check if user can update the object //or move these checks to the manager //string status = ""; //if ( !CanUserUpdateCredential( id, user, ref status ) ) // cache.Item.CanEditRecord = false; credential = cache.Item; return(true); } } catch (Exception ex) { LoggingHelper.DoTrace(6, "===CacheManager.IsCredentialAvailableFromCache === exception " + ex.Message); } } return(false); }
public static void AddCredentialToCache(Credential entity, string key) { int cacheMinutes = UtilityManager.GetAppKeyValue("credentialCacheMinutes", 60); //string key = "credential_" + entity.Id.ToString(); if (cacheMinutes > 0) { var newCache = new CachedCredential() { Item = entity, lastUpdated = DateTime.Now }; if (HttpContext.Current != null) { if (HttpContext.Current.Cache[key] != null) { HttpRuntime.Cache.Remove(key); HttpRuntime.Cache.Insert(key, newCache, null, DateTime.Now.AddHours(cacheMinutes), TimeSpan.Zero); LoggingHelper.DoTrace(7, string.Format("===CacheManager.AddCredentialToCache $$$ Updating cached version of credential, Id: {0}, {1}, key: {2}", entity.Id, entity.Name, key)); } else { LoggingHelper.DoTrace(7, string.Format("===CacheManager.AddCredentialToCache ****** Inserting new cached version of credential, Id: {0}, {1}, key: {2}", entity.Id, entity.Name, key)); System.Web.HttpRuntime.Cache.Insert(key, newCache, null, DateTime.Now.AddHours(cacheMinutes), TimeSpan.Zero); } } } //return entity; }
public void UpdateCodeTableCounts() { LoggingHelper.DoTrace(5, "CacheManager.UpdateCodeTableCounts - started"); string connectionString = MainConnection(); try { //running this after add/update of an org will only be partly complete. //would need to run it after any of cred, asmt, and lopp using (SqlConnection c = new SqlConnection(connectionString)) { c.Open(); using (SqlCommand command = new SqlCommand("[CodeTables_UpdateTotals]", c)) { command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = 300; command.ExecuteNonQuery(); command.Dispose(); c.Close(); } } } catch (Exception ex) { LoggingHelper.LogError(ex, "UpdateCodeTableCounts", false); } //NOT seeing this!!!!! LoggingHelper.DoTrace(5, "CacheManager.UpdateCodeTableCounts - completed"); }
public void ImportPendingRecords() { string where = " [EntityStateId] = 1 "; // int pTotalRows = 0; SaveStatus status = new SaveStatus(); List <ThisEntity> list = AssessmentManager.Search(where, "", 1, 500, ref pTotalRows); LoggingHelper.DoTrace(1, string.Format(thisClassName + " - ImportPendingRecords(). Processing {0} records =================", pTotalRows)); foreach (ThisEntity item in list) { status = new SaveStatus(); //SWP contains the resource url //pending records will have a CTID, it should be used to get the envelope! //if ( !ImportByResourceUrl( item.SubjectWebpage, status ) ) if (!ImportByCtid(item.CTID, status)) { //check for 404 LoggingHelper.DoTrace(1, string.Format(" - (). Failed to import pending record: {0}, message(s): {1}", item.Id, status.GetErrorsAsString())); } else { LoggingHelper.DoTrace(1, string.Format(" - (). Successfully imported pending record: {0}", item.Id)); } } }
public ApiResponse ValidateLearningOpportunityConnection(string ctid) { bool isValid = true; List <string> messages = new List <string>(); var response = new ApiResponse(); //some validation? string apiKey = ""; //can the api validation and request validation be done at the same time to minimize //if ( !AuthorizationServices.IsAuthTokenValid( true, ref apiKey, ref statusMessage ) ) //{ // response.Messages.Add( "Error: A valid Apikey was not provided in an Authorization Header. " + statusMessage ); // return response; //} if (string.IsNullOrWhiteSpace(ctid) || ctid.Length != 39) { response.Messages.Add("A valid LearningOpportunity CTID must be provided."); return(response); } // string status = ""; if (ConnectionServices.DoesLearningOpportunityHaveCredentialConnection(ctid, ref status)) { response.Successful = true; } else { LoggingHelper.DoTrace(6, string.Format("CredentialFinderWebAPI.ValidationController.ValidateLearningOpportunityConnection FAILED for LearningOpportunityCTID:{0}", ctid)); response.Messages.Add("The LearningOpportunity is not connected to any credentials."); } return(response); }
public bool ProcessEnvelope(ReadEnvelope item, SaveStatus status) { if (item == null || string.IsNullOrWhiteSpace(item.EnvelopeIdentifier)) { status.AddError(thisClassName + " A valid ReadEnvelope must be provided."); return(false); } DateTime createDate = new DateTime(); DateTime envelopeUpdateDate = new DateTime(); if (DateTime.TryParse(item.NodeHeaders.CreatedAt.Replace("UTC", "").Trim(), out createDate)) { status.SetEnvelopeCreated(createDate); } if (DateTime.TryParse(item.NodeHeaders.UpdatedAt.Replace("UTC", "").Trim(), out envelopeUpdateDate)) { status.SetEnvelopeUpdated(envelopeUpdateDate); } string payload = item.DecodedResource.ToString(); string envelopeIdentifier = item.EnvelopeIdentifier; string ctdlType = RegistryServices.GetResourceType(payload); string envelopeUrl = RegistryServices.GetEnvelopeUrl(envelopeIdentifier); LoggingHelper.DoTrace(5, " envelopeUrl: "+ envelopeUrl); LoggingHelper.WriteLogFile(UtilityManager.GetAppKeyValue("logFileTraceLevel", 5), item.EnvelopeCetermsCtid + "_ConceptScheme", payload, "", false); //just store input for now return(Import(payload, envelopeIdentifier, status)); //return true; } //
public static List <int> GetAllIds(Guid parentUid) { List <int> list = new List <int>(); Pathway entity = new Pathway(); Entity parent = EntityManager.GetEntity(parentUid); LoggingHelper.DoTrace(7, string.Format("Entity_Pathway_GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId)); try { using (var context = new EntityContext()) { List <DBEntity> results = context.Entity_HasPathway .Where(s => s.EntityId == parent.Id) .OrderBy(s => s.Pathway.Name) //not sure .ToList(); if (results != null && results.Count > 0) { foreach (DBEntity item in results) { list.Add(item.PathwayId); } } return(list); } } catch (Exception ex) { LoggingHelper.LogError(ex, thisClassName + ".Entity_Pathway_GetAll"); } return(list); }
} // //public static void MapToDB( ThisEntity from, DBEntity to ) //{ // //want to ensure fields from create are not wiped // if ( to.Id == 0 ) // { // if ( IsValidDate( from.Created ) ) // to.Created = from.Created; // } // to.Id = from.Id; // to.CredentialId = from.CredentialId; // to.RelationshipTypeId = from.RelationshipTypeId; // to.EntityId = from.ParentId; //} public static void MapFromDB(DBEntity from, ThisEntity to, bool isForDetailPageCondition = false) { to.Id = from.Id; to.CredentialId = from.CredentialId; to.ParentId = from.EntityId; to.RelationshipTypeId = from.RelationshipTypeId; //to.Credential = from.Credential; to.Credential = new Credential(); if (from.Credential != null && from.Credential.Id > 0) { to.ProfileSummary = from.Credential.Name; CredentialMinimumMap(from.Credential, to.Credential); } else { to.Credential = CredentialManager.GetBasic(to.CredentialId); if (to.Credential != null && to.Credential.Id > 0) { to.ProfileSummary = to.Credential.Name; //CredentialMinimumMap( from.Credential, to.Credential ); } else { to.ProfileSummary = string.Format("Credential ({0}) has not been downloaded", to.CredentialId); LoggingHelper.DoTrace(1, string.Format(thisClassName + ".MapFromDB() Credential ({0}) has not been downloaded. ParentEntityId: {1}, Entity.CredentialId: {2}", to.CredentialId, to.ParentId, to.Id)); } } if (IsValidDate(from.Created)) { to.Created = ( DateTime )from.Created; } }
public bool ProcessEnvelope(ReadEnvelope item, SaveStatus status) { if (item == null || string.IsNullOrWhiteSpace(item.EnvelopeIdentifier)) { status.AddError("A valid ReadEnvelope must be provided."); return(false); } string payload = item.DecodedResource.ToString(); string envelopeIdentifier = item.EnvelopeIdentifier; string ctdlType = RegistryServices.GetResourceType(payload); string envelopeUrl = RegistryServices.GetEnvelopeUrl(envelopeIdentifier); if (ImportServiceHelpers.IsAGraphResource(payload)) { //if ( payload.IndexOf( "\"en\":" ) > 0 ) return(ImportV3(payload, envelopeIdentifier, status)); //else // return ImportV2( payload, envelopeIdentifier, status ); } else { LoggingHelper.DoTrace(5, " envelopeUrl: "+ envelopeUrl); LoggingHelper.WriteLogFile(1, "lopp_" + item.EnvelopeIdentifier, payload, "", false); input = JsonConvert.DeserializeObject <InputEntity>(item.DecodedResource.ToString()); return(Import(input, envelopeIdentifier, status)); } }
public static string DisplayMessages(string message) { LoggingHelper.DoTrace(1, message); //Console.WriteLine( message ); return(message); }
/// <summary> /// Main search /// </summary> /// <param name="data"></param> /// <param name="pTotalRows"></param> /// <returns></returns> public static List <OrganizationSummary> DoSearch(MainSearchInput data, ref int pTotalRows) { string where = ""; int userId = 0; AppUser user = AccountServices.GetCurrentUser(); if (user != null && user.Id > 0) { userId = user.Id; } //only target full entities where = " ( base.EntityStateId = 3 ) "; SetKeywordFilter(data.Keywords, true, ref where); //SetAuthorizationFilter( user, ref where ); SearchServices.HandleCustomFilters(data, 59, ref where); SetPropertiesFilter(data, ref where); SearchServices.SetRolesFilter(data, ref where); SetBoundariesFilter(data, ref where); SetFrameworksFilter(data, ref where); SetOrgServicesFilter(data, ref where); //check for org category (credentially, or QA). Only valid if one item //SetOrgCategoryFilter( data, ref where ); //Not updated - I'm not sure we're still using this. - NA 5/12/2017 LoggingHelper.DoTrace(5, thisClassName + ".Search(). Filter: " + where); return(EntityMgr.MainSearch(where, data.SortOrder, data.StartPage, data.PageSize, ref pTotalRows)); }
public bool UpdateModifiedDate(Guid entityUid, ref SaveStatus status) { bool isValid = false; if (!IsValidGuid(entityUid)) { status.AddError(thisClassName + ".UpdateModifiedDate(). Error - missing a valid identifier for the Entity"); return(false); } using (var context = new EntityContext()) { DBentity efEntity = context.Entity .FirstOrDefault(s => s.EntityUid == entityUid); if (efEntity != null && efEntity.Id > 0) { efEntity.LastUpdated = DateTime.Now; int count = context.SaveChanges(); if (count >= 0) { isValid = true; LoggingHelper.DoTrace(7, thisClassName + string.Format(".UpdateModifiedDate - update last updated for TypeId: {0}, BaseId: {1}", efEntity.EntityTypeId, efEntity.EntityBaseId)); } } else { status.AddError(thisClassName + ".UpdateModifiedDate(). Error - Entity was not found."); LoggingHelper.LogError(thisClassName + string.Format(".UpdateModifiedDate - record was not found. entityUid: {0}", entityUid), true); } } return(isValid); }///
} // public static bool IsADuplicateRequest(string actionComment) { string sessionKey = GetCurrentSessionId() + "_lastHit"; bool isDup = false; try { if (HttpContext.Current != null) { if (HttpContext.Current.Session != null) { string lastAction = HttpContext.Current.Session[sessionKey].ToString(); if (lastAction.ToLower() == actionComment.ToLower()) { LoggingHelper.DoTrace(7, "ActivityServices. Duplicate action: " + actionComment); return(true); } } } } catch { } return(isDup); }
public static List <ThisEntity> DoSearch(MainSearchInput data, ref int totalRows) { string where = ""; List <string> competencies = new List <string>(); //only target full entities where = " ( base.EntityStateId = 3 ) "; SearchServices.HandleCustomFilters(data, 61, ref where); SetKeywordFilter(data.Keywords, false, ref where); SearchServices.SetSubjectsFilter(data, CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE, ref where); SetPropertiesFilter(data, ref where); SearchServices.SetRolesFilter(data, ref where); SearchServices.SetBoundariesFilter(data, ref where); //SetBoundariesFilter( data, ref where ); //CIP SetFrameworksFilter(data, ref where); //Competencies SetCompetenciesFilter(data, ref where, ref competencies); LoggingHelper.DoTrace(5, "LearningOpportunityServices.Search(). Filter: " + where); return(EntityMgr.Search(where, data.SortOrder, data.StartPage, data.PageSize, ref totalRows, ref competencies)); }
//public bool DeleteAll( Entity parent, ref SaveStatus status, DateTime? lastUpdated = null ) //{ // bool isValid = true; // if ( parent == null || parent.Id == 0 ) // { // status.AddError( thisClassName + ". Error - the provided target parent entity was not provided." ); // return false; // } // int expectedDeleteCount = 0; // try // { // using ( var context = new EntityContext() ) // { // var results = context.Entity_CostProfile.Where( s => s.EntityId == parent.Id && ( lastUpdated == null || s.LastUpdated < lastUpdated ) ) // .ToList(); // if ( results == null || results.Count == 0 ) // return true; // expectedDeleteCount = results.Count; // foreach ( var item in results ) // { // context.Entity_CostProfile.Remove( item ); // var count = context.SaveChanges(); // if ( count > 0 ) // { // } // } // } // } // catch ( System.Data.Entity.Infrastructure.DbUpdateConcurrencyException dbcex ) // { // if ( dbcex.Message.IndexOf( "an unexpected number of rows (0)" ) > 0 ) // { // //don't know why this happens, quashing for now. // LoggingHelper.DoTrace( 1, string.Format( thisClassName + ".DeleteAll. Parent type: {0}, ParentId: {1}, expectedDeletes: {2}. Message: {3}", parent.EntityTypeId, parent.EntityBaseId, expectedDeleteCount, dbcex.Message ) ); // } // else // { // var msg = BaseFactory.FormatExceptions( dbcex ); // LoggingHelper.DoTrace( 1, string.Format( thisClassName + ".DeleteAll. ParentType: {0}, baseId: {1}, DbUpdateConcurrencyException: {2}", parent.EntityType, parent.EntityBaseId, msg ) ); // } // } // catch ( Exception ex ) // { // var msg = BaseFactory.FormatExceptions( ex ); // LoggingHelper.DoTrace( 1, string.Format( thisClassName + ".DeleteAll. ParentType: {0}, baseId: {1}, exception: {2}", parent.EntityType, parent.EntityBaseId, msg ) ); // } // return isValid; //} // private bool UpdateParts(ThisEntity entity, ref SaveStatus status) { bool isAllValid = true; // try { if (new Entity_ReferenceManager().Add(entity.Condition, entity.RowId, CodesManager.ENTITY_TYPE_COST_PROFILE, ref status, CodesManager.PROPERTY_CATEGORY_CONDITION_ITEM, false) == false) { isAllValid = false; } //JurisdictionProfile Entity_JurisdictionProfileManager jpm = new Entity_JurisdictionProfileManager(); jpm.SaveList(entity.Jurisdiction, entity.RowId, Entity_JurisdictionProfileManager.JURISDICTION_PURPOSE_SCOPE, ref status); } catch (Exception ex) { LoggingHelper.DoTrace(1, thisClassName + ".UpdateParts(). Exception while processing condition/jurisdiction. " + ex.Message); status.AddError(ex.Message); } if (entity.Items != null && entity.Items.Count > 0) { new CostProfileItemManager().SaveList(entity.Items, entity.Id, ref status); } return(isAllValid); }
public void FormatCompetencyChildren(ApiCompetency competency, InputCompetency input, List <InputCompetency> allCompetencies, MappingHelperV3 helper) { foreach (var item in input.hasChild) { //get the competency var c = allCompetencies.Where(s => s.CtdlId == item).FirstOrDefault(); if (c != null && !string.IsNullOrWhiteSpace(c.CTID)) { var ac = new ApiCompetency() { CompetencyText = helper.HandleLanguageMap(c.competencyText, "CompetencyText"), CTID = c.CTID, CompetencyLabel = helper.HandleLanguageMap(c.competencyLabel, "competencyLabel"), HasChild = null, HasChildId = null }; if (c.hasChild != null && c.hasChild.Any()) { ac.HasChild = new List <ApiCompetency>(); FormatCompetencyChildren(ac, c, allCompetencies, helper); } competency.HasChild.Add(ac); } else { //log error LoggingHelper.DoTrace(1, string.Format("ImportCompetencyFramework.FormatCompetencyChildren() CompetencyCTID: {0}, child: {1} was not found in the list of competencies", competency.CTID, item)); } } }
public static void HandleAddressGeoCoding() { //should we do all? int maxRecords = 0; LoggingHelper.DoTrace(5, thisClassName + string.Format(".HandleAddressGeoCoding - maxRecords: {0}", maxRecords)); DateTime started = DateTime.Now; string report = ""; string messages = ""; var list = new Entity_AddressManager().ResolveMissingGeodata(ref messages, maxRecords); var saveDuration = DateTime.Now.Subtract(started); LoggingHelper.DoTrace(5, thisClassName + string.Format(".NormalizeAddresses - Completed - seconds: {0}", saveDuration.Seconds)); if (!string.IsNullOrWhiteSpace(messages)) { report = string.Format("<p>Normalize Addresses. Duration: {0} seconds <br/>", saveDuration.Seconds) + messages + "</p>"; } foreach (var address in list) { string msg = string.Format(" - Unable to resolve address: Id: {0}, address1: {1}, city: {2}, region: {3}, postalCode: {4}, country: {5} ", address.Id, address.StreetAddress, address.AddressLocality, address.AddressRegion, address.PostalCode, address.AddressCountry); LoggingHelper.DoTrace(2, msg); report += System.Environment.NewLine + msg; } //no reporting of successes here }
// public static List <ConceptSchemeSummary> Search(MainSearchInput data, ref int totalRows) { string where = ""; List <string> messages = new List <string>(); List <string> competencies = new List <string>(); //int userId = 0; //AppUser user = AccountServices.GetCurrentUser(); //if ( user != null && user.Id > 0 ) // userId = user.Id; //only target records with a ctid where = " (len(Isnull(base.Ctid,'')) = 39) "; SetKeywordFilter(data.Keywords, false, ref where); //SearchServices.SetLanguageFilter( data, CodesManager.ENTITY_TYPE_CONCEPT_SCHEME, ref where ); //// //SearchServices.SetAuthorizationFilter( user, "ConceptScheme_Summary", ref where ); //SearchServices.HandleCustomFilters( data, 60, ref where ); // //can this be replaced by following SearchServices.SetRolesFilter(data, ref where); //owned/offered //SearchServices.SetOrgRolesFilter( data, 3, ref where ); //probably N/A SearchServices.SetBoundariesFilter(data, ref where); LoggingHelper.DoTrace(5, "ConceptSchemeServices.Search(). Filter: " + where); return(Manager.Search(where, data.SortOrder, data.StartPage, data.PageSize, ref totalRows)); }
public static List <ThisEntity> DoSearch(MainSearchInput data, ref int totalRows) { string where = ""; List <string> competencies = new List <string>(); int userId = 0; AppUser user = AccountServices.GetCurrentUser(); if (user != null && user.Id > 0) { userId = user.Id; } //only target full entities where = " ( base.EntityStateId = 3 ) "; SetKeywordFilter(data.Keywords, false, ref where); SearchServices.SetSubjectsFilter(data, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref where); SearchServices.HandleCustomFilters(data, 60, ref where); SetPropertiesFilter(data, ref where); SearchServices.SetRolesFilter(data, ref where); SearchServices.SetBoundariesFilter(data, ref where); //CIP SetFrameworksFilter(data, ref where); //Competencies SetCompetenciesFilter(data, ref where, ref competencies); LoggingHelper.DoTrace(5, "AssessmentServices.Search(). Filter: " + where); return(EntityMgr.Search(where, data.SortOrder, data.StartPage, data.PageSize, ref totalRows)); }
void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started //apparantly can prevent error: /* * Session state has created a session id, but cannot save it because the response was already flushed by the application */ string sessionId = Session.SessionID; try { //Do we want to track the referer somehow?? string lRefererPage = GetUserReferrer(); bool isBot = false; string ipAddress = this.GetUserIPAddress(); //check for bots //use common method string agent = GetUserAgent(ref isBot); string url = "MISSING"; try { HttpContext con = HttpContext.Current; url = con.Request.Url.ToString(); } catch { //skip } if (isBot == false) { AppUser user = new AppUser(); //not always helpful if (User.Identity.IsAuthenticated) { user = AccountServices.GetCurrentUser(User.Identity.Name); } string userState = user.Id > 0 ? string.Format("User: {0}", user.FullName()) : "none"; LoggingHelper.DoTrace(6, string.Format("Session_Start. referrer: {0}, starting Url: {1} agent: {2}, IP Address: {3}, User?: {4}", lRefererPage, url, agent, ipAddress, userState)); string startMsg = "Session Started. SessionID: " + sessionId; startMsg += ", IP Address: " + ipAddress; startMsg += ", User: "******", Agent: " + agent; ActivityServices.SessionStartActivity(startMsg, sessionId, ipAddress, lRefererPage, isBot); } else { LoggingHelper.DoBotTrace(8, string.Format("Session_Start. Skipping bot: referrer: {0}, agent: {1}", lRefererPage, agent)); } } catch (Exception ex) { LoggingHelper.LogError(ex, "Session_Start. ================="); } } //
public void Organization(string id) { int recordId = 0; var label = "Organization"; var response = new ApiResponse(); DateTime overall = DateTime.Now; var entity = new MD.OrganizationDetail(); bool skippingCache = FormHelper.GetRequestKeyValue("skipCache", false); bool includingAll = FormHelper.GetRequestKeyValue("includeAllData", false); List <string> messages = new List <string>(); try { if (int.TryParse(id, out recordId)) { entity = API.OrganizationServices.GetDetailForAPI(recordId, skippingCache, includingAll); } else if (ServiceHelper.IsValidCtid(id, ref messages)) { entity = API.OrganizationServices.GetDetailByCtidForAPI(id, skippingCache); } else { messages.Add("ERROR - Invalid request. Either provide a CTID which starts with 'ce-' or the integer identifier of an existing organization. "); } //HttpContext.Server.ScriptTimeout = 300; if (entity.Meta_Id == 0 && !messages.Any()) { messages.Add(string.Format("ERROR - Invalid request - the {0} was not found. ", label)); } if (messages.Any()) { response.Successful = false; response.Messages.AddRange(messages); SendResponse(response); } else { var saveDuration = DateTime.Now.Subtract(overall); //if ( saveDuration.TotalSeconds > 1 ) LoggingHelper.DoTrace(6, string.Format(" Organization: '{1}' detail Duration: {0:N2} seconds", saveDuration.TotalSeconds, entity.Name)); //map to new ActivityServices.SiteActivityAdd(label, "View", "Detail", string.Format("User viewed {0}: {1} ({2})", label, entity.Name, entity.Meta_Id), 0, 0, recordId); response.Successful = true; response.Result = entity; SendResponse(response); } } catch (Exception ex) { LoggingHelper.LogError(ex, "API-OrganizationDetail. Id" + id); response.Messages.Add(string.Format("Error encountered returning data. {0} ", ex.Message)); response.Successful = false; SendResponse(response); } }
public SaveStatus ImportCredentialByCtid(string ctid) { LoggingHelper.DoTrace(6, thisClassName + string.Format("Request to import credential by ctid: {0}", ctid)); Import.Services.ImportCredential mgr = new Import.Services.ImportCredential(); mgr.ImportByCtid(ctid, status); new RegistryServices().ImportPending(); return(status); }
public bool DeleteAll(int costProfileId, ref SaveStatus status) { bool isValid = false; int expectedDeleteCount = 0; using (var context = new EntityContext()) { try { var results = context.Entity_CostProfileItem.Where(s => s.CostProfileId == costProfileId) .ToList(); if (results == null || results.Count == 0) { return(true); } expectedDeleteCount = results.Count; foreach (var item in results) { context.Entity_CostProfileItem.Remove(item); int count = context.SaveChanges(); if (count > 0) { isValid = true; } else { //if doing a delete on spec, may not have been any properties } } } catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException dbcex) { if (dbcex.Message.IndexOf("an unexpected number of rows (0)") > 0) { //don't know why this happens, quashing for now. LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. costProfileId: {0}, expectedDeletes: {1}. DbUpdateConcurrencyException: {2}", costProfileId, expectedDeleteCount, dbcex.Message)); isValid = true; } else { var msg = BaseFactory.FormatExceptions(dbcex); LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. costProfileId: {0}, DbUpdateConcurrencyException: {1}", costProfileId, msg)); } } catch (Exception ex) { var msg = BaseFactory.FormatExceptions(ex); LoggingHelper.DoTrace(1, string.Format(thisClassName + ".DeleteAll. costProfileId: {0}, Exception: {1}", costProfileId, msg)); if (msg.IndexOf("was deadlocked on lock resources") > 0) { //retry = true; } } } return(isValid); }
/// <summary> /// Get import summary for the requested time period /// </summary> /// <param name="startDateTime">yyyy-MM-dd hh:mm</param> /// <param name="endDateTime">yyyy-MM-dd hh:mm</param> public static bool ImportPeriodSummary(string startDateTime, string endDateTime, ref List <CodeItem> output, ref string message) { string connectionString = MainConnection(); var result = new DataTable(); CodeItem item = new CodeItem(); try { using (SqlConnection c = new SqlConnection(connectionString)) { c.Open(); using (SqlCommand command = new SqlCommand("[ImportSummaryReport]", c)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@StartDate", startDateTime)); command.Parameters.Add(new SqlParameter("@EndDate", endDateTime)); try { using (SqlDataAdapter adapter = new SqlDataAdapter()) { adapter.SelectCommand = command; adapter.Fill(result); } } catch (Exception ex) { LoggingHelper.DoTrace(2, "ImportPeriodSummary - Exception:\r\n " + ex.Message); //LoggingHelper.LogError( ex, "ImportPeriodSummary", true, "Credential Search For Elastic Error" ); message = "Error encountered" + ex.Message; return(false); } } } try { foreach (DataRow dr in result.Rows) { item = new CodeItem(); item.EntityType = GetRowColumn(dr, "ActivityType", ""); item.Description = GetRowColumn(dr, "Event", ""); item.Totals = GetRowColumn(dr, "total", 0); output.Add(item); } } catch (Exception ex) { } return(true); } catch (Exception ex) { LoggingHelper.LogError(ex, "ImportPeriodSummary", false); return(false); } }
/// <summary> /// Get all components for the provided entity /// The returned entities are just the base /// </summary> /// <param name="parentUid"></param> /// <returns></returns> public static List <PathwayComponent> GetAll(Guid parentUid, int childComponentsAction = 1) { List <PathwayComponent> list = new List <PathwayComponent>(); PathwayComponent entity = new PathwayComponent(); Entity parent = EntityManager.GetEntity(parentUid); LoggingHelper.DoTrace(7, string.Format("Entity_PathwayComponent_GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId)); /* * ideal order * - get destination component * - get all children * - children of children? * - get hasChild * - if different from destination component, get children */ //20-08-19 - try displaying in same order as read and see what we have try { using (var context = new EntityContext()) { List <DBEntity> results = context.Entity_HasPathwayComponent .Where(s => s.EntityId == parent.Id) .OrderBy(s => s.Created) //.OrderBy( s => s.ComponentRelationshipTypeId ) .ThenBy(s => s.PathwayComponent.Name) .ToList(); if (results != null && results.Count > 0) { foreach (DBEntity item in results) { //actually the relationship type is not applicable in the component entity = new PathwayComponent() { ComponentRelationshipTypeId = item.ComponentRelationshipTypeId }; //not sure if we will have variances in what is returned PathwayComponentManager.MapFromDB(item.PathwayComponent, entity, childComponentsAction); int index = list.FindIndex(a => a.CTID == entity.CTID); //20-07-27 shouldn't we be doing an exists here //if ( index == -1 ) //{ list.Add(entity); //} } } return(list); } } catch (Exception ex) { LoggingHelper.LogError(ex, thisClassName + ".Entity_PathwayComponent_GetAll"); } return(list); }
public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager) { LoggingHelper.DoTrace(6, "ApplicationUser().GenerateUserIdentityAsync"); // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return(userIdentity); }