コード例 #1
0
        private void ProcessEditForm(int id, FormCollection collection)
        {
            var allowUpload = Settings.GetValueAsBool("S2", "PersonExport");

            var jsonGridData = collection["gridData"];
            var gridData     = JsonConvert.DeserializeObject <List <GridDataRow> >(jsonGridData);

            var dataAccess = new People(DbContext);

            var results = dataAccess.Get(id);

            if (results.Failed)
            {
                EventLogger.LogSystemActivity(OwnedSystem,
                                              Severity.Error,
                                              string.Format("Error getting person with id of {0} from R1SM", id),
                                              results.Message);

                RedirectToAction("Index", "People");
            }

            var person = results.Entity;

            if (AllowRuleAdministration)
            {
                UpdateRoles(person, gridData);
            }

            // If an admin edited this we need to see if any of the RSM specific stuff has changed.
            if (User.IsInRole("admin"))
            {
                person.IsAdmin = collection.GetValueAsBool("IsAdmin");

                person.LockedOut = collection.GetValueAsBool("Person.LockedOut");

                person.username = collection["Person.username"];
                var newPass = collection["Person.password"];

                if ((newPass.Length > 0) && (newPass != person.password))
                {
                    // Get encryption and decryption key information from the configuration.
                    var cfg        = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                    var machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");

                    var hash = new HMACSHA512 {
                        Key = Utilities.HexToByte(machineKey.ValidationKey)
                    };

                    var hash1 = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(collection["Person.password"] + ".rSmSa1t" + newPass.Length.ToString())));
                    var hash2 = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(hash1 + "an0tH3r5alt!" + newPass.Length.ToString())));

                    person.password =
                        Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(hash2)));
                }

                EventLogger.LogUserActivity(Severity.Informational,
                                            User.Identity.Name + " modified access for " + person.DisplayName, "");
            }

            // Saving the person implies acceptance of the levels as assigned.
            person.NeedsApproval = false;
            person.Credentials   = collection["Person.Credentials"];
            person.NickFirst     = collection["Person.NickFirst"];
            DbContext.SubmitChanges();

            try
            {
                if (allowUpload)
                {
                    // Now update the S2 box with the new employee record.
                    this.API.SavePerson(person);
                }
                else
                {
                    person.NeedsUpload = true;
                    DbContext.SubmitChanges();
                }
            }
            catch
            {
                // If the update fails (likely due to a network issue)
                // queue up the person to be uploaded by the service later.
                person.NeedsUpload = true;
                DbContext.SubmitChanges();
            }
        }
コード例 #2
0
        public static void Main()
        {
            // <Snippet1>

            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");

            // Get the section.
            CustomErrorsSection customErrorsSection =
                (CustomErrorsSection)configuration.GetSection(
                    "system.web/customErrors");

            // Get the collection
            CustomErrorCollection customErrorsCollection =
                customErrorsSection.Errors;

            // </Snippet1>


            // <Snippet2>
            // Create a new CustomErrorCollection object.
            CustomErrorCollection newcustomErrorCollection =
                new System.Web.Configuration.CustomErrorCollection();

            // </Snippet2>


            // <Snippet3>
            // Get the currentDefaultRedirect
            string currentDefaultRedirect =
                customErrorsSection.DefaultRedirect;

            // </Snippet3>

            // <Snippet4>
            // Using the Set method.
            CustomError newCustomError =
                new CustomError(404, "customerror404.htm");

            // Update the configuration file.
            if (!customErrorsSection.SectionInformation.IsLocked)
            {
                // Add the new custom error to the collection.
                customErrorsCollection.Set(newCustomError);
                configuration.Save();
            }

            // </Snippet4>

            // <Snippet5>
            // Using the Add method.
            CustomError newCustomError2 =
                new CustomError(404, "customerror404.htm");

            // Update the configuration file.
            if (!customErrorsSection.SectionInformation.IsLocked)
            {
                // Add the new custom error to the collection.
                customErrorsCollection.Add(newCustomError2);
                configuration.Save();
            }

            // </Snippet5>


            // <Snippet6>
            // Using the Clear method.
            if (!customErrorsSection.SectionInformation.IsLocked)
            {
                // Execute the Clear method.
                customErrorsCollection.Clear();
                configuration.Save();
            }

            // </Snippet6>

            // <Snippet7>
            // Using the Remove method.
            if (!customErrorsSection.SectionInformation.IsLocked)
            {
                // Remove the error with statuscode 404.
                customErrorsCollection.Remove("404");
                configuration.Save();
            }

            // </Snippet7>


            // <Snippet8>
            // Using method RemoveAt.
            if (!customErrorsSection.SectionInformation.IsLocked)
            {
                // Remove the error at 0 index
                customErrorsCollection.RemoveAt(0);
                configuration.Save();
            }

            // </Snippet8>


            // <Snippet9>
            // Get the current Mode.
            CustomErrorsMode currentMode =
                customErrorsSection.Mode;

            // Set the current Mode.
            customErrorsSection.Mode =
                CustomErrorsMode.RemoteOnly;

            // </Snippet9>

            // <Snippet10>
            // Get the error with collection index 0.
            CustomError customError =
                customErrorsCollection[0];

            // </Snippet10>

            // <Snippet11>
            // Get the error with status code 404.
            CustomError customError1 =
                customErrorsCollection["404"];

            // </Snippet11>

            // <Snippet12>
            // Create a new CustomErrorsSection object.
            CustomErrorsSection newcustomErrorsSection =
                new CustomErrorsSection();

            // </Snippet12>
        }
コード例 #3
0
        /// <summary>
        /// Commits specified properties (specified in the constructor) to the web.config file.
        /// WARNING - Causes an application restart!
        /// </summary>
        public List <Exception> Commit()
        {
            List <Exception> exceptions = new List <Exception>();

            Security.SecurityParams spa = Security.GetSecurityParams();

            //Wrap this all, as there inumerable things that could cause this to fail (permissions issues, medium trust, etc.)
            try
            {
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

                AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
                appSection.SectionInformation.ForceSave = true;

                LogSecurityEvent("Web.config file opened for editing", "The web.config file has been opened for programmatic editing by the AspDotNetStorefront application.  This could be due to changing or setting an encryption key or machine key.  Additional information will be recorded in the security log.", spa);

                //We need to unprotect the web.config.  Otherwise we cannot write to it.
                if (appSection.SectionInformation.IsProtected)
                {
                    appSection.SectionInformation.UnprotectSection();
                    LogSecurityEvent("Web.config file decrypted", "The web.config appSettings section has been automatically decrypted to support editing.  It will be re-encrypted after editing if ProtectWebConfig is true.", spa);
                }

                //DO NOT SAVE UNTIL ALL ROUTINES ARE COMPLETE, AS COMMITTING WILL RESTART THE APPLICATION!

                #region Modify encryptKey
                try
                {
                    if (m_setEncryptKey)
                    {
                        string AddressSaltField = AppLogic.AppConfig("AddressCCSaltField");
                        string OrdersSaltField  = AppLogic.AppConfig("OrdersCCSaltField");
                        string oldEncryptKey    = spa.EncryptKey;

                        if (spa.EncryptIterations == 0)
                        {
                            spa.EncryptIterations = 1;
                        }

                        if (m_encryptKeyGenMethod == KeyGenerationMethod.Auto)
                        {
                            if (m_encryptKeyLength == KeyLength.Random)
                            {
                                m_encryptKey = Security.CreateRandomKey(4, 25);
                            }
                            else
                            {
                                Security.CreateRandomKey((int)m_encryptKeyLength);
                            }
                        }

                        spa.EncryptKey = m_encryptKey;

                        DBTransaction t = new DBTransaction();

                        using (SqlConnection dbconn = DB.dbConn())
                        {
                            dbconn.Open();

                            string query = "SELECT AddressID,CustomerID,CardNumber, eCheckBankABACode, eCheckBankAccountNumber FROM Address WHERE " +
                                           " CardNumber IS NOT NULL AND CONVERT(NVARCHAR(4000),CardNumber)<>{0} AND CONVERT(NVARCHAR(4000),CardNumber)<>{1} OR ( " +
                                           " eCheckBankABACode IS NOT NULL AND CONVERT(NVARCHAR(4000),eCheckBankABACode)<>{0} AND CONVERT(NVARCHAR(4000),eCheckBankABACode)<>{1} AND " +
                                           " eCheckBankAccountNumber IS NOT NULL AND CONVERT(NVARCHAR(4000),eCheckBankAccountNumber)<>{0} AND CONVERT(NVARCHAR(4000),eCheckBankAccountNumber)<>{1}) " +
                                           " ORDER BY AddressID ";

                            query = string.Format(query, DB.SQuote(AppLogic.ro_CCNotStoredString), DB.SQuote(String.Empty));

                            using (IDataReader rsAddress = DB.GetRS(query, dbconn))
                            {
                                using (DataTable dtAddress = new DataTable())
                                {
                                    dtAddress.Load(rsAddress);

                                    foreach (DataRow row in dtAddress.Rows)
                                    {
                                        String CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            String CNDecrypted = Security.UnmungeString(CN, row[AddressSaltField].ToString());
                                            if (CNDecrypted.StartsWith(Security.ro_DecryptFailedPrefix))
                                            {
                                                CNDecrypted = DB.RowField(row, "CardNumber");
                                            }
                                            row["CardNumber"] = CNDecrypted;
                                        }

                                        // eCheck Details...
                                        String abaCode = DB.RowField(row, "eCheckBankABACode");
                                        if (abaCode.Length != 0 &&
                                            abaCode != AppLogic.ro_CCNotStoredString)
                                        {
                                            String abaCodeDecrypted = Security.UnmungeString(abaCode, row[AddressSaltField].ToString());
                                            if (abaCodeDecrypted.StartsWith(Security.ro_DecryptFailedPrefix))
                                            {
                                                abaCodeDecrypted = DB.RowField(row, "eCheckBankABACode");
                                            }
                                            row["eCheckBankABACode"] = abaCodeDecrypted;
                                        }

                                        String bankAccountNumber = DB.RowField(row, "eCheckBankAccountNumber");
                                        if (bankAccountNumber.Length != 0 &&
                                            bankAccountNumber != AppLogic.ro_CCNotStoredString)
                                        {
                                            String bankAccountNumberDecrypted = Security.UnmungeString(bankAccountNumber, row[AddressSaltField].ToString());
                                            if (bankAccountNumberDecrypted.StartsWith(Security.ro_DecryptFailedPrefix))
                                            {
                                                bankAccountNumberDecrypted = DB.RowField(row, "eCheckBankAccountNumber");
                                            }
                                            row["eCheckBankAccountNumber"] = bankAccountNumberDecrypted;
                                        }
                                    }

                                    foreach (DataRow row in dtAddress.Rows)
                                    {
                                        String CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            String CNEncrypted = Security.MungeString(CN, row[AddressSaltField].ToString(), spa);

                                            t.AddCommand("update Address set CardNumber=" + DB.SQuote(CNEncrypted) + " where AddressID=" + DB.RowFieldInt(row, "AddressID").ToString());
                                            CN = "1111111111111111";
                                            CN = null;
                                            row["CardNumber"] = "1111111111111111";
                                            row["CardNumber"] = null;
                                        }

                                        // eCheck Details...
                                        String abaCode = DB.RowField(row, "eCheckBankABACode");
                                        if (abaCode.Length != 0 &&
                                            abaCode != AppLogic.ro_CCNotStoredString)
                                        {
                                            String abaCodeEncrypted = Security.MungeString(abaCode, row[AddressSaltField].ToString(), spa);

                                            t.AddCommand("update Address set eCheckBankABACode=" + DB.SQuote(abaCodeEncrypted) + " where AddressID=" + DB.RowFieldInt(row, "AddressID").ToString());
                                            abaCode = "1111111111111111";
                                            abaCode = null;
                                            row["eCheckBankABACode"] = "1111111111111111";
                                            row["eCheckBankABACode"] = null;
                                        }

                                        String bankAccountNumber = DB.RowField(row, "eCheckBankAccountNumber");
                                        if (bankAccountNumber.Length != 0 &&
                                            bankAccountNumber != AppLogic.ro_CCNotStoredString)
                                        {
                                            String bankAccountNumberEncrypted = Security.MungeString(bankAccountNumber, row[AddressSaltField].ToString(), spa);

                                            t.AddCommand("update Address set eCheckBankAccountNumber=" + DB.SQuote(bankAccountNumberEncrypted) + " where AddressID=" + DB.RowFieldInt(row, "AddressID").ToString());
                                            bankAccountNumber = "1111111111111111";
                                            bankAccountNumber = null;
                                            row["eCheckBankAccountNumber"] = "1111111111111111";
                                            row["eCheckBankAccountNumber"] = null;
                                        }
                                    }
                                }
                            }
                        }

                        using (SqlConnection dbconn = DB.dbConn())
                        {
                            dbconn.Open();

                            string query = "SELECT OrderNumber,OrderGUID,CustomerID,CustomerGUID,EMail,CustomerID,CardNumber, eCheckBankABACode, eCheckBankAccountNumber FROM Orders WHERE " +
                                           " CardNumber IS NOT NULL AND CONVERT(NVARCHAR(4000),CardNumber)<>{0} AND CONVERT(NVARCHAR(4000),CardNumber)<>{1} OR ( " +
                                           " eCheckBankABACode IS NOT NULL AND CONVERT(NVARCHAR(4000),eCheckBankABACode)<>{0} AND CONVERT(NVARCHAR(4000),eCheckBankABACode)<>{1} AND " +
                                           " eCheckBankAccountNumber IS NOT NULL AND CONVERT(NVARCHAR(4000),eCheckBankAccountNumber)<>{0} AND CONVERT(NVARCHAR(4000),eCheckBankAccountNumber)<>{1}) " +
                                           " ORDER BY OrderNumber ";

                            query = string.Format(query, DB.SQuote(AppLogic.ro_CCNotStoredString), DB.SQuote(String.Empty));

                            using (IDataReader rsOrders = DB.GetRS(query, dbconn))
                            {
                                using (DataTable dtOrders = new DataTable())
                                {
                                    dtOrders.Load(rsOrders);

                                    foreach (DataRow row in dtOrders.Rows)
                                    {
                                        String CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            String CNDecrypted = Security.UnmungeString(CN, row[OrdersSaltField].ToString());
                                            if (CNDecrypted.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                CNDecrypted = DB.RowField(row, "CardNumber");
                                            }
                                            row["CardNumber"] = CNDecrypted;
                                        }


                                        // eCheck Details...
                                        String abaCode = DB.RowField(row, "eCheckBankABACode");
                                        if (abaCode.Length != 0 &&
                                            abaCode != AppLogic.ro_CCNotStoredString)
                                        {
                                            String abaCodeDecrypted = Security.UnmungeString(abaCode, row[OrdersSaltField].ToString());
                                            if (abaCodeDecrypted.StartsWith(Security.ro_DecryptFailedPrefix))
                                            {
                                                abaCodeDecrypted = DB.RowField(row, "eCheckBankABACode");
                                            }
                                            row["eCheckBankABACode"] = abaCodeDecrypted;
                                        }

                                        String bankAccountNumber = DB.RowField(row, "eCheckBankAccountNumber");
                                        if (bankAccountNumber.Length != 0 &&
                                            bankAccountNumber != AppLogic.ro_CCNotStoredString)
                                        {
                                            String bankAccountNumberDecrypted = Security.UnmungeString(bankAccountNumber, row[OrdersSaltField].ToString());
                                            if (bankAccountNumberDecrypted.StartsWith(Security.ro_DecryptFailedPrefix))
                                            {
                                                bankAccountNumberDecrypted = DB.RowField(row, "eCheckBankAccountNumber");
                                            }
                                            row["eCheckBankAccountNumber"] = bankAccountNumberDecrypted;
                                        }
                                    }

                                    foreach (DataRow row in dtOrders.Rows)
                                    {
                                        String CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            String CNEncrypted = Security.MungeString(CN, row[OrdersSaltField].ToString(), spa);
                                            t.AddCommand("update Orders set CardNumber=" + DB.SQuote(CNEncrypted) + " where OrderNumber=" + DB.RowFieldInt(row, "OrderNumber").ToString());
                                            CN = "1111111111111111";
                                            CN = null;
                                            row["CardNumber"] = "1111111111111111";
                                            row["CardNumber"] = null;
                                        }

                                        // eCheck Details...
                                        String abaCode = DB.RowField(row, "eCheckBankABACode");
                                        if (abaCode.Length != 0 &&
                                            abaCode != AppLogic.ro_CCNotStoredString)
                                        {
                                            String abaCodeEncrypted = Security.MungeString(abaCode, row[OrdersSaltField].ToString(), spa);

                                            t.AddCommand("update Orders set eCheckBankABACode=" + DB.SQuote(abaCodeEncrypted) + " where OrderNumber=" + DB.RowFieldInt(row, "OrderNumber").ToString());
                                            abaCode = "1111111111111111";
                                            abaCode = null;
                                            row["eCheckBankABACode"] = "1111111111111111";
                                            row["eCheckBankABACode"] = null;
                                        }

                                        String bankAccountNumber = DB.RowField(row, "eCheckBankAccountNumber");
                                        if (bankAccountNumber.Length != 0 &&
                                            bankAccountNumber != AppLogic.ro_CCNotStoredString)
                                        {
                                            String bankAccountNumberEncrypted = Security.MungeString(bankAccountNumber, row[OrdersSaltField].ToString(), spa);

                                            t.AddCommand("update Orders set eCheckBankAccountNumber=" + DB.SQuote(bankAccountNumberEncrypted) + " where OrderNumber=" + DB.RowFieldInt(row, "OrderNumber").ToString());
                                            bankAccountNumber = "1111111111111111";
                                            bankAccountNumber = null;
                                            row["eCheckBankAccountNumber"] = "1111111111111111";
                                            row["eCheckBankAccountNumber"] = null;
                                        }
                                    }
                                }
                            }
                        }

                        using (SqlConnection dbconn = DB.dbConn())
                        {
                            dbconn.Open();
                            using (IDataReader rsSecurityLog = DB.GetRS("select LogID,SecurityAction,Description from SecurityLog", dbconn))
                            {
                                using (DataTable dtSecurityLog = new DataTable())
                                {
                                    dtSecurityLog.Load(rsSecurityLog);

                                    foreach (DataRow row in dtSecurityLog.Rows)
                                    {
                                        String DD          = DB.RowField(row, "Description");
                                        String DDDecrypted = Security.UnmungeString(DD);
                                        if (DDDecrypted.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            DDDecrypted = DB.RowField(row, "Description");
                                        }
                                        row["Description"] = DDDecrypted;

                                        String DDA          = DB.RowField(row, "SecurityAction");
                                        String DDADecrypted = Security.UnmungeString(DDA);
                                        if (DDADecrypted.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            DDADecrypted = DB.RowField(row, "SecurityAction");
                                        }
                                        row["SecurityAction"] = DDADecrypted;
                                    }

                                    // Only the table schema is enforcing the null constraint
                                    dtSecurityLog.Columns["Description"].AllowDBNull    = true;
                                    dtSecurityLog.Columns["SecurityAction"].AllowDBNull = true;

                                    foreach (DataRow row in dtSecurityLog.Rows)
                                    {
                                        String DD  = DB.RowField(row, "Description");
                                        String DDA = DB.RowField(row, "SecurityAction");
                                        if (DD.Length != 0 ||
                                            DDA.Length != 0)
                                        {
                                            String DDEncrypted  = Security.MungeString(DD, spa);
                                            String DDAEncrypted = Security.MungeString(DDA, spa);
                                            t.AddCommand("update SecurityLog set SecurityAction=" + DB.SQuote(DDAEncrypted) + ", Description=" + DB.SQuote(DDEncrypted) + " where logid=" + DB.RowFieldInt(row, "logid").ToString());
                                            DD = "1111111111111111";
                                            DD = null;
                                            row["Description"] = "1111111111111111";
                                            row["Description"] = null;
                                            DDA = "1111111111111111";
                                            DDA = null;
                                            row["SecurityAction"] = "1111111111111111";
                                            row["SecurityAction"] = null;
                                        }
                                    }
                                }
                            }
                        }

                        if (t.Commit())
                        {
                            appSection.Settings["EncryptKey"].Value = m_encryptKey;
                            AppLogic.SetAppConfig("NextKeyChange", DateTime.Now.AddMonths(3).ToString());
                            LogSecurityEvent("EncryptKey Changed", "The encryption key was changed by a super admin using the built-in ChangeEncryptionKey Utility", spa);
                        }
                        else
                        {
                            //Set the encrypt key back, as it was not changed
                            spa.EncryptKey = oldEncryptKey;
                            LogSecurityEvent("Change EncryptKey", "A database error prevented the encryption key from being changed", spa);
                        }
                    }
                }
                catch (Exception ex)
                {
                    SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    LogSecurityEvent("Change EncryptKey Failed", "An exception prevented the encryption key from being changed.  View the system event log for more details", spa);
                    exceptions.Add(ex);
                }
                #endregion

                #region Modify machine key
                try
                {
                    if (m_setMachineKey)
                    {
                        //Make sure that if the KeyGenerationType is set to Manual, the user has specified a key
                        if ((m_decryptKeyGenMethod == KeyGenerationMethod.Manual && String.IsNullOrEmpty(m_decryptKey)) ||
                            (m_validationKeyGenMethod == KeyGenerationMethod.Manual && String.IsNullOrEmpty(m_validationKey)))
                        {
                            throw new ArgumentException("If your KeyGenerationMethod is set to manual, you MUST manually specify a valid key!");
                        }

                        //Random cannot be used for machine keys
                        if ((m_decryptKeyGenMethod == KeyGenerationMethod.Auto && m_decryptionKeyLength == KeyLength.Random) ||
                            (m_validationKeyGenMethod == KeyGenerationMethod.Auto && m_validationKeyLength == KeyLength.Random))
                        {
                            throw new ArgumentException("If your KeyGeneration Method is set to Auto, you must manually set the keylength");
                        }

                        MachineKeySection machineKeySec = (MachineKeySection)config.GetSection("system.web/machineKey");

                        machineKeySec.CompatibilityMode = m_compatibilityMode;
                        machineKeySec.Validation        = m_validationKeyType;

                        //Setting to anything other than AES will likely cause authentication failures, failure to add to cart, etc.
                        machineKeySec.Decryption = "AES";

                        if (m_decryptKeyGenMethod == KeyGenerationMethod.Auto)
                        {
                            m_decryptKey = Security.CreateRandomKey((int)m_decryptionKeyLength);
                        }
                        else
                        {
                            //Turn the manual key into a hex-encoded string
                            m_decryptKey = Security.ConvertToHex(m_decryptKey);
                        }

                        if (m_validationKeyGenMethod == KeyGenerationMethod.Auto)
                        {
                            m_validationKey = Security.CreateRandomKey((int)m_validationKeyLength);
                        }
                        else
                        {
                            //Turn the manual key into a hex-encoded string
                            m_validationKey = Security.ConvertToHex(m_validationKey);
                        }

                        machineKeySec.DecryptionKey = m_decryptKey;
                        machineKeySec.ValidationKey = m_validationKey;
                        machineKeySec.SectionInformation.ForceSave = true;

                        LogSecurityEvent("Static Machine Key Set/Changed", "The static machine key was set or changed by a super admin using the built-in Machine Key Utility", spa);
                    }
                }
                catch (Exception ex)
                {
                    SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    LogSecurityEvent("Static Machine Key Set/Change Failed", "The static machine key could not be set or changed.  See the system event log for additional details.", spa);
                    exceptions.Add(ex);
                }
                #endregion

                #region Modify DBConn
                if (m_setDBConn)
                {
                    //TODO
                }
                #endregion

                #region Protect Web.Config

                if (m_protectWebConfig && !appSection.SectionInformation.IsProtected)
                {
                    appSection.SectionInformation.ProtectSection(m_webConfigEncryptProvider.ToString());
                    LogSecurityEvent("Web.config file encrypted", "The web.config appSettings section has been encrypted.", spa);
                }
                else if (!m_protectWebConfig && appSection.SectionInformation.IsProtected)
                {
                    appSection.SectionInformation.UnprotectSection();
                    LogSecurityEvent("Web.config file decrypted", "The web.config appSettings section has been decrypted.", spa);
                }


                #endregion

                LogSecurityEvent("Web.config file saved", "The web.config file has been written to disk.  See prior security log entries for details.", spa);

                //FINALLY, NOW SAVE
                config.Save(ConfigurationSaveMode.Minimal);
            }
            catch (Exception ex)
            {
                SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                LogSecurityEvent("Web.config editing failed", "An attempt to edit the web.config file programmatically failed.  See system event log for details.", spa);
                exceptions.Add(ex);
            }

            return(exceptions);
        }
