protected void Application_EndRequest(object sender, EventArgs e) { if (HttpContext.Response.StatusCode != (int)HttpStatusCode.Unauthorized) { int statusCode = (int)HttpStatusCode.OK; Exception ex = HttpContext.Server.GetLastError(); var httpException = ex as HttpException; if (httpException != null) { statusCode = httpException.GetHttpCode(); } else { statusCode = HttpContext.Response.StatusCode; } if (statusCode != (int)HttpStatusCode.OK) { if (ErrorHandler.CustomErrors != null) { if ((ErrorHandler.CustomErrors.Mode == CustomErrorsMode.On) || ((ErrorHandler.CustomErrors.Mode == CustomErrorsMode.RemoteOnly) && (!HttpContext.Current.Request.IsLocal))) { // clear error on server if (ErrorHandler.CustomErrors.Errors.AllKeys.Contains("" + statusCode)) { HttpContext.Response.StatusCode = statusCode; var url = ErrorHandler.CustomErrors.Errors["" + statusCode].Redirect; if (ErrorHandler.IsAjaxRequest(HttpContext.Current.Request)) { HttpContext.Server.ClearError(); HttpContext.Response.AddHeader("location", url); } else { HttpContext.Server.ClearError(); HttpContext.Response.Redirect(url); } } } } } else { if (ex != null) { TraceManager.Error("Not catched error : " + ex.Message); } } } }
public static void ReformatDBUpdateError(DbUpdateException dbEx) { Exception raise = HandleDbUpdateException(dbEx); string message = string.Empty; Exception exp = raise; while (exp.InnerException != null) { if (!string.IsNullOrEmpty(message)) { message = message + " \n\n"; } message += exp.InnerException.Message; exp = exp.InnerException; } TraceManager.Error("DBUtil", "ReformatDBUpdateError", message); raise = new InvalidOperationException(message, raise); throw raise; }
public static void ReformatDBConstraintError(System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; var builder = new StringBuilder(string.Empty); foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format( "{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); builder.Append(message + "\n"); // raise a new exception nesting // the current instance as InnerException TraceManager.Error("DBUtil", "ReformatDBConstraintError", message); } } raise = new InvalidOperationException(builder.ToString(), raise); throw raise; }
public void Seed(ProjectDBContext context) { if (initalizationInLoad) { throw new Exception("Initialiation is pending on this server."); } initalizationInLoad = true; try { ProjectDBContainer dbContainer = new ProjectDBContainer(); dbContainer.db = context; var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance; Version VersionAppCode = null; Version VersionInitializedData = null; Version VersionPendingInitialization = null; InitVersion(dbContainer); GetVersion(dbContainer, out VersionAppCode, out VersionInitializedData, out VersionPendingInitialization); string VersionAppCodeValue = GenericModelHelper.GetPropValue <Version>(VersionAppCode, "Value").ToString(); string VersionInitializedDataValue = GenericModelHelper.GetPropValue <Version>(VersionInitializedData, "Value").ToString(); string VersionPendingInitializationValue = GenericModelHelper.GetPropValue <Version>(VersionPendingInitialization, "Value").ToString(); if (VersionPendingInitializationValue != "false") { throw new Exception("Initialiation is pending on an other server."); } try { VersionCurrent = new System.Version(VersionInitializedDataValue); } catch (Exception) { VersionCurrent = new System.Version(VersionAppCodeValue); } bool versionIsUptodate = true; try { if ((new System.Version(VersionInitializedDataValue)).CompareTo(new System.Version(InitializedDataVersion)) < 0) { versionIsUptodate = false; } } catch (Exception) { versionIsUptodate = false; } if (!versionIsUptodate) { GenericModelHelper.SetPropValue <Version>(VersionPendingInitialization, "Value", "true"); context.SaveChanges(); try { LoadDatas(dbContainer); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { TraceManager.Error("TDBInitializer", "Seed", "Error DbEntityValidationException."); DBUtil.UndoChange(context); DBUtil.ReformatDBConstraintError(dbEx); } catch (DbUpdateException dbEx) { TraceManager.Error("TDBInitializer", "Seed", "Error DbUpdateException."); DBUtil.UndoChange(context); DBUtil.ReformatDBUpdateError(dbEx); } catch (Exception e) { DBUtil.UndoChange(context); throw e; } finally { GetVersion(dbContainer, out VersionAppCode, out VersionInitializedData, out VersionPendingInitialization); GenericModelHelper.SetPropValue <Version>(VersionPendingInitialization, "Value", "false"); context.SaveChanges(); TraceManager.Info("TDBInitializer", "Seed", "VersionPendingInitialization reset to false."); } GenericModelHelper.SetPropValue <Version>(VersionAppCode, "Value", AddCodeVersion); GenericModelHelper.SetPropValue <Version>(VersionInitializedData, "Value", InitializedDataVersion); context.SaveChanges(); } } catch (Exception e) { throw e; } finally { initalizationInLoad = false; } }
protected string SetFromWebService(Dictionary <string, string> target, IHeterogeneousConfigurationElement heterogeneousElem) { WebServiceElement webService = (WebServiceElement)heterogeneousElem; string userProfileKey = ""; string parameters = ""; foreach (ObjectFieldElement parameter in webService) { object value = ExtractObjectFieldValue(parameter); if (!string.IsNullOrEmpty(userProfileKey)) { userProfileKey += ","; } userProfileKey += value; if (!string.IsNullOrEmpty(parameters)) { parameters += "&"; } else { parameters += "?"; } parameters += parameter.Key + "=" + value; } TraceManager.Info("AUserInfo", "RefreshUserProfile", "Refresh profile from web service " + webService.URL + parameters); string url = webService.URL; if (url.Contains("$(")) { string pat = @"\$\(([\w\d]+)\)"; // Instantiate the regular expression object. Regex r = new Regex(pat, RegexOptions.IgnoreCase); // Match the regular expression pattern against a text string. Match m = r.Match(url); while (m.Success) { string appSetting = ConfigurationManager.AppSettings[m.Groups[1].Value]; url = url.Replace(m.Value, appSetting); m = m.NextMatch(); } } String profilURL = url + parameters; Uri address = new Uri(profilURL); HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(address); request.Timeout = 200000; request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); /*var encoding = ASCIIEncoding.ASCII; * string responseText = ""; * using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) * { * responseText = reader.ReadToEnd(); * }*/ response.Close(); Dictionary <string, string> userProfileReturn = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(responseText); foreach (var item in userProfileReturn) { target.Add(item.Key, item.Value); } } catch (WebException e) { TraceManager.Error("AUserInfo", "RefreshUserProfile", "Service user profile do not work : " + address.AbsoluteUri + " Error : " + e.Message); } return(userProfileKey); }
public static TUserInfo PrepareUserInfo() { /* * var tests= BIASettingsReader.BIANetSection?.Authentication?.Tests; * foreach(HeterogeneousConfigurationElementBase test in tests) * { * if (test is Test1Element) * { * string toto = ((Test1Element)test).KeyTest1; * } * if (test is Test2Element) * { * string toto = ((Test2Element)test).KeyTest2; * } * }*/ TUserInfo user = new TUserInfo(); string cachingParameter = BIASettingsReader.BIANetSection?.Authentication?.Parameters?.Caching; bool manageSession = false; if (cachingParameter == "Session") { HttpSessionState Session = HttpContext.Current.Session; if (Session != null) { manageSession = true; if (Session[AuthenticationConstants.SessionUserInfo] != null) { AUserInfo <TUserProperties> .UserInfoContainer container = (AUserInfo <TUserProperties> .UserInfoContainer)Session[AuthenticationConstants.SessionUserInfo]; user.userInfoContainer = container; CheckInfoToRefresh(user); } else { Session[AuthenticationConstants.SessionUserInfo] = user.userInfoContainer; } } } IPrincipal principal = HttpContext.Current.User; user.Identity = (WindowsIdentity)principal.Identity; if (!user.Identity.IsAuthenticated) { ClientCertificateInHeaderCollection clientCertificateInHeader = BIASettingsReader.BIANetSection?.Authentication?.Identities?.OfType <ClientCertificateInHeaderCollection>().FirstOrDefault(); if (clientCertificateInHeader != null && !user.Identity.IsAuthenticated) { NameValueCollection headers = HttpContext.Current.Request.Headers; string certHeader = headers[clientCertificateInHeader.Key]; if (!String.IsNullOrEmpty(certHeader)) { try { byte[] clientCertBytes = Convert.FromBase64String(certHeader); X509Certificate2 Certificate = new X509Certificate2(clientCertBytes); if (Certificate != null) { if (IsCertificatValid(Certificate, clientCertificateInHeader)) { user.Identity = new WindowsIdentity(GetCertificatValue(Certificate, clientCertificateInHeader.WindowsIdentity)); } } } catch (Exception ex) { TraceManager.Error("Error when analyse certificat.", ex); } } else { certHeader = ""; } } } /* * if (((user.Identity == null || user.Identity.IsAuthenticated==false) && (windowsIdentity != null && windowsIdentity.IsAuthenticated)) || (user.Certificate == null && certificat != null)) * { * if (retrivedFromSession) * { * user = new TUserInfo(); * HttpContext.Current.Session[AuthenticationConstants.SessionUserInfo] = user.userInfoContainer; * } * user.Identity = windowsIdentity; * user.Certificate = certificat; * } * if (user.Identity == null) user.Identity = windowsIdentity;*/ /*if (retrivedFromSession && user.Identity.IsAuthenticated && user.Login == null) * { * user.userInfoContainer.identitiesShouldBeRefreshed = true; * }*/ user.FinalizePreparation(); if (manageSession && (user.Login == null)) { HttpContext.Current.Session[AuthenticationConstants.SessionUserInfo] = null; } return(user); }