Ejemplo n.º 1
0
        /// <summary>
        /// Cambia la password.-
        /// Si pOldPassword es = null se resetea y luego se asigna pNewPassword
        /// </summary>
        /// <param name="pUserName">Nombre de usuario</param>
        /// <param name="pOldPassword">Password anterior.- Si es en String.Empty se resetea</param>
        /// <param name="pNewPassword">Nueva password</param>
        public void ChangePassword(string pUserName, string pOldPassword, string pNewPassword)
        {
            if (string.IsNullOrEmpty(pOldPassword))
            {
                try
                {
                    pOldPassword = FwkMembership.ResetUserPassword(pUserName, _ProviderName);
                }
                catch (System.Web.Security.MembershipPasswordException)
                {
                    FwkMembership.UnlockUser(pUserName, _ProviderName);
                    pOldPassword = FwkMembership.ResetUserPassword(pUserName, _ProviderName);
                }
                catch (Exception er)
                {
                    throw er;
                }
            }

            if (!FwkMembership.ChangeUserPassword(pUserName,
                                                  pOldPassword,
                                                  pNewPassword, _ProviderName))
            {
                TechnicalException te = new TechnicalException(string.Format(Fwk.Security.Properties.Resource.User_InvalidCredentialsMessage, pUserName));
                ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                te.ErrorId = "4007";
                throw te;
            }
        }
        /// <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);
        }
Ejemplo n.º 3
0
        string GetCnnString()
        {
            if (!String.IsNullOrEmpty(strDb))
            {
                return(strDb);
            }

            if (!String.IsNullOrEmpty(_CnnStringName))
            {
                strDb = System.Configuration.ConfigurationManager.ConnectionStrings[_CnnStringName].ConnectionString;
            }
            else
            {
                strDb = _ConnectionString;
            }

            if (String.IsNullOrEmpty(strDb))
            {
                TechnicalException te = new TechnicalException("Debe especificar cnnStringName en el archivo de configuración.");
                te.ErrorId = "9003";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException <DatabaseTarget>(te);
                throw te;
            }
            return(strDb);
        }
        /// <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;
            }
        }
Ejemplo n.º 5
0
      /// <summary>
      /// Inicializa buscando la info de cada dominio en la bd
      /// </summary>
      /// <param name="domainName"></param>
      /// <param name="cnnStringName"></param>
      /// <param name="performWindowsContextImpersonalization"></param>
      private void Init(string domainName, string cnnStringName, bool performWindowsContextImpersonalization)
      {
          DomainUrlInfo domainUrlInfo = DomainsUrl_Get_FromSp(cnnStringName, domainName);

          if (domainUrlInfo == null)
          {
              throw new Fwk.Exceptions.TechnicalException("No se encontró la información del dominio especificado");
          }

          _LDAPPath       = domainUrlInfo.LDAPPath;
          _LDAPUser       = FilterOutDomain(domainUrlInfo.Usr);
          _LDAPPassword   = domainUrlInfo.Pwd;
          _LDAPDomainName = domainName;
          domainUrlInfo   = null;

          if (performWindowsContextImpersonalization)
          {
              ImpersonateWindowsContext();
          }

          try
          {
              _directoryEntrySearchRoot = new DirectoryEntry(_LDAPPath, _LDAPUser, _LDAPPassword, AuthenticationTypes.Secure);

              _LDAPDomain = GetValue(GetProperty(_directoryEntrySearchRoot, ADProperties.DISTINGUISHEDNAME), "DC");
          }
          catch (TechnicalException e)  // Cuando el usuario no existe o clave erronea
          {
              Exception          te1 = ProcessActiveDirectoryException(e);
              TechnicalException te  = new TechnicalException(string.Format(Resource.AD_Impersonation_Error, te1.Message), te1.InnerException);
              ExceptionHelper.SetTechnicalException <ADWrapper>(te);
              te.ErrorId = "4103";
              throw te;
          }
      }
Ejemplo n.º 6
0
        /// <summary>
        /// Invokes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (GeneralException exception)
            {
                await HandleExceptionAsync(httpContext, exception);
            }
            catch (ArgumentException exception)
            {
                var businessException = new BusinessException(exception.Message, exception);

                await HandleExceptionAsync(httpContext, businessException);
            }
            catch (ElasticsearchClientException exception)
            {
                var technicalException = new TechnicalException("An error has occurred in the request against elasticsearch", exception);
                technicalException.Data.Add("additionalMessage", exception.Message);

                await HandleExceptionAsync(httpContext, technicalException);
            }
            catch (Exception exception)
            {
                var generalException = new GeneralException("An unhandled exception has occurred.", exception);
                await HandleExceptionAsync(httpContext, generalException);
            }
        }