コード例 #4
0
        static void Main(string[] args)
        {
            // Display title and info.
            Console.WriteLine("ASP.NET Configuration Info");
            Console.WriteLine("Type: CommaDelimitedStringCollection");
            Console.WriteLine();

            // Set the path of the config file.
            string configPath = "/aspnet";

            // Get the Web application configuration object.
            Configuration config =
                WebConfigurationManager.OpenWebConfiguration(configPath);

            // Get the section related object.
            AuthorizationSection configSection =
                (AuthorizationSection)config.GetSection("system.web/authorization");

            // Get the authorization rule collection.
            AuthorizationRuleCollection authorizationRuleCollection =
                configSection.Rules;

            // Create a CommaDelimitedStringCollection object.
            CommaDelimitedStringCollection myStrCollection =
                new CommaDelimitedStringCollection();

            for (int i = 0; i < authorizationRuleCollection.Count; i++)
            {
                if (authorizationRuleCollection.Get(i).Action.ToString().ToLower()
                    == "allow")
                {
                    // Add values to the CommaDelimitedStringCollection object.
                    myStrCollection.AddRange(
                        authorizationRuleCollection.Get(i).Users.ToString().Split(
                            ",".ToCharArray()));
                }
            }

            Console.WriteLine("Allowed Users: {0}",
                              myStrCollection.ToString());

            // Count the elements in the collection.
            Console.WriteLine("Allowed User Count: {0}",
                              myStrCollection.Count);

            // Call the Contains method.
            Console.WriteLine("Contains 'userName1': {0}",
                              myStrCollection.Contains("userName1"));

            // Determine the index of an element
            // in the collection.
            Console.WriteLine("IndexOf 'userName0': {0}",
                              myStrCollection.IndexOf("userName0"));

            // Call IsModified.
            Console.WriteLine("IsModified: {0}",
                              myStrCollection.IsModified);

            // Call IsReadyOnly.
            Console.WriteLine("IsReadOnly: {0}",
                              myStrCollection.IsReadOnly);

            Console.WriteLine();
            Console.WriteLine("Add a user name to the collection.");
            // Insert a new element in the collection.
            myStrCollection.Insert(myStrCollection.Count, "userNameX");

            Console.WriteLine("Collection Value: {0}",
                              myStrCollection.ToString());

            Console.WriteLine();
            Console.WriteLine("Remove a user name from the collection.");
            // Remove an element of the collection.
            myStrCollection.Remove("userNameX");

            Console.WriteLine("Collection Value: {0}",
                              myStrCollection.ToString());

            // Display and wait
            Console.ReadLine();
        }
コード例 #5
0
        /// <summary>
        /// Gets the current applications &lt;NSIClient&gt; section.
        /// </summary>
        /// <param name="configLevel">
        /// The &lt;ConfigurationUserLevel&gt; that the config file
        /// is retrieved from.
        /// </param>
        /// <returns>
        /// The configuration file's &lt;NSIClient&gt; section.
        /// </returns>
        public static NSIClientSettings GetSection(ConfigurationUserLevel configLevel)
        {
            /*
             * This class is setup using a factory pattern that forces you to
             * name the section &lt;NSIClient&gt; in the config file.
             * If you would prefer to be able to specify the name of the section,
             * then remove this method and mark the constructor public.
             */
            Configuration     config         = null;
            HttpContext       ctx            = HttpContext.Current;
            NSIClientSettings clientSettings = null;

            if (ctx != null)
            {
                string virtualPath = ctx.Request.ApplicationPath;

                try
                {
                    config = WebConfigurationManager.OpenWebConfiguration(virtualPath);
                }
                catch (ConfigurationErrorsException ex)
                {
                    string message = Resources.ExceptionReadingConfiguration + ex.Message;
                    if (virtualPath != null)
                    {
                        message = string.Format(
                            CultureInfo.InvariantCulture,
                            Resources.InfoWebConfigLocation,
                            message,
                            ctx.Server.MapPath(virtualPath));
                    }

                    Console.WriteLine(ex.ToString());
                    Console.WriteLine(message);
                    try
                    {
                        var map = new WebConfigurationFileMap();
                        var vd  = new VirtualDirectoryMapping(ctx.Server.MapPath(virtualPath), true);

                        map.VirtualDirectories.Add(virtualPath, vd);
                        config = WebConfigurationManager.OpenMappedWebConfiguration(map, virtualPath);
                    }
                    catch (ConfigurationException e)
                    {
                        Console.WriteLine(e.ToString());

                        // read-only..
                        clientSettings =
                            (NSIClientSettings)
                            WebConfigurationManager.GetWebApplicationSection(typeof(NSIClientSettings).Name);
                    }

                    // throw new NSIClientException(message, ex);
                }
            }
            else
            {
                config = ConfigurationManager.OpenExeConfiguration(configLevel);
            }

            if (config != null)
            {
                clientSettings = (NSIClientSettings)config.GetSection("NSIClientSettings");
                if (clientSettings == null)
                {
                    clientSettings = new NSIClientSettings();
                    config.Sections.Add("NSIClientSettings", clientSettings);
                }

                clientSettings._config = config;
            }
            else
            {
                if (clientSettings == null)
                {
                    throw new NsiClientException("Missing NSIClientSettings. Cannot add NSIClientSettings settings");
                }
            }

            return(clientSettings);
        }
コード例 #6
0
        /// <summary>
        /// Initializes the provider. Takes, as input, the name of the provider and a
        /// NameValueCollection of configuration settings. This method is used to set
        /// property values for the provider instance, including implementation-specific
        /// values and options specified in the configuration file
        /// (Machine.config or Web.config).
        ///
        /// "name" The friendly name of the provider.</param>
        /// config A collection of the name/value pairs representing the
        /// provider-specific attributes specified in the
        /// configuration for this provider.</param>
        /// </summary>
        /// <param name="name">Friendly name of provider</param>
        /// <param name="config">Representing the provider specific attributes</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (string.IsNullOrEmpty(config["cacheName"]))
            {
                throw new ConfigurationErrorsException("The 'cacheName' attribute cannot be null or empty string");
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config["description"] = "NCache Session Storage Provider";
            }

            if (name == null || name.Length == 0)
            {
                name = SOURCE;
            }

            //initialize the base class
            base.Initialize(name, config);

            //get the application virtual path
            _appName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            if (NCacheSessionStateConfigReader.LoadSessionLocationSettings() != null)
            {
                _isLocationAffinityEnabled = true;
            }

            string[] boolValStrings = { "exceptionsEnabled", "writeExceptionsToEventLog",
                                        "enableLogs",        "enableDetailLogs", "enableSessionLocking" };
            string   configVal = null;
            bool     value     = false;

            for (int i = 0; i < boolValStrings.Length; i++)
            {
                configVal = config[boolValStrings[i]];
                if (configVal != null)
                {
                    if (configVal != "true" && configVal != "false")
                    {
                        throw new ConfigurationErrorsException("The '" + boolValStrings[i] + "' attribute must be one of the following values: true, false.");
                    }
                    else
                    {
                        value = Convert.ToBoolean(configVal);
                        switch (i)
                        {
                        case 0: _exceptionsEnabled = value; break;

                        case 1: _writeExceptionsToEventLog = value; break;

                        case 2: _logs = value; break;

                        case 3:
                        {
                            _detailedLogs = value;
                            _logs         = value;
                        }
                        break;

                        case 4: _lockSessions = value; break;
                        }
                    }
                }
            }

            if (config["sessionAppId"] != null)
            {
                s_applicationId = config["sessionAppId"];
            }

            if (config["sessionLockingRetry"] != null)
            {
                this._sessionLockingRetries = Convert.ToInt32(config["sessionLockingRetry"]);
            }

            if (config["emptySessionWhenLocked"] != null)
            {
                this._emptySessionWhenLocked = Convert.ToBoolean(config["emptySessionWhenLocked"]);
            }

            //get cache name from configurations
            _cacheId = config["cacheName"];


            Configuration       cfg           = WebConfigurationManager.OpenWebConfiguration(_appName);
            SessionStateSection sessionConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            _defaultTimeout = sessionConfig.Timeout.Minutes;

            string inprocDelay = config["inprocDelay"];

            if (!string.IsNullOrEmpty(inprocDelay))
            {
                _inprocDelay = Convert.ToInt32(inprocDelay);
            }

            if (_inprocDelay <= 5000)
            {
                _inprocDelay = 5000;
            }

            if (!String.IsNullOrEmpty(config["operationRetry"]))
            {
                try
                {
                    this._operationRetry = Convert.ToInt32(config["operationRetry"]);
                }
                catch (Exception e)
                {
                    throw new Exception("Invalid value specified for operationRetry.");
                }
            }


            if (!String.IsNullOrEmpty(config["operationRetryInterval"]))
            {
                try
                {
                    this._operationRetryInterval = Convert.ToInt32(config["operationRetryInterval"]);
                }
                catch (Exception e)
                {
                    throw new Exception("Invalid value specified for operationRetryInterval.");
                }
            }



            InitializeCache();
        }
