コード例 #1
0
ファイル: Test.cs プロジェクト: iringtools/samples
        public ObjectDataLayerTest()
        {
            _settings = new NameValueCollection();

            _settings["ProjectName"] = "12345_000";
            _settings["XmlPath"] = @"..\ObjectDataLayer.NUnit\12345_000\";
            _settings["ApplicationName"] = "OBJ";
            _settings["TestMode"] = "WriteFiles"; //UseFiles/WriteFiles

            _baseDirectory = Directory.GetCurrentDirectory();
            _baseDirectory = _baseDirectory.Substring(0, _baseDirectory.LastIndexOf("\\bin"));
            _settings["BaseDirectoryPath"] = _baseDirectory;
            Directory.SetCurrentDirectory(_baseDirectory);

            _adapterSettings = new AdapterSettings();
            _adapterSettings.AppendSettings(_settings);

            string appSettingsPath = String.Format("{0}{1}.{2}.config",
                _adapterSettings["XmlPath"],
                _settings["ProjectName"],
                _settings["ApplicationName"]
            );

            if (File.Exists(appSettingsPath))
            {
                AppSettingsReader appSettings = new AppSettingsReader(appSettingsPath);
                _adapterSettings.AppendSettings(appSettings);
            }

            _dataLayer = new ObjectDataLayer(_adapterSettings);
        }
コード例 #2
0
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        // Get the key from config file
        string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
        //System.Windows.Forms.MessageBox.Show(key);
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
コード例 #3
0
        public SPRSynchronizationUtility(StreamWriter logFile, string scope, string app)
        {
            _logFile = logFile;
            _settings = new NameValueCollection();
            _settings["XmlPath"] = @".\App_Data\";

            _baseDirectory = Directory.GetCurrentDirectory();

            if (_baseDirectory.Contains("\\bin"))
            {
                _baseDirectory = _baseDirectory.Substring(0, _baseDirectory.LastIndexOf("\\bin"));
                Directory.SetCurrentDirectory(_baseDirectory);
            }
            _settings["BaseDirectoryPath"] = _baseDirectory;
            _settings["ProjectName"] = scope;
            _settings["ApplicationName"] = app;

            _adapterSettings = new AdapterSettings();
            _adapterSettings.AppendSettings(_settings);
            string appSettingsPath = String.Format("{0}{1}.{2}.config",
                _adapterSettings["XmlPath"],
                _settings["ProjectName"],
                _settings["ApplicationName"]
            );

            if (File.Exists(appSettingsPath))
            {
                AppSettingsReader appSettings = new AppSettingsReader(appSettingsPath);
                _adapterSettings.AppendSettings(appSettings);
            }

            _dataLayer = new SPRDataLayer(_adapterSettings);
            _dataLayer.GetDictionary();
            _dataLayer.EnableLogging(_logFile);
        }