Ejemplo n.º 7
0
        /// <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);
        }
Ejemplo n.º 8
0
        public HttpResponseMessage userMustChangePasswordNextLogon(MustChangePasswordNextLogonReq req)
        {
            try
            {
                var fwk_domain_name = _LDAPService.Get_correct_DomainName(req.domain);


                ActiveDirectoryService.User_MustChangePasswordNextLogon(req.userName, true, fwk_domain_name);

                return(apiHelper.fromObject <String>("La operacion de solicitud de cambio de contraseña en proximo loging se realizó exitosamente."));
            }
            catch (Exception ex)
            {
                var msg = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex, false);
                if (msg.ToLower().Contains("impersonali") || msg.ToLower().Contains("acceso"))
                {
                    TechnicalException t = new TechnicalException("No es posible resetear " + req.userName + " en el dominio " + req.domain
                                                                  + " deberá comunicarse  con CAIS ");
                    ex = t;
                }
                if (msg.Contains("E_ACCESSDENIED"))
                {
                    TechnicalException t = new TechnicalException("No es posible resetear " + req.userName + " en el dominio " + req.domain
                                                                  + " deberá comunicarse con CAIS ");
                    ex = t;
                }
                return(apiHelper.fromEx(ex));
            }
        }
Ejemplo n.º 9
0
        public HttpResponseMessage userChangePassword(userChangePasswordReq req)
        {
            try
            {
                var fwk_domain_name = _LDAPService.Get_correct_DomainName(req.domainName);

                ActiveDirectoryService.User_Reset_Password(req.userName, req.newPassword, fwk_domain_name);

                DAC.MeucciDAC.ReseteoWeb_Log(req.emp_Id, req.userName, req.dom_id, req.userId, "", Common.changePwd, req.host);
                //DAC.MeucciDAC.ReseteoWeb_EnviosMails(req.emp_Id, req.WindowsUser, req.dom_id, req.ResetUserId, Common.resetear, req.host);
                return(apiHelper.fromObject <String>("La contraseña se cambio exitosamente. "));
            }
            catch (Exception ex)
            {
                var msg = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex, false);
                if (msg.ToLower().Contains("impersonali") || msg.ToLower().Contains("acceso"))
                {
                    TechnicalException t = new TechnicalException("No es posible resetear " + req.userName + " en el dominio " + req.domainName
                                                                  + " deberá comunicarse  con CAIS ");
                    ex = t;
                }
                if (msg.Contains("E_ACCESSDENIED"))
                {
                    TechnicalException t = new TechnicalException("No es posible resetear " + req.userName + " en el dominio " + req.domainName
                                                                  + " deberá comunicarse con CAIS ");
                    ex = t;
                }
                return(apiHelper.fromEx(ex));
            }
        }