コード例 #7
0
        public static void Main()
        {
            try
            {
                // Get the Web application configuration.
                Configuration configuration =
                    WebConfigurationManager.OpenWebConfiguration("");

                // Get the section.
                PagesSection pagesSection =
                    (PagesSection)configuration.GetSection("system.web/pages");

                // <Snippet2>
                // <Snippet20>
                // Get the AutoImportVBNamespace property.
                Console.WriteLine("AutoImportVBNamespace: '{0}'",
                                  pagesSection.Namespaces.AutoImportVBNamespace.ToString());

                // Set the AutoImportVBNamespace property.
                pagesSection.Namespaces.AutoImportVBNamespace = true;
                // </Snippet20>

                // <Snippet21>
                // Get all current Namespaces in the collection.
                for (int i = 0; i < pagesSection.Namespaces.Count; i++)
                {
                    Console.WriteLine(
                        "Namespaces {0}: '{1}'", i,
                        pagesSection.Namespaces[i].Namespace);
                }
                // </Snippet21>

                // <Snippet22>
                // <Snippet28>
                // Create a new NamespaceInfo object.
                System.Web.Configuration.NamespaceInfo namespaceInfo =
                    new System.Web.Configuration.NamespaceInfo("System");
                // </Snippet28>

                // <Snippet29>
                // Set the Namespace property.
                namespaceInfo.Namespace = "System.Collections";
                // </Snippet29>

                // Execute the Add Method.
                pagesSection.Namespaces.Add(namespaceInfo);
                // </Snippet22>

                // <Snippet23>
                // Add a NamespaceInfo object using a constructor.
                pagesSection.Namespaces.Add(
                    new System.Web.Configuration.NamespaceInfo(
                        "System.Collections.Specialized"));
                // </Snippet23>

                // <Snippet25>
                // Execute the RemoveAt method.
                pagesSection.Namespaces.RemoveAt(0);
                // </Snippet25>

                // <Snippet24>
                // Execute the Clear method.
                pagesSection.Namespaces.Clear();
                // </Snippet24>

                // <Snippet26>
                // Execute the Remove method.
                pagesSection.Namespaces.Remove("System.Collections");
                // </Snippet26>

                // <Snippet27>
                // Get the current AutoImportVBNamespace property value.
                Console.WriteLine(
                    "Current AutoImportVBNamespace value: '{0}'",
                    pagesSection.Namespaces.AutoImportVBNamespace);

                // Set the AutoImportVBNamespace property to false.
                pagesSection.Namespaces.AutoImportVBNamespace = false;
                // </Snippet27>
                // </Snippet2>

                // <Snippet3>
                // Get the current PageParserFilterType property value.
                Console.WriteLine(
                    "Current PageParserFilterType value: '{0}'",
                    pagesSection.PageParserFilterType);

                // Set the PageParserFilterType property to
                // "MyNameSpace.AllowOnlySafeControls".
                pagesSection.PageParserFilterType =
                    "MyNameSpace.AllowOnlySafeControls";
                // </Snippet3>

                // <Snippet4>
                // Get the current Theme property value.
                Console.WriteLine(
                    "Current Theme value: '{0}'",
                    pagesSection.Theme);

                // Set the Theme property to "MyCustomTheme".
                pagesSection.Theme = "MyCustomTheme";
                // </Snippet4>

                // <Snippet5>
                // Get the current EnableViewState property value.
                Console.WriteLine(
                    "Current EnableViewState value: '{0}'",
                    pagesSection.EnableViewState);

                // Set the EnableViewState property to false.
                pagesSection.EnableViewState = false;
                // </Snippet5>

                // <Snippet6>
                // Get the current CompilationMode property value.
                Console.WriteLine(
                    "Current CompilationMode value: '{0}'",
                    pagesSection.CompilationMode);

                // Set the CompilationMode property to CompilationMode.Always.
                pagesSection.CompilationMode = CompilationMode.Always;
                // </Snippet6>

                // <Snippet7>
                // Get the current ValidateRequest property value.
                Console.WriteLine(
                    "Current ValidateRequest value: '{0}'",
                    pagesSection.ValidateRequest);

                // Set the ValidateRequest property to true.
                pagesSection.ValidateRequest = true;
                // </Snippet7>

                // <Snippet8>
                // Get the current EnableViewStateMac property value.
                Console.WriteLine(
                    "Current EnableViewStateMac value: '{0}'",
                    pagesSection.EnableViewStateMac);

                // Set the EnableViewStateMac property to true.
                pagesSection.EnableViewStateMac = true;
                // </Snippet8>

                // <Snippet9>
                // Get the current AutoEventWireup property value.
                Console.WriteLine(
                    "Current AutoEventWireup value: '{0}'",
                    pagesSection.AutoEventWireup);

                // Set the AutoEventWireup property to false.
                pagesSection.AutoEventWireup = false;
                // </Snippet9>

                // <Snippet10>
                // Get the current MaxPageStateFieldLength property value.
                Console.WriteLine(
                    "Current MaxPageStateFieldLength value: '{0}'",
                    pagesSection.MaxPageStateFieldLength);

                // Set the MaxPageStateFieldLength property to 4098.
                pagesSection.MaxPageStateFieldLength = 4098;
                // </Snippet10>

                // <Snippet11>
                // Get the current UserControlBaseType property value.
                Console.WriteLine(
                    "Current UserControlBaseType value: '{0}'",
                    pagesSection.UserControlBaseType);

                // Set the UserControlBaseType property to
                // "MyNameSpace.MyCustomControlBaseType".
                pagesSection.UserControlBaseType =
                    "MyNameSpace.MyCustomControlBaseType";
                // </Snippet11>

                // <Snippet12>
                // <Snippet30>
                // Get all current Controls in the collection.
                for (int i = 0; i < pagesSection.Controls.Count; i++)
                {
                    Console.WriteLine("Control {0}:", i);
                    Console.WriteLine("  TagPrefix = '{0}' ",
                                      pagesSection.Controls[i].TagPrefix);
                    Console.WriteLine("  TagName = '{0}' ",
                                      pagesSection.Controls[i].TagName);
                    Console.WriteLine("  Source = '{0}' ",
                                      pagesSection.Controls[i].Source);
                    Console.WriteLine("  Namespace = '{0}' ",
                                      pagesSection.Controls[i].Namespace);
                    Console.WriteLine("  Assembly = '{0}' ",
                                      pagesSection.Controls[i].Assembly);
                }
                // </Snippet30>

                // <Snippet31>
                // <Snippet33>
                // Create a new TagPrefixInfo object.
                System.Web.Configuration.TagPrefixInfo tagPrefixInfo =
                    new System.Web.Configuration.TagPrefixInfo("MyCtrl", "MyNameSpace", "MyAssembly", "MyControl", "MyControl.ascx");
                // </Snippet33>

                // <Snippet39>
                // Execute the Add Method.
                pagesSection.Controls.Add(tagPrefixInfo);
                // </Snippet39>
                // </Snippet31>

                // <Snippet32>
                // Add a TagPrefixInfo object using a constructor.
                pagesSection.Controls.Add(
                    new System.Web.Configuration.TagPrefixInfo(
                        "MyCtrl", "MyNameSpace", "MyAssembly", "MyControl",
                        "MyControl.ascx"));
                // </Snippet32>
                // </Snippet12>

                // <Snippet13>
                // Get the current StyleSheetTheme property value.
                Console.WriteLine(
                    "Current StyleSheetTheme value: '{0}'",
                    pagesSection.StyleSheetTheme);

                // Set the StyleSheetTheme property.
                pagesSection.StyleSheetTheme =
                    "MyCustomStyleSheetTheme";
                // </Snippet13>

                // <Snippet14>
                // Get the current EnableSessionState property value.
                Console.WriteLine(
                    "Current EnableSessionState value: '{0}'",
                    pagesSection.EnableSessionState);

                // Set the EnableSessionState property to
                // PagesEnableSessionState.ReadOnly.
                pagesSection.EnableSessionState =
                    PagesEnableSessionState.ReadOnly;
                // </Snippet14>

                // <Snippet15>
                // Get the current MasterPageFile property value.
                Console.WriteLine(
                    "Current MasterPageFile value: '{0}'",
                    pagesSection.MasterPageFile);

                // Set the MasterPageFile property to "MyMasterPage.ascx".
                pagesSection.MasterPageFile = "MyMasterPage.ascx";
                // </Snippet15>

                // <Snippet16>
                // Get the current Buffer property value.
                Console.WriteLine(
                    "Current Buffer value: '{0}'", pagesSection.Buffer);

                // Set the Buffer property to true.
                pagesSection.Buffer = true;
                // </Snippet16>

                // <Snippet17>
                // <Snippet40>
                // Get all current TagMappings in the collection.
                for (int i = 0; i < pagesSection.TagMapping.Count; i++)
                {
                    Console.WriteLine("TagMapping {0}:", i);
                    Console.WriteLine("  TagTypeName = '{0}'",
                                      pagesSection.TagMapping[i].TagType);
                    Console.WriteLine("  MappedTagTypeName = '{0}'",
                                      pagesSection.TagMapping[i].MappedTagType);
                }
                // </Snippet40>

                // <Snippet42>
                // Add a TagMapInfo object using a constructor.
                pagesSection.TagMapping.Add(
                    new System.Web.Configuration.TagMapInfo(
                        "MyNameSpace.MyControl", "MyNameSpace.MyOtherControl"));
                // </Snippet42>
                // </Snippet17>

                // <Snippet18>
                // Get the current PageBaseType property value.
                Console.WriteLine(
                    "Current PageBaseType value: '{0}'",
                    pagesSection.PageBaseType);

                // Set the PageBaseType property to
                // "MyNameSpace.MyCustomPagelBaseType".
                pagesSection.PageBaseType =
                    "MyNameSpace.MyCustomPagelBaseType";
                // </Snippet18>

                // <Snippet19>
                // Get the current SmartNavigation property value.
                Console.WriteLine(
                    "Current SmartNavigation value: '{0}'",
                    pagesSection.SmartNavigation);

                // Set the SmartNavigation property to true.
                pagesSection.SmartNavigation = true;
                // </Snippet19>

                // Update if not locked.
                if (!pagesSection.SectionInformation.IsLocked)
                {
                    configuration.Save();
                    Console.WriteLine("** Configuration updated.");
                }
                else
                {
                    Console.WriteLine("** Could not update, section is locked.");
                }
            }
            catch (System.Exception e)
            {
                // Unknown error.
                Console.WriteLine("A unknown exception detected in" +
                                  "UsingPagesSection Main.");
                Console.WriteLine(e);
            }
            Console.ReadLine();
        }
コード例 #8
0
        public static void Main()
        {
            try
            {
                //  <Snippet1>

                // Get the Web application configuration
                System.Configuration.Configuration configuration =
                    WebConfigurationManager.OpenWebConfiguration("/aspnetTest");

                // Get the section.
                System.Web.Configuration.ProcessModelSection
                    processModelSection =
                    (ProcessModelSection)configuration.GetSection(
                        "system.web/processModel");

                // </Snippet1>

                // <Snippet2>

                // Get the current Enable property value.

                bool enable = processModelSection.Enable;

                // Set the Enable property to false.
                processModelSection.Enable = false;

                // </Snippet2>

                // <Snippet3>

                // Get the current MemoryLimit property value.
                int memLimit = processModelSection.MemoryLimit;

                // Set the MemoryLimit property to 50.
                processModelSection.MemoryLimit = 50;

                // </Snippet3>

                // <Snippet4>

                // Get the current MinIOThreads property value.
                int minIOThreads = processModelSection.MinIOThreads;

                // Set the MinIOThreads property to 1.
                processModelSection.MinIOThreads = 1;

                // </Snippet4>

                // <Snippet5>

                // Get the current MaxIOThreads property value.
                int maxIOThreads =
                    processModelSection.MaxIOThreads;

                // Set the MaxIOThreads property to 64.
                processModelSection.MaxIOThreads = 64;

                // </Snippet5>

                // <Snippet6>

                // Get the current MinWorkerThreads property value.
                int minWorkerThreads =
                    processModelSection.MinWorkerThreads;

                // Set the MinWorkerThreads property to 2.
                processModelSection.MinWorkerThreads = 2;

                // </Snippet6>

                // <Snippet7>

                // Get the current MaxWorkerThreads property value.
                int maxWorkerThreads =
                    processModelSection.MaxWorkerThreads;

                // Set the MaxWorkerThreads property to 128.
                processModelSection.MaxWorkerThreads = 128;

                // </Snippet7>

                // <Snippet8>

                // Get the current RequestLimit property value.
                int reqLimit =
                    processModelSection.RequestLimit;

                // Set the RequestLimit property to 4096.
                processModelSection.RequestLimit = 4096;

                // </Snippet8>

                // <Snippet9>

                // Get the current RestartQueueLimit property value.
                int restartQueueLimit =
                    processModelSection.RestartQueueLimit;

                // Set the RestartQueueLimit property to 8.
                processModelSection.RestartQueueLimit = 8;

                // </Snippet9>

                // <Snippet10>

                // Get the current RequestQueueLimit property value.
                int requestQueueLimit =
                    processModelSection.RequestQueueLimit;

                // Set the RequestQueueLimit property to 10240.
                processModelSection.RequestQueueLimit = 10240;

                // </Snippet10>

                // <Snippet11>

                // Get the current ResponseRestartDeadlockInterval property
                // value.
                TimeSpan respRestartDeadlock =
                    processModelSection.ResponseRestartDeadlockInterval;

                // Set the ResponseRestartDeadlockInterval property to
                // TimeSpan.Parse("04:00:00").
                processModelSection.ResponseRestartDeadlockInterval =
                    TimeSpan.Parse("04:00:00");

                // </Snippet11>

                // <Snippet12>

                // Get the current Timeout property value.
                TimeSpan timeout =
                    processModelSection.Timeout;

                // Set the Timeout property to TimeSpan.Parse("00:00:30").
                processModelSection.Timeout =
                    TimeSpan.Parse("00:00:30");

                // </Snippet12>

                // <Snippet13>

                // Get the current PingFrequency property value.
                TimeSpan pingFreq =
                    processModelSection.PingFrequency;

                // Set the PingFrequency property to
                // TimeSpan.Parse("00:01:00").
                processModelSection.PingFrequency =
                    TimeSpan.Parse("00:01:00");

                // </Snippet13>

                // <Snippet14>

                // Get the current PingTimeout property value.
                TimeSpan pingTimeout =
                    processModelSection.PingTimeout;

                // Set the PingTimeout property to TimeSpan.Parse("00:00:30").
                processModelSection.PingTimeout =
                    TimeSpan.Parse("00:00:30");

                // </Snippet14>

                // <Snippet15>

                // Get the current ShutdownTimeout property value.
                TimeSpan shutDownTimeout =
                    processModelSection.ShutdownTimeout;

                // Set the ShutdownTimeout property to
                // TimeSpan.Parse("00:00:30").
                processModelSection.ShutdownTimeout =
                    TimeSpan.Parse("00:00:30");

                // </Snippet15>

                // <Snippet16>

                // Get the current IdleTimeout property value.
                TimeSpan idleTimeout =
                    processModelSection.IdleTimeout;

                // Set the IdleTimeout property to TimeSpan.Parse("12:00:00").
                processModelSection.IdleTimeout =
                    TimeSpan.Parse("12:00:00");

                // </Snippet16>

                // <Snippet17>

                // Get the current ResponseDeadlockInterval property value.
                TimeSpan respDeadlock =
                    processModelSection.ResponseDeadlockInterval;

                // Set the ResponseDeadlockInterval property to
                // TimeSpan.Parse("00:05:00").
                processModelSection.ResponseDeadlockInterval =
                    TimeSpan.Parse("00:05:00");

                // </Snippet17>

                // <Snippet18>

                // Get the current ClientConnectedCheck property value.
                TimeSpan clConnectCheck =
                    processModelSection.ClientConnectedCheck;

                // Set the ClientConnectedCheck property to
                // TimeSpan.Parse("00:15:00").
                processModelSection.ClientConnectedCheck =
                    TimeSpan.Parse("00:15:00");

                // </Snippet18>

                // <Snippet19>

                // Get the current UserName property value.
                string userName =
                    processModelSection.UserName;

                // Set the UserName property to "CustomUser".
                processModelSection.UserName = "******";

                // </Snippet19>

                // <Snippet20>

                // Get the current Password property value.
                string password =
                    processModelSection.Password;

                // Set the Password property to "CUPassword".
                processModelSection.Password = "******";

                // </Snippet20>

                // <Snippet21>

                // Get the current ComAuthenticationLevel property value.
                ProcessModelComAuthenticationLevel comAuthLevel =
                    processModelSection.ComAuthenticationLevel;

                // Set the ComAuthenticationLevel property to
                // ProcessModelComAuthenticationLevel.Call.
                processModelSection.ComAuthenticationLevel =
                    ProcessModelComAuthenticationLevel.Call;

                // </Snippet21>

                // <Snippet22>

                // Get the current ComImpersonationLevel property value.
                ProcessModelComImpersonationLevel comImpLevel =
                    processModelSection.ComImpersonationLevel;

                // Set the ComImpersonationLevel property to
                // ProcessModelComImpersonationLevel.Anonymous.
                processModelSection.ComImpersonationLevel =
                    ProcessModelComImpersonationLevel.Anonymous;

                // </Snippet22>

                // <Snippet23>

                // Get the current LogLevel property value.
                ProcessModelLogLevel comLogLevel =
                    processModelSection.LogLevel;

                // Set the LogLevel property to ProcessModelLogLevel.All.
                processModelSection.LogLevel = ProcessModelLogLevel.All;

                // </Snippet23>

                // <Snippet24>

                // Get the current WebGarden property value.
                bool webGarden =
                    processModelSection.WebGarden;

                // Set the WebGarden property to true.
                processModelSection.WebGarden = true;

                // </Snippet24>

                // <Snippet25>

                // Get the current CpuMask property value.
                int cpuMask =
                    processModelSection.CpuMask;

                // Set the CpuMask property to 0x000000FF.
                processModelSection.CpuMask = 0x000000FF;

                // </Snippet25>

                // <Snippet26>

                // Get the current AsyncOption property value.
                // not in use anymore
                // int asyncOpt =
                // processModelSection.AsyncOption;

                // Set the AsyncOption property to 0.
                // processModelSection.AsyncOption = 0;

                // </Snippet26>

                // <Snippet27>

                // Get the current MaxAppDomains property value.
                int maxAppdomains =
                    processModelSection.MaxAppDomains;

                // Set the MaxAppDomains property to 4.
                processModelSection.MaxAppDomains = 4;

                // </Snippet27>

                // <Snippet28>

                // Get the current ServerErrorMessageFile property value.
                string srvErrMsgFile =
                    processModelSection.ServerErrorMessageFile;

                // Set the ServerErrorMessageFile property to
                // "custommessages.log".
                processModelSection.ServerErrorMessageFile =
                    "custommessages.log";

                // </Snippet28>

                // Update if not locked.
                if (!processModelSection.SectionInformation.IsLocked)
                {
                    configuration.Save();
                }
            }
            catch (System.ArgumentException e)
            {
                // Never display this.
                string error = e.ToString();
                // Unknown error.

                string msgToDisplay =
                    "Error detected in UsingProcessModelSection.";
            }
        }
コード例 #9
0
        public HttpResponseMessage ConfigureSystem([FromBody] SystemModel systemModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    string errMsg = "";

                    //Configure JS File used by all APIs (configFile.js)
                    string configFilepath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Scripts/Utility/configFile.js");
                    string jsSettings     = "var settingsManager = {\"websiteURL\": \"" + systemModel.WebsiteUrl + "\"};";

                    var lines = File.ReadAllLines(configFilepath);
                    lines[0] = jsSettings;
                    File.WriteAllLines(configFilepath, lines);


                    var configuration = WebConfigurationManager.OpenWebConfiguration("~");

                    var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
                    appSettingsSection.Settings["Organization"].Value    = systemModel.Organization;
                    appSettingsSection.Settings["ApplicationName"].Value = systemModel.ApplicationName;
                    appSettingsSection.Settings["WebsiteUrl"].Value      = systemModel.WebsiteUrl;


                    var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
                    section.ConnectionStrings["KioskWebDBEntities"].ConnectionString        = GetConnectionString(systemModel.DatabaseServer, systemModel.DatabaseName, systemModel.DatabaseUser, systemModel.DatabasePassword);
                    section.ConnectionStrings["CardIssuanceKIOSKEntities"].ConnectionString = GetConnectionStringThirdParty(systemModel.DatabaseServerThirdParty, systemModel.DatabaseNameThirdParty, systemModel.DatabaseUserThirdParty, systemModel.DatabasePasswordThirdParty);

                    var mailHelperSection = (MailHelper)configuration.GetSection("mailHelperSection");
                    mailHelperSection.Mail.FromEmailAddress = systemModel.FromEmailAddress;
                    mailHelperSection.Mail.Username         = systemModel.SmtpUsername;
                    mailHelperSection.Mail.Password         = systemModel.SmtpPassword;

                    mailHelperSection.Smtp.Host = systemModel.SmtpHost;
                    mailHelperSection.Smtp.Port = systemModel.SmtpPort;

                    configuration.Save();


                    bool result = true;

                    if (string.IsNullOrEmpty(errMsg))
                    {
                        return(result.Equals(true) ? Request.CreateResponse(HttpStatusCode.OK, "Successful") : Request.CreateResponse(HttpStatusCode.BadRequest, "Request failed"));
                    }
                    else
                    {
                        var response = Request.CreateResponse(HttpStatusCode.BadRequest, errMsg);
                        return(response);
                    }
                }
                else
                {
                    string errors = ModelStateValidation.GetErrorListFromModelState(ModelState);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, errors));
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.WriteError(ex);
                var response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
                return(response);
            }
        }
コード例 #10
0
        static EditableImageGalleryAttribute()
        {
            DynamicImageMappingsConfig mappingsConfig = new DynamicImageMappingsConfig(WebConfigurationManager.OpenWebConfiguration("~/web.config"));

            //Add in the Dynamic Image mappings we need to allow the images to be
            //generated without being blocked
            DynamicImageMapping thumbnailMapping = new DynamicImageMapping
            {
                Width      = 150,
                Height     = 150,
                ResizeMode = DynamicResizeMode.UniformFill,
                Format     = DynamicImageFormat.Jpeg
            };

            DynamicImageMapping previewMapping = new DynamicImageMapping
            {
                Width      = 400,
                Height     = 400,
                ResizeMode = DynamicResizeMode.UniformFill,
                Format     = DynamicImageFormat.Jpeg
            };

            mappingsConfig.Settings.Add(thumbnailMapping);
            mappingsConfig.Settings.Add(previewMapping);
        }
コード例 #11
0
    private void saveFingerPrint(int device_id, string employees)
    {
        lan_download  page_object    = new lan_download();
        List <string> employees_list = JsonConvert.DeserializeObject <List <string> >(employees);
        string        drive          = page_object.getDrives();
        string        keyname        = "FingerPrintLocation";
        string        pat            = ConfigurationManager.AppSettings["FingerPrintLocation"];
        string        pat1           = pat.Substring(0, 3);
        string        pat2           = pat.Substring(3);
        int           enroll_id      = 0;
        int           i = 0;

        string path = string.Empty, path1 = string.Empty, path2 = string.Empty, path3 = string.Empty, path4 = string.Empty, path5 = string.Empty, path6 = string.Empty, path7 = string.Empty, path8 = string.Empty, path9 = string.Empty;
        int    status = 0, status1 = 0, status2 = 0, status3 = 0, status4 = 0, status5 = 0, status6 = 0, status7 = 0, status8 = 0, status9 = 0;

        if (drive == pat1)
        {
            if (!Directory.Exists(pat))
            {
                Directory.CreateDirectory(pat);
            }
        }
        else
        {
            string newdrive = drive + pat2;
            if (!Directory.Exists(newdrive))
            {
                Directory.CreateDirectory(newdrive);
            }
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");

            // var section = WebConfigurationManager.GetSection("appSettings");
            //webConfigApp = section as Configuration;
            string Key_c   = keyname;
            string Value_c = newdrive;

            webConfigApp.AppSettings.Settings[Key_c].Value = Value_c;

            webConfigApp.Save();
        }

        for (i = 0; i < employees_list.Count; i++)
        {
            enroll_id = Convert.ToInt32(employees_list[i]);
            path      = pat + enroll_id + ".anv";
            path1     = pat + enroll_id + "_" + 1 + ".anv";
            path2     = pat + enroll_id + "_" + 2 + ".anv";
            path3     = pat + enroll_id + "_" + 3 + ".anv";
            path4     = pat + enroll_id + "_" + 4 + ".anv";
            path5     = pat + enroll_id + "_" + 5 + ".anv";
            path6     = pat + enroll_id + "_" + 6 + ".anv";
            path7     = pat + enroll_id + "_" + 7 + ".anv";
            path8     = pat + enroll_id + "_" + 8 + ".anv";
            path9     = pat + enroll_id + "_" + 9 + ".anv";

            var file  = Directory.GetFiles(pat, enroll_id + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file1 = Directory.GetFiles(pat, enroll_id + "_" + 1 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file2 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 2 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file3 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 3 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file4 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 4 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file5 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 5 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file6 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 6 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file7 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 7 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file8 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 8 + ".anv", SearchOption.TopDirectoryOnly).Length;
            var file9 = Directory.GetFiles(pat, enroll_id.ToString() + "_" + 9 + ".anv", SearchOption.TopDirectoryOnly).Length;

            if (file == 0)
            {
                status = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 0, path);

                if (file1 == 0)
                {
                    status1 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 1, path1);
                }
                if (file2 == 0)
                {
                    status2 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 2, path2);
                }
                if (file3 == 0)
                {
                    status3 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 3, path3);
                }
                if (file4 == 0)
                {
                    status4 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 4, path4);
                }
                if (file5 == 0)
                {
                    status5 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 5, path5);
                }
                if (file6 == 0)
                {
                    status6 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 6, path6);
                }
                if (file7 == 0)
                {
                    status7 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 7, path7);
                }
                if (file8 == 0)
                {
                    status8 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 8, path8);
                }
                if (file9 == 0)
                {
                    status9 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 9, path9);
                }
            }
            else
            {
                status  = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 0, path);
                status1 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 1, path1);
                status2 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 2, path2);
                status3 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 3, path3);
                status4 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 4, path4);
                status5 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 5, path5);
                status6 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 6, path6);
                status7 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 7, path7);
                status8 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 8, path8);
                status9 = AnvizNew.CKT_GetFPTemplateSaveFile(device_id, enroll_id, 9, path9);
            }
        }
    }
コード例 #12
0
        private IEnumerable <string> ConfigNavigation()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.Path);

            return(config.SectionGroups.Cast <ConfigurationSectionGroup>().SelectMany(ProcessSectionGroup));
        }
コード例 #13
0
        public void RunDeploy(String[] args)
        {
            if (args.Length < 3)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 3 Arguments are required in order to use the -deploy mode, type rdfWebDeploy -help to see usage summary");
                return;
            }
            if (args.Length > 3)
            {
                if (!this.SetOptions(args.Skip(3).ToArray()))
                {
                    Console.Error.WriteLine("rdfWebDeploy: Deployment aborted since one/more options were not valid");
                    return;
                }
            }

            if (this._noLocalIis)
            {
                Console.WriteLine("rdfWebDeploy: No Local IIS Server available so switching to -xmldeploy mode");
                XmlDeploy xdeploy = new XmlDeploy();
                xdeploy.RunXmlDeploy(args);
                return;
            }

            //Define the Server Manager object
            Admin.ServerManager manager = null;

            try
            {
                //Connect to the Server Manager
                if (!this._noIntegratedRegistration)
                {
                    manager = new Admin.ServerManager();
                }

                //Open the Configuration File
                System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(args[1], this._site);
                Console.Out.WriteLine("rdfWebDeploy: Opened the Web.config file for the specified Web Application");

                //Detect Folders
                String appFolder     = Path.GetDirectoryName(config.FilePath);
                String binFolder     = Path.Combine(appFolder, "bin\\");
                String appDataFolder = Path.Combine(appFolder, "App_Data\\");
                if (!Directory.Exists(binFolder))
                {
                    Directory.CreateDirectory(binFolder);
                    Console.WriteLine("rdfWebDeploy: Created a bin\\ directory for the web application");
                }
                if (!Directory.Exists(appDataFolder))
                {
                    Directory.CreateDirectory(appDataFolder);
                    Console.WriteLine("rdfWebDeploy: Created an App_Data\\ directory for the web application");
                }

                //Deploy dotNetRDF and required DLLs to the bin directory of the application
                String sourceFolder       = RdfWebDeployHelper.ExecutablePath;
                IEnumerable <String> dlls = RdfWebDeployHelper.RequiredDLLs;
                if (this._virtuoso)
                {
                    dlls = dlls.Concat(RdfWebDeployHelper.RequiredVirtuosoDLLs);
                }
                if (this._fulltext)
                {
                    dlls = dlls.Concat(RdfWebDeployHelper.RequiredFullTextDLLs);
                }
                foreach (String dll in dlls)
                {
                    if (File.Exists(Path.Combine(sourceFolder, dll)))
                    {
                        File.Copy(Path.Combine(sourceFolder, dll), Path.Combine(binFolder, dll), true);
                        Console.WriteLine("rdfWebDeploy: Deployed " + dll + " to the web applications bin directory");
                    }
                    else
                    {
                        Console.Error.WriteLine("rdfWebDeploy: Error: Required DLL " + dll + " which needs deploying to the web applications bin directory could not be found");
                        return;
                    }
                }

                //Deploy the configuration file to the App_Data directory
                if (File.Exists(args[2]))
                {
                    File.Copy(args[2], Path.Combine(appDataFolder, args[2]), true);
                    Console.WriteLine("rdfWebDeploy: Deployed the configuration file to the web applications App_Data directory");
                }
                else if (!File.Exists(Path.Combine(appDataFolder, args[2])))
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: Unable to continue deployment as the configuration file " + args[2] + " could not be found either locally for deployment to the App_Data folder or already present in the App_Data folder");
                    return;
                }

                //Set the AppSetting for the configuration file
                config.AppSettings.Settings.Remove("dotNetRDFConfig");
                config.AppSettings.Settings.Add("dotNetRDFConfig", "~/App_Data/" + Path.GetFileName(args[2]));
                Console.WriteLine("rdfWebDeploy: Set the \"dotNetRDFConfig\" appSetting to \"~/App_Data/" + Path.GetFileName(args[2]) + "\"");

                //Now load the Configuration Graph from the App_Data folder
                Graph g = new Graph();
                FileLoader.Load(g, Path.Combine(appDataFolder, args[2]));

                Console.WriteLine("rdfWebDeploy: Successfully deployed required DLLs and appSettings");
                Console.WriteLine();

                //Get the sections of the Configuration File we want to edit
                HttpHandlersSection handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection;
                if (handlersSection == null)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Handlers section of the web applications Web.Config file");
                    return;
                }

                //Detect Handlers from the Configution Graph and deploy
                IUriNode rdfType     = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
                IUriNode dnrType     = g.CreateUriNode(new Uri(ConfigurationLoader.PropertyType));
                IUriNode httpHandler = g.CreateUriNode(new Uri(ConfigurationLoader.ClassHttpHandler));

                //Deploy for IIS Classic Mode
                if (!this._noClassicRegistration)
                {
                    Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Classic Mode");
                    foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject))
                    {
                        if (n.NodeType == NodeType.Uri)
                        {
                            String handlerPath = ((IUriNode)n).Uri.AbsolutePath;
                            INode  type        = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault();
                            if (type == null)
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified");
                                continue;
                            }
                            if (type.NodeType == NodeType.Literal)
                            {
                                String handlerType = ((ILiteralNode)type).Value;

                                //First remove any existing registration
                                handlersSection.Handlers.Remove("*", handlerPath);

                                //Then add the new registration
                                handlersSection.Handlers.Add(new HttpHandlerAction(handlerPath, handlerType, "*"));

                                Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file");
                            }
                            else
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal");
                                continue;
                            }
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node");
                        }
                    }

                    //Deploy Negotiate by File Extension if appropriate
                    if (this._negotiate)
                    {
                        HttpModulesSection modulesSection = config.GetSection("system.web/httpModules") as HttpModulesSection;
                        if (modulesSection == null)
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file");
                            return;
                        }
                        modulesSection.Modules.Remove("NegotiateByExtension");
                        modulesSection.Modules.Add(new HttpModuleAction("NegotiateByExtension", "VDS.RDF.Web.NegotiateByFileExtension"));
                        Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module");
                    }

                    Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Classic Mode");
                }

                //Save the completed Configuration File
                config.Save(ConfigurationSaveMode.Minimal);
                Console.WriteLine();

                //Deploy for IIS Integrated Mode
                if (!this._noIntegratedRegistration)
                {
                    Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Integrated Mode");
                    Admin.Configuration                  adminConfig        = manager.GetWebConfiguration(this._site, args[1]);
                    Admin.ConfigurationSection           newHandlersSection = adminConfig.GetSection("system.webServer/handlers");
                    Admin.ConfigurationElementCollection newHandlers        = newHandlersSection.GetCollection();

                    foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject))
                    {
                        if (n.NodeType == NodeType.Uri)
                        {
                            String handlerPath = ((IUriNode)n).Uri.AbsolutePath;
                            INode  type        = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault();
                            if (type == null)
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified");
                                continue;
                            }
                            if (type.NodeType == NodeType.Literal)
                            {
                                String handlerType = ((ILiteralNode)type).Value;

                                //First remove any existing registration
                                foreach (Admin.ConfigurationElement oldReg in newHandlers.Where(el => el.GetAttributeValue("name").Equals(handlerPath)).ToList())
                                {
                                    newHandlers.Remove(oldReg);
                                }

                                //Then add the new registration
                                Admin.ConfigurationElement reg = newHandlers.CreateElement("add");
                                reg["name"] = handlerPath;
                                reg["path"] = handlerPath;
                                reg["verb"] = "*";
                                reg["type"] = handlerType;
                                newHandlers.AddAt(0, reg);

                                Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file");
                            }
                            else
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal");
                                continue;
                            }
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node");
                        }

                        //Deploy Negotiate by File Extension if appropriate
                        if (this._negotiate)
                        {
                            Admin.ConfigurationSection newModulesSection = adminConfig.GetSection("system.webServer/modules");
                            if (newModulesSection == null)
                            {
                                Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file");
                                return;
                            }

                            //First remove the Old Module
                            Admin.ConfigurationElementCollection newModules = newModulesSection.GetCollection();
                            foreach (Admin.ConfigurationElement oldReg in newModules.Where(el => el.GetAttribute("name").Equals("NegotiateByExtension")).ToList())
                            {
                                newModules.Remove(oldReg);
                            }

                            //Then add the new Module
                            Admin.ConfigurationElement reg = newModules.CreateElement("add");
                            reg["name"] = "NegotiateByExtension";
                            reg["type"] = "VDS.RDF.Web.NegotiateByFileExtension";
                            newModules.AddAt(0, reg);

                            Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module");
                        }
                    }

                    manager.CommitChanges();
                    Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Integrated Mode");
                }
            }
            catch (ConfigurationException configEx)
            {
                Console.Error.WriteLine("rdfWebDeploy: Configuration Error: " + configEx.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (manager != null)
                {
                    manager.Dispose();
                }
            }
        }
コード例 #14
0
 public Kongzhi_WebConfig(string path)
 {
     config = WebConfigurationManager.OpenWebConfiguration(path);
 }
コード例 #15
0
        private bool ExecuteTest()
        {
            string str;

            this.errorMsgs = new List <string>();
            DbTransaction transaction = null;
            DbConnection  connection  = null;

            try
            {
                if (this.ValidateConnectionStrings(out str))
                {
                    using (connection = new SqlConnection(this.GetConnectionString()))
                    {
                        connection.Open();
                        DbCommand command = connection.CreateCommand();
                        transaction         = connection.BeginTransaction();
                        command.Connection  = connection;
                        command.Transaction = transaction;
                        command.CommandText = "CREATE TABLE installTest(Test bit NULL)";
                        command.ExecuteNonQuery();
                        command.CommandText = "DROP TABLE installTest";
                        command.ExecuteNonQuery();
                        transaction.Commit();
                        connection.Close();
                        goto Label_00E4;
                    }
                }
                this.errorMsgs.Add(str);
            }
            catch (Exception exception)
            {
                this.errorMsgs.Add(exception.Message);
                if (transaction != null)
                {
                    try
                    {
                        transaction.Rollback();
                    }
                    catch (Exception exception2)
                    {
                        this.errorMsgs.Add(exception2.Message);
                    }
                }
                if ((connection != null) && (connection.State != ConnectionState.Closed))
                {
                    connection.Close();
                    connection.Dispose();
                }
            }
Label_00E4:
            if (!TestFolder(base.Request.MapPath(Globals.ApplicationPath + "/config/test.txt"), out str))
            {
                this.errorMsgs.Add(str);
            }
            try
            {
                System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration(base.Request.ApplicationPath);
                if (configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString == "none")
                {
                    configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = "required";
                }
                else
                {
                    configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = "none";
                }
                configuration.Save();
            }
            catch (Exception exception3)
            {
                this.errorMsgs.Add(exception3.Message);
            }
            if (!TestFolder(base.Request.MapPath(Globals.ApplicationPath + "/storage/test.txt"), out str))
            {
                this.errorMsgs.Add(str);
            }
            return(this.errorMsgs.Count == 0);
        }
コード例 #16
0
        static void Main(string[] args)
        {
            string inputStr  = String.Empty;
            string optionStr = String.Empty;
            string parm1     = String.Empty;
            string parm2     = String.Empty;

            // Define a regular expression to allow only
            // alphanumeric inputs that are at most 20 character
            // long. For instance "/iii:".
            Regex rex = new Regex(@"[^\/w]{1,20}");

            parm1 = "none";
            parm2 = "false";

            // Parse the user's input.
            if (args.Length < 1)
            {
                // No option entered.
                Console.Write("Input parameters missing.");
                return;
            }
            else
            {
                // Get the user's options.
                inputStr = args[0].ToLower();


                if (args.Length == 3)
                {
                    // These to be used when serializing
                    // (writing) to the configuration file.
                    parm1 = args[1].ToLower();
                    parm2 = args[2].ToLower();

                    if (!(rex.Match(parm1)).Success &&
                        !(rex.Match(parm2)).Success)
                    {
                        // Wrong option format used.
                        Console.Write("Input format not allowed.");
                        return;
                    }
                }

                if (!(rex.Match(inputStr)).Success)
                {
                    // Wrong option format used.
                    Console.Write("Input format not allowed.");
                    return;
                }
            }

            // <Snippet1>

            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");

            // Get the <urlMapping> section.
            UrlMappingsSection urlMappingSection =
                (UrlMappingsSection)configuration.GetSection(
                    "system.web/urlMappings");

            // <Snippet2>

            // Get the url mapping collection.
            UrlMappingCollection urlMappings =
                urlMappingSection.UrlMappings;

            // </Snippet2>

            // </Snippet1>

            try
            {
                switch (inputStr)
                {
                case "/add":

                    // <Snippet3>

                    // Create a new UrlMapping object.
                    urlMapping = new UrlMapping(
                        "~/home.aspx", "~/default.aspx?parm1=1");

                    // Add the urlMapping to
                    // the collection.
                    urlMappings.Add(urlMapping);

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet3>

                    shownUrl  = urlMapping.Url;
                    mappedUrl = urlMapping.MappedUrl;

                    msg = String.Format(
                        "Shown URL: {0}\nMapped URL:  {1}\n",
                        shownUrl, mappedUrl);


                    Console.Write(msg);

                    break;

                case "/clear":

                    // <Snippet4>

                    // Clear the url mapping collection.
                    urlMappings.Clear();

                    // Update the configuration file.

                    // Define the save modality.
                    ConfigurationSaveMode saveMode =
                        ConfigurationSaveMode.Minimal;

                    urlMappings.EmitClear =
                        Convert.ToBoolean(parm2);

                    if (parm1 == "none")
                    {
                        if (!urlMappingSection.IsReadOnly())
                        {
                            configuration.Save();
                        }
                        msg = String.Format(
                            "Default modality, EmitClear:      {0}",
                            urlMappings.EmitClear.ToString());
                    }
                    else
                    {
                        if (parm1 == "full")
                        {
                            saveMode = ConfigurationSaveMode.Full;
                        }
                        else
                        if (parm1 == "modified")
                        {
                            saveMode = ConfigurationSaveMode.Modified;
                        }

                        if (!urlMappingSection.IsReadOnly())
                        {
                            configuration.Save(saveMode);
                        }

                        msg = String.Format(
                            "Save modality:      {0}",
                            saveMode.ToString());
                    }

                    // </Snippet4>

                    Console.Write(msg);

                    break;

                case "/removeobject":

                    // <Snippet5>

                    // Create a UrlMapping object.
                    urlMapping = new UrlMapping(
                        "~/home.aspx", "~/default.aspx?parm1=1");

                    // Remove it from the collection
                    // (if exists).
                    urlMappings.Remove(urlMapping);

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet5>

                    shownUrl  = urlMapping.Url;
                    mappedUrl = urlMapping.MappedUrl;

                    msg = String.Format(
                        "Shown URL:      {0}\nMapped URL: {1}\n",
                        shownUrl, mappedUrl);

                    Console.Write(msg);

                    break;

                case "/removeurl":

                    // <Snippet6>

                    // Remove the URL with the
                    // specified name from the collection
                    // (if exists).
                    urlMappings.Remove("~/default.aspx");

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet6>

                    break;

                case "/removeindex":

                    // <Snippet7>

                    // Remove the URL at the
                    // specified index from the collection.
                    urlMappings.RemoveAt(0);

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet7>

                    break;

                case "/all":

                    // <Snippet8>

                    StringBuilder allUrlMappings = new StringBuilder();

                    foreach (UrlMapping url_Mapping in urlMappings)
                    {
                        // <Snippet9>
                        shownUrl = url_Mapping.Url;
                        // </Snippet9>

                        // <Snippet10>
                        mappedUrl = url_Mapping.MappedUrl;
                        // </Snippet10>

                        msg = String.Format(
                            "Shown URL:  {0}\nMapped URL: {1}\n",
                            shownUrl, mappedUrl);

                        allUrlMappings.AppendLine(msg);
                    }

                    // </Snippet8>

                    Console.Write(allUrlMappings.ToString());
                    break;


                default:
                    // Option is not allowed..
                    Console.Write("Input not allowed.");
                    break;
                }
            }
            catch (ArgumentException e)
            {
                // Never display this. Use it for
                // debugging purposes.
                msg = e.ToString();
            }
        }
コード例 #17
0
        protected void InstallBtn_Click(object sender, EventArgs e)
        {
            ////////////////////////////////////////
            ////////////////////////////////////////
            ////////////////////////////////////////
            string createSchemaFile = "~/ControlRoom/Modules/Install/CreateSchema.sql";
            string initialDataFile  = "~/ControlRoom/Modules/Install/InsertInitialData.sql";
            ////////////////////////////////////////
            ////////////////////////////////////////
            ////////////////////////////////////////

            string        conn        = null;
            string        rcon        = null;
            bool          localDbMode = DBServer.Text.ToUpper() == "(LOCALDB)";
            Configuration webConfig   = null;

            if (string.IsNullOrEmpty(Mailaddress.Text))
            {
                return;
            }

            this.Log().Info("GRA setup started, using LocalDb is: {0}", localDbMode);

            // test writing to Web.config before we go further
            if (!localDbMode)
            {
                if (!this.IsValid)
                {
                    return;
                }

                try {
                    webConfig = WebConfigurationManager.OpenWebConfiguration("~");
                } catch (Exception ex) {
                    this.Log().Error("There was an error reading the Web.config: {0}", ex.Message);
                    FailureText.Text = "There was an error when trying to read the Web.config file, see below:";
                    errorLabel.Text  = ex.Message;
                    return;
                }
                try {
                    webConfig.Save();
                } catch (Exception ex) {
                    this.Log().Error("There was an error writing the Web.config file: {0}",
                                     ex.Message);
                    FailureText.Text = "There was an error when trying to write to the Web.config file, see below:";
                    errorLabel.Text  = ex.Message;
                    return;
                }
            }

            if (localDbMode)
            {
                conn = GlobalUtilities.SRPDB;
                rcon = GlobalUtilities.SRPDB;

                // set reasonable defaults
                string dataSource = @"(localdb)\ProjectsV12";
                string dbName     = "SRP";

                // try to parse out data source and database name
                try {
                    var builder = new SqlConnectionStringBuilder(conn);
                    if (!string.IsNullOrEmpty(builder.DataSource))
                    {
                        dataSource = builder.DataSource;
                    }
                    if (!string.IsNullOrEmpty(builder.InitialCatalog))
                    {
                        dbName = builder.InitialCatalog;
                    }
                } catch (Exception) {
                    // if we can't parse the connection string, use defaults
                }

                string localDbCs = string.Format("server={0}", dataSource);

                string existsQuery = string.Format("SELECT [database_id] FROM [sys].[databases] "
                                                   + "WHERE [Name] = '{0}'",
                                                   dbName);
                object result = null;
                try {
                    result = SqlHelper.ExecuteScalar(localDbCs, CommandType.Text, existsQuery);
                } catch (Exception ex) {
                    this.Log().Error("There was an error when trying to connect to LocalDb: {0}",
                                     ex.Message);
                    FailureText.Text = "There was an error when trying to connect to LocalDb, see below:";
                    errorLabel.Text  = ex.Message;
                    return;
                }

                if (result == null)
                {
                    string createDb = string.Format("CREATE DATABASE [{0}]", dbName);
                    try {
                        SqlHelper.ExecuteNonQuery(localDbCs, CommandType.Text, createDb);
                    } catch (Exception ex) {
                        this.Log().Error("There was an error creating the database: {0}",
                                         ex.Message);
                        FailureText.Text = "There was an error creating the database, see below:";
                        errorLabel.Text  = ex.Message;
                    }
                }
            }
            else
            {
                if (!this.IsValid)
                {
                    return;
                }

                conn = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                                     DBServer.Text,
                                     DBName.Text,
                                     UserName.Text,
                                     Password.Text);
                rcon = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}",
                                     DBServer.Text,
                                     DBName.Text,
                                     RunUser.Text,
                                     RuntimePassword.Text);
            }
            var mailHost = Mailserver.Text;


            try {
                SqlHelper.ExecuteNonQuery(conn, CommandType.Text, "SELECT 1");
            } catch (Exception ex) {
                this.Log().Error("There was an error when trying to connect with the SA account: {0}",
                                 ex.Message);
                FailureText.Text = "There was an error when trying to connect with the SA account, see below:";
                errorLabel.Text  = ex.Message;
                return;
            }

            try {
                SqlHelper.ExecuteNonQuery(rcon, CommandType.Text, "SELECT 1");
            } catch (Exception ex) {
                this.Log().Error("There was an error when trying to connect with the runtime account: {0}",
                                 ex.Message);
                FailureText.Text = "There was an error when trying to connect with the runtime account, see below:";
                errorLabel.Text  = ex.Message;
                return;
            }

            ////////////////////////////////////////
            ////////////////////////////////////////
            ////////////////////////////////////////
            List <string> issues = new List <string>();

            this.Log().Info("Executing the queries to create the database schema.");
            issues = ExecuteSqlFile(createSchemaFile, conn);

            if (issues.Count == 0)
            {
                this.Log().Info("Executing the queries to insert the initial data.");
                issues = ExecuteSqlFile(initialDataFile, conn);
                if (issues.Count != 0)
                {
                    issues.Add(LogAndReturnError("Could not insert initial data. GRA will not work until the data will insert properly. Please resolve the issue, recreate the database, and run this process again."));
                }
            }
            else
            {
                // schema create didn't work
                issues.Add(LogAndReturnError("Not inserting initial data due to schema issue. Please resolve the issue, recreate the database, and run this process again."));
            }

            if (issues.Count == 0)
            {
                // update email address with what the user entered
                this.Log().Info("Updating the administrative email addresses to: {0}",
                                Mailaddress);
                using (var connection = new SqlConnection(conn)) {
                    try {
                        connection.Open();
                        try {
                            // update the sysadmin user's email
                            SqlCommand updateEmail = new SqlCommand("UPDATE [SRPUser] SET [EmailAddress] = @emailAddress WHERE [Username] = 'sysadmin';",
                                                                    connection);
                            updateEmail.Parameters.AddWithValue("@emailAddress", Mailaddress.Text);
                            updateEmail.ExecuteNonQuery();
                        } catch (Exception ex) {
                            issues.Add(LogAndReturnError(string.Format("Unable to update sysadmin email: {0}",
                                                                       ex.Message)));
                        }
                        try {
                            // update the sysadmin contact email and mail from address
                            // TODO email - provide better setup for email
                            SqlCommand updateEmail = new SqlCommand("UPDATE [SRPSettings] SET [Value] = @emailAddress WHERE [Name] IN ('ContactEmail', 'FromEmailAddress');",
                                                                    connection);
                            updateEmail.Parameters.AddWithValue("@emailAddress", Mailaddress.Text);
                            updateEmail.ExecuteNonQuery();
                        } catch (Exception ex) {
                            issues.Add(LogAndReturnError(string.Format("Unable to update settings emails: {0}", ex.Message)));
                        }
                    } catch (Exception ex) {
                        issues.Add(LogAndReturnError(string.Format("Error connecting to update email address: {0}", ex.Message)));
                    } finally {
                        connection.Close();
                    }
                }
            }

            if (issues.Count == 0 && !localDbMode)
            {
                // modify the Web.config
                this.Log().Info(() => "Updating the Web.config file with the provided settings");

                webConfig = WebConfigurationManager.OpenWebConfiguration("~");

                var csSection = (ConnectionStringsSection)webConfig.GetSection("connectionStrings");
                csSection.ConnectionStrings[GlobalUtilities.SRPDBConnectionStringName].ConnectionString = rcon;

                if (mailHost != "(localhost)")
                {
                    var mailSection = (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");
                    mailSection.Smtp.Network.Host = mailHost;
                }
                webConfig.Save();
            }

            if (issues.Count == 0)
            {
                // Delete the Install File
                //System.IO.File.Delete(Server.MapPath(InstallFile));
                this.Log().Info(() => "Great Reading Adventure setup complete!");
                try {
                    // TODO email - move this template out to the database
                    var values = new {
                        SystemName      = "The Great Reading Adventure",
                        ControlRoomLink = string.Format("{0}{1}",
                                                        WebTools.GetBaseUrl(Request),
                                                        "/ControlRoom/"),
                    };

                    StringBuilder body = new StringBuilder();
                    body.Append("<p>Congratulations! You have successfully configured ");
                    body.Append("{SystemName}!</p><p>You may now ");
                    body.Append("<a href=\"{ControlRoomLink}\">log in</a> using the default ");
                    body.Append("system administrator credentials.</p><p>For more information on ");
                    body.Append("setting up and using the {SystemName} software, feel free to ");
                    body.Append("visit the <a href=\"http://manual.greatreadingadventure.com/\">manual</a>");
                    body.Append("and <a href=\"http://forum.greatreadingadventure.com/\">forum</a>.");
                    body.Append("</p>");

                    new EmailService().SendEmail(Mailaddress.Text,
                                                 "{SystemName} - Setup complete!"
                                                 .FormatWith(values),
                                                 body.ToString().FormatWith(values));
                    this.Log().Info(() => "Welcome email sent.");
                } catch (Exception ex) {
                    this.Log().Error(() => "Welcome email sending failure: {Message}"
                                     .FormatWith(ex));
                }

                Response.Redirect("~/ControlRoom/");
            }
            else
            {
                FailureText.Text = "There have been errors, see details below.";
                StringBuilder errorText = new StringBuilder();
                foreach (var issue in issues)
                {
                    errorText.Append(issue);
                    errorText.AppendLine("<br>");
                }
                errorLabel.Text = errorText.ToString();
            }
        }
コード例 #18
0
 public EmailGenerator()
 {
     config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
 }
コード例 #19
0
 public ConfigurationHelper(string path)
 {
     config = WebConfigurationManager.OpenWebConfiguration(path);
 }
コード例 #20
0
ファイル: SelfUpdaterCheckJob.cs プロジェクト: wforney/portal
        public void Execute(IJobExecutionContext context_)
        {
            var context = (JobExecutionContextImpl)context_;

            var executeJob = bool.Parse(context.JobDetail.JobDataMap["ExcecuteJob"].ToString());


            if (executeJob)
            {
                var projectManagers = ProjectManagerHelper.GetProjectManagers();
                var updateList      = new List <InstallationState>();
                foreach (var projectManager in projectManagers)
                {
                    var availablePackages = ProjectManagerHelper.GetAvailablePackagesLatestList(projectManager);

                    var installedPackages = ProjectManagerHelper.GetInstalledPackagesLatestList(projectManager, true);


                    foreach (var installedPackage in installedPackages)
                    {
                        var update = projectManager.GetUpdatedPackage(availablePackages, installedPackage);
                        if (update != null)
                        {
                            var package = new InstallationState();
                            package.Installed = installedPackage;
                            package.Update    = update;
                            package.Source    = projectManager.SourceRepository.Source;

                            if (updateList.Any(d => d.Installed.Id == package.Installed.Id))
                            {
                                var addedPackage = updateList.First(d => d.Installed.Id == package.Installed.Id);
                                if (package.Update != null)
                                {
                                    if (addedPackage.Update == null || addedPackage.Update.Version < package.Update.Version)
                                    {
                                        updateList.Remove(addedPackage);
                                        updateList.Add(package);
                                    }
                                }
                            }
                            else
                            {
                                updateList.Add(package);
                            }
                        }
                    }
                }

                // UpdateList is a list with packages that has updates
                if (updateList.Any())
                {
                    var sb = new StringBuilder();
                    try
                    {
                        var entities = new SelfUpdaterEntities();

                        foreach (
                            var self in
                            updateList.Select(
                                pack =>
                                new SelfUpdatingPackages
                        {
                            PackageId = pack.Installed.Id,
                            PackageVersion = pack.Update.Version.ToString(),
                            Source = pack.Source,
                            Install = false
                        }))
                        {
                            if (!entities.SelfUpdatingPackages.Any(x => x.PackageId == self.PackageId && x.PackageVersion == self.PackageVersion))
                            {
                                entities.AddToSelfUpdatingPackages(self);
                                sb.AppendFormat("Adding package {0} version {1} to update.", self.PackageId,
                                                self.PackageVersion);
                                sb.AppendLine();
                            }
                        }

                        entities.SaveChanges();

                        var config  = WebConfigurationManager.OpenWebConfiguration("~/");
                        var section = config.GetSection("system.web/httpRuntime");
                        ((HttpRuntimeSection)section).WaitChangeNotification    = 123456789;
                        ((HttpRuntimeSection)section).MaxWaitChangeNotification = 123456789;
                        config.Save();
                    }
                    catch (Exception e)
                    {
                        ErrorHandler.Publish(LogLevel.Error, e);
                    }

                    try
                    {
                        var body     = sb.ToString();
                        var emailDir = ConfigurationManager.AppSettings["SelfUpdaterMailconfig"];
                        if (!string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(emailDir))
                        {
                            var mail = new MailMessage();
                            mail.From = new MailAddress("*****@*****.**");

                            mail.To.Add(new MailAddress(emailDir));
                            mail.Subject = string.Format("Updates Manager chekcker job");

                            mail.Body       = body;
                            mail.IsBodyHtml = false;

                            using (var client = new SmtpClient())
                            {
                                client.Send(mail);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorHandler.Publish(LogLevel.Error, e);
                    }
                }
            }
        }
コード例 #21
0
    /// <summary>
    ///
    /// </summary>
    private void GuardarCambios()
    {
        string strIdSistema = (string)Session["idsistema"];


        if (!string.IsNullOrEmpty(strIdSistema))
        {
            try
            {
                ServiciosCD40.Redes n = new ServiciosCD40.Redes();
                n.IdSistema = strIdSistema;
                n.IdRed     = TxtIdRed.Text;
                n.Prefijo   = UInt16.Parse(DropDownList1.Text);

                NewItem = TxtIdRed.Text;

                //Si se va a insertar un nuevo registro
                if (!TxtIdRed.ReadOnly)
                {
                    if (ServicioCD40.InsertSQL(n) < 0)
                    {
                        logDebugView.Warn("(Redes-GuardarCambios): No se ha podido guardar la red.");
                    }
                    else
                    {
                        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                        KeyValueConfigurationElement sincronizar = config.AppSettings.Settings["SincronizaCD30"];
                        if ((sincronizar != null) && (Int32.Parse(sincronizar.Value) == 1))
                        {
                            SincronizaCD30.SincronizaCD30 sincro = new SincronizaCD30.SincronizaCD30();
                            switch (sincro.AltaRed((int)n.Prefijo, n.IdRed))
                            {
                            case 132:
                                cMsg.alert(String.Format((string)GetGlobalResourceObject("Espaniol", "Cod132"), n.IdRed));
                                break;

                            case 133:
                                cMsg.alert(String.Format((string)GetGlobalResourceObject("Espaniol", "Cod133"), n.IdRed));
                                break;

                            case 134:
                                cMsg.alert(String.Format((string)GetGlobalResourceObject("Espaniol", "Cod134"), n.IdRed));
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
                else
                {
                    //Si es una actualización, comprobamos si se ha cambiado el prefijo

                    if (n.Prefijo != iPrefijoRedElto)
                    {
                        //Se verifica que existe algún destino de telefonía con el prefijo asignado
                        //Si existe, se indica que se debe eliminar el destino para poder cambiar
                        //el prefijo de la red
                        if (ServicioCD40.Red_ConDestinosTlf(n.IdSistema, iPrefijoRedElto))
                        {
                            string strMsg = string.Empty;

                            if (null != GetLocalResourceObject("MsgMod_PrefRedConDestinosTelefonia"))
                            {
                                strMsg = string.Format(GetLocalResourceObject("MsgMod_PrefRedConDestinosTelefonia").ToString(), n.IdRed);
                            }
                            else
                            {
                                strMsg = string.Format("En el sistema existen destinos de telefonía que utilizan la red {0}. Antes de modificar el prefijo, debe eliminar estos destinos", n.IdRed);
                            }

                            cMsg.alert(strMsg);
                            return;
                        }
                    }
                    IndexListBox1 = ListBox1.SelectedIndex;

                    if (ServicioCD40.UpdateSQL(n) < 0)
                    {
                        logDebugView.Warn("(Redes-GuardarCambios): No se ha podido actualizar la red.");
                    }
                }
            }
            catch (Exception ex)
            {
                logDebugView.Error("(Redes-GuardarCambios): ", ex);
            }

            BtAceptar.Visible  = false;
            BtCancelar.Visible = false;
            //TxtIdRed.Visible = false;
            ListBox1.Enabled   = true;
            BtNuevo.Visible    = PermisoSegunPerfil;
            BtEliminar.Visible = BtModificar.Visible = PermisoSegunPerfil && ListBox1.Items.Count > 0;
            //Label1.Visible = false;
            //Label2.Visible = false;
            //DropDownList1.Visible = false;
            ListBox1.Enabled = true;
            ListBox1.Items.Clear();
            MuestraDatos(DameDatos());
        }
    }
コード例 #22
0
        protected void Button1Click(object sender, EventArgs e)
        {
            const string memberTypeAlias = "ForumUser";
            const string memberTypeName = "Forum User";
            const string memberTabName = "Content";
            const int textStringId = -88;
            const int numericId = -51;
            const int truefalseId = -49;
            const int datetimeId = -36;
            const string forumUserTwitterUrl = "forumUserTwitterUrl";
            const string forumUserPosts = "forumUserPosts";
            const string forumUserKarma = "forumUserKarma";
            const string forumUserAllowPrivateMessages = "forumUserAllowPrivateMessages";
            const string forumUserLastPrivateMessage = "forumUserLastPrivateMessage";
            const string forumUserIsAdmin = "forumUserIsAdmin";
            const string forumUserIsBanned = "forumUserIsBanned";
            const string forumUserIsAuthorised = "forumUserIsAuthorised";

            // First Create the MemberType
            var mt = CreateMemberType(memberTypeAlias, memberTypeName);

            // Now create the tab
            mt.AddVirtualTab(memberTabName);

            // Just trying to stop any timeouts
            Server.ScriptTimeout = 1000;

            // Add the properties            
            // forumUserTwitterUrl > textString
            var dt = DataTypeDefinition.GetDataTypeDefinition(textStringId);
            mt.AddPropertyType(dt, forumUserTwitterUrl, "Twitter Username");
            var prop = mt.getPropertyType(forumUserTwitterUrl);
            prop.Mandatory = false;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Save();

            // forumUserPosts > Numeric
            dt = DataTypeDefinition.GetDataTypeDefinition(numericId);
            mt.AddPropertyType(dt, forumUserPosts, "Users Post Amount");
            prop = mt.getPropertyType(forumUserPosts);
            prop.Mandatory = true;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Description = "Make sure this has a value, 0 by default";
            prop.Save();

            // forumUserKarma > Numeric
            dt = DataTypeDefinition.GetDataTypeDefinition(numericId);
            mt.AddPropertyType(dt, forumUserKarma, "Users Karma Amount");
            prop = mt.getPropertyType(forumUserKarma);
            prop.Mandatory = false;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Save();

            // forumUserAllowPrivateMessages > True/False
            dt = DataTypeDefinition.GetDataTypeDefinition(truefalseId);
            mt.AddPropertyType(dt, forumUserAllowPrivateMessages, "Users Allow Private Messages");
            prop = mt.getPropertyType(forumUserAllowPrivateMessages);
            prop.Mandatory = false;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Save();

            // Just trying to stop any timeouts
            Server.ScriptTimeout = 1000;

            // forumUserLastPrivateMessage > Date With time
            dt = DataTypeDefinition.GetDataTypeDefinition(datetimeId);
            mt.AddPropertyType(dt, forumUserLastPrivateMessage, "Date/Time Of Last Private Message");
            prop = mt.getPropertyType(forumUserLastPrivateMessage);
            prop.Mandatory = true;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Description = "This must have a value, default value should be the date and time the user registered/was created";
            prop.Save();

            // forumUserIsAdmin > True/False
            dt = DataTypeDefinition.GetDataTypeDefinition(truefalseId);
            mt.AddPropertyType(dt, forumUserIsAdmin, "Forum User Is Admin");
            prop = mt.getPropertyType(forumUserIsAdmin);
            prop.Mandatory = false;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Save();

            // forumUserIsBanned > True/False
            dt = DataTypeDefinition.GetDataTypeDefinition(truefalseId);
            mt.AddPropertyType(dt, forumUserIsBanned, "Forum User Is Banned From Forum");
            prop = mt.getPropertyType(forumUserIsBanned);
            prop.Mandatory = false;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Save();

            // forumUserIsAuthorised > True/False
            dt = DataTypeDefinition.GetDataTypeDefinition(truefalseId);
            mt.AddPropertyType(dt, forumUserIsAuthorised, "Forum User Is Authorised");
            prop = mt.getPropertyType(forumUserIsAuthorised);
            prop.Mandatory = false;
            prop.TabId = GetTabByCaption(mt, memberTabName).Id;
            prop.Save();

            // Just trying to stop any timeouts
            Server.ScriptTimeout = 1000;

            // Lastly create the group
            MemberGroup.MakeNew(memberTypeAlias, User.GetUser(0));

            // ----------- Web.Config ------------


            // set resetpassword to 'true' in web.config
            var config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            var section = (MembershipSection)config.GetSection("system.web/membership");

            var defaultProvider = section.DefaultProvider;
            var providerSettings = section.Providers[defaultProvider];
            providerSettings.Parameters.Set("enablePasswordReset", "true");
            config.Save();

            // Just trying to stop any timeouts
            Server.ScriptTimeout = 1000;

            // !!!!!!!!!!!!! >>> NOT NEEDED NOW <<< !!!!!!!!!!!!!!!!
            //------ Write the rest extensions to the restExtensions.config
            // look for <RestExtensions>
            //var configfilepath = Server.MapPath(@"~/config/restExtensions.config");
            //var configfiledata = File.ReadAllText(configfilepath);
            //var keytolookfor = "<RestExtensions>";
            //// Get the rest extensions in a string
            //var sb = new StringBuilder();
            //sb.Append(Environment.NewLine).Append("<ext assembly=\"nForum.BusinessLogic\" type=\"nForum.BusinessLogic.nForumBaseExtensions\" alias=\"Solution\">").Append(Environment.NewLine);
            //sb.Append("<permission method=\"MarkAsSolution\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("<permission method=\"ThumbsUpPost\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("<permission method=\"ThumbsDownPost\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("<permission method=\"NewForumPost\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("<permission method=\"NewForumTopic\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("<permission method=\"SubScribeToTopic\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("<permission method=\"UnSubScribeToTopic\" allowAll=\"true\" />").Append(Environment.NewLine);
            //sb.Append("</ext>").Append(Environment.NewLine);
            //// add the rest file data to the current file
            //configfiledata = configfiledata.Replace(keytolookfor, keytolookfor + sb);
            //// now save it!
            //File.WriteAllText(configfilepath, configfiledata);

            // Just trying to stop any timeouts
            Server.ScriptTimeout = 1000;

            //----- Write the url rewriting to the UrlRewriting.config
            // look for <rewrites>
            var configfilepath = Server.MapPath(@"~/config/UrlRewriting.config");
            var configfiledata = File.ReadAllText(configfilepath);
            var keytolookfor = "<rewrites>";
            // Get the rest extensions in a string
            var sb = new StringBuilder();
            sb.Clear();
            sb.Append(Environment.NewLine).Append("<add name=\"memberprofilerewrite\" ").Append(Environment.NewLine);
            sb.Append("virtualUrl=\"^~/member/(.*).aspx\" ").Append(Environment.NewLine);
            sb.Append("rewriteUrlParameter=\"ExcludeFromClientQueryString\" ").Append(Environment.NewLine);
            sb.Append("destinationUrl=\"~/memberprofile.aspx?mem=$1\" ").Append(Environment.NewLine);
            sb.Append("ignoreCase=\"true\" />").Append(Environment.NewLine);
            // add the rest file data to the current file
            configfiledata = configfiledata.Replace(keytolookfor, keytolookfor + sb);
            // now save it!
            File.WriteAllText(configfilepath, configfiledata);

            //------ Write the nforum index to the ExamineIndex.config
            //look for <ExamineLuceneIndexSets>
            configfilepath = Server.MapPath(@"~/config/ExamineIndex.config");
            configfiledata = File.ReadAllText(configfilepath);
            keytolookfor = "<ExamineLuceneIndexSets>";
            sb = new StringBuilder();
            sb.Append(Environment.NewLine).Append("<IndexSet SetName=\"nForumEntrySet\" IndexPath=\"~/App_Data/TEMP/ExamineIndexes/nForumEntryIndexSet/\">").Append(Environment.NewLine);
            sb.Append("<IndexAttributeFields>").Append(Environment.NewLine);
            sb.Append("<add Name=\"id\" EnableSorting=\"true\" Type=\"Number\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"nodeName\" EnableSorting=\"true\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"updateDate\" EnableSorting=\"true\" Type=\"DateTime\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"createDate\" EnableSorting=\"true\" Type=\"DateTime\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"writerName\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"path\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"nodeTypeAlias\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"parentID\" EnableSorting=\"true\" Type=\"Number\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"sortOrder\" EnableSorting=\"true\" Type=\"Number\" />").Append(Environment.NewLine);          
            sb.Append("</IndexAttributeFields>").Append(Environment.NewLine);
            sb.Append("<IndexUserFields>").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategoryDescription\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategoryIsMainCategory\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategoryIsPrivate\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategoryPermissionKarmaAmount\" Type=\"Number\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategoryPostPermissionKarmaAmount\" Type=\"Number\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategorySubscribedList\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumCategoryParentID\" />").Append(Environment.NewLine);            
            sb.Append("<add Name=\"forumPostContent\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostOwnedBy\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostLastEdited\" EnableSorting=\"true\" Type=\"DateTime\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostInReplyTo\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostIsSolution\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostIsTopicStarter\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostKarma\" EnableSorting=\"true\" Type=\"Number\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostUsersVoted\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumPostParentID\" />").Append(Environment.NewLine);            
            sb.Append("<add Name=\"forumTopicOwnedBy\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumTopicClosed\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumTopicSolved\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumTopicParentCategoryID\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumTopicIsSticky\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumTopicSubscribedList\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"forumTopicLastPostDate\" EnableSorting=\"true\" Type=\"DateTime\" />").Append(Environment.NewLine);            
            sb.Append("</IndexUserFields>").Append(Environment.NewLine);
            sb.Append("<IncludeNodeTypes>").Append(Environment.NewLine);
            sb.Append("<add Name=\"ForumCategory\"/>").Append(Environment.NewLine);
            sb.Append("<add Name=\"ForumPost\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"ForumTopic\" />").Append(Environment.NewLine);
            sb.Append("<add Name=\"Forum\" />").Append(Environment.NewLine);         
            sb.Append("</IncludeNodeTypes>").Append(Environment.NewLine);
            sb.Append("<ExcludeNodeTypes />").Append(Environment.NewLine);
            sb.Append("</IndexSet>").Append(Environment.NewLine);
            configfiledata = configfiledata.Replace(keytolookfor, keytolookfor + sb);
            File.WriteAllText(configfilepath, configfiledata);
            Server.ScriptTimeout = 1000;

            //------ Write the nforum settings to the ExamineSettings.config
            configfilepath = Server.MapPath(@"~/config/ExamineSettings.config");
            configfiledata = File.ReadAllText(configfilepath).Replace("<providers>", "");
            keytolookfor = "<ExamineIndexProviders>";
            sb = new StringBuilder();
            sb.Append(Environment.NewLine).Append("<#providers#><add name=\"nForumEntryIndexer\" ").Append(Environment.NewLine);
            sb.Append("type=\"UmbracoExamine.UmbracoContentIndexer, UmbracoExamine\" ").Append(Environment.NewLine);
            sb.Append("dataService=\"UmbracoExamine.DataServices.UmbracoDataService, UmbracoExamine\" ").Append(Environment.NewLine);
            sb.Append("indexSet=\"nForumEntrySet\" ").Append(Environment.NewLine);
            sb.Append("supportUnpublished=\"false\" ").Append(Environment.NewLine);
            sb.Append("supportProtected=\"false\" ").Append(Environment.NewLine);
            sb.Append("runAsync=\"true\" ").Append(Environment.NewLine);
            sb.Append("interval=\"10\" ").Append(Environment.NewLine);
            sb.Append("analyzer=\"Lucene.Net.Analysis.Standard.StandardAnalyzer, Lucene.Net\" ").Append(Environment.NewLine);
            sb.Append("enableDefaultEventHandler=\"true\"/>").Append(Environment.NewLine);
            configfiledata = configfiledata.Replace(keytolookfor, keytolookfor + sb);
            File.WriteAllText(configfilepath, configfiledata);
            Server.ScriptTimeout = 1000;

            //------ Write the nforum settings to the ExamineSettings.config
            configfilepath = Server.MapPath(@"~/config/ExamineSettings.config");
            configfiledata = File.ReadAllText(configfilepath).Replace("<providers>", "").Replace("<#providers#>", "<providers>");
            keytolookfor = "<ExamineSearchProviders defaultProvider=\"InternalSearcher\">";
            sb = new StringBuilder();
            sb.Append(Environment.NewLine).Append("<providers><add name=\"nForumEntrySearcher\" type=\"UmbracoExamine.UmbracoExamineSearcher, UmbracoExamine\" ").Append(Environment.NewLine);
            sb.Append("indexSet=\"nForumEntrySet\" analyzer=\"Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net\"/>").Append(Environment.NewLine);
            configfiledata = configfiledata.Replace(keytolookfor, keytolookfor + sb);
            File.WriteAllText(configfilepath, configfiledata);
            Server.ScriptTimeout = 1000;

            // -- All done hide and show panels
            pnlFirstInfo.Visible = false;
            btnComplete.Visible = false;
            pnlSecondInfor.Visible = true;

        }
コード例 #23
0
        static ProcessConfiguration()
        {
            try
            {
                System.Configuration.Configuration config;
                string folderName;

                var exeName = PathUtil.GetExeName();

                var isWebApplication = StringUtil.CompareIgnoreCase(
                    Path.GetFileNameWithoutExtension(exeName), TisServicesConst.IIS_PROCESS_NAME);

                bool isClientConfiguration = true;

                if (isWebApplication)
                {
                    folderName = HttpRuntime.AppDomainAppPath;

                    config = WebConfigurationManager.OpenWebConfiguration(
                        System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath,
                        System.Web.Hosting.HostingEnvironment.SiteName);

                    ProcessConfigFile = config.FilePath;

                    isClientConfiguration = System.Web.Hosting.HostingEnvironment.ApplicationID.EndsWith(WebConfigConstants.EFLOW_WEB_APP_NAME) == false;

                    if (isClientConfiguration)
                    {
                        // WebCompletion eFlow server
                        ClientServiceModelSection = ServiceModelSectionGroup.GetSectionGroup(config);
                    }
                }
                else
                {
                    if (IsDevelopementProcess(Path.GetFileNameWithoutExtension(exeName)))
                    {
                        // devenv (Visual Studio)
                        folderName        = Path.Combine(RegistryUtil.eFlowPath, @"Bin");
                        ProcessConfigFile = String.Empty;
                    }
                    else
                    {
                        // eFlow client
                        folderName        = PathUtil.GetExePath();
                        ProcessConfigFile = Path.Combine(folderName, exeName + TisServicesConst.CONFIG_FILE_EXT);
                    }

                    if (!File.Exists(ProcessConfigFile))
                    {
                        IsCustomConfig    = true;
                        ProcessConfigFile = Path.Combine(folderName, DEFAULT_CONFIG_FILE);
                    }

                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

                    fileMap.ExeConfigFilename = ProcessConfigFile;

                    config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                    ClientServiceModelSection = ServiceModelSectionGroup.GetSectionGroup(config);
                }

                var basicConfigElement  = config.AppSettings.Settings[APPSETTING_KEY_BASIC];
                var loggerConfigElement = config.AppSettings.Settings[APPSETTING_KEY_LOGGER];

                var basicConfigFilePart = basicConfigElement != null ? basicConfigElement.Value :
                                          isClientConfiguration?Path.Combine(CLIENT_DEFAULT_FOLDER, BASIC_CONFIG_DEFAULT_FILE_NAME) : Path.Combine(SERVER_DEFAULT_FOLDER, BASIC_CONFIG_DEFAULT_FILE_NAME);

                var loggerConfigFilePart = loggerConfigElement != null ? loggerConfigElement.Value :
                                           isClientConfiguration?Path.Combine(CLIENT_DEFAULT_FOLDER, LOGGER_CONFIG_DEFAULT_FILE_NAME) : Path.Combine(SERVER_DEFAULT_FOLDER, LOGGER_CONFIG_DEFAULT_FILE_NAME);

                BasicConfigFile  = Path.Combine(folderName, basicConfigFilePart);
                LoggerConfigFile = Path.Combine(folderName, loggerConfigFilePart);

                if (isWebApplication)
                {
                    Log.WriteInfo("HostingEnvironment : ApplicationID : [{0}], ApplicationPhysicalPath : [{1}], ApplicationVirtualPath : [{2}].",
                                  System.Web.Hosting.HostingEnvironment.ApplicationID,
                                  System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath,
                                  System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                }

                Log.WriteInfo("In use : Process configuration file : [{0}], Basic configuration file : [{1}], Logger configuration file : [{2}].",
                              ProcessConfigFile, BasicConfigFile, LoggerConfigFile);
            }
            catch (Exception exc)
            {
                Log.WriteException(exc);
            }
        }
コード例 #24
0
 public DataBaseConfigService(string path)
 {
     config = WebConfigurationManager.OpenWebConfiguration(path);
 }
コード例 #25
0
        private string ReadConnectionString()
        {
            Configuration conf = WebConfigurationManager.OpenWebConfiguration("~");

            return(conf.ConnectionStrings.ConnectionStrings["SampleDatabaseContext"].ConnectionString);
        }
コード例 #26
0
        public ActionResult Login(UserViewModel model)
        {
            string TokenUri = "Http://localhost:62367/api/Token";

            //var getTokenUrl = string.Format(ApiEndPoints.AuthorisationTokenEndpoint.Post.Token, ConfigurationManager.AppSettings["ApiBaseUri"]);

            using (HttpClient httpClient = new HttpClient())
            {
                HttpContent content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", model.UserName),
                    new KeyValuePair <string, string>("password", model.Password)
                });

                HttpResponseMessage Responses = httpClient.PostAsync(TokenUri, content).Result;
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                string resultContent = Responses.Content.ReadAsStringAsync().Result;

                var result = JsonConvert.DeserializeObject <Token>(resultContent);
                //
                FormsAuthentication.SetAuthCookie(result.AccessToken, true);
                AuthenticationProperties options = new AuthenticationProperties();

                options.AllowRefresh = true;
                options.IsPersistent = true;
                //options.ExpiresUtc = DateTime.UtcNow.AddSeconds(int.Parse(token.expires_in));

                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.UserName),           //Name is the default name claim type, and UserName is the one known also in Web API.
                    new Claim(ClaimTypes.NameIdentifier, result.UserName), //If you want to use User.Identity.GetUserId in Web API, you need a NameIdentifier
                    new Claim("AcessToken", result.AccessToken)
                };

                var identity   = new ClaimsIdentity(claims, "ApplicationCookie");
                var authTicket = new AuthenticationTicket(new ClaimsIdentity(claims, "ApplicationCookie"), new AuthenticationProperties
                {
                    ExpiresUtc = result.Expires,

                    IssuedUtc = result.Issued
                });
                byte[] userData      = DataSerializers.Ticket.Serialize(authTicket);
                string protectedText = TextEncodings.Base64Url.Encode(userData);
                Response.SetCookie(new HttpCookie("CloudChef.WebApi.Auth")
                {
                    HttpOnly = true,
                    Expires  = result.Expires.UtcDateTime,
                    Value    = protectedText
                });
                var claimidentity           = (ClaimsIdentity)User.Identity;
                IEnumerable <Claim> claimsI = claimidentity.Claims;
                string        BToken        = claimsI.Where(x => x.Type == "AcessToken").Select(x => x.Value).FirstOrDefault().ToString();
                Configuration webConfigApp  = WebConfigurationManager.OpenWebConfiguration("~");
                var           settings      = webConfigApp.AppSettings.Settings;
                if (settings["BearerToken"] == null)
                {
                    settings.Add("BearerToken", BToken);
                }
                else
                {
                    settings["BearerToken"].Value = BToken;
                }
                webConfigApp.Save(ConfigurationSaveMode.Modified);

                Request.GetOwinContext().Authentication.SignIn(options, identity);
            }


            return(RedirectToAction("Index", "Home"));
            //var TokenResponse = await loginClient.Login(model);
            //if (TokenResponse.StatusIsSuccessful)
            //{
            //    FormAuthHelper.ValidateUser(model, TokenResponse, Response);

            //}
            //Session["token"] = TokenResponse.Data;
            //return RedirectToAction("Index", "Home");
        }
コード例 #27
0
        public HttpResponseMessage Configurations(ConfigurationModel configurationModel)
        {
            try
            {
                Configuration      config             = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
                CampusLogicSection campusLogicSection = (CampusLogicSection)config.GetSection("campusLogicConfig");
                SmtpSection        smtpSection        = (SmtpSection)config.GetSection("system.net/mailSettings/smtp");
                AppSettingsSection appSettings        = config.AppSettings;

                //Workarounds until we can figure out why the properties won't deserialize as is
                campusLogicSection.EventNotifications = configurationModel.CampusLogicSection.EventNotifications;
                campusLogicSection.EventNotifications.EventNotificationsEnabled =
                    configurationModel.CampusLogicSection.EventNotificationsEnabled;
                foreach (EventNotificationHandler eventNotificationHandler in configurationModel.CampusLogicSection.EventNotificationsList)
                {
                    campusLogicSection.EventNotifications.Add(eventNotificationHandler);
                }

                campusLogicSection.FileStoreSettings = configurationModel.CampusLogicSection.FileStoreSettings;
                foreach (FieldMapSettings fieldMapSetting in configurationModel.CampusLogicSection.FileStoreSettings.FileStoreMappingCollection)
                {
                    campusLogicSection.FileStoreSettings.FileStoreMappingCollectionConfig.Add(fieldMapSetting);
                }

                campusLogicSection.DocumentSettings = configurationModel.CampusLogicSection.DocumentSettings;
                foreach (FieldMapSettings fieldMapSetting in configurationModel.CampusLogicSection.DocumentSettings.FieldMappingCollection)
                {
                    campusLogicSection.DocumentSettings.FieldMappingCollectionConfig.Add(fieldMapSetting);
                }

                campusLogicSection.StoredProcedures = configurationModel.CampusLogicSection.StoredProcedures;
                campusLogicSection.StoredProcedures.StoredProceduresEnabled =
                    configurationModel.CampusLogicSection.StoredProceduresEnabled;

                foreach (StoredProcedureDto storedProcedure in configurationModel.CampusLogicSection.StoredProcedureList)
                {
                    StoredProcedureElement storedProcedureElement = new StoredProcedureElement();
                    storedProcedureElement.Name = storedProcedure.Name;

                    foreach (ParameterDto parameter in storedProcedure.ParameterList)
                    {
                        ParameterElement parameterElement = new ParameterElement();
                        parameterElement.Name     = parameter.Name;
                        parameterElement.DataType = parameter.DataType;
                        parameterElement.Length   = parameter.Length;
                        parameterElement.Source   = parameter.Source;

                        storedProcedureElement.Add(parameterElement);
                    }

                    campusLogicSection.StoredProcedures.Add(storedProcedureElement);
                }

                campusLogicSection.BatchProcessingTypes = configurationModel.CampusLogicSection.BatchProcessingTypes;
                campusLogicSection.BatchProcessingTypes.BatchProcessingEnabled = configurationModel.CampusLogicSection.BatchProcessingEnabled;
                foreach (BatchProcessingTypeDto batchProcessingType in configurationModel.CampusLogicSection.BatchProcessingTypesList)
                {
                    BatchProcessingTypeElement batchProcessingTypeElement = new BatchProcessingTypeElement();
                    batchProcessingTypeElement.TypeName = batchProcessingType.TypeName;

                    foreach (BatchProcessDto batchProcess in batchProcessingType.BatchProcesses)
                    {
                        var batchProcessElement = new BatchProcessElement();
                        batchProcessElement.BatchName = batchProcess.BatchName;

                        if (batchProcessingTypeElement.TypeName == ConfigConstants.AwardLetterPrintBatchType)
                        {
                            batchProcessElement.MaxBatchSize          = batchProcess.MaxBatchSize;
                            batchProcessElement.FilePath              = batchProcess.FilePath;
                            batchProcessElement.FileNameFormat        = batchProcess.FileNameFormat;
                            batchProcessElement.BatchExecutionMinutes = batchProcess.BatchExecutionMinutes;
                            batchProcessElement.IndexFileEnabled      = batchProcess.IndexFileEnabled;
                            batchProcessElement.FileDefinitionName    = batchProcess.FileDefinitionName;
                        }

                        batchProcessingTypeElement.Add(batchProcessElement);
                    }

                    campusLogicSection.BatchProcessingTypes.Add(batchProcessingTypeElement);
                }

                campusLogicSection.FileDefinitionSettings = configurationModel.CampusLogicSection.FileDefinitionSettings;
                campusLogicSection.FileDefinitionSettings.FileDefinitionsEnabled = configurationModel.CampusLogicSection.FileDefinitionsEnabled;
                foreach (var listSetting in configurationModel.CampusLogicSection.FileDefinitionsList)
                {
                    FileDefinitionSetting fileDefinitionSetting = new FileDefinitionSetting();
                    fileDefinitionSetting.Name                = listSetting.Name;
                    fileDefinitionSetting.FileNameFormat      = listSetting.FileNameFormat;
                    fileDefinitionSetting.IncludeHeaderRecord = listSetting.IncludeHeaderRecord;
                    fileDefinitionSetting.FileExtension       = listSetting.FileExtension;
                    fileDefinitionSetting.FileFormat          = listSetting.FileFormat;

                    foreach (var fieldMapping in listSetting.FieldMappingCollection)
                    {
                        fileDefinitionSetting.FieldMappingCollectionConfig.Add(fieldMapping);
                    }

                    campusLogicSection.FileDefinitionSettings.Add(fileDefinitionSetting);
                }

                campusLogicSection.ApiIntegrations = configurationModel.CampusLogicSection.ApiIntegrations;
                campusLogicSection.ApiIntegrations.ApiIntegrationsEnabled = configurationModel.CampusLogicSection.ApiIntegrationsEnabled;
                foreach (ApiIntegrationDto apiIntegration in configurationModel.CampusLogicSection.ApiIntegrationsList)
                {
                    ApiIntegrationElement apiIntegrationElement = new ApiIntegrationElement();
                    apiIntegrationElement.ApiId          = apiIntegration.ApiId;
                    apiIntegrationElement.ApiName        = apiIntegration.ApiName;
                    apiIntegrationElement.Authentication = apiIntegration.Authentication;
                    apiIntegrationElement.TokenService   = apiIntegration.TokenService;
                    apiIntegrationElement.Root           = apiIntegration.Root;
                    apiIntegrationElement.Username       = apiIntegration.Username;
                    apiIntegrationElement.Password       = apiIntegration.Password;

                    campusLogicSection.ApiIntegrations.Add(apiIntegrationElement);
                }

                campusLogicSection.ApiEndpoints = configurationModel.CampusLogicSection.ApiEndpoints;
                foreach (ApiIntegrationEndpointDto apiEndpoint in configurationModel.CampusLogicSection.ApiEndpointsList)
                {
                    ApiIntegrationEndpointElement endpointElement = new ApiIntegrationEndpointElement();
                    endpointElement.Name              = apiEndpoint.Name;
                    endpointElement.Endpoint          = apiEndpoint.Endpoint;
                    endpointElement.ApiId             = apiEndpoint.ApiId;
                    endpointElement.Method            = apiEndpoint.Method;
                    endpointElement.MimeType          = apiEndpoint.MimeType;
                    endpointElement.ParameterMappings = JArray.Parse(apiEndpoint.ParameterMappings).ToString();

                    campusLogicSection.ApiEndpoints.Add(endpointElement);
                }

                campusLogicSection.PowerFaidsSettings = configurationModel.CampusLogicSection.PowerFaidsSettings;
                campusLogicSection.PowerFaidsSettings.PowerFaidsEnabled = configurationModel.CampusLogicSection.PowerFaidsEnabled;
                foreach (var record in configurationModel.CampusLogicSection.PowerFaidsList)
                {
                    PowerFaidsSetting powerFaidsSetting = new PowerFaidsSetting();
                    powerFaidsSetting.Event                   = record.Event;
                    powerFaidsSetting.Outcome                 = record.Outcome;
                    powerFaidsSetting.ShortName               = record.ShortName;
                    powerFaidsSetting.RequiredFor             = record.RequiredFor;
                    powerFaidsSetting.Status                  = record.Status;
                    powerFaidsSetting.DocumentLock            = record.DocumentLock;
                    powerFaidsSetting.VerificationOutcome     = record.VerificationOutcome;
                    powerFaidsSetting.VerificationOutcomeLock = record.VerificationOutcomeLock;
                    powerFaidsSetting.TransactionCategory     = record.TransactionCategory;

                    campusLogicSection.PowerFaidsSettings.PowerFaidsSettingCollectionConfig.Add(powerFaidsSetting);
                }

                campusLogicSection.BulkActionSettings        = configurationModel.CampusLogicSection.BulkActionSettings;
                campusLogicSection.ISIRUploadSettings        = configurationModel.CampusLogicSection.ISIRUploadSettings;
                campusLogicSection.ISIRCorrectionsSettings   = configurationModel.CampusLogicSection.ISIRCorrectionsSettings;
                campusLogicSection.AwardLetterUploadSettings = configurationModel.CampusLogicSection.AwardLetterUploadSettings;
                campusLogicSection.DataFileUploadSettings    = configurationModel.CampusLogicSection.DataFileUploadSettings;
                campusLogicSection.FileMappingUploadSettings = configurationModel.CampusLogicSection.FileMappingUploadSettings;
                campusLogicSection.AwardLetterPrintSettings  = configurationModel.CampusLogicSection.AwardLetterPrintSettings;
                campusLogicSection.SMTPSettings             = configurationModel.CampusLogicSection.SMTPSettings;
                campusLogicSection.ClientDatabaseConnection = configurationModel.CampusLogicSection.ClientDatabaseConnection;
                campusLogicSection.DocumentImportSettings   = configurationModel.CampusLogicSection.DocumentImportSettings;
                smtpSection.DeliveryMethod             = configurationModel.SmtpSection.DeliveryMethod;
                smtpSection.DeliveryFormat             = configurationModel.SmtpSection.DeliveryFormat;
                smtpSection.From                       = configurationModel.SmtpSection.From;
                smtpSection.Network.ClientDomain       = configurationModel.SmtpSection.Network.ClientDomain;
                smtpSection.Network.DefaultCredentials = configurationModel.SmtpSection.Network.DefaultCredentials;
                smtpSection.Network.EnableSsl          = configurationModel.SmtpSection.Network.EnableSsl;
                smtpSection.Network.Host               = configurationModel.SmtpSection.Network.Host;
                smtpSection.Network.Password           = configurationModel.SmtpSection.Network.Password;
                smtpSection.Network.Port               = configurationModel.SmtpSection.Network.Port;
                smtpSection.Network.TargetName         = configurationModel.SmtpSection.Network.TargetName;
                smtpSection.Network.UserName           = configurationModel.SmtpSection.Network.UserName;
                smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation = configurationModel.SmtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation;
                appSettings.Settings.Clear();

                foreach (var appSetting in configurationModel.AppSettingsSection)
                {
                    appSettings.Settings.Add(FirstCharToUpper(appSetting.Key), appSetting.Value);
                }

                Assembly     clConnectAssembly = Assembly.GetExecutingAssembly();
                AssemblyName clConnect         = clConnectAssembly.GetName();

                appSettings.Settings["ClConnectVersion"].Value             = clConnect.Version.ToString();
                appSettings.Settings["Webpages:Version"].Value             = "2.0.0.0";
                appSettings.Settings["Webpages:Enabled"].Value             = "false";
                appSettings.Settings["PreserveLoginUrl"].Value             = "true";
                appSettings.Settings["ClientValidationEnabled"].Value      = "true";
                appSettings.Settings["UnobtrusiveJavaScriptEnabled"].Value = "true";

                if (appSettings.Settings["Environment"].Value == EnvironmentConstants.SANDBOX)
                {
                    appSettings.Settings["StsUrl"].Value               = ApiUrlConstants.STS_URL_SANDBOX;
                    appSettings.Settings["SvWebApiUrl"].Value          = ApiUrlConstants.SV_API_URL_SANDBOX;
                    appSettings.Settings["AwardLetterWebApiUrl"].Value = ApiUrlConstants.AL_API_URL_SANDBOX;
                    appSettings.Settings["PmWebApiUrl"].Value          = ApiUrlConstants.PM_API_URL_SANDBOX;
                    appSettings.Settings["SuWebApiUrl"].Value          = ApiUrlConstants.SU_API_URL_SANDBOX;
                }
                else
                {
                    appSettings.Settings["StsUrl"].Value               = ApiUrlConstants.STS_URL_PRODUCTION;
                    appSettings.Settings["SvWebApiUrl"].Value          = ApiUrlConstants.SV_API_URL_PRODUCTION;
                    appSettings.Settings["AwardLetterWebApiUrl"].Value = ApiUrlConstants.AL_API_URL_PRODUCTION;
                    appSettings.Settings["PmWebApiUrl"].Value          = ApiUrlConstants.PM_API_URL_PRODUCTION;
                    appSettings.Settings["SuWebApiUrl"].Value          = ApiUrlConstants.SU_API_URL_PRODUCTION;
                }

                ClearOldFileDefinitions(campusLogicSection);

                config.Save();
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                logger.ErrorFormat("SetupController SaveConfigurations Error: {0}", ex);
                return(Request.CreateResponse(HttpStatusCode.ExpectationFailed));
            }
        }
コード例 #28
0
        /// <summary>
        /// Initialise the session state store.
        /// </summary>
        /// <param name="name">session state store name. Defaults to "MongoSessionStateStore" if not supplied</param>
        /// <param name="config">configuration settings</param>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            // Initialize values from web.config.
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (name.Length == 0)
            {
                name = "MongoSessionStateStore";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "MongoDB Session State Store provider");
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            // Initialize the ApplicationName property.
            _applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            // Get <sessionState> configuration element.
            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);

            _config = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            // Initialize connection string.
            _connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

            if (_connectionStringSettings == null || _connectionStringSettings.ConnectionString.Trim() == "")
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            _connectionString = _connectionStringSettings.ConnectionString;

            // Initialize WriteExceptionsToEventLog
            _writeExceptionsToEventLog = false;

            if (config["writeExceptionsToEventLog"] != null)
            {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
                {
                    _writeExceptionsToEventLog = true;
                }
            }

            // Initialise WriteConcern options.
            // Defaults to fsynch=false, w=1 (Provides acknowledgment of write operations on a standalone mongod or the primary in a replica set.)
            // replicasToWrite config item comes into use when > 0. This translates to the WriteConcern wValue, by adding 1 to it.
            // e.g. replicasToWrite = 1 is taken as meaning "I want to wait for write operations to be acknowledged at the primary + {replicasToWrite} replicas"
            // MongoDB C# Driver references on WriteConcern : http://docs.mongodb.org/manual/core/write-operations/#write-concern
            bool fsync = false;

            if (config["fsync"] != null)
            {
                if (config["fsync"].ToUpper() == "TRUE")
                {
                    fsync = true;
                }
            }

            int replicasToWrite = 1;

            if (config["replicasToWrite"] != null)
            {
                if (!int.TryParse(config["replicasToWrite"], out replicasToWrite))
                {
                    throw new ProviderException("Replicas To Write must be a valid integer");
                }
            }

            string wValue = "1";

            if (replicasToWrite > 0)
            {
                wValue = (1 + replicasToWrite).ToString(CultureInfo.InvariantCulture);
            }

            _writeConcern = new WriteConcern
            {
                FSync = fsync,
                W     = WriteConcern.WValue.Parse(wValue)
            };
        }