コード例 #4
0
    public static string Decrypt(string cipherString, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(cipherString);
        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        string key = (string)settingsReader.GetValue("search", typeof(String));
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
            
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                     
        tdes.Clear();
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
コード例 #5
0
ファイル: Test.cs プロジェクト: iringtools/rest_dl
        public Tests()
        {
            _objectType = "Function";

               string baseDir = Directory.GetCurrentDirectory();
               Directory.SetCurrentDirectory(baseDir.Substring(0, baseDir.LastIndexOf("\\bin")));

               AdapterSettings adapterSettings = new AdapterSettings();
               adapterSettings.AppendSettings(new AppSettingsReader("App.config"));

               FileInfo log4netConfig = new FileInfo("Log4net.config");
               log4net.Config.XmlConfigurator.Configure(log4netConfig);

               string twConfigFile = String.Format("{0}{1}.{2}.config",
             adapterSettings["AppDataPath"],
             adapterSettings["ProjectName"],
             adapterSettings["ApplicationName"]
               );

               AppSettingsReader twSettings = new AppSettingsReader(twConfigFile);
               adapterSettings.AppendSettings(twSettings);

               _dataLayer = new Bechtel.DataLayer.RestDataLayer2(adapterSettings);

               _filter = Utility.Read<DataFilter>(adapterSettings["FilterPath"]);

               //_scenarios = Utility.Read<Scenarios>("Scenarios.xml");
               _objectType = adapterSettings["ObjectType"];
               _modifiedProperty = adapterSettings["ModifiedProperty"];
               _modifiedValue = adapterSettings["ModifiedValue"];
               _objectDefinition = GetObjectDefinition(_objectType);
        }
コード例 #6
0
ファイル: d3.cs プロジェクト: akmaplus/My_sources_cs
    static void Main(string[] args)
    {
        AppSettingsReader asr = new AppSettingsReader();   // Получаем специальные данные из файла *.config.

        int repeatCount   =   (int)     asr.GetValue("RepeatCount", typeof(int)     );

        string textColor  =   (string)  asr.GetValue("TextColor",   typeof(string)  );

        Console.Write("RepeatCount:{0} TextColor:{1}", repeatCount, textColor);
    }
コード例 #7
0
    public static string Decrypt(string cipherString, bool useHashing)
    {
        /*
         *  Reference to: Syed Moshiur - Software Developer
         *  http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C
         *
         */
        byte[] keyArray;
        //get the byte code of the string

        byte[] toEncryptArray = Convert.FromBase64String(cipherString);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();
        //Get your key from config file to open the lock!
        string key = (string)settingsReader.GetValue("SecurityKey",
                                                     typeof(String));

        if (useHashing)
        {
            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //release any resource held by the MD5CryptoServiceProvider

            hashmd5.Clear();
        }
        else
        {
            //if hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(key);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(
                             toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
コード例 #8
0
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        /*
         *  Reference to: Syed Moshiur - Software Developer
         *  http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C
         *
         */
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();
        // Get the key from config file

        string key = (string)settingsReader.GetValue("SecurityKey",
                                                         typeof(String));

        //If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //Always release the resources and flush data
            // of the Cryptographic service provide. Best Practice

            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)
        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)

        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        //transform the specified region of bytes array to resultArray
        byte[] resultArray =
          cTransform.TransformFinalBlock(toEncryptArray, 0,
          toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
コード例 #9
0
ファイル: Test.cs プロジェクト: iringtools/sp_3d
        public SP3DDataLayerTest()
        {
            _settings = new NameValueCollection();

            _settings["XmlPath"] = @".\12345_000\";
            _settings["ProjectName"] = "12345_000";
            _settings["ApplicationName"] = "SP3D";

            _baseDirectory = Directory.GetCurrentDirectory();
            _baseDirectory = _baseDirectory.Substring(0, _baseDirectory.LastIndexOf("\\bin"));
            _settings["BaseDirectoryPath"] = _baseDirectory;
            Directory.SetCurrentDirectory(_baseDirectory);

            _adapterSettings = new AdapterSettings();
            _adapterSettings.AppendSettings(_settings);

            string appSettingsPath = String.Format("{0}12345_000.SP3D.config",
                _adapterSettings["XmlPath"]
            );

            if (File.Exists(appSettingsPath))
            {
                AppSettingsReader appSettings = new AppSettingsReader(appSettingsPath);
                _adapterSettings.AppendSettings(appSettings);
            }

            var ninjectSettings = new NinjectSettings { LoadExtensions = false };
            _kernel = new StandardKernel(ninjectSettings);

            _kernel.Load(new XmlExtensionModule());

            string relativePath = String.Format(@"{0}BindingConfiguration.{1}.{2}.xml",
            _settings["XmlPath"],
            _settings["ProjectName"],
            _settings["ApplicationName"]
              );

            //Ninject Extension requires fully qualified path.
            string bindingConfigurationPath = Path.Combine(
              _settings["BaseDirectoryPath"],
              relativePath
            );

            _kernel.Load(bindingConfigurationPath);

               // _sp3dDataLayer = _kernel.Get<SP3DDataLayer>(); This will reset the new updated adaptersettings with default values.

            _sp3dDataLayer = new SP3DDataLayer(_adapterSettings);
        }
コード例 #10
0
    public void lanzarReporteComprobanteDeCaja(int consecutivo, int folio, int caja, DateTime foperacion)
    {
        //short consecutivo = mc.Consecutivo;
        //int folio = mc.Folio;
        //short caja = mc.Caja;
        //string FOperacion = Convert.ToString(mc.FOperacion);
        AppSettingsReader settings = new AppSettingsReader();

        string strReporte = Server.MapPath("~/") + settings.GetValue("RutaComprobanteDeCaja", typeof(string));

        if (!File.Exists(strReporte))
        {
            return;
        }
        try
        {
            string strServer   = settings.GetValue("Servidor", typeof(string)).ToString();
            string strDatabase = settings.GetValue("Base", typeof(string)).ToString();
            usuario = (SeguridadCB.Public.Usuario)HttpContext.Current.Session["Usuario"];

            string    strUsuario = usuario.IdUsuario.Trim();
            string    strPW      = usuario.ClaveDesencriptada;
            ArrayList Par        = new ArrayList();

            Par.Add("@Consecutivo=" + consecutivo);
            Par.Add("@Folio=" + folio);
            Par.Add("@Caja=" + caja);
            Par.Add("@FOperacion=" + foperacion);

            ClaseReporte Reporte = new ClaseReporte(strReporte, Par, strServer, strDatabase, strUsuario, strPW);
            HttpContext.Current.Session["RepDoc"]            = Reporte.RepDoc;
            HttpContext.Current.Session["ParametrosReporte"] = Par;
            Nueva_Ventana("../../Reporte/Reporte.aspx", "Carta", 0, 0, 0, 0);
            Reporte = null;
        }
        catch (Exception ex)
        {
            objApp.ImplementadorMensajes.MostrarMensaje("Error: " + ex.Message);
        }
    }
コード例 #11
0
        public static string Decrypt(string cipherString)
        {
            byte[] keyArray;
            //get the byte code of the string

            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            System.Configuration.AppSettingsReader settingsReader =
                new AppSettingsReader();
            //Get your key from config file to open the lock!
            string key = SecuredKey;//(string)settingsReader.GetValue("SecurityKey",   typeof(String));

            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashsha1 = new MD5CryptoServiceProvider();

            keyArray = hashsha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //release any resource held by the MD5CryptoServiceProvider

            hashsha1.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes.
            //We choose ECB(Electronic code Book)

            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(
                toEncryptArray, 0, toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor
            tdes.Clear();
            //return the Clear decrypted TEXT
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
コード例 #12
0
        private decimal?ObtenerPrecioCombustible()
        {
            try {
                if (this.vista.UnidadOperativaID == null)
                {
                    throw new Exception("El indentificador de la unidad operativa no debe ser nulo");
                }
                AppSettingsReader n = new AppSettingsReader();
                ConfiguracionUnidadOperativaBO configUO = null;
                int moduloID = (int)this.vista.ModuloID;

                ModuloBO modulo = new ModuloBO()
                {
                    ModuloID = moduloID
                };
                ModuloBR        moduloBR = new ModuloBR();
                List <ModuloBO> modulos  = moduloBR.ConsultarCompleto(dctx, modulo);

                if (modulos.Count > 0)
                {
                    modulo = modulos[0];

                    List <ConfiguracionUnidadOperativaBO> lstConfigUO = new ModuloBR().ConsultarConfiguracionUnidadOperativa(this.dctx, new ConfiguracionUnidadOperativaBO()
                    {
                        UnidadOperativa = new UnidadOperativaBO()
                        {
                            Id = this.vista.UnidadOperativaID
                        }
                    }, this.vista.ModuloID);
                    configUO = lstConfigUO.FirstOrDefault();
                }
                if (configUO != null)
                {
                    return(configUO.PrecioUnidadCombustible);
                }
                return(null);
            } catch (Exception ex) {
                throw new Exception(nombreClase + ".ObtenerPrecioCombustible: Error al consultar el precio del combustible. " + ex.Message);
            }
        }
コード例 #13
0
ファイル: ConfigReader.cs プロジェクト: ekohlenberg/lift
        public static string getString(string property, string defaultValue)
        {
            string result = defaultValue;

            lock ( sync )
            {
                if (properties.ContainsKey(property))
                {
                    result = (string)properties[property];
                }
                else
                {
                    try
                    {
                        if (settingsReader == null)
                        {
                            settingsReader = new AppSettingsReader();
                        }
                        object o = settingsReader.GetValue(property, typeof(System.Object));
                        if (o != null)
                        {
                            result = o.ToString();
                        }
                        else
                        {
                            result = defaultValue;
                        }

                        properties.Add(property, result);
                    }
                    catch
                    {
                        Logger.log(Logger.Level.WARNING, "Missing config property: " + property);
                        properties.Add(property, defaultValue);
                    }
                }
            }

            return(result);
        }
コード例 #14
0
        public ActionResult ResetPassword(int id, string password, string username)
        {
            var user = _userService.GetById(id);

            if (user != null)
            {
                string randomPassword = password;
                user.Password = PasswordHelper.HashString(randomPassword, user.UserName);
                _userService.Update(user);

                var webLink                 = AppSettingsReader.GetValue("Url", typeof(String)) as string;
                var imgSrc                  = webLink + "/Content/quickspatch/img/logo-o.svg";
                var urlChangePass           = webLink + "/Authentication/ChangePasswordCourier?code=" + PasswordHelper.HashString(id.ToString(), user.UserName);
                var fromEmail               = AppSettingsReader.GetValue("EmailFrom", typeof(String)) as string;
                var webapi                  = AppSettingsReader.GetValue("WebApiUrlFranchisee", typeof(String)) as string;
                var displayName             = AppSettingsReader.GetValue("EmailFromDisplayName", typeof(String)) as string;
                var franchiseeConfiguration = _franchiseeConfigurationService.GetFranchiseeConfiguration();
                var franchiseeName          = franchiseeConfiguration != null ? franchiseeConfiguration.Name : "";
                var emailContent            = TemplateHelpper.FormatTemplateWithContentTemplate(
                    TemplateHelpper.ReadContentFromFile(TemplateConfigFile.RestorePasswordCourierTemplate, true),
                    new
                {
                    img_src         = imgSrc,
                    full_name       = Framework.Utility.CaculatorHelper.GetFullName(user.FirstName, user.MiddleName, user.LastName),
                    web_link        = webLink,
                    user_name       = user.UserName,
                    password        = randomPassword,
                    url_change_pass = urlChangePass,
                    franchisee_Name = franchiseeName,
                    web_api         = webapi
                });
                // send email
                var logo = franchiseeConfiguration != null ? franchiseeConfiguration.Logo : new byte[0];
                _emailHandler.SendEmailSsl(fromEmail, new[] { user.Email }, SystemMessageLookup.GetMessage("SubjectToSendEmailForCreateUser"),
                                           emailContent, logo, true, displayName);
            }


            return(Json(true, JsonRequestBehavior.AllowGet));
        }
コード例 #15
0
    //Nueva funcionalidad
    protected void lnkInforme_Click(object sender, EventArgs e)
    {
        AppSettingsReader settings      = new AppSettingsReader();
        int           folioConciliacion = Convert.ToInt32(grvConciliacion.DataKeys[Convert.ToInt32(fldIndiceConcilacion.Value.Trim())].Value);
        cConciliacion conciliacion      = listaConciliaciones.Find(x => x.Folio == folioConciliacion);
        string        strReporte        = Server.MapPath("~/") + settings.GetValue("RutaReporteInformeContabilidad", typeof(string));

        if (!File.Exists(strReporte))
        {
            return;
        }
        try
        {
            string strServer   = settings.GetValue("Servidor", typeof(string)).ToString();
            string strDatabase = settings.GetValue("Base", typeof(string)).ToString();

            usuario = (SeguridadCB.Public.Usuario)HttpContext.Current.Session["Usuario"];
            string    strUsuario = usuario.IdUsuario.Trim();
            string    strPW      = usuario.ClaveDesencriptada;
            ArrayList Par        = new ArrayList();

            Par.Add("@CorporativoConciliacion=" + conciliacion.Corporativo);
            Par.Add("@SucursalConciliacion=" + conciliacion.Sucursal);
            Par.Add("@FolioConciliacion=" + conciliacion.Folio);
            Par.Add("@MesConciliacion=" + conciliacion.Mes);
            Par.Add("@AñoConciliacion=" + conciliacion.Año);

            ClaseReporte Reporte = new ClaseReporte(strReporte, Par, strServer, strDatabase, strUsuario, strPW);
            //Reporte.Imprimir_Reporte();
            HttpContext.Current.Session["RepDoc"]            = Reporte.RepDoc;
            HttpContext.Current.Session["ParametrosReporte"] = Par;
            Nueva_Ventana("Reporte/Reporte.aspx", "Carta", 0, 0, 0, 0);
            //if (Reporte.Hay_Error) Mensaje("Error.", Reporte.Error);
            Reporte = null;
        }
        catch (Exception ex)
        {
            objApp.ImplementadorMensajes.MostrarMensaje("Error: " + ex.Message);
        }
    }
コード例 #16
0
        /// <summary>
        /// Constructor for Login (2 parameters)
        /// </summary>
        public UserConfiguration(string uID, string pw)
        {
            userID           = uID;
            password         = pw;
            connectionString = "";
            authentication   = "";
            reportDirectory  = "";

            // get all the config information that you're going to need once and just return the values when
            // the getter properties are called

            try
            {
                AppSettingsReader asr = new AppSettingsReader();

                // use sql or nt authentication
                authentication = (asr.GetValue("AuthMode", authentication.GetType())).ToString();

                // connection string
                if (authentication.ToLower().Equals("nt"))
                {
                    connectionString = (asr.GetValue("dbNTConnectionString", connectionString.GetType())).ToString();
                }
                else
                {
                    connectionString = (asr.GetValue("dbConnectionString", connectionString.GetType())).ToString() +
                                       ";user ID=" + userID + ";password="******"crystalReportPath", authentication.GetType())).ToString();
            }

            catch (Exception e)
            {
                // log the exception
                throw;
            }
        }
コード例 #17
0
        public Products()
        {
            InitializeComponent();

            // look for SimpleTextAuditorTxtFileName setting at .config file
            AppSettingsReader appConfiguration    = new AppSettingsReader();
            string            outputAuditFileName = string.Empty;

            try
            {
                outputAuditFileName = (string)appConfiguration.GetValue("SimpleTextAuditorTxtFileName", typeof(string));
            }

            // SimpleTextAuditorTxtFileName not found! use default filename
            catch (InvalidOperationException)
            {
                outputAuditFileName = "c:\\noraudit.txt";
            }

            // show fileName to user
            lblFileName.Text = outputAuditFileName;
        }
コード例 #18
0
 /// <summary>
 /// Genera el reporte para la impresión de la plantilla del Check List
 /// </summary>
 public void ImprimirPlantillaCheckListRD()
 {
     try
     {
         ContratoRDBR      contratoBR = new ContratoRDBR();
         AppSettingsReader n          = new AppSettingsReader();
         int moduloID = Convert.ToInt32(n.GetValue("ModuloID", typeof(int)));
         Dictionary <string, Object> datosImprimir = contratoBR.ObtenerPlantillaCheckList(dataContext, new ContratoRDBO {
             Sucursal = new SucursalBO {
                 UnidadOperativa = new UnidadOperativaBO {
                     Id = this.vista.UnidadAdscripcionID.Value
                 }
             }
         }, moduloID);
         vista.EstablecerPaqueteNavegacionImprimir("CU012", datosImprimir);
         vista.IrAImprimir();
     }
     catch (Exception ex)
     {
         throw new Exception(nombreClase + ".ImprimirPlantillaCheckListRD: Inconsistencia al intentar cargar los datos a imprimir." + ex.Message);
     }
 }
コード例 #19
0
 private void PopulateComboBox()
 {
     try
     {
         AppSettingsReader configReader = new AppSettingsReader();
         connString = (string)configReader.GetValue("connString", typeof(string));
         SqlConnection cn = new SqlConnection(connString);
         cn.Open();
         SqlCommand    cmd = new SqlCommand("SELECT Name FROM Person.CityDetails ORDER BY Name", cn);
         SqlDataReader dr  = cmd.ExecuteReader();
         while (dr.Read())
         {
             comboBox1.Items.Add(dr[0].ToString());
         }
         cn.Close();
     }
     catch (Exception e)
     {
         MessageBox.Show("Cannot read the CityDetails table from SQL Server.\n\nPlease ensure that SQL Server is running, the Person.CityDetails table exists,\nand the CityImageViewer.exe.config file is correctly configured.\n\n\nDebug info:\n\n" + e.Message, "Cannot initialize CityImageViewer", MessageBoxButtons.OK, MessageBoxIcon.Stop);
         this.Close();
     }
 }
    protected void btnGuardarConciliacion_Click(object sender, EventArgs e)
    {
        usuario    = (SeguridadCB.Public.Usuario)HttpContext.Current.Session["Usuario"];
        parametros = Session["Parametros"] as Parametros;
        AppSettingsReader settings  = new AppSettingsReader();
        short             modulo    = Convert.ToSByte(settings.GetValue("Modulo", typeof(string)).ToString());
        string            parametro = parametros.ValorParametro(modulo, "Cuenta Sobregiro");

        if (ddlTipoConciliacion.SelectedItem.Text.Equals("CONCILIACION DE INGRESOS POR COBRANZA A ABONAR PEDIDO") || ddlTipoConciliacion.SelectedItem.Text.Equals("CONCILIACION DE INGRESOS Y EGRESOS SIN ARCHIVO") || ddlTipoConciliacion.SelectedItem.Text.Equals("CONCILIACION DE INGRESOS POR COBRANZA A ABONAR") || ddlCuentaBancaria.SelectedItem.Text.Trim().Equals(parametro.Trim()))
        {
            if (AgregarArchivoExterno())
            {
                if (GuardarConciliacionSinInterno(usuario.IdUsuario))
                {
                    limpiarVariablesSession();
                    Response.Redirect("~/Inicio.aspx");
                }
            }
        }
        else
        {
            if ((Session["nuevaconciliacionobjApp"] as Conciliacion.RunTime.App).Conciliacion.ListaArchivos.Count < 1)
            {
                (Session["nuevaconciliacionobjApp"] as Conciliacion.RunTime.App).ImplementadorMensajes.MostrarMensaje("Aún no ha agregado ningún archivo interno.");
            }
            else
            {
                if (AgregarArchivoExterno())
                {
                    if (GuardarConciliacion(usuario.IdUsuario))
                    {
                        (Session["nuevaconciliacionobjApp"] as Conciliacion.RunTime.App).Conciliacion.ListaArchivos.Clear();
                        limpiarVariablesSession();
                        Response.Redirect("~/Inicio.aspx");
                    }
                }
            }
        }
    }
コード例 #21
0
        public static string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();


            string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key = keyArray;


            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            byte[] resultArray =
                cTransform.TransformFinalBlock(toEncryptArray, 0,
                                               toEncryptArray.Length);

            tdes.Clear();

            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
        public async Task <OAuthResponse> OAuthAccess(string accessCode)
        {
            AppSettingsReader configurationAppSettings = new AppSettingsReader();

            var clientId = (string)configurationAppSettings.GetValue(ConfigKeys.SlackClientId, typeof(string));

            var clientSecret = (string)configurationAppSettings.GetValue(ConfigKeys.SlackClientSecret, typeof(string));

            var redirectUrl = Statics.GetApiUrl() + ApiUrl.SlackRedirectUri;

            var request = new OAuthRequest
            {
                client_secret = clientSecret,
                client_id     = clientId,
                code          = accessCode,
                redirect_uri  = redirectUrl
            };

            var resp = await _client.InvokeApi <OAuthRequest, OAuthResponse>(ApiUrl.SlackOAuth, request);

            return(resp.ResponseData);
        }
コード例 #23
0
        private static FileHandler InstantiateDefaultFileHandler()
        {
            AppSettingsReader appSettingsReader = new AppSettingsReader();

            string ourMail    = (string)appSettingsReader.GetValue("OurMailAddress", typeof(string));
            string targetMail = (string)appSettingsReader.GetValue("TargetMailAddress", typeof(string));

            ISmtpHandler        smtpHandler = GetSmtpHandler(appSettingsReader);
            ISendingFileFactory fileFactory = new SendingFileFactory();

            FileSender sender = new FileSender(ourMail, targetMail, smtpHandler, fileFactory);

            IFileManipulator manipulator = new FileManipulator();

            string mailToSendFolderPath  = (string)appSettingsReader.GetValue("MailToSendFP", typeof(string));
            string invalidMailFolderPath = (string)appSettingsReader.GetValue("InvalidMailFP", typeof(string));

            // NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            NotifyFilters notifyFilter = (NotifyFilters)appSettingsReader.GetValue("NotifyFilter", typeof(int));
            string        filter       = (string)appSettingsReader.GetValue("Filter", typeof(string));
            IFileWatcher  watcher      = new FileWatcher(mailToSendFolderPath, filter, notifyFilter, manipulator);

            ILog logger = LogManager.GetLogger(typeof(FileHandler));

            FileHandler result = new FileHandler(mailToSendFolderPath, invalidMailFolderPath, watcher, manipulator, sender, logger);

            return(result);

            SmtpHandler GetSmtpHandler(AppSettingsReader settingsReader)
            {
                string             host            = (string)settingsReader.GetValue("Host", typeof(string));
                int                port            = (int)settingsReader.GetValue("Port", typeof(int));
                SmtpDeliveryMethod method          = (SmtpDeliveryMethod)settingsReader.GetValue("SMTPDeliveryMethod", typeof(int));
                string             ourMailPassword = (string)settingsReader.GetValue("OurMailPassword", typeof(string));
                bool               enableSsl       = (bool)settingsReader.GetValue("EnableSSL", typeof(bool));

                return(new SmtpHandler(host, port, method, new NetworkCredential(ourMail, ourMailPassword), enableSsl));
            }
        }
コード例 #24
0
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // add all entity types to the combo box.
            int[] values = (int[])Enum.GetValues(typeof(EntityType));
            for (int i = 0; i < values.Length; i++)
            {
                // add the item, but strip off the 'Entity' suffix
                cbxEntity.Items.Add(new ListItem(GeneralUtils.EntityTypeToEntityName((EntityType)i), i.ToString()));
            }

            // check for user info
            if (SessionHelper.GetUserID() == string.Empty)
            {
                Response.Redirect("Login.aspx");
            }

            #region get autiding simple text filename to use

            // look for SimpleTextAuditorTxtFileName setting at .config file
            string            _outputAuditFileName = string.Empty;
            AppSettingsReader appConfiguration     = new AppSettingsReader();
            try
            {
                _outputAuditFileName = (string)appConfiguration.GetValue("SimpleTextAuditorTxtFileName", typeof(string));
            }

            // SimpleTextAuditorTxtFileName not found! use default filename
            catch (InvalidOperationException)
            {
                _outputAuditFileName = "c:\\noraudit.txt";
            }

            this.lblAuditTextFileName.Text = _outputAuditFileName;

            #endregion
        }
    }
コード例 #25
0
        static BookingDAOImplFactory()
        {
            AppSettingsReader asr           = new AppSettingsReader();
            string            bookingConfig = asr.GetValue("bookingDAOTypes", typeof(string)).ToString();

            string[] tokens = bookingConfig.Split(':');

            for (int i = 0; i < tokens.Length;)
            {
                BookingTypes bt        = (BookingTypes)Convert.ToInt32(tokens[i]);
                string       className = tokens[i + 1];

                Assembly asm           = Assembly.GetExecutingAssembly();
                object   objBookingDAO = asm.CreateInstance(className);

                IBookingDAOImpl bookingDAOImpl = (IBookingDAOImpl)objBookingDAO;

                s_bookingDAOs.Add(bt, bookingDAOImpl);

                i += 2;
            }
        }
コード例 #26
0
 private void LoginButton_Click(object sender, EventArgs e)
 {
     try
     {
         //获取记录
         var reader   = new AppSettingsReader();
         var username = reader.GetValue("Username", typeof(string));
         var password = reader.GetValue("Password", typeof(string));
         //获取输入
         string inputUsername = UserNameTextbox.Text;
         string inputPassword = PasswordTextbox.Text;
         if (inputUsername == string.Empty)
         {
             MessageBox.Show("用户名不能为空", "Error");
             return;
         }
         else if (inputPassword == String.Empty)
         {
             MessageBox.Show("密码不能为空", "Error");
         }
         else if (inputUsername == username.ToString() &&
                  inputPassword == password.ToString())
         {
             var startup = new StartupWindow();
             startup.Closed +=
                 (object senderObject, EventArgs eventArgs) => this.Close();
             startup.Show();
             this.Hide();
         }
         else
         {
             MessageBox.Show("用户名或密码错误", "Error");
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show("error: " + exception.Message, "Error");
     }
 }
コード例 #27
0
        static void Main(string[] args)
        {
            string procName = Process.GetCurrentProcess().ProcessName;

            if (Process.GetProcessesByName(procName).Length > 1)
            {
                MessageBox.Show("Only one instance of " + procName + " can be running at time.", "BD3 Service",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            else
            {
                AppSettingsReader configurationAppSettings = new AppSettingsReader();
                String            baseAddress = (string)configurationAppSettings.GetValue("ServerAddress", typeof(string));

                WebApp.Start <Startup>(url: baseAddress);


                // Start OWIN host
                BD3Server.Run(args);
            }
        }
コード例 #28
0
        public ImpersonateUser(int logintype)
        {
            AppSettingsReader  appSettingsReader = new AppSettingsReader();
            string             userName          = (string)appSettingsReader.GetValue("ImpersonateUser", typeof(string));
            string             password          = (string)appSettingsReader.GetValue("ImpersonatePassword", typeof(string));
            string             domain            = null;
            SecurityPermission secPerm           = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            secPerm.Assert();

            IntPtr token   = IntPtr.Zero;
            bool   success = false;
            string error   = "No specific information.";

            try
            {
                if (LogonUser(userName, domain, password, logintype, LOGON32_PROVIDER_DEFAULT, ref token))
                {
                    WindowsIdentity tempWindowsIdentity = new WindowsIdentity(token, "NTLM", WindowsAccountType.Normal, true);
                    impersonationContext = tempWindowsIdentity.Impersonate(); // actually impersonate the user
                    if (impersonationContext != null)
                    {
                        success = true;
                    }
                }
            }
            catch (Exception e)
            {
                error = "ERROR: " + e.Message;
            }

            CodeAccessPermission.RevertAssert();

            if (!success)
            {
                this.Dispose();
                throw new Exception("The logon attempt as user " + domain + "\\" + userName + " with password " + password + " failed. " + error);
            }
        }
コード例 #29
0
ファイル: Outlook.cs プロジェクト: kanadeiar/bnska
        public static void CreateMailItemToMayorovYurzin(string[] attachments)
        {
            AppSettingsReader ar         = new AppSettingsReader();
            string            subjectStr = (string)ar.GetValue("OutlookSubject", typeof(string));
            string            toStr      = (string)ar.GetValue("OutlookTo", typeof(string));
            string            bodyStr    = (string)ar.GetValue("OutlookBody", typeof(string));

            COutlook.Application app      = new COutlook.Application();
            COutlook.MailItem    mailItem = app.CreateItem(COutlook.OlItemType.olMailItem);
            mailItem.Subject = subjectStr;
            mailItem.To      = toStr;
            mailItem.Body    = bodyStr;
            if (attachments != null)
            {
                foreach (var a in attachments)
                {
                    mailItem.Attachments.Add(a);
                }
            }
            mailItem.Importance = COutlook.OlImportance.olImportanceNormal;
            mailItem.Display(false);
        }
コード例 #30
0
 /// <summary>
 /// getConfigValue
 /// </summary>
 /// <typeparam name="T">passed type</typeparam>
 /// <param name="appSettingsReader">System.Configuration.AppSettingsReader</param>
 /// <param name="keyName">string</param>
 /// <param name="keyValue">ref T</param>
 /// <param name="defaultValue">T</param>
 private void getConfigValue <T>(AppSettingsReader appSettingsReader,
                                 string keyName, ref T keyValue, T defaultValue)
 {
     keyValue = defaultValue; // provide a default
     try
     {
         string tempS = (string)appSettingsReader.GetValue(keyName, typeof(System.String));
         if ((tempS != null) && (tempS.Trim().Length > 0))
         {
             keyValue = (T)TypeDescriptor.GetConverter(keyValue.GetType()).ConvertFrom(tempS);
         }
         else
         {
             Debug.WriteLine("Registry failed to read value from " + keyName);
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
         // if key does not exist, not a problem. Caller must pre-assign values anyway
     }
 }
コード例 #31
0
        private static void ConfigureContainer(Container container, AppSettingsReader settingsReader)
        {
            // Default Quartz scheduler
            container.Register <IScheduler>(() =>
            {
                var scheduler = StdSchedulerFactory.GetDefaultScheduler();
                scheduler.Start();
                return(scheduler);
            }, Lifestyle.Singleton);

            // RestSharp rest client
            container.Register <IRestClient>(() => new RestClient(), Lifestyle.Transient);

            // Register default logger
            container.Register <ILogger>(() => new NLog.LogFactory().GetCurrentClassLogger());

            // retrieve service settings from App.config
            container.Register <ServiceSettings>(() =>
            {
                string apiUrl        = settingsReader.GetValue("ApiUrl", typeof(string)) as string;
                Uri configServiceUrl = null;
                Uri pollingUrl       = null;

                Uri.TryCreate(settingsReader.GetValue("ConfigServiceUrl", typeof(string)) as string, UriKind.Absolute, out configServiceUrl);
                Uri.TryCreate(settingsReader.GetValue("PollingUrl", typeof(string)) as string, UriKind.Absolute, out pollingUrl);

                return(new ServiceSettings
                {
                    ConfigServiceUrl = configServiceUrl,
                    PollingUrl = pollingUrl,
                    ApiUrl = apiUrl,
                });
            });

            // set up Quartz logging
            Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter {
                Level = Common.Logging.LogLevel.Info
            };
        }
コード例 #32
0
        public string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            // Get the key from config file
            string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

            //System.Windows.Forms.MessageBox.Show(key);
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //Release the resources and flush data.
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            //Set the secret key for the tripleDes algorithm
            tdes.Key = keyArray;
            //Mode of operation. there are other four modes (ECB..)
            tdes.Mode = CipherMode.ECB;
            //Padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            //Transform the specified region of bytes array to resultArray
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            //Return the encrypted data into unreadable string format
            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
コード例 #33
0
        public static bool SendEmail(string body)
        {
            try
            {
                AppSettingsReader app         = new AppSettingsReader();
                string            from        = (string)app.GetValue("FromEmailAddress", typeof(String));
                string            pass        = (string)app.GetValue("FromEmailPassword", typeof(String));
                string            hostName    = (string)app.GetValue("SMTPHost", typeof(String));
                string            nameDisplay = (string)app.GetValue("FromEmailDisplayName", typeof(String));
                int    port    = (int)app.GetValue("SMTPPort", typeof(int));
                string To      = "*****@*****.**";
                string subject = "Mail góp ý";

                SmtpClient smtp = new SmtpClient();
                smtp.Host                  = hostName;
                smtp.Port                  = port;
                smtp.EnableSsl             = true;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new System.Net.NetworkCredential(from, pass);

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(from, nameDisplay);
                mail.To.Add(To);
                mail.Subject      = subject;
                mail.Body         = body;
                mail.IsBodyHtml   = true;
                mail.BodyEncoding = UTF8Encoding.UTF8;

                smtp.Send(mail);

                return(true);
            }
            catch (Exception ex)
            {
                var Err = ex.InnerException + ex.Message;
                return(false);
            }
        }
コード例 #34
0
    { /// <summary>
      /// Encrypt a string using dual encryption method. Return a encrypted cipher Text
      /// </summary>
      /// <param name="toEncrypt">string to be encrypted</param>
      /// <param name="useHashing">use hashing? send to for extra secirity</param>
      /// <returns></returns>
        public static string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            // Get the key from config file
            string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

            //System.Windows.Forms.MessageBox.Show(key);
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key     = keyArray;
            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            var rawString = Convert.ToBase64String(resultArray, 0, resultArray.Length);

            byte[] ba        = Encoding.UTF8.GetBytes(rawString);
            var    hexString = BitConverter.ToString(ba);

            hexString = hexString.Replace("-", "");
            return(hexString);
        }
コード例 #35
0
        /// <summary>
        /// Decrypts a cipher sting
        /// </summary>
        /// <param name="cipherString">String to decrypt</param>
        /// <returns>Decrypted string</returns>
        public string DecryptString(string cipherString)
        {
            try
            {
                if (cipherString != " " && cipherString != "")
                {
                    byte[] keyArray;
                    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

                    System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
                    string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

                    MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                    hashmd5.Clear();

                    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                    tdes.Key     = keyArray;
                    tdes.Mode    = CipherMode.ECB;
                    tdes.Padding = PaddingMode.PKCS7;

                    ICryptoTransform cTransform  = tdes.CreateDecryptor();
                    byte[]           resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                    tdes.Clear();
                    return(UTF8Encoding.UTF8.GetString(resultArray));
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("DecryptString exception : " + e.ToString());
                Console.WriteLine("====================DecryptString exception : " + cipherString);
                return(null);
            }
        }
コード例 #36
0
        private static MailMessage initMail(string receiver) // receiver = NTID
        {
            PCMSDBContext     db = new PCMSDBContext();
            AppSettingsReader appSettingsReader = new AppSettingsReader();
            string            smtpAccount       = (string)appSettingsReader.GetValue("SMTPAccount", typeof(string));
            string            remail            = string.Empty;
            //
            MembershipUser member = Membership.GetUser(receiver);

            remail = member.Email;

            MailMessage message = new MailMessage();

            message.From = new MailAddress(smtpAccount);
            message.To.Add(remail);

            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.IsBodyHtml      = true;

            return(message);
        }
コード例 #37
0
ファイル: Criptografia.cs プロジェクト: cgermanmr/DepositoApp
        // /// <summary>
        // /// Cypher a text with TripleDES algorithm
        // /// </summary>
        // /// <param name="toEncrypt">text to cypher</param>
        // /// <param name="key">key to cypher</param>
        // /// <param name="useHashing">true if the key must be hashed (more secure)</param>
        // /// <returns>cypher text</returns>
        public string CypherTripleDES(string toEncrypt, string key, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);

            AppSettingsReader settingsReader = new AppSettingsReader();

            // //System.Windows.Forms.MessageBox.Show(key);
            // //If hashing use get hashcode regards to your key
            if ((useHashing))
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key));
                // //Always release the resources and flush data
                // // of the Cryptographic service provide. Best Practice
                hashmd5.Clear();
            }
            else
            {
                keyArray = Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            // //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            // //mode of operation. there are other 4 modes.
            // //We choose ECB(Electronic code Book)
            tdes.Mode = CipherMode.ECB;
            // //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateEncryptor();

            // //transform the specified region of bytes array to resultArray
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            // //Release resources held by TripleDes Encryptor
            tdes.Clear();
            // //Return the encrypted data into unreadable string format
            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));
        }
コード例 #38
0
        public Log(string filename)
        {
            AppSettingsReader asr = new AppSettingsReader();

            m_active = false;

            // Bekijk wat de logdir moet zijn.
            String logdir = @"C:\TEMP";

            try
            {
                logdir = (String)asr.GetValue("Logdir", typeof(String));
            }
            catch (InvalidOperationException)
            {
                // ignore;
            }
            if (logdir == "")
            {
                logdir = @"C:\TEMP";
            }

            // ... en concludeer wat de filenaam van de log moet zijn.
            m_logfilename = Path.Combine(logdir, filename);

            // Bekijk of we wel willen loggen of niet
            string log = "";

            try
            {
                log = (String)asr.GetValue("Log", typeof(String));
            }
            catch (InvalidOperationException)
            {
                // ignore;
            }
            // Forceer openen van de logfile door gebruik te maken van de 'active' property
            active = (log == "1");
        }
コード例 #39
0
        private static MailMessage initMail(Status.SettingType stype)
        {
            PCMSDBContext     db = new PCMSDBContext();
            AppSettingsReader appSettingsReader = new AppSettingsReader();
            string            smtpAccount       = (string)appSettingsReader.GetValue("SMTPAccount", typeof(string));

            // 승인 발생시 승인요청 알림.
            Setting conf = db.Settings.Where(s => s.type == stype).First();

            String[] toaddr = conf.value.Split(';');

            MailMessage message = new MailMessage();

            message.From = new MailAddress(smtpAccount);
            try
            {
                foreach (var a in toaddr)
                {
                    if (!string.IsNullOrEmpty(a))
                    {
                        MembershipUser member = Membership.GetUser(a);
                        string         remail = member.Email;
                        if (!string.IsNullOrEmpty(remail))
                        {
                            message.To.Add(remail);
                        }
                    }
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.IsBodyHtml      = true;

            return(message);
        }
コード例 #40
0
ファイル: cUtilInterfaz.cs プロジェクト: cosejo/SGAG
    public static string LeerParametro(string pNombreParam)
    {
        string Resultado;

        //obtener la ruta del archivo de configuracion
        AppSettingsReader _configReader = new AppSettingsReader();

        // Leer el valor de configuracion
        Resultado = _configReader.GetValue(pNombreParam, typeof(string)).ToString();
        if (Resultado == null)
        {
            Resultado = "";
        }
        return Resultado;
    }
コード例 #41
0
 internal RabbmitMQSettings(AppSettingsReader reader)
 {
     this.reader = reader;
 }
コード例 #42
0
 internal ServiceAppSettings(AppSettingsReader reader)
 {
     this.reader = reader;
 }
コード例 #43
0
ファイル: Helper.cs プロジェクト: rcaneja/OCRMDSS
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();
        // Get the key from config file

        string key = "password";
        //System.Windows.Forms.MessageBox.Show(key);
        //If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //Always release the resources and flush data
            // of the Cryptographic service provide. Best Practice

            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)
        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)

        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        //transform the specified region of bytes array to resultArray
        byte[] resultArray =
          cTransform.TransformFinalBlock(toEncryptArray, 0,
          toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
コード例 #44
0
 internal BillingApiSettings(AppSettingsReader reader)
 {
     _reader = reader;
 }
コード例 #45
0
ファイル: FileService.cs プロジェクト: Hagser/csharp
 public static string GetPath()
 {
     AppSettingsReader asr = new AppSettingsReader();
     string v = asr.GetValue("path", typeof(string)) as string;
     return v;
 }
コード例 #46
0
 internal ReportApiSettings(AppSettingsReader reader)
 {
     _reader = reader;
 }
コード例 #47
0
 internal UserManagementApiSettings(AppSettingsReader reader)
 {
     _reader = reader;
 }
コード例 #48
0
 internal PackageBuilderApiSettings(AppSettingsReader reader)
 {
     _reader = reader;
 }
コード例 #49
0
ファイル: FileService.cs プロジェクト: Hagser/csharp
 private string getASRV(string key)
 {
     AppSettingsReader asr = new AppSettingsReader();
     string v = asr.GetValue(key, typeof(string)) as string;
     return v;
 }
コード例 #50
0
 public void TestInit()
 {
     _reader = new AppSettingsReader();
 }