Ejemplo n.º 10
0
        /// <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;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Elimina una regla de la base de datos
        /// </summary>
        /// <param name="ruleName"></param>
        /// <param name="applicationName"></param>
        /// <param name="connectionStringName"></param>
        /// <returns></returns>
        public static void DeleteRule(string ruleName, string applicationName, string connectionStringName)
        {
            aspnet_Rule waspnet_Rule = null;

            try
            {
                Guid wApplicationId = GetApplication(applicationName, connectionStringName);

                using (Fwk.Security.RuleProviderDataContext dc = new Fwk.Security.RuleProviderDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString))
                {
                    waspnet_Rule = dc.aspnet_Rules.First <aspnet_Rule>(s => s.name.Equals(ruleName.Trim()) && s.ApplicationId.Equals(wApplicationId));
                    dc.aspnet_Rules.DeleteOnSubmit(waspnet_Rule);
                    dc.SubmitChanges();
                }
            }
            catch (TechnicalException tx)
            { throw tx; }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException(string.Format(Resource.Rule_ProblemGetingData_Error, ruleName), ex);
                te.ErrorId = "4003";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                throw te;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Determina si existe una regla.-
        /// </summary>
        /// <param name="pRuleName">Nombre de la regla</param>
        /// <param name="applicationName">Nombre de la aplicación</param>
        /// <param name="connectionStringName">Nombre de la regla</param>
        /// <returns>boolean</returns>
        public static bool ExistRule(string pRuleName, string applicationName, string connectionStringName)
        {
            bool wExist = false;

            try
            {
                Guid wApplicationId = GetApplication(applicationName, connectionStringName);

                using (Fwk.Security.RuleProviderDataContext dc = new Fwk.Security.RuleProviderDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString))
                {
                    wExist = dc.aspnet_Rules.Any(s => s.name.Trim().Equals(pRuleName.Trim()) && s.ApplicationId == wApplicationId);
                }


                return(wExist);
            }
            catch (TechnicalException tx)
            { throw tx; }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException(string.Format(Resource.Rule_ProblemGetingData_Error, pRuleName), ex);
                te.ErrorId = "4004";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                throw te;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ruleName"></param>
        /// <param name="applicationName"></param>
        /// <param name="connectionStringName"></param>
        /// <returns></returns>
        public static FwkAuthorizationRule GetRule(string ruleName, string applicationName, string connectionStringName)
        {
            aspnet_Rule waspnet_Rule = null;

            try
            {
                Guid wApplicationId = GetApplication(applicationName, connectionStringName);

                using (Fwk.Security.RuleProviderDataContext dc = new Fwk.Security.RuleProviderDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString))
                {
                    if (dc.aspnet_Rules.Any <aspnet_Rule>(s => s.name.Equals(ruleName.Trim()) && s.ApplicationId == wApplicationId))
                    {
                        waspnet_Rule = dc.aspnet_Rules.First <aspnet_Rule>(s => s.name.Equals(ruleName.Trim()) && s.ApplicationId == wApplicationId);
                    }
                    FwkAuthorizationRule rule = new FwkAuthorizationRule(waspnet_Rule.name, waspnet_Rule.expression, waspnet_Rule.ApplicationId.Value);
                    rule.Description = waspnet_Rule.Description;
                    rule.Id          = waspnet_Rule.Id;
                    return(rule);
                }
            }
            catch (TechnicalException tx)
            { throw tx; }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException(string.Format(Resource.Rule_ProblemGetingData_Error, ruleName), ex);
                te.ErrorId = "4003";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                throw te;
            }
        }