コード例 #29
0
 public static IContainer Compose()
 {
     return(Compose(WebConfigurationManager.OpenWebConfiguration("~/")));
 }
コード例 #30
0
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(applicationPath))
            {
                applicationPath = Request.ApplicationPath;
                initRequestUrl  = Request.Url.ToString();
                //Logging(Request, null, initRequestUrl, null, "Application Started", GetRequestInfo());
                try
                {
                    string        str  = HttpContext.Current.Request.ApplicationPath.ToString();
                    Configuration conf = WebConfigurationManager.OpenWebConfiguration(str);
                    ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
                    Application["MaxJsonLength"] = section.MaxJsonLength.ToString();
                }
                catch { }

                started = true;
            }

            if (!pulseStarted
                //&& !HttpContext.Current.Request.Url.AbsolutePath.Contains("/CronJob.aspx")
                )
            {
                StartBackgroundTask(Config.EnableSsl);
            }
            string extBasePath = Config.ExtBasePath ?? "";
            string appPath     = Request.ApplicationPath;

            if (Request.Path == appPath &&
                appPath.ToLower() != extBasePath.ToLower() &&
                Request.ApplicationPath != "/" &&
                Request.Headers["X-Forwarded-For"] != null
                )
            {
                string redirectUrl = Request.Path + "/";
                try
                {
                    Dictionary <string, string> requestHeader = new Dictionary <string, string>();
                    foreach (string x in Request.Headers.Keys)
                    {
                        requestHeader[x] = Request.Headers[x];
                    }
                    requestHeader["Host"]            = Request.Url.Host;
                    requestHeader["ApplicationPath"] = appPath;

                    string url = Utils.transformProxyUrl(redirectUrl, requestHeader);
                    Response.Redirect(url);
                }
                catch
                {
                }
            }
            else
            {
                // IIS restriction, modifying cache-control invalidate default document handling in classic pipeline(so must switch to integrated if this is required)
                if (Config.PageCacheControl > 0)
                {
                    // must deliberately set this for time based caching or it becomes public
                    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                    // no-cache, max-age and expiry has no effect on forward/backward button(and most likely history)
                    // chrome/firefox default is no-cache if there is no cache-control, except forward/backward button
                    Response.Cache.SetExpires(DateTime.UtcNow.AddSeconds(Config.PageCacheControl.Value));
                }
                else if (Config.PageCacheControl == 0)
                {
                    // deliberately want to retain default asp.net behavior(say to use classic pipeline
                    // won't do anything to the cache control pipeline
                }
                else  // extreme no-cache
                {
                    //this is absolutely no caching, effectively same as 'form post', even back/forward button in chrome would hit server
                    Response.Cache.SetNoStore();
                }
            }
        }