/// <summary> /// Establece los valores basicos de error producido en el componente ADWrapper /// </summary> /// <param name="te"></param> protected static void SetError(Fwk.Exceptions.TechnicalException te) { te.Namespace = typeof(ADWrapper).Namespace; te.Source = "Fwk active directory component"; te.UserName = Environment.UserName; te.UserName = Environment.MachineName; }
/// <summary> /// Reset password. To execute it ensure that you was used impersonalization constructor. /// </summary> /// <param name="userName">user name</param> /// <param name="password">new passsword</param> /// <param name="unlockAccount">Lock or unlock flag</param> public void User_ResetPwd(string userName, string password, bool unlockAccount) { DirectoryEntry userDirectoryEntry = null; try { userDirectoryEntry = this.User_Get(userName); if (userDirectoryEntry == null) { StringBuilder strErr = new StringBuilder(); strErr.AppendLine(string.Format(Fwk.Security.Properties.Resource.User_NotExist, userName)); strErr.AppendLine(String.Concat("Error Code:", LoginResult.LOGIN_USER_DOESNT_EXIST)); Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException(strErr.ToString()); ExceptionHelper.SetTechnicalException <ADWrapper>(te); throw te; } userDirectoryEntry.Invoke("SetPassword", new object[] { password }); if (unlockAccount) { userDirectoryEntry.Properties["LockOutTime"].Value = 0; } userDirectoryEntry.Properties["pwdLastSet"].Value = 0; // -1;//must be changed at the next logon. userDirectoryEntry.CommitChanges(); userDirectoryEntry.Close(); } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { throw ProcessActiveDirectoryException(ex); } }
/// <summary> /// Busca la lista de dominios en una base de datos.- A diferencia de DomainsUrl_GetList. Este metodo recive como parametro /// la cadena de coneccion y no su nombre de App.config /// </summary> /// <param name="cnnString">Cadena de coneccion</param> /// <returns>Lista de DomainsUrl</returns> public static List <DomainUrlInfo> DomainsUrl_GetList2(string cnnString) { List <DomainUrlInfo> wDomainUrlInfoList = new List <DomainUrlInfo>(); try { using (SqlDomainURLDataContext dc = new SqlDomainURLDataContext(cnnString)) { IEnumerable <DomainUrlInfo> liste = from s in dc.DomainsUrls select new DomainUrlInfo { DomainName = s.DomainName, LDAPPath = s.LDAPPath, Id = s.DomainID, SiteName = s.SiteName, DomainDN = s.DomainDN }; return(liste.ToList <DomainUrlInfo>()); } } catch (Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException("Error al intentar obtener la lista de dominios desde la base de datos: ", ex); LDAPHelper.SetError(te); te.ErrorId = "15004"; throw te; } }
internal static void ProcessWebException(string msg) { TechnicalException te = new TechnicalException(msg); HttpContext.Current.Session["Error"] = te; HttpContext.Current.Response.Redirect("~/ErrorMessageViewer.aspx"); }
/// <summary> /// /// </summary> /// <param name="ex"></param> /// <returns></returns> internal static Exception ProcessActiveDirectoryException(Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException(ex.Message, ex); ExceptionHelper.SetTechnicalException <ADWrapper>(te); switch (ex.GetType().FullName) { case "System.Runtime.InteropServices.COMException": //((System.Runtime.InteropServices.COMException)(ex)) "El servidor no es operacional.\r\n" { te.ErrorId = "4100"; break; } case "System.DirectoryServices.DirectoryServicesCOMException": //Error de inicio de sesión: nombre de usuario desconocido o contraseña incorrecta. { te.ErrorId = "4101"; break; } default: { te.ErrorId = "4100"; break; } } return(te); }
/// <summary> /// Obtiene de la bases de datos aspnet y tabla aspnet_Applications el Guid de la Aplicacion /// </summary> /// <param name="applicationName">Nombre de la aplicacion. Coincide con CompanyId en la arquitectura</param> /// <param name="cnnstringName"></param> /// <returns></returns> public static Guid GetApplication(string applicationName, string cnnstringName) { Guid wApplicationNameId = new Guid(); try { using (Fwk.Security.RuleProviderDataContext dc = new Fwk.Security.RuleProviderDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[cnnstringName].ConnectionString)) { aspnet_Application app = dc.aspnet_Applications.Where(p => p.LoweredApplicationName.Equals(applicationName.ToLower())).FirstOrDefault<aspnet_Application>(); if (app != null) wApplicationNameId = app.ApplicationId; else { TechnicalException te = new TechnicalException(String.Format(Fwk.Security.Properties.Resource.ApplicationName_NotExist, applicationName, cnnstringName)); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4002"; throw te; } } return wApplicationNameId; } catch (TechnicalException tx) { throw tx; } catch (Exception ex) { TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4000"; throw te; } }
/// <summary> /// Obtiene la lista de controladores de dominio para un DomainID especificado /// </summary> private List <DomainController> GetDomainControllersByDomainId(String pConnString, Int32 pDomainId) { try { using (SqlDomainControllersDataContext dc = new SqlDomainControllersDataContext(pConnString)) { IEnumerable <DomainController> list = from s in dc.DomainControllers where s.DomainId == pDomainId select new DomainController { DomainId = s.DomainId, HostName = s.DCHostName, Id = s.DCId, Ip = s.DCIp }; return(list.ToList <DomainController>()); } } catch (Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException("Error al intentar obtener la lista de dominios desde la base de datos: ", ex); LDAPHelper.SetError(te); te.ErrorId = "15004"; throw te; } }
public frmDialogBase GetDialog(String assemblyInfo) { frmDialogBase frm; try { var f = Fwk.HelperFunctions.ReflectionFunctions.CreateInstance(assemblyInfo); if (f == null) { throw new Fwk.Exceptions.TechnicalException(String.Concat("No se puede cargar el formulario por q falta el archivo ", assemblyInfo, "\r\n verifique el nokmbre de la clase")); } frm = (frmDialogBase)f; } catch (FileNotFoundException fe) { TechnicalException te = new Fwk.Exceptions.TechnicalException(String.Concat("No se puede cargar el formulario por q falta el archivo ", fe.FileName, "\r\n o alguna dependencia")); throw te; } catch (System.InvalidCastException) { TechnicalException te = new Fwk.Exceptions.TechnicalException(String.Concat("No se puede cargar el formulario por que no es de un tipo frmDialogBase valido , Debe heredar de frmDialogBase.-")); throw te; } catch (Exception ex) { TechnicalException te = new TechnicalException(String.Concat("No se puede cargar el formulario ", assemblyInfo, " ", ex.Message)); throw te; } return(frm); }
/// <summary> /// Log error from dispatcher on xml File /// </summary> /// <param name="ex"></param> internal static TechnicalException LogDispatcherErrorConfig(Exception ex) { StringBuilder s = new StringBuilder("Se ha intentado levantar el despachador de servicios."); s.AppendLine("Verifique que esten correctamente configurados en el .config los AppSettings."); s.AppendLine("ServiceDispatcherName y ServiceDispatcherConnection"); if (ex != null) { s.AppendLine(".................................."); s.AppendLine("Error Interno:"); s.AppendLine(Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex)); } TechnicalException te = new TechnicalException(s.ToString()); te.ErrorId = "7007"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException<FacadeHelper>(te); try { // TODO: ver prefijo del log Fwk.Logging.Event ev = new Fwk.Logging.Event(EventType.Error, Fwk.Bases.ConfigurationsHelper.HostApplicationName, s.ToString(), Environment.MachineName, Environment.UserName); Fwk.Logging.Targets.XmlTarget target = new Logging.Targets.XmlTarget(); target.FileName = String.Concat(Fwk.HelperFunctions.DateFunctions.Get_Year_Mont_Day_String(DateTime.Now,'-') ,"_", "DispatcherErrorsLog.xml"); target.Write(ev); } catch { } return te; }
/// <summary> /// Retorna las reglas en las que esta vinculado un Rol /// </summary> /// <param name="roleName">Nombre del rol.</param> /// <param name="applicationName">Nombre de la aplicacion. Coincide con CompanyId en la arquitectura</param> /// <param name="connectionStringName">Nombre de cadena de coneccion del archivo de configuracion.-</param> /// <returns></returns> public static List<FwkAuthorizationRule> GetRulesByRole(string roleName, string applicationName, string connectionStringName) { List<FwkAuthorizationRule> wAllRules = null; try { wAllRules = GetRulesAuxList(applicationName, connectionStringName); var rules_byRol = from s in wAllRules where s.Expression.Contains(string.Concat("R:", roleName.Trim())) select s; return rules_byRol.ToList<FwkAuthorizationRule>(); } catch (TechnicalException tx) { throw tx; } catch (InvalidOperationException) { TechnicalException te = new TechnicalException(string.Format(Resource.Role_WithoutRules, roleName)); te.ErrorId = "4002"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException<FwkMembership>(te); throw te; } catch (Exception ex) { TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4000"; throw te; } }
/// <summary> /// Crea un nuevo usuario. /// </summary> /// <param name="pUser">UsuarioBE a crear</param> /// <returns>UserId del nuevo usuario.</returns> public void Create(User pUser) { //TODO: Ver tema de nuevo GUID para el usuario //Guid wUserGUID = Guid.NewGuid(); MembershipCreateStatus pStatus = MembershipCreateStatus.UserRejected; // se inserta en las membership el nuevo usuario User wNewUser = FwkMembership.CreateUser(pUser.UserName, pUser.Password, pUser.Email, pUser.QuestionPassword, pUser.AnswerPassword, pUser.IsApproved, out pStatus, _ProviderName); // se inserta el usuario custom if (pStatus == MembershipCreateStatus.Success) { //UsersDAC.Create(pUser, CustomParameters, _ProviderName, pCustomUserTable); // Se insertan los roles if (pUser.Roles != null) { RolList roleList = pUser.GetRolList(); FwkMembership.CreateRolesToUser(roleList, pUser.UserName, _ProviderName); } pUser.ProviderId = wNewUser.ProviderId; wNewUser = null; } else { TechnicalException te = new TechnicalException(string.Format(Fwk.Security.Properties.Resource.User_Created_Error_Message, pUser.UserName, pStatus)); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4008"; throw te; } }
/// <summary> /// Este metoo autentica elusuario pero no espesifica el error. Tal como lo hace User_Logon retornando LoginResult /// </summary> /// <param name="LDAPPath">url ldap o coneccion ldap perteneciente al dominio</param> /// <param name="domainName">Nombre de dominio</param> /// <param name="username">Nombre de usuario</param> /// <param name="pwd">password</param> /// <returns></returns> public static bool User_Logon_IsAuthenticated(string LDAPPath, string domainName, string username, string pwd) { string domainAndUsername = String.Concat(domainName + @"\" + username); try { DirectoryEntry Entry = new DirectoryEntry(LDAPPath, username, pwd, AuthenticationTypes.Secure); DirectorySearcher searcher = new DirectorySearcher(Entry); searcher.SearchScope = SearchScope.OneLevel; System.DirectoryServices.SearchResult results = searcher.FindOne(); if (results != null) { return(true); } } catch (Exception ex) { TechnicalException te = new Fwk.Exceptions.TechnicalException(ex.Message); LDAPHelper.SetError(te); te.ErrorId = "15004"; throw te; } return(false); }
/// <summary> /// Obtiene una propiedad determinada de un archivo de configuracion .- /// </summary> /// <param name="configProvider">Proveedor de configuuracion</param> /// <param name="pGroupName">Nombre del grupo donde se encuentra la propiedad</param> /// <param name="pPropertyName">Nombre de la propiedad a obtener</param> /// <returns>String con la propiedad</returns> /// <Author>Marcelo Oviedo</Author> internal static string GetProperty(string configProvider, string pGroupName, string pPropertyName) { string wBaseConfigFile = String.Empty; ConfigProviderElement provider = ConfigurationManager.GetProvider(configProvider); ConfigurationFile wConfigurationFile = GetConfig(provider); Group wGroup = wConfigurationFile.Groups.GetFirstByName(pGroupName); if (wGroup == null) { TechnicalException te = new TechnicalException(string.Concat(new String[] { "No se encuentra el grupo ", pGroupName, " en la de configuración: ", wBaseConfigFile })); te.ErrorId = "8006"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(LocalFileConfigurationManager)); throw te; } Key wKey = wGroup.Keys.GetFirstByName(pPropertyName); if (wKey == null) { TechnicalException te = new TechnicalException(string.Concat(new String[] { "No se encuentra la propiedad ", pPropertyName, " en el grupo de propiedades: ", pGroupName, " en la de configuración: ", wBaseConfigFile })); te.ErrorId = "8007"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(LocalFileConfigurationManager)); throw te; } return wKey.Value.Text; }
/// <summary> /// Retorna el GUID de la aplicación busca en la bse de datos configurada por defecto /// </summary> /// <param name="pCompanyId">Nombre de la aplicación </param> /// <param name="providerName">Nombre del proveedor de membership</param> /// <returns>GUID de la aplicacion</returns> public static string GetApplicationID(String pCompanyId, string providerName) { String wApplicationId = String.Empty; Database wDataBase = null; DbCommand wCmd = null; try { wDataBase = DatabaseFactory.CreateDatabase(GetProvider_ConnectionStringName(providerName)); wCmd = wDataBase.GetStoredProcCommand("[aspnet_Personalization_GetApplicationId]"); // ApplicationName wDataBase.AddInParameter(wCmd, "ApplicationName", System.Data.DbType.String, pCompanyId); wDataBase.AddOutParameter(wCmd, "ApplicationId", System.Data.DbType.Guid, 64); wDataBase.ExecuteScalar(wCmd); wApplicationId = Convert.ToString(wDataBase.GetParameterValue(wCmd, "ApplicationId")); return wApplicationId; } catch (Exception ex) { TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4000"; throw te; } }
/// <summary> /// Busca el archivo lo carga a _Services que es un ServiceConfigurationCollection /// </summary> ///<param name="xmlConfigFile"></param> /// <returns></returns> /// <date>2007-07-13T00:00:00</date> /// <author>moviedo</author> static ServiceConfigurationCollection LoadAllServices(string xmlConfigFile) { try { if (!System.IO.File.Exists(xmlConfigFile)) { //Application.StartupPath xmlConfigFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), xmlConfigFile); } String xml = FileFunctions.OpenTextFile(xmlConfigFile); return((ServiceConfigurationCollection)SerializationFunctions.DeserializeFromXml(typeof(ServiceConfigurationCollection), xml)); } catch (System.IO.IOException ioex) { TechnicalException te = new TechnicalException(Fwk.Bases.Properties.Resources.ServiceManagement_SourceInfo_Error, ioex); if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) { te.Source = string.Concat("Despachador de servicios en ", Environment.MachineName); } else { te.Source = ConfigurationsHelper.HostApplicationName; } te.ErrorId = "7004"; te.Assembly = typeof(XmlServiceConfigurationManager).AssemblyQualifiedName; te.Class = typeof(XmlServiceConfigurationManager).Name; te.Namespace = typeof(XmlServiceConfigurationManager).Namespace; throw te; } catch (TechnicalException te) { throw te; } catch (Exception ex) { string strError = string.Concat("Error al inicializar la metadata de los servicios \r\n ", "Nombre de archivo :", xmlConfigFile, Environment.NewLine); Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException(strError, ex); if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) { te.Source = string.Concat("Despachador de servicios en ", Environment.MachineName); } else { te.Source = ConfigurationsHelper.HostApplicationName; } te.ErrorId = "7004"; te.Assembly = typeof(XmlServiceConfigurationManager).AssemblyQualifiedName; te.Class = typeof(XmlServiceConfigurationManager).Name; te.Namespace = typeof(XmlServiceConfigurationManager).Namespace; throw te; } }
public void AddContronToPannel(DevExpress.XtraEditors.PanelControl panel, Fwk.UI.Controls.Menu.Tree.MenuItem item, object obj) { using (WaitCursorHelper w = new WaitCursorHelper(_ParentForm)) { Xtra_UC_Base ctrl = null; Type T = null; try { T = Fwk.HelperFunctions.ReflectionFunctions.CreateType(item.AssemblyInfo); } catch (FileNotFoundException fe) { TechnicalException te = new Fwk.Exceptions.TechnicalException(String.Concat("No se puede cargar el user control por q falta el archivo ", fe.FileName, "\r\n o alguna dependencia")); throw te; } catch (System.TypeLoadException) { TechnicalException te = null; if (item.AssemblyInfo.Split(',').Count() == 2) { te = new Fwk.Exceptions.TechnicalException(String.Concat("No se puede cargar el user control [", item.AssemblyInfo.Split(',')[0], "] en el archivo ", item.AssemblyInfo.Split(',')[1])); } te = new Fwk.Exceptions.TechnicalException(String.Concat("No se puede cargar el user control definido en [", item.AssemblyInfo, "]")); throw te; } catch (Exception ex) { TechnicalException te = new TechnicalException(String.Concat("No se puede cargar el user control ", item.AssemblyInfo, " ", ex.Message)); throw te; } if (!controls.Contains(string.Concat(T.FullName, item.ID))) { ctrl = (Xtra_UC_Base)Fwk.HelperFunctions.ReflectionFunctions.CreateInstance(item.AssemblyInfo); ctrl.ParentPanel = panel; ctrl.Tag = item.Tag; ctrl.Key = item.ID.ToString(); panel.Controls.Add(ctrl); controls.Add(ctrl.Key); ctrl.Dock = System.Windows.Forms.DockStyle.Fill; ctrl.OnExitControlEvent += new ExitControlHandler(ctrl_OnExitControlEvent); ctrl.OnLunchUserControlEvent += ctrl_OnLunchUserControlEvent; ctrl.Populate(obj); } else { ctrl = GetControlFromPanel(string.Concat(T.FullName, item.ID), panel); } CurrentControl = ctrl; ctrl.BringToFront(); ctrl.Refresh(); } }
/// <summary> /// Busca el archivo lo carga a _Services que es un ServiceConfigurationCollection /// </summary> ///<param name="xmlConfigFile"></param> /// <returns></returns> /// <date>2007-07-13T00:00:00</date> /// <author>moviedo</author> static ServiceConfigurationCollection LoadAllServices(string xmlConfigFile) { try { if (!System.IO.File.Exists(xmlConfigFile)) { //Application.StartupPath xmlConfigFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), xmlConfigFile); } String xml = FileFunctions.OpenTextFile(xmlConfigFile); return (ServiceConfigurationCollection)SerializationFunctions.DeserializeFromXml(typeof(ServiceConfigurationCollection), xml); } catch (System.IO.IOException ioex) { TechnicalException te = new TechnicalException(Fwk.Bases.Properties.Resources.ServiceManagement_SourceInfo_Error, ioex); if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) te.Source = string.Concat("Despachador de servicios en ", Environment.MachineName); else te.Source = ConfigurationsHelper.HostApplicationName; te.ErrorId = "7004"; te.Assembly = typeof(XmlServiceConfigurationManager).AssemblyQualifiedName; te.Class = typeof(XmlServiceConfigurationManager).Name; te.Namespace = typeof(XmlServiceConfigurationManager).Namespace; throw te; } catch (TechnicalException te) { throw te; } catch (Exception ex) { string strError = string.Concat("Error al inicializar la metadata de los servicios \r\n ", "Nombre de archivo :", xmlConfigFile, Environment.NewLine); Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException(strError, ex); if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) te.Source = string.Concat("Despachador de servicios en ", Environment.MachineName); else te.Source = ConfigurationsHelper.HostApplicationName; te.ErrorId = "7004"; te.Assembly = typeof(XmlServiceConfigurationManager).AssemblyQualifiedName; te.Class = typeof(XmlServiceConfigurationManager).Name; te.Namespace = typeof(XmlServiceConfigurationManager).Namespace; throw te; } }
/// <summary> /// Ejecuta un servicio de negocio. /// </summary> /// <param name="providerName">Nombre del proveedor de metadata de servicios.-</param> /// <param name="pRequest">Request con datos de entrada para la ejecución del servicio.</param> /// <returns>XML con el resultado de la ejecución del servicio.</returns> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> public IServiceContract ExecuteService(string providerName, IServiceContract pRequest) { IServiceContract wResult = null; if (string.IsNullOrEmpty(pRequest.ServiceName)) { TechnicalException te = new TechnicalException("El despachador de servicio no pudo continuar debido\r\n a que el nombre del servicio no fue establecido"); Fwk.Exceptions.ExceptionHelper.SetTechnicalException<SimpleFacade>(te); te.ErrorId = "7005"; throw te; } Boolean wExecuteOndispatcher = true; IRequest req = (IRequest)pRequest; ServiceConfiguration wServiceConfiguration = FacadeHelper.GetServiceConfiguration(providerName, pRequest.ServiceName); //establezco el nombre del proveedor de seguridad al request req.SecurityProviderName = FacadeHelper.GetProviderInfo(providerName).SecurityProviderName; req.ContextInformation.SetProviderName(providerName); //if (String.IsNullOrEmpty(req.ContextInformation.DefaultCulture)) // req.ContextInformation.DefaultCulture = FacadeHelper.GetProviderInfo(providerName).DefaultCulture; // Validación de disponibilidad del servicio. FacadeHelper.ValidateAvailability(wServiceConfiguration, out wResult); if (wResult != null) if (wResult.Error != null) return wResult; // Caching del servicio. if (req.CacheSettings != null && req.CacheSettings.CacheOnServerSide) //--------->>> Implement the cache factory { wResult = GetCaheDataById(req, wServiceConfiguration); if (wResult != null) wExecuteOndispatcher = false; } // Realiza la ejecucion del servicio if (wExecuteOndispatcher) { // ejecución del servicio. if (wServiceConfiguration.TransactionalBehaviour == Fwk.Transaction.TransactionalBehaviour.Suppres) wResult = FacadeHelper.RunNonTransactionalProcess(pRequest, wServiceConfiguration); else wResult = FacadeHelper.RunTransactionalProcess(pRequest, wServiceConfiguration); } return wResult; }
/// <summary> /// Almacena la configuración de un servicio de negocio. /// </summary> /// <param name="serviceName">Nombre del servicio a actualizar.</param> /// <param name="pServiceConfiguration">Configuración del servicio de negocio.</param> /// <param name="applicationId">Identificador de aplicacion a la que pertenece el servicio</param> /// <param name="cnnString">Nombre de cadena de conexion</param> internal static void SetServiceConfiguration(String serviceName, ServiceConfiguration pServiceConfiguration, string applicationId, string cnnString) { if (GetServiceConfiguration(serviceName, applicationId, cnnString) == null) { Fwk.Exceptions.TechnicalException wTex = new Fwk.Exceptions.TechnicalException(string.Concat("El servicio ", pServiceConfiguration.Name, " no se actualizó por que no se encontro configurado en la base de datos.")); wTex.ErrorId = "7002"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException <DatabaseServiceConfigurationManager>(wTex); throw wTex; } try { Database wBPConfig = DatabaseFactory.CreateDatabase(cnnString); using (System.Data.Common.DbCommand wCmd = wBPConfig.GetStoredProcCommand("fwk_Service_u")) { wBPConfig.AddInParameter(wCmd, "UpdateServiceName", System.Data.DbType.String, serviceName); wBPConfig.AddInParameter(wCmd, "Name", System.Data.DbType.String, pServiceConfiguration.Name); wBPConfig.AddInParameter(wCmd, "Description", System.Data.DbType.String, pServiceConfiguration.Description); wBPConfig.AddInParameter(wCmd, "Handler", System.Data.DbType.String, pServiceConfiguration.Handler); wBPConfig.AddInParameter(wCmd, "Request", System.Data.DbType.String, pServiceConfiguration.Request); wBPConfig.AddInParameter(wCmd, "Response", System.Data.DbType.String, pServiceConfiguration.Response); wBPConfig.AddInParameter(wCmd, "Available", System.Data.DbType.String, pServiceConfiguration.Available); wBPConfig.AddInParameter(wCmd, "Audit", System.Data.DbType.String, pServiceConfiguration.Audit); wBPConfig.AddInParameter(wCmd, "TransactionalBehaviour", System.Data.DbType.String, Enum.GetName(typeof(TransactionalBehaviour), pServiceConfiguration.TransactionalBehaviour)); wBPConfig.AddInParameter(wCmd, "IsolationLevel", System.Data.DbType.String, Enum.GetName(typeof(Fwk.Transaction.IsolationLevel), pServiceConfiguration.IsolationLevel)); wBPConfig.AddInParameter(wCmd, "ApplicationId", System.Data.DbType.String, pServiceConfiguration.ApplicationId); wBPConfig.AddInParameter(wCmd, "CreatedUserName", System.Data.DbType.String, pServiceConfiguration.CreatedUserName); if (Fwk.HelperFunctions.DateFunctions.IsSqlDateTimeOutOverflow(pServiceConfiguration.CreatedDateTime) == false) { wBPConfig.AddInParameter(wCmd, "CreatedDateTime", System.Data.DbType.DateTime, pServiceConfiguration.CreatedDateTime); } int wAffected = wBPConfig.ExecuteNonQuery(wCmd); if (wAffected == 0) { Fwk.Exceptions.TechnicalException wTex = new Fwk.Exceptions.TechnicalException("El servicio " + pServiceConfiguration.Name + " no se actualizó por que no se encontro configurado en la base de datos."); wTex.ErrorId = "7002"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException <DatabaseServiceConfigurationManager>(wTex); throw wTex; } } } catch (Exception ex) { TechnicalException te = new TechnicalException("Problemas con Fwk.ServiceManagement al realizar operaciones con la base de datos \r\n", ex); ExceptionHelper.SetTechnicalException <DatabaseServiceConfigurationManager>(te); te.ErrorId = "7200"; throw te; } }
/// <summary> /// Esta funcion utiliza chequea el loging de un usuario contra un dominio /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="logError"></param> /// <returns></returns> public LoginResult User_Logon(string userName, string password, out Fwk.Exceptions.TechnicalException logError) { LoginResult wLoginResult = LoginResult.LOGIN_OK; Win32Exception win32Error = null; logError = null; SafeTokenHandle safeTokenHandle; #region Busco el usuario con un DirectoryEntry con usuario administrador this.User_Get(userName, password, out wLoginResult); if (wLoginResult == LoginResult.ERROR_SERVER_IS_NOT_OPERATIONAL) { win32Error = new Win32Exception(); logError = new Fwk.Exceptions.TechnicalException(win32Error.Message); LDAPHelper.SetError(logError); logError.ErrorId = "15004"; logError.Source = string.Concat(logError.Source, Environment.NewLine, win32Error.Source); return(wLoginResult); } #endregion if (wLoginResult == LoginResult.LOGIN_OK) { return(wLoginResult); } //obtain a handle to an access token. bool returnValue = LogonUser(userName, _DomainUrlInfo.DomainName, password, (int)LOGON32.LOGON32_LOGON_INTERACTIVE, (int)LOGON32.LOGON32_PROVIDER_DEFAULT, out safeTokenHandle); if (!returnValue) { int ret = GetLastError(); win32Error = new Win32Exception(); logError = new Fwk.Exceptions.TechnicalException(win32Error.Message); LDAPHelper.SetError(logError); logError.ErrorId = "15004"; logError.Source = string.Concat(logError.Source, Environment.NewLine, win32Error.Source); } return(wLoginResult); }
/// <summary> /// Retorna todos los DolmainUrl por medio de un sp usp_GetDomainsUrl_All que lee de bd encriptada /// </summary> /// <param name="cnnStringName">Nombre de la cadena de cnn</param> /// <returns></returns> public static List <DomainUrlInfo> DomainsUrl_Get_FromSp_all(string cnnStringName) { String wApplicationId = String.Empty; DomainUrlInfo wDomainUrlInfo = null; List <DomainUrlInfo> list = new List <DomainUrlInfo>(); try { using (SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[cnnStringName].ConnectionString)) using (SqlCommand cmd = new SqlCommand("dbo.usp_GetDomainsUrl_All", cnn)) { cmd.CommandType = CommandType.StoredProcedure; cnn.Open(); using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { wDomainUrlInfo = new DomainUrlInfo(); wDomainUrlInfo.DomainDN = dr["DomainDN"].ToString(); wDomainUrlInfo.DomainName = dr["DomainName"].ToString(); wDomainUrlInfo.LDAPPath = dr["LDAPPath"].ToString(); wDomainUrlInfo.Pwd = dr["Pwd"].ToString(); wDomainUrlInfo.SiteName = dr["SiteName"].ToString(); wDomainUrlInfo.Usr = dr["Usr"].ToString(); list.Add(wDomainUrlInfo); } } return(list); } } catch (Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException("Error al intentar obtener los datos del dominio desde la base de datos: ", ex); LDAPHelper.SetError(te); te.ErrorId = "15004"; throw te; } }
/// <summary> /// Realiza el mapeo de una Exception a un ServiceError /// </summary> /// <param name="ex">Exception</param> /// <returns><see cref="ServiceError"/></returns> public static ServiceError GetServiceError(Exception ex) { ServiceError wServiceError = new ServiceError(); wServiceError.Message = ex.Message; wServiceError.InnerMessageException = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex); wServiceError.Source = ex.Source; wServiceError.StackTrace = ex.StackTrace; FwkExceptionTypes t = Fwk.Exceptions.ExceptionHelper.GetFwkExceptionTypes(ex); wServiceError.Type = Enum.GetName(typeof(FwkExceptionTypes), t); switch (t) { case FwkExceptionTypes.TechnicalException: { TechnicalException tex = (TechnicalException)ex; wServiceError.ErrorId = tex.ErrorId; wServiceError.Machine = tex.Machine; wServiceError.UserName = tex.UserName; wServiceError.Namespace = tex.Namespace; wServiceError.Class = tex.Class; wServiceError.Assembly = tex.Assembly; wServiceError.ServiceName = tex.ServiceName; break; } case FwkExceptionTypes.FunctionalException: { FunctionalException fex = (FunctionalException)ex; wServiceError.ErrorId = fex.ErrorId; wServiceError.Type = ex.GetType().Name; wServiceError.ServiceName = fex.ServiceName; break; } case FwkExceptionTypes.OtherException: { wServiceError.Type = ex.GetType().Name; break; } } return(wServiceError); }
/// <summary> /// Constructor estatico del bloque de configuracion del framework /// </summary> static ConfigurationManager() { TechnicalException te; try { _ConfigProvider = System.Configuration.ConfigurationManager.GetSection("FwkConfigProvider") as ConfigProviderSection; if (_ConfigProvider == null) { te = new TechnicalException("No se puede cargar el proveedor de configuracion del framework fwk, verifique si existe la seccion [FwkConfigProvider] en el archivo de configuracion."); te.ErrorId = "8000"; te.Namespace = "Fwk.Configuration"; te.Class = "Fwk.Configuration.ConfigurationManager [static constructor --> ConfigurationManager()]"; te.UserName = Environment.UserName; te.Machine = Environment.MachineName; if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) te.Source = "Sistema de Configuration del framework en "; else te.Source = ConfigurationsHelper.HostApplicationName; throw te; } } catch (System.Exception ex) { te = new TechnicalException("No se puede cargar el proveedor de configuracion del framework fwk, verifique si existe la seccion [FwkConfigProvider] en el archivo de configuracion. \r\n", ex); te.ErrorId = "8000"; te.Namespace = "Fwk.Configuration"; te.Class = "Fwk.Configuration.ConfigurationManager [static constructor --> ConfigurationManager()]"; te.UserName = Environment.UserName; te.Machine = Environment.MachineName; if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) te.Source = "Sistema de Configuration del framework en "; else te.Source = ConfigurationsHelper.HostApplicationName; throw te; } _DefaultProvider = _ConfigProvider.DefaultProvider; }
/// <summary> /// /// </summary> /// <param name="providerName"></param> /// <returns></returns> public static RoleProvider GetRoleProvider(string providerName) { try { RoleProvider rol = Roles.Providers[providerName]; if (rol == null) { TechnicalException te = new TechnicalException(string.Format(Resource.ProviderNameNotFound, providerName, "rol")); te.ErrorId = "4001"; //te.Source = "FwkMembership block"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException<FwkMembership>(te); throw te; } return rol; } catch (System.Configuration.Provider.ProviderException pe) { StringBuilder err = new StringBuilder("El la configuracion RoleProvider lanzo el siguiente error:"); err.AppendLine( pe.Message); err.AppendLine("Revise la configuraciopn del porveedor por defecto que este correcta (cadena de conexion, application Name, etc)" ); //if (pe.Message.Contains("The connection name") || pe.Message.Contains("was not found in the applications configuration or the connection string is empty.")) //{ //} TechnicalException te = new TechnicalException(err.ToString()); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4000"; throw te; } catch (System.Configuration.ConfigurationException c) { TechnicalException te = new TechnicalException(Resource.RoleProviderConfigError, c); te.ErrorId = "4001"; //te.Source = "FwkMembership block"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException<FwkMembership>(te); throw te; } }
/// <summary> /// Verifican que usuario y password sean validos /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="providerName">Nombre del proveedor de membership</param> /// <returns></returns> public static Boolean ValidateUser(string userName, string password, string providerName) { SqlMembershipProvider wProvider = GetSqlMembershipProvider(providerName); TechnicalException te = null; bool isValid = wProvider.ValidateUser(userName, password); if (!isValid) { MembershipUser user = wProvider.GetUser(userName,true); if (user != null) { //User exists if (!user.IsApproved) { //Account Unapproved te = new TechnicalException("Your account is not approved."); te.ErrorId = "4011"; throw te; } else if (user.IsLockedOut) { //Account Locked te= new TechnicalException("Your account is locked."); te.ErrorId = "4012"; throw te; } else { te = new TechnicalException("Invalid username or password."); te.ErrorId = "4013"; throw te; } } else { te = new TechnicalException("Invalid username or password."); te.ErrorId = "4013"; throw te; } } return isValid; }
static Helper() { lookFile = new object(); try { //Cnnstring = ConfigurationManager.ConnectionStrings["BB_MovistarSM_LogsEntities"].ConnectionString; logFileFullName = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "{0}_LogFile.xml"); if (Fwk.Configuration.ConfigurationManager.GetProperty("Engine", "LogOnFile") != null) { logOnFile = Convert.ToBoolean(Fwk.Configuration.ConfigurationManager.GetProperty("Engine", "LogOnFile")); } } catch (Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException("Error al leer configuración en Helper()", ex); te.ErrorId = "1"; throw te; } }
public static RolList GetAllRoles_FullInfo(string applicationName, string connectionStringName) { RolList wRolList = null; Rol wRol = null; try { Guid wApplicationId = GetApplication(applicationName, connectionStringName); using (Fwk.Security.RuleProviderDataContext dc = new Fwk.Security.RuleProviderDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString)) { var roles = from s in dc.aspnet_Roles where s.ApplicationId == wApplicationId select s; wRolList = new RolList(); foreach (aspnet_Role aspnet_rol in roles) { wRol = new Rol(); wRol.Description = aspnet_rol.Description; wRol.RolName = aspnet_rol.RoleName; wRolList.Add(wRol); } } return wRolList; } catch (TechnicalException tx) { throw tx; } catch (Exception ex) { TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4000"; throw te; } }
/// <summary> /// /// </summary> /// <param name="pFwkCategory"></param> /// <param name="connectionStringName">Nombre de cadena de coneccion del archivo de configuracion.-</param> /// <param name="applicationName">Nombre de la aplicacion. Coincide con CompanyId en la arquitectura</param> public static void CreateCategory(FwkCategory pFwkCategory, string applicationName, string connectionStringName) { Database wDataBase = null; DbCommand wCmd = null; try { Guid wApplicationId = GetApplication(applicationName, connectionStringName); wDataBase = DatabaseFactory.CreateDatabase(connectionStringName); StringBuilder str = new StringBuilder(FwkMembershipScripts.Category_i); str.Replace("[ApplicationId]", wApplicationId.ToString()); if (pFwkCategory.ParentId == null) pFwkCategory.ParentId = 0; str.Replace("[ParentCategoryId]", pFwkCategory.ParentId.ToString()); str.Replace("[CategoryName]", pFwkCategory.Name.ToLower()); wCmd = wDataBase.GetSqlStringCommand(str.ToString()); wCmd.CommandType = CommandType.Text; pFwkCategory.CategoryId = Convert.ToInt32(wDataBase.ExecuteScalar(wCmd)); if (pFwkCategory.FwkRulesInCategoryList != null) if (pFwkCategory.FwkRulesInCategoryList.Count != 0) CreateRuleInCategory(pFwkCategory, applicationName.ToLower(), connectionStringName); } catch (TechnicalException tx) { throw tx; } catch (Exception ex) { TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex); ExceptionHelper.SetTechnicalException<FwkMembership>(te); te.ErrorId = "4000"; throw te; } }
/// <summary> /// Intenta buscar un objeto <see cref="DomainUrlInfo"/> /// Si no lo encuenta lanza una TechnicalException con ErrorId = 4001 /// </summary> /// <param name="domainName"></param> /// <returns></returns> internal static DomainUrlInfo Find_DomainUrlInfo(string domainName) { if (_DomainUrlList == null) { _DomainUrlList = Fwk.Security.ActiveDirectory.ADWrapper.DomainsUrl_GetList(string.Empty); } DomainUrlInfo wDomainUrlInfo = _DomainUrlList.Find(p => p.DomainName.Equals(domainName, StringComparison.InvariantCultureIgnoreCase)); if (wDomainUrlInfo == null) { TechnicalException te = new TechnicalException(string.Format(Resource.AD_NotExistDomainsURL, domainName)); te.ErrorId = "4001"; te.Source = "FwkMembership block"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException<FwkMembership>(te); throw te; } return wDomainUrlInfo; }
/// <summary> /// Constructor de Logger. /// </summary> public Logger() { appId = Fwk.Bases.ConfigurationsHelper.HostApplicationName; try { _LoggingSection = ConfigurationManager.GetSection("FwkLogging") as LoggingSection; } catch (System.Configuration.ConfigurationException ex) { TechnicalException te = new TechnicalException("Hay problemas al intentar cargar la configuracion FwkLogging. \r\n ", ex); te.Assembly = "Fwk.Logging"; te.Class = "LoginSection"; te.ErrorId = "9002"; te.Namespace = "Fwk.Logging"; te.UserName = Environment.UserName; te.Machine = Environment.MachineName; throw te; } }
/// <summary> /// Constructor estatico . Inicializa la sección FwkServiceMetadata /// </summary> static ServiceMetadata() { TechnicalException te; try { _ProviderSection = ConfigurationManager.GetSection("FwkServiceMetadata") as ServiceProviderSection; if (_ProviderSection == null) { te = new TechnicalException("No se puede cargar el proveedor de configuracion de Metadata de servicios del framework fwk, verifique si existe la seccion [FwkServiceMetadata] en el archivo de configuracion."); te.ErrorId = "7000"; te.Namespace = "Fwk.ServiceManagement"; te.Class = "Fwk.Configuration.ServiceManagement [static constructor --> ServiceMetadata()]"; te.UserName = Environment.UserName; te.Machine = Environment.MachineName; te.Source = ConfigurationsHelper.HostApplicationName; throw te; } } catch (System.Exception ex) { te = new TechnicalException("No se puede cargar el proveedor de configuracion de Metadata de servicios del framework fwk, verifique si existe la seccion [FwkServiceMetadata] en el archivo de configuracion.",ex); te.ErrorId = "7000"; te.Namespace = "Fwk.ServiceManagement"; te.Class = "Fwk.Configuration.ServiceManagement [static constructor --> ServiceMetadata()]"; te.UserName = Environment.UserName; te.Machine = Environment.MachineName; te.Source = ConfigurationsHelper.HostApplicationName; throw te; } if (_Repository == null) { _Repository = new Dictionary<string, ServiceConfigurationCollection>(); } }
static Helper() { lookFile = new object(); try { //Cnnstring = ConfigurationManager.ConnectionStrings["BB_MovistarSM_LogsEntities"].ConnectionString; logFileFullName = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "{0}_LogFile.xml"); if (Fwk.Configuration.ConfigurationManager.GetProperty("Engine", "LogOnFile") != null) logOnFile = Convert.ToBoolean(Fwk.Configuration.ConfigurationManager.GetProperty("Engine", "LogOnFile")); } catch (Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException("Error al leer configuración en Helper()", ex); te.ErrorId = "1"; throw te; } }
/// <summary> /// Devuelve la configuración de un servicio buscóndolo en la base de datos de configuracón. /// </summary> /// <param name="serviceName">Nombre del servicio</param> /// <param name="applicationId">Identificador de aplicacion a la que pertenece el servicio</param> /// <param name="cnnString">Nombre de cadena de conexion</param> /// <returns></returns> internal static ServiceConfiguration GetServiceConfiguration(string serviceName, string applicationId, string cnnString) { ServiceConfiguration wServiceConfiguration = null; ; try { Database wBPConfig = DatabaseFactory.CreateDatabase(cnnString); System.Data.Common.DbCommand dbCommand = wBPConfig.GetStoredProcCommand("fwk_Service_g_Name"); wBPConfig.AddInParameter(dbCommand, "Name", System.Data.DbType.String, serviceName); if (!string.IsNullOrEmpty(applicationId)) wBPConfig.AddInParameter(dbCommand, "ApplicationId", System.Data.DbType.String, applicationId); using (IDataReader dataReader = wBPConfig.ExecuteReader(dbCommand)) { while (dataReader.Read()) { wServiceConfiguration = GetServiceConfigurationFromRow(dataReader); } if (wServiceConfiguration == null) { throw new Fwk.Exceptions.TechnicalException(string.Concat("El servicio " , serviceName , " no se encuentra configurado.")); } } } catch (Exception ex) { TechnicalException te = new TechnicalException("Problemas con Fwk.ServiceManagement al realizar operaciones con la base de datos \r\n", ex); ExceptionHelper.SetTechnicalException<DatabaseServiceConfigurationManager>(te); te.ErrorId = "7200"; throw te; } return wServiceConfiguration; }
/// <summary> /// Aqui se cargan por unica vez los Domain Controllers y DomainUrlInfoList /// </summary> //void LoadControllersFromDatabase(string pConnString) //{ ///TODO: Aqui se debera agregar la utilizacion de un diccionario para mentener los valores por cada cadena de conexion /// hay que usar _DomainControllerDictionary y _DomainUrlInfoDictionary /// ///Se comenta por que en teoria no se usaria mas.. directamente se obtendra _DomainUrlInfo necesario //if (_DomainUrlInfoList == null) //{ // _DomainUrlInfoList = DomainsUrl_GetList2(System.Configuration.ConfigurationManager.ConnectionStrings[pConnString].ConnectionString); // if (_DomainUrlInfoList == null) // throw new Fwk.Exceptions.TechnicalException("Error al intentar obtener la lista de dominios: La lista se encuentra vacía."); //} //if (_DomainControllers == null) //{ // _DomainControllers = GetDomainControllersByDomainId(System.Configuration.ConfigurationManager.ConnectionStrings[pConnString].ConnectionString, _DomainUrlInfo.Id); // if (_DomainControllers == null || _DomainControllers.Count == 0) // throw new Fwk.Exceptions.TechnicalException("No se encuentra configurado ningún controlador de dominio para el sitio especificado."); //} //} #endregion #region Funciones que no usan LDAP en C++ /// <summary> /// Esta funcion utiliza chequea el loging de un usuario contra un dominio /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="logError"></param> /// <returns></returns> public LoginResult User_Logon(string userName, string password, out Fwk.Exceptions.TechnicalException logError) { LoginResult wLoginResult = LoginResult.LOGIN_OK; Win32Exception win32Error = null; logError = null; SafeTokenHandle safeTokenHandle; #region Busco el usuario con un DirectoryEntry con usuario administrador this.User_Get(userName, password, out wLoginResult); if (wLoginResult == LoginResult.ERROR_SERVER_IS_NOT_OPERATIONAL) { win32Error = new Win32Exception(); logError = new Fwk.Exceptions.TechnicalException(win32Error.Message); LDAPHelper.SetError(logError); logError.ErrorId = "15004"; logError.Source = string.Concat(logError.Source, Environment.NewLine, win32Error.Source); return wLoginResult; } #endregion if (wLoginResult == LoginResult.LOGIN_OK) return wLoginResult; //obtain a handle to an access token. bool returnValue = LogonUser(userName, _DomainUrlInfo.DomainName, password, (int)LOGON32.LOGON32_LOGON_INTERACTIVE, (int)LOGON32.LOGON32_PROVIDER_DEFAULT, out safeTokenHandle); if (!returnValue) { int ret = GetLastError();//int ret = Marshal.GetLastWin32Error(); win32Error = new Win32Exception(); logError = new Fwk.Exceptions.TechnicalException(win32Error.Message); LDAPHelper.SetError(logError); logError.ErrorId = "15004"; logError.Source = string.Concat(logError.Source, Environment.NewLine, win32Error.Source); #region old code //switch (ret) //{ // case (126): // return LoginResult.LOGIN_USER_OR_PASSWORD_INCORRECT; // case (1314): // return LoginResult.LOGIN_OK; // case (1326): // return LoginResult.LOGIN_USER_OR_PASSWORD_INCORRECT; // default: // throw new Exception( // "Unexpected Logon Failure. Contact Administrator"); //} //throw new System.ComponentModel.Win32Exception(ret); #endregion } #region old code //using (safeTokenHandle) //{ // err = string.Concat("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No")); // err = string.Concat("Value of Windows NT token: " + safeTokenHandle); // Check the identity. ///////Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name); // Use the token handle returned by LogonUser. //WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()); //using (WindowsImpersonationContext impersonatedUser = newId.Impersonate()) //{ // // Check the identity. // Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name); //} // Releasing the context object stops the impersonation // Check the identity. //Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name); //} #endregion return wLoginResult; }
/// <summary> /// Procesa la exepcion que se produce al intentar conectarce al cliente y genera un /// ServiceError el cual es insertado al Response.- /// </summary> /// <param name="pEx">Exepcion</param> /// <param name="pURL">Direccion web del servicio web donde esta el despachador de servicio</param> /// <returns>ServiceError <see cref="ServiceError"/></returns> public static ServiceError Process(Exception pEx, String pURL) { ServiceError wServiceError = null; switch (pEx.GetType().FullName) { case "System.Net.WebException": { wServiceError = ProcessWebException((System.Net.WebException)pEx, pURL); wServiceError.Assembly = "Fwk.Bases.Connector.dll"; wServiceError.Namespace = "Fwk.Bases.Connector"; wServiceError.Class = "Wrapper : IServiceInterfaceWrapper"; wServiceError.ErrorId = "1000"; break; } case "System.Configuration.ConfigurationErrorsException": { wServiceError = ProcessConfigurationException((System.Configuration.ConfigurationException)pEx); wServiceError.Assembly = "Fwk.Bases.dll"; wServiceError.Namespace = ""; wServiceError.Class = ""; break; } case "System.Web.Services.Protocols.SoapException": { wServiceError = ProcessSoapException((System.Web.Services.Protocols.SoapException)pEx); wServiceError.Assembly = "Fwk.ServiceManagement.dll"; wServiceError.Namespace = "Fwk.ServiceManagement"; wServiceError.Class = "ServiceManagement : Despachador de servicios "; break; } case "Fwk.Exceptions.TechnicalException": { TechnicalException te = (TechnicalException)pEx; wServiceError = ProcessDefaultException(pEx); wServiceError.Assembly = te.Assembly; wServiceError.Namespace = te.Namespace; wServiceError.Class = te.Class; wServiceError.ErrorId = te.ErrorId; wServiceError.Source = te.Source; break; } default: { wServiceError = ProcessDefaultException(pEx); wServiceError.Assembly = "Se desconoce.. examine el error"; wServiceError.Namespace = "Se desconoce.. examine el error"; wServiceError.Class = "Wrapper : IServiceInterfaceWrapper"; break; } } wServiceError.UserName = Environment.UserName; wServiceError.Machine = Environment.MachineName; wServiceError.StackTrace = pEx.StackTrace; if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) { wServiceError.Source = "Cliente " + Environment.MachineName; } else { wServiceError.Source = ConfigurationsHelper.HostApplicationName; } wServiceError.Type = ExceptionHelper.GetFwkExceptionTypesName(pEx);//pEx.GetType().FullName; return(wServiceError); }
/// <summary> /// Retorna un Logs asociado al archivo especificado /// en la propiedad FileName, si es que este existe. En caso /// contrario, retorna un 'nuevo' Logs. /// </summary> /// <returns>Logs.</returns> Events OpenLogsFromFile() { #region validacion if (this.FileName.Trim().Length == 0) { TechnicalException te = new TechnicalException("Debe especificar un nombre de archivo para guardar el log."); te.Assembly = "Fwk.Logging"; te.Class = "XmlTarget"; te.ErrorId = "9000"; te.Namespace = "Fwk.Logging"; te.UserName = Environment.UserName; te.Machine = Environment.MachineName; throw te; } #endregion Events wLog = new Events (); if (!File.Exists(this.FileName)) { return wLog; } wLog = Events.GetFromXml<Events>(Fwk.HelperFunctions.FileFunctions.OpenTextFile(this.FileName)); return wLog; }
/// <summary> /// Permite volver a cargar la configuracion si es que en el inicio estatico no lo hiso correctamente /// </summary> internal static void ReloadConfig(out String stringMessage) { stringMessage = string.Empty; //ConnectionString donde proviene la configuracion del Service Dispatcher ConfigurationsHelper.ServiceDispatcherConnection = System.Configuration.ConfigurationManager.AppSettings["ServiceDispatcherConnection"]; string serviceDispatcherName = System.Configuration.ConfigurationManager.AppSettings["ServiceDispatcherName"]; if (!String.IsNullOrEmpty(ConfigurationsHelper.ServiceDispatcherConnection) || !String.IsNullOrEmpty(serviceDispatcherName)) { #region Check cnn string if exist if (System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationsHelper.ServiceDispatcherConnection] == null) { TechnicalException te = new TechnicalException(string.Concat("No se puede encontrar la cadena de conexión : ", ConfigurationsHelper.ServiceDispatcherConnection)); ExceptionHelper.SetTechnicalException<DatabaseConfigManager>(te); te.ErrorId = "8200"; stringMessage = Audit.LogDispatcherErrorConfig(te).Message; DefaultSettings = true; } #endregion if (DefaultSettings == false) { #region Try coinnect tod serivice dispatcher database try { using (FwkDatacontext context = new FwkDatacontext(System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationsHelper.ServiceDispatcherConnection].ConnectionString)) { ServiceDispatcherConfig = context.fwk_ServiceDispatchers.Where(s => s.InstanseName.Equals(serviceDispatcherName.Trim())).FirstOrDefault(); if (ServiceDispatcherConfig == null) { TechnicalException te = new TechnicalException(string.Concat("No se puede encontrar la configuracion del despachador de servicio en la base de datos\r\nCadena de conexión : ", ConfigurationsHelper.ServiceDispatcherConnection)); ExceptionHelper.SetTechnicalException<DatabaseConfigManager>(te); te.ErrorId = "7009"; stringMessage = Audit.LogDispatcherErrorConfig(te).Message; } } ConfigurationsHelper.HostApplicationName = ServiceDispatcherConfig.InstanseName; } catch (Exception ex) { DefaultSettings = true; stringMessage = Audit.LogDispatcherErrorConfig(ex).Message; } #endregion } } else { DefaultSettings = true; } if (DefaultSettings) { ServiceDispatcherConfig = new fwk_ServiceDispatcher(); ServiceDispatcherConfig.AuditMode = (int)AuditMode.None; ServiceDispatcherConfig.HostIp = "127.0.0.1"; ServiceDispatcherConfig.InstanseName = "Fwk Dispatcher (default name)"; stringMessage = Audit.LogDispatcherErrorConfig(null).Message; } }
/// <summary> /// Completa el error del que va dentro del Request con informacion de : /// Assembly, Class, Namespace, UserName, InnerException, etc /// </summary> /// <param name="pMessage">Mensaje personalizado</param> /// <param name="pErrorId">Id del Error</param> /// <param name="pException">Alguna Exception que se quiera incluir</param> /// <date>2007-08-07T00:00:00</date> /// <author>moviedo</author> internal static TechnicalException GetTechnicalException(String pMessage, String pErrorId, Exception pException) { TechnicalException te = new TechnicalException(pMessage, pException); te.ErrorId = pErrorId; te.Assembly = "Fwk.Bases"; te.Class = "FacadeHelper"; te.Namespace = "Fwk.BusinessFacades.Utils"; //te.UserName = Environment.UserName; te.Machine = Environment.MachineName; if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName)) te.Source = "Despachador de servicios en " + Environment.MachineName; else te.Source = ConfigurationsHelper.HostApplicationName; return te; }
private static void LoadFile(TreeNode pConfigManagerTreeNode, ContextMenuStrip mnContextCnfgManFile, ContextMenuStrip mnContextCnfgManFile_Fail, ContextMenuStrip mnGroupOrProperty, ConfigProviderElement provider, bool isRefresh) { ConfigurationFile wConfigurationFile; ListDictionary wDictionary = new ListDictionary(); try { if (isRefresh) { wConfigurationFile = Fwk.Configuration.ConfigurationManager.RefreshConfigurationFile(provider.Name); } else { wConfigurationFile = Fwk.Configuration.ConfigurationManager.GetConfigurationFile(provider.Name); } //wConfigurationFile.FileName = System.IO.Path.GetFileName(wConfigurationFile.BaseConfigFile); #region [Set to FileNode] TreeNode wFileNode = new TreeNode(wConfigurationFile.FileName); wFileNode.ToolTipText = string.Concat("Proveedor tipo: ", provider.ConfigProviderType.ToString());; wDictionary.Add("FullFileName", wConfigurationFile.ProviderName); wDictionary.Add("ConfigurationFile", wConfigurationFile); wDictionary.Add("provider", provider.Name); wFileNode.Tag = wDictionary; wFileNode.ContextMenuStrip = mnContextCnfgManFile; wFileNode.ImageIndex = pConfigManagerTreeNode.TreeView.ImageList.Images.IndexOfKey("inifile.ico"); wFileNode.SelectedImageIndex = pConfigManagerTreeNode.TreeView.ImageList.Images.IndexOfKey("inifile.ico"); #region Agrego todos los grupos LoadGroupFromFile(pConfigManagerTreeNode, wFileNode, wConfigurationFile.Groups, mnGroupOrProperty); #endregion #endregion //Si todo funciono buien agrego el nodo pConfigManagerTreeNode.Nodes.Add(wFileNode); } catch (InvalidOperationException er) { TechnicalException te = new Fwk.Exceptions.TechnicalException("It's not valid configuration manager file", er); FwkMessageView.Show(te, "Config manager", MessageBoxButtons.OK, Fwk.Bases.FrontEnd.Controls.MessageBoxIcon.Error); } catch (TechnicalException er1) { if (er1.ErrorId.Equals("8011") || er1.ErrorId.Equals("8200") || er1.ErrorId.Equals("8012")) { TreeNode wFileNode = new TreeNode(provider.BaseConfigFile); wFileNode.ContextMenuStrip = mnContextCnfgManFile_Fail; wFileNode.ToolTipText = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(er1); wDictionary.Add("FullFileName", provider.BaseConfigFile); wDictionary.Add("ConfigurationFile", null); wDictionary.Add("provider", provider.Name); wFileNode.Tag = wDictionary; //wFileNode.ContextMenuStrip = mnContextCnfgManFile; wFileNode.ImageIndex = pConfigManagerTreeNode.TreeView.ImageList.Images.IndexOfKey("alert.png"); wFileNode.SelectedImageIndex = pConfigManagerTreeNode.TreeView.ImageList.Images.IndexOfKey("alert.png"); pConfigManagerTreeNode.Nodes.Add(wFileNode); } else { FwkMessageView.Show(er1, "Config manager", MessageBoxButtons.OK, Fwk.Bases.FrontEnd.Controls.MessageBoxIcon.Error); } } }
/// <summary> /// Guarda los cambios en el archivo /// </summary> /// <param name="xmlConfigFile">Nombre del archivo que contiene la metadata.</param> /// <param name="services">Repositorio de servicios enmemoria.</param> static void SaveServiceConfigFile(string xmlConfigFile, ServiceConfigurationCollection services) { String xml = SerializationFunctions.SerializeToXml(services); try { HelperFunctions.FileFunctions.SaveTextFile(xmlConfigFile, xml, false); } catch (System.UnauthorizedAccessException) { TechnicalException te = new TechnicalException(string.Concat("No tiene permiso para actualizar el archivo ", xmlConfigFile)); te.ErrorId = "7100"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException<XmlServiceConfigurationManager>(te); throw te; } }
/// <summary> /// Realiza cambios a una propiedad.- /// </summary> /// <param name="provider">Proveedor de configuracion</param> /// <param name="groupName">Nombre del grupo donde se encuentra la propiedad</param> /// <param name="property">Propiedad actualizada. Este objeto puede contener todos sus valores modifcados</param> /// <param name="propertyName">Nombre de la propiedad que se mofdifico.- Este valor es el original sin modificacion</param> internal static void ChangeProperty(ConfigProviderElement provider, string groupName, Key property, string propertyName) { TechnicalException te = new TechnicalException(string.Concat("No esta nimplementada esta funcionalidad de ConfigurationMannager contra servicios ", provider.BaseConfigFile)); te.ErrorId = "8008"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(LocalFileConfigurationManager)); throw te; }
/// <summary> /// Obtiene un grupo determinado en el archivo de configuracion /// </summary> /// <param name="configProvider">Proveedor de configuuracion</param> /// <param name="pGroupName"></param> /// <returns>Hashtable con los grupos contenidos en el archivo de configuracion</returns> /// <Author>Marcelo Oviedo</Author> internal static Group GetGroup(string configProvider, string pGroupName) { string wBaseConfigFile = string.Empty; ConfigProviderElement provider = ConfigurationManager.GetProvider(configProvider); ConfigurationFile wConfigurationFile = GetConfig(provider); Group wGroup = wConfigurationFile.Groups.GetFirstByName(pGroupName); if (wGroup == null) { TechnicalException te = new TechnicalException(string.Concat(new String[] { "No se encuentra el grupo [", pGroupName, "] en el archivo de configuración: ", wBaseConfigFile })); te.ErrorId = "8006"; Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(LocalFileConfigurationManager)); throw te; } return wGroup; }
/// <summary> /// Este metoo autentica elusuario pero no espesifica el error. Tal como lo hace User_Logon retornando LoginResult /// </summary> /// <param name="LDAPPath">url ldap o coneccion ldap perteneciente al dominio</param> /// <param name="domainName">Nombre de dominio</param> /// <param name="username">Nombre de usuario</param> /// <param name="pwd">password</param> /// <returns></returns> public static bool User_Logon_IsAuthenticated(string LDAPPath, string domainName, string username, string pwd) { string domainAndUsername = String.Concat(domainName + @"\" + username); try { DirectoryEntry Entry = new DirectoryEntry(LDAPPath, username, pwd, AuthenticationTypes.Secure); DirectorySearcher searcher = new DirectorySearcher(Entry); searcher.SearchScope = SearchScope.OneLevel; System.DirectoryServices.SearchResult results = searcher.FindOne(); if (results != null) return true; } catch (Exception ex) { TechnicalException te = new Fwk.Exceptions.TechnicalException(ex.Message); LDAPHelper.SetError(te); te.ErrorId = "15004"; throw te; } return false; }
/// <summary> /// Esta funcion utiliza chequea el loging de un usuario contra un dominio /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="logError"></param> /// <returns></returns> public LoginResult User_Logon(string userName, string password, out Fwk.Exceptions.TechnicalException logError) { LoginResult wLoginResult = LoginResult.LOGIN_OK; Win32Exception win32Error = null; logError = null; SafeTokenHandle safeTokenHandle; #region Busco el usuario con un DirectoryEntry con usuario administrador this.User_Get(userName, password, out wLoginResult); if (wLoginResult == LoginResult.ERROR_SERVER_IS_NOT_OPERATIONAL) { win32Error = new Win32Exception(); logError = new Fwk.Exceptions.TechnicalException(win32Error.Message); LDAPHelper.SetError(logError); logError.ErrorId = "15004"; logError.Source = string.Concat(logError.Source, Environment.NewLine, win32Error.Source); return wLoginResult; } #endregion if (wLoginResult == LoginResult.LOGIN_OK) return wLoginResult; //obtain a handle to an access token. bool returnValue = LogonUser(userName, _DomainUrlInfo.DomainName, password, (int)LOGON32.LOGON32_LOGON_INTERACTIVE, (int)LOGON32.LOGON32_PROVIDER_DEFAULT, out safeTokenHandle); if (!returnValue) { int ret = GetLastError(); win32Error = new Win32Exception(); logError = new Fwk.Exceptions.TechnicalException(win32Error.Message); LDAPHelper.SetError(logError); logError.ErrorId = "15004"; logError.Source = string.Concat(logError.Source, Environment.NewLine, win32Error.Source); } return wLoginResult; }
/// <summary> /// /// </summary> /// <returns></returns> DirectoryEntry GetImpersonate_SearchRoot_DE() { try { return new DirectoryEntry(_DomainUrlInfo.LDAPPath, _DomainUrlInfo.Usr, _DomainUrlInfo.Pwd, AuthenticationTypes.Secure); } catch (Exception e)// Cuando el usuario no existe o clave erronea { Exception te1 = ADHelper.ProcessActiveDirectoryException(e); TechnicalException te = new TechnicalException(string.Format(Resource.AD_Impersonation_Error, te1.Message), te1.InnerException); ExceptionHelper.SetTechnicalException<ADHelper>(te); te.ErrorId = "4103"; throw te; } }
/// <summary> /// Obtiene la lista de Grupos de LDAP a los que pertenece el usuario /// </summary> /// <param name="pUserName">Nombre de usuario</param> //public List<ADGroup> User_SearchGroupList(string pUserName) //{ // List<ADGroup> wGroups = null; // String wFilter; // String[] wAttributes; // LdapEntryList wResults; // ADGroup wADGroup; // // Parámetros de búsqueda // wFilter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", pUserName); // wAttributes = new String[1]; // array vacío, para que traiga todos los disponibles // wAttributes[0] = ADProperties.MEMBEROF; // wResults = new LdapEntryList(); // // Busca y verifica que exista el usuario // if (_LdapWrapper.Search(wFilter, wAttributes, wResults) > 0) // { // LdapEntry wUser = wResults.First<LdapEntry>(); // if (wUser.ContainsKey(ADProperties.MEMBEROF)) // { // foreach (String wGrp in wUser[ADProperties.MEMBEROF]) // { // foreach (string wG in GetGroupFromMemberOf(wGrp)) // { // wADGroup = Group_GetByName(wG); // if (wADGroup != null) // wGroups.Add(wADGroup); // } // } // } // } // return null; //} ///// <summary> ///// Autentica un usuario ///// </summary> ///// <param name="pUserName">Nombre de usuario</param> ///// <param name="pPassword">Clave</param> //public LoginResult User_CheckLogin(string pUserName, string pPassword) //{ // String wFilter; // String[] wAttributes; // LdapEntryList wResults; // // Parámetros de búsqueda // wFilter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", pUserName); // wAttributes = new String[3]; // wAttributes[0] = ADProperties.USERACCOUNTCONTROL; // wAttributes[1] = ADProperties.PWDLASTSET; // wAttributes[2] = "lockoutTime"; // TODO: agregar "lockoutTime" a la clase ADProperties; // wResults = new LdapEntryList(); // // Busca y verifica que exista el usuario // if (_LdapWrapper.Search(wFilter, wAttributes, wResults) == 0) // { // return LoginResult.LOGIN_USER_DOESNT_EXIST; // } // // Verifica que la cuenta no esté deshabilitada // Int32 wUserAccountControl = Convert.ToInt32(wResults.First()[ADProperties.USERACCOUNTCONTROL].First()); // Int32 wUserAccountControlDisabled = Convert.ToInt32(ADAccountOptions.UF_ACCOUNTDISABLE); // if ((wUserAccountControl & wUserAccountControlDisabled) != 0) // { // return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE; // } // if (wResults.First().ContainsKey("lockoutTime")) // { // Int64 wLockOutTime = Convert.ToInt64(wResults.First()["lockoutTime"].First()); // if (wLockOutTime > 0) // { // return LoginResult.LOGIN_USER_ACCOUNT_LOCKOUT; // } // } // // Verifica que no deba cambiar la clave // Int64 wPwdLastSet = Convert.ToInt64(wResults.First()[ADProperties.PWDLASTSET].First()); // if (wPwdLastSet == 0) // { // return LoginResult.ERROR_PASSWORD_MUST_CHANGE; // } // // Autentica // try // { // if (!_LdapWrapper.Bind(_DomainController.HostName, _DomainUrlInfo.DomainDN, pUserName, pPassword, false)) // { // return LoginResult.LOGIN_USER_OR_PASSWORD_INCORRECT; // } // } // catch (LdapAuthenticationException) // { // return LoginResult.LOGIN_USER_OR_PASSWORD_INCORRECT; // } // // Pasó hasta acá, login OK // return LoginResult.LOGIN_OK; //} /// <summary> /// Obtiene un Grupo de LDAP, dado un nombre /// </summary> //public ADGroup Group_GetByName(string pName) //{ // String wFilter; // String[] wAttributes; // LdapEntryList wResults; // // Parámetros de búsqueda // wFilter = String.Format("(&(objectClass=group)(sAMAccountName={0}))", pName); // wAttributes = new String[0]; // todos lso atributos disponibles // wResults = new LdapEntryList(); // buffer de resultados // // Busca y verifica que exista el usuario // if (_LdapWrapper.Search(wFilter, wAttributes, wResults) == 0) // { // return new ADGroup(wResults.First<LdapEntry>()); // } // return null; //} /// <summary> /// Obtiene la lista completa de grupos del LDAP /// </summary> //public List<ADGroup> Groups_GetAll() //{ // List<ADGroup> wGroups = null; // String wFilter; // String[] wAttributes; // LdapEntryList wResults; // ADGroup wADGroup; // // Parámetros de búsqueda // wFilter = "(&(objectClass=group))"; // wAttributes = new String[0]; // array vacío, para que traiga todos los disponibles // wResults = new LdapEntryList(); // // Busca y verifica que exista el usuario // if (_LdapWrapper.Search(wFilter, wAttributes, wResults) > 0) // { // foreach (LdapEntry wGrp in wResults) // { // wADGroup = new ADGroup(wGrp); // if (wADGroup != null) // wGroups.Add(wADGroup); // } // } // return null; //} /// <summary> /// Resetea la clave de un usuario de LDAP /// </summary> /// <param name="pUserName">Nombre de usuario de la cuenta a la que se resetea la clave</param> /// <param name="pNewPwd">Nuevo Password, en caso de ser NULL, no se resetea la cuenta, se realizan el resto de las acciones</param> /// <param name="pForceChangeOnFirstLogon">Cuando es true, fuerza al usuario a cambiar la clave especificada en el próximo login</param> /// <param name="pUnlockAccount">Cuando es true, desbloquea la cuenta</param> //public void ResetPwd(string pUserName, string pNewPwd, bool pForceChangeOnFirstLogon, bool pUnlockAccount) //{ // String wUserDN = GetUserDN(pUserName); // _LdapWrapper.SetPassword(wUserDN, pNewPwd, pForceChangeOnFirstLogon, pUnlockAccount); //} #endregion #region Métodos Privados /// <summary> /// Obtiene el nombre distinguido de la entrada de LDAP, para un usuario específico /// </summary> /// <param name="pUserName">Nombre de Usuario</param> //private String GetUserDN(string pUserName) //{ // String pUserDN; // String wFilter; // String[] wAttributes; // LdapEntryList wResults; // // parámetros de búsqueda // wFilter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", pUserName); // wAttributes = new String[10]; // wAttributes[0] = ADProperties.DISTINGUISHEDNAME; // wResults = new LdapEntryList(); // if (_LdapWrapper.Search(wFilter, wAttributes, wResults) == 0) // { // throw new TechnicalException("No se encuentra el usuario"); // } // pUserDN = wResults.First()[ADProperties.DISTINGUISHEDNAME].First(); // return pUserDN; //} /// <summary> /// Obtiene la lista de controladores de dominio para un DomainID especificado /// </summary> private List<DomainController> GetDomainControllersByDomainId(String pConnString, Int32 pDomainId) { try { using (SqlDomainControllersDataContext dc = new SqlDomainControllersDataContext(pConnString)) { IEnumerable<DomainController> list = from s in dc.DomainControllers where s.DomainId == pDomainId select new DomainController { DomainId = s.DomainId, HostName = s.DCHostName, Id = s.DCId, Ip = s.DCIp }; return list.ToList<DomainController>(); } } catch (Exception ex) { Fwk.Exceptions.TechnicalException te = new Fwk.Exceptions.TechnicalException("Error al intentar obtener la lista de dominios desde la base de datos: ", ex); LDAPHelper .SetError(te); te.ErrorId = "15004"; throw te; } }
/// <summary> /// Procesa la excepcion original y la retorna. /// </summary> /// <param name="err"><see cref="ServiceError"/></param> /// <returns></returns> public static Exception ProcessException(ServiceError err) { Exception ex; Exception inner = null; if (!String.IsNullOrEmpty(err.InnerMessageException)) { inner = new Exception(err.InnerMessageException); } switch (err.Type) { case "FunctionalException": case "Fwk.Exceptions.FunctionalException": { if (inner != null) { if (!String.IsNullOrEmpty(err.ErrorId)) { ex = new FunctionalException(Convert.ToInt32(err.ErrorId), inner, err.Message); } else { ex = new FunctionalException(null, inner, err.Message); } ((FunctionalException)ex).ServiceName = err.ServiceName; } else { if (!String.IsNullOrEmpty(err.ErrorId)) { ex = new FunctionalException(Convert.ToInt32(err.ErrorId), err.Message); } else { ex = new FunctionalException(err.Message); } ((FunctionalException)ex).ServiceName = err.ServiceName; } ex.Source = err.Source; ((FunctionalException)ex).ErrorId = err.ErrorId; //((FunctionalException)ex).StackTrace = err.StackTrace; break; } case "TechnicalException": case "Fwk.Exceptions.TechnicalException": { ex = new TechnicalException(err.Message, inner); ex.Source = err.Source; ((TechnicalException)ex).ErrorId = err.ErrorId; ((TechnicalException)ex).Machine = err.Machine; ((TechnicalException)ex).UserName = err.UserName; ((TechnicalException)ex).Namespace = err.Namespace; ((TechnicalException)ex).Class = err.Class; ((TechnicalException)ex).Assembly = err.Assembly; ((TechnicalException)ex).ServiceName = err.ServiceName; //((TechnicalException)ex).StackTrace = err.StackTrace; break; } default: { ex = new Exception(err.Message, inner); break; } } return(ex); }