Ejemplo n.º 14
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            lblError.Text = "NO Error";
            try
            {
                if (SetAD(false))
                {
                    TechnicalException logError = null;

                    lblResult.Text = _ADHelper.User_Logon(txtUsr.Text, txtpassword.Text, out logError).ToString();

                    if (logError != null)
                    {
                        lblError.Text = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(logError);
                    }
                    else
                    {
                        lblError.Text = "NO Error";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Ejecuta un servicio de negocio.
        /// </summary>
        /// <param name="providerName">Nombre del proveedor de metadata de servicios.-</param>
        /// <param name="serviceName">Nombre del servicio de negocio.</param>
        /// <param name="pXmlRequest">XML 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 static string ExecuteService(string providerName, string serviceName, string pXmlRequest)
        {
            string wResult;

            ServiceConfiguration wServiceConfiguration = FacadeHelper.GetServiceConfiguration(providerName, serviceName);

            IServiceContract wRequest = (IServiceContract)ReflectionFunctions.CreateInstance(wServiceConfiguration.Request);

            if (wRequest == null)
            {
                TechnicalException te = new TechnicalException(string.Concat("El despachador de servicio no pudo continuar debido\r\na que no logro construir el requets del servicio: ",
                                                                             serviceName, "\r\nVerifique que se encuentre los componentes necesarios para su ejecucion esten en el servidor de aplicación. "));

                Fwk.Exceptions.ExceptionHelper.SetTechnicalException <StaticFacade>(te);

                if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName))
                {
                    te.Source = "Despachador de servicios en " + Environment.MachineName;
                }
                else
                {
                    te.Source = ConfigurationsHelper.HostApplicationName;
                }

                te.ErrorId = "7003";
                throw te;
            }
            wRequest.SetXml(pXmlRequest);

            wResult = ExecuteService(providerName, wRequest).GetXml();

            return(wResult);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Obtiene una lista de usuarios
        /// </summary>
        /// <param name="providerName">Nombre del proveedor de membership</param>
        /// <returns>lista de <see cref="User"/></returns>
        public static List <User> GetAllUsers(string providerName)
        {
            SqlMembershipProvider provider = GetSqlMembershipProvider(providerName);

            List <User> wUsersList = new List <User>();
            int         pageSize   = 10;
            int         totalUsers;
            int         totalPages;


            try
            {
                MembershipUserCollection list = provider.GetAllUsers(0, pageSize, out totalUsers);
                totalPages = ((totalUsers - 1) / pageSize) + 1;
                AddUsers(wUsersList, list);
                for (int currentPage = 1; currentPage < totalPages; currentPage++)
                {
                    list = provider.GetAllUsers(currentPage, pageSize, out totalUsers);
                    AddUsers(wUsersList, list);
                }
            }
            catch (Exception ex)
            {
                Fwk.Exceptions.TechnicalException te = new TechnicalException("Fwk membership user error ", ex);
                ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                te.ErrorId = "4000";
                throw te;
            }

            return(wUsersList);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Obtiene una lista de Roles  de un usuario
 /// </summary>
 /// <param name="userName">Nombre de Usuario</param>
 /// <param name="providerName">Nombre del proveedor de membership</param>
 /// <returns>String[] con los roles del usuario</returns>
 public static String[] GetRolesForUser_StringArray(String userName, string providerName)
 {
     if (string.IsNullOrEmpty(providerName))
     {
         providerName = GetSqlMembershipProvider(providerName).Name;
     }
     try
     {
         return(GetRoleProvider(providerName).GetRolesForUser(userName));
     }
     catch (TechnicalException err)
     {
         throw err;
     }
     catch (System.Configuration.Provider.ProviderException pe)
     {
         TechnicalException te = new TechnicalException(
             String.Format("El proveedor SqlMembership {0} lanzo el siguiente error: {1}", providerName, pe.Message)
             );
         ExceptionHelper.SetTechnicalException <FwkMembership>(te);
         te.ErrorId = "4000";
         throw te;
     }
     catch (Exception ex)
     {
         TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex);
         ExceptionHelper.SetTechnicalException <FwkMembership>(te);
         te.ErrorId = "4000";
         throw te;
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Obtiene una lista de usuarios de un determinado rol.- Solo obtiene nombre de usuario
        /// </summary>
        /// <param name="roleName">Nombre del rol</param>
        /// <param name="providerName">Nombre del proveedor de membership</param>
        /// <returns>lista de <see cref="User"/> </returns>
        public static List <User> GetUsersInRole(String roleName, string providerName)
        {
            SqlMembershipProvider wProvider = GetSqlMembershipProvider(providerName);

            User        wUserByApp;
            List <User> wUsersList = new List <User>();

            try
            {
                foreach (string s in Roles.Providers[wProvider.Name].GetUsersInRole(roleName))
                {
                    wUserByApp = new User(s);
                    wUsersList.Add(wUserByApp);
                }
            }
            catch (Exception ex)
            {
                Fwk.Exceptions.TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex);
                ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                te.ErrorId = "4000";
                throw te;
            }

            return(wUsersList);
        }
Ejemplo n.º 19
0
        static void chkExp(int?alerSince, DateTime expTime)
        {
            DateTime today = DateTime.Now;

            //Si ya paso
            if (DateTime.Compare(today, expTime) >= 0)
            {
                TechnicalException te = new TechnicalException("Your pelsoft license has expired . Please contact your suppor software provider for renew");
                te.Source  = "Pelsoft Lic manager";
                te.ErrorId = "101";
                throw te;
            }

            TimeSpan dateDif = today - expTime;

            //Si faltan 5= o menos dias que aviar desde
            //alerSince >= days => 0
            if (alerSince >= (dateDif.Days * -1))
            {
                TechnicalException te = new TechnicalException(string.Format("Your pelsoft license will expire in {0} days. Please contact your suppor software provider for renew", dateDif.Days * -1));
                te.Source  = "Pelsoft Lic manager";
                te.ErrorId = "101";
                throw te;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Asigna roles a un usuario
        /// </summary>
        /// <param name="pRolList">Lista de roles</param>
        /// <param name="userName">Usuario</param>
        /// <param name="providerName">Nombre del proveedor de membership</param>
        public static void CreateRolesToUser(RolList pRolList, String userName, string providerName)
        {
            SqlMembershipProvider wProvider = GetSqlMembershipProvider(providerName);

            try
            {
                Roles.Providers[wProvider.Name].AddUsersToRoles(new string[] { userName }, pRolList.GetArrayNames());

                //foreach (Rol rol in pRolList)
                //{
                //    if (!Roles.Providers[providerName].IsUserInRole(userName, rol.RolName))
                //    {
                //        //Roles.AddUserToRoles(userName, new string[] { rol.RolName });

                //        Roles.Providers[providerName].AddUsersToRoles(new string[] { userName }, new string[] { rol.RolName });
                //    }
                //}
            }
            catch (Exception ex)
            {
                Fwk.Exceptions.TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex);
                ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                te.ErrorId = "4000";
                throw te;
            }
        }
        /// <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;


            try
            {
                using (SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[GetProvider_ConnectionStringName(providerName)].ConnectionString))
                    using (SqlCommand cmd = new SqlCommand("aspnet_Personalization_GetApplicationId", cnn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("@ApplicationName", pCompanyId);
                        SqlParameter param = new SqlParameter();
                        param.ParameterName = "@ApplicationId";
                        param.SqlDbType     = SqlDbType.UniqueIdentifier;
                        param.Direction     = ParameterDirection.Output;

                        cmd.Parameters.Add(param);
                        cnn.Open();

                        cmd.ExecuteNonQuery();

                        wApplicationId = cmd.Parameters["@ApplicationId"].ToString();
                        return(wApplicationId);
                    }
            }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException(Fwk.Security.Properties.Resource.MembershipSecurityGenericError, ex);
                ExceptionHelper.SetTechnicalException <FwkMembership>(te);
                te.ErrorId = "4000";
                throw te;
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="provider">Proveedor de configuracion</param>
        /// <param name="group">Grupo</param>
        internal static void AddGroup(ConfigProviderElement provider, Group group)
        {
            ConfigurationFile wConfigurationFile = GetConfig(provider);


            wConfigurationFile.Groups.Add(group);
            fwk_ConfigManager confg;

            try
            {
                using (FwkDatacontext dc = new FwkDatacontext(GetCnnString(provider)))
                {
                    foreach (Key k in group.Keys)
                    {
                        confg = new fwk_ConfigManager();
                        confg.ConfigurationFileName = provider.BaseConfigFile;
                        confg.key       = k.Name;
                        confg.encrypted = k.Encrypted;
                        confg.value     = k.Value.Text;
                        confg.group     = group.Name;
                        dc.fwk_ConfigManagers.InsertOnSubmit(confg);
                    }
                    dc.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException("Problemas con Fwk.Configuration al realizar operaciones con la base de datos \r\n", ex);
                ExceptionHelper.SetTechnicalException <DatabaseConfigManager>(te);
                te.ErrorId = "8200";
                throw te;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Busca un criptographer determinado por medio de su nombre de archivo de encriptacion y tipo de algoritmo simetrico
        /// </summary>
        /// <typeparam name="T">Tipo de algoritmo simetrico</typeparam>
        /// <param name="keyFileName">nombre de archivo de encriptacion </param>
        /// <returns>Argoritmo <see cref="SymetriCypher"/></returns>
        public static SymetriCypher <T> Get <T>(string keyFileName) where T : SymmetricAlgorithm
        {
            if (string.IsNullOrEmpty(keyFileName))
            {
                TechnicalException te = new TechnicalException("La clave de encriptacion no puede ser nula");
                ExceptionHelper.SetTechnicalException <SymetriCypher <T> >(te);
                te.ErrorId = "4401";
                throw te;
            }

            SymetriCypher <T> symetriCypher = null;

            if (list.ContainsKey(string.Concat(keyFileName, typeof(T).FullName)))
            {
                symetriCypher = (SymetriCypher <T>)list[string.Concat(keyFileName, typeof(T).FullName)];
            }
            else
            {
                symetriCypher             = new SymetriCypher <T>();
                symetriCypher.KeyFileName = keyFileName;
                list.Add(string.Concat(keyFileName, typeof(T).FullName), symetriCypher);
            }

            return(symetriCypher);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Cambia el nombre de un grupo.-
        /// </summary>
        /// <param name="provider">Proveedor de configuracion</param>
        /// <param name="groupName">Nombre del grupo</param>
        /// <param name="newGroupName">Nuevo nombre del grupo</param>
        internal static void ChangeGroupName(ConfigProviderElement provider, string groupName, string newGroupName)
        {
            //ConfigurationFile wConfigurationFile = GetConfig(provider);
            try
            {
                using (FwkDatacontext dc = new FwkDatacontext(GetCnnString(provider)))
                {
                    var configs = dc.fwk_ConfigManagers.Where(p =>
                                                              p.group.Equals(groupName) &&
                                                              p.ConfigurationFileName.Equals(provider.BaseConfigFile));

                    foreach (fwk_ConfigManager confg in configs)
                    {
                        confg.group = newGroupName;
                    }
                    dc.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException("Problemas con Fwk.Configuration al realizar operaciones con la base de datos \r\n", ex);
                ExceptionHelper.SetTechnicalException <DatabaseConfigManager>(te);
                te.ErrorId = "8200";
                throw te;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Solo chequea si existe el proveedor. Si no, lanza una excepción.-
        /// </summary>
        /// <param name="providerName"></param>
        static void CheckWrapperExist(string providerName, IServiceContract res)
        {
            //Dado que el proveedor por defecto es agregado como String.Empty
            if (String.IsNullOrEmpty(providerName))
            {
                providerName = _DefaultProviderName;
            }

            if (!_WraperPepository.ContainsKey(providerName))
            {
                TechnicalException te;
                if (providerName.Equals(_DefaultProviderName))
                {
                    te = new TechnicalException(string.Concat("El proveedor de configuración del wrapper por defecto del lado del cliente, no existe, verifique en el archivo de configuracion si existe la seccion FwkWrapper y el proveedor por defecto"));
                }
                else
                {
                    te = new TechnicalException(string.Concat("El proveedor de configuración del wrapper ", providerName, " del lado del cliente, no existe, verifique en el archivo de configuracion si existe la seccion FwkWrapper y el proveedor mencionado"));
                }

                te.ErrorId = "6000";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(WrapperFactory));
                res.Error = ProcessConnectionsException.Process(te);
            }
        }
Ejemplo n.º 26
0
 /// <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)
 {
     try
     {
         using (FwkDatacontext dc = new FwkDatacontext(GetCnnString(provider)))
         {
             var prop = dc.fwk_ConfigManagers.Where(config =>
                                                    config.ConfigurationFileName.ToLower().Equals(provider.BaseConfigFile.ToLower()) &&
                                                    config.group.ToLower().Equals(groupName.ToLower()) &&
                                                    config.key.ToLower().Equals(propertyName.ToLower())
                                                    ).FirstOrDefault <fwk_ConfigManager>();
             prop.value     = property.Value.Text;
             prop.encrypted = property.Encrypted;
             prop.key       = property.Name;
             dc.SubmitChanges();
         }
     }
     catch (Exception ex)
     {
         TechnicalException te = new TechnicalException("Problemas con Fwk.Configuration al realizar operaciones con la base de datos \r\n", ex);
         ExceptionHelper.SetTechnicalException <DatabaseConfigManager>(te);
         te.ErrorId = "8200";
         throw te;
     }
 }
Ejemplo n.º 27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="eventIdList"></param>
 public override void Remove(List <Guid> eventIdList)
 {
     using (SqlConnection wCnn = new SqlConnection(GetCnnString()))
         using (SqlCommand wCmd = new SqlCommand())
         {
             try
             {
                 wCnn.Open();
                 wCmd.Connection  = wCnn;
                 wCmd.CommandType = CommandType.StoredProcedure;
                 wCmd.CommandText = "fwk_Logs_d";
                 SqlParameter wParam = wCmd.Parameters.Add("Id", SqlDbType.UniqueIdentifier);
                 foreach (Guid id in eventIdList)
                 {
                     wParam.Value = id;
                     wCmd.ExecuteNonQuery();
                 }
             }
             catch (Exception ex)
             {
                 TechnicalException te = new TechnicalException("Error de Fwk.Logging al intentar elimiar log en base de datos", ex);
                 te.ErrorId = "9004";
                 Fwk.Exceptions.ExceptionHelper.SetTechnicalException <DatabaseTarget>(te);
                 throw te;
             }
         }
 }
Ejemplo n.º 28
0
        internal static LoogonUserResult User_Logon(string userName, string password, string domain)
        {
            LoogonUserResult loogonUserResult = new LoogonUserResult();

            loogonUserResult.Autenticated = false;
            try
            {
                LDAPHelper         _ADHelper = new LDAPHelper(domain, ActiveDirectoryService.CnnStringName, true, false);
                TechnicalException logError  = null;

                loogonUserResult.LogResult = _ADHelper.User_Logon(userName, password, out logError).ToString();

                if (logError != null)
                {
                    loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(logError);
                }
                else
                {
                    loogonUserResult.ErrorMessage = string.Empty;
                    loogonUserResult.Autenticated = true;
                }
            }
            catch (Exception ex)
            {
                loogonUserResult.ErrorMessage = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex);
            }
            return(loogonUserResult);
        }
Ejemplo n.º 29
0
        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);
        }
Ejemplo n.º 30
0
        /// <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;
            }
        }