/// <summary>
        /// Converts the JSON into the XML equivalent.
        /// </summary>
        private static void ConvertJson(ConfigurationEntity entity, XElement xml, JObject jo)
        {
            foreach (var jp in jo.Children().OfType <JProperty>())
            {
                if (jp.Value.Type == JTokenType.Array)
                {
                    var ci = GetConfigInfo(jp.Name);
                    if (ci.entity == ConfigurationEntity.None)
                    {
                        continue;
                    }

                    var ja = jp.Value as JArray;
                    foreach (var ji in ja !)
                    {
                        if (ji.Type == JTokenType.Object)
                        {
                            var xe = new XElement(ci.name);
                            ConvertJson(ci.entity, xe, (JObject)ji);
                            xml.Add(xe);
                        }
                    }
                }
                else
                {
                    xml.Add(new XAttribute(XmlJsonRename.GetXmlName(entity, jp.Name), jp.Value));
                }
            }
        }
Esempio n. 2
0
        private void CreateConfiguration()
        {
            // Connect to storage.
            var account = CloudStorageAccount.Parse(this.ConnectionString);
            var client  = account.CreateCloudTableClient();

            // Create tables.
            var table = client.GetTableReference("Configuration");

            table.Create();

            // Create configuration settings.
            var settings = new List <Setting>()
            {
                new Setting()
                {
                    Namespace = "Token", Key = "SigningKey", Value = "7yccElovdbvWnGIzzSrd2TkeejPCWr3F"
                }
            };

            foreach (var setting in settings)
            {
                // Create setting.
                var entity    = new ConfigurationEntity(setting);
                var operation = TableOperation.Insert(entity);

                var result = table.Execute(operation);
            }
        }
Esempio n. 3
0
        public ActionResult Create(ConfigurationViewModel viewModel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }
                else
                {
                    ConfigurationEntity entity = new ConfigurationEntity();

                    entity.ApplicationId = viewModel.ApplicationId;
                    entity.DataType      = viewModel.DataType;
                    entity.Value         = viewModel.Value;
                    entity.Key           = viewModel.Key;
                    entity.IsActive      = false;
                    entity.IsNew         = false;

                    OperationResult <bool> result = this.configurationRepository.Save(entity);
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 4
0
            public ConfigurationEntity GetConfigurationEntity(string configId)
            {
                string           commandText           = "SELECT * FROM tbl_config_detail WHERE config_id=@CONFIG_ID";
                DataTable        outputDataTable       = new DataTable();
                TalentDataAccess talentSqlAccessDetail = new TalentDataAccess();

                try
                {
                    //Construct The Call
                    talentSqlAccessDetail.Settings = settings;
                    talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteDataSet;
                    talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@CONFIG_ID", configId));
                    ErrorObj err = new ErrorObj();
                    talentSqlAccessDetail.CommandElements.CommandText = commandText;
                    err = talentSqlAccessDetail.SQLAccess(DestinationDatabase.TALENT_CONFIG);
                    if ((!(err.HasError)) && (!(talentSqlAccessDetail.ResultDataSet == null)))
                    {
                        outputDataTable = talentSqlAccessDetail.ResultDataSet.Tables[0];
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    talentSqlAccessDetail = null;
                }
                if (outputDataTable.Rows.Count > 0)
                {
                    return(ConfigurationEntity.GetEntity(outputDataTable.Rows[0]));
                }
                return(null);
            }
Esempio n. 5
0
        public ActionResult Edit(int id, ConfigurationViewModel viewModel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }
                else
                {
                    var entity = new ConfigurationEntity();

                    entity.Id            = viewModel.Id;
                    entity.ApplicationId = viewModel.ApplicationId;
                    entity.DataType      = viewModel.DataType;
                    entity.IsActive      = viewModel.IsActive;
                    entity.Key           = viewModel.Key;
                    entity.Value         = viewModel.Value;
                    entity.IsNew         = viewModel.IsNew;
                    entity.IsProcessed   = viewModel.IsProcessed;

                    this.configurationRepository.Edit(id, entity);
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
        /// <summary>
        /// Store or update configuration entity in table storage
        /// </summary>
        /// <param name="entity">entity.</param>
        /// <returns><see cref="Task"/> that represents configuration entity is saved or updated.</returns>
        private async Task <TableResult> StoreOrUpdateEntityAsync(ConfigurationEntity entity)
        {
            await this.EnsureInitializedAsync();

            TableOperation addOrUpdateOperation = TableOperation.InsertOrReplace(entity);

            return(await this.configurationCloudTable.ExecuteAsync(addOrUpdateOperation));
        }
        private ConfigurationEntity Convert(ConfigurationObject obj)
        {
            ConfigurationEntity result = new ConfigurationEntity();

            result.Value = obj.Value;
            result.Name  = obj.Name;
            return(result);
        }
Esempio n. 8
0
        /// <summary>
        /// Method to delete the configuration entity.
        /// </summary>
        /// <param name="entity">The configuration to be deleted.</param>
        /// <returns>A unit of execution to say whether or not the delete happened successfully.</returns>
        public Task DeleteConfigurationAsync(ConfigurationEntity entity)
        {
            if (entity is null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            return(this.DeleteEntityAsync(entity));
        }
Esempio n. 9
0
        private int DataLength(ConfigurationEntity entity)
        {
            int defaultKeysLength  = entity.DefaultKey1.Length + entity.DefaultKey2.Length + entity.DefaultKey3.Length + entity.DefaultKey4.Length;
            int variableKeysLength = entity.VariableKey1.Length + entity.VariableKey2.Length + entity.VariableKey3.Length + entity.VariableKey4.Length;
            int length             = entity.TableName.Length + entity.DefaultName.Length + entity.MasterConfigId.Length + defaultKeysLength +
                                     variableKeysLength + entity.DefaultValue.Length + entity.AllowedValues.Length + entity.AllowedPlaceHolders.Length;

            return(length);
        }
        public async Task <ConfigurationEntity> Update(ConfigurationEntity configuration)
        {
            ConfigurationEntity currentEntity = await Get();

            _context.Configurations.Update(currentEntity);

            await _context.SaveChangesAsync();

            return(configuration);
        }
Esempio n. 11
0
        public ConfigurationObject(ConfigurationEntity entity)
        {
            if (entity == null)
            {
                return;
            }

            Name  = entity.Name;
            Value = entity.Value;
        }
Esempio n. 12
0
        private GUIDType GenerateGUID(int id, ConfigurationEntity entity)
        {
            GUIDType guidValue = new GUIDType();

            guidValue.FirstPart  = GetFirstPart(entity.TableName);
            guidValue.SecondPart = GetSecondPart(entity.DefaultName);
            guidValue.ThirdPart  = GetThirdPart(DataLength(entity).ToString());
            guidValue.FourthPart = GetFourthPart(id.ToString());
            return(guidValue);
        }
Esempio n. 13
0
            /// <summary>
            /// XML Comment
            /// </summary>
            /// <param name="entity"></param>
            /// <param name="givenTransaction"></param>
            /// <returns></returns>
            /// <remarks></remarks>
            public bool SaveEntity(ConfigurationEntity entity, string moduleName, SqlTransaction givenTransaction)
            {
                bool   result      = false;
                string commandText = "INSERT INTO [tbl_config_detail] ([CONFIG_ID],[TABLE_NAME], [MASTER_CONFIG], [DEFAULT_KEY1],[DEFAULT_KEY2], [DEFAULT_KEY3], [DEFAULT_KEY4], [VARIABLE_KEY1], [VARIABLE_KEY2], [VARIABLE_KEY3], [VARIABLE_KEY4], [DISPLAY_NAME], [DEFAULT_NAME],[DEFAULT_VALUE], [ALLOWED_VALUE], [ALLOWED_PLACE_HOLDER], [Description], [MODULE_NAME], [CREATED_TIMESTAMP])" +
                                     " VALUES (@CONFIG_ID, @TABLE_NAME, @MASTER_CONFIG, @DEFAULT_KEY1, @DEFAULT_KEY2, @DEFAULT_KEY3, @DEFAULT_KEY4, @VARIABLE_KEY1, @VARIABLE_KEY2, @VARIABLE_KEY3, @VARIABLE_KEY4, @DISPLAY_NAME, @DEFAULT_NAME, @DEFAULT_VALUE, @ALLOWED_VALUE, @ALLOWED_PLACE_HOLDER, @Description, @ModuleName, GETDATE())";
                int affectedRows = 0;
                TalentDataAccess talentSqlAccessDetail = new TalentDataAccess();
                ErrorObj         err = new ErrorObj();

                //Construct The Call
                talentSqlAccessDetail.Settings = settings;
                talentSqlAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteNonQuery;
                talentSqlAccessDetail.CommandElements.CommandText          = commandText;
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@CONFIG_ID", entity.ConfigurationId));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@TABLE_NAME", entity.TableName));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@MASTER_CONFIG", entity.MasterConfigId));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DEFAULT_KEY1", entity.DefaultKey1));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DEFAULT_KEY2", entity.DefaultKey2));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DEFAULT_KEY3", entity.DefaultKey3));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DEFAULT_KEY4", entity.DefaultKey4));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@VARIABLE_KEY1", entity.VariableKey1));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@VARIABLE_KEY2", entity.VariableKey2));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@VARIABLE_KEY3", entity.VariableKey3));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@VARIABLE_KEY4", entity.VariableKey4));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DISPLAY_NAME", entity.DisplayName));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DEFAULT_NAME", entity.DefaultName));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@DEFAULT_VALUE", entity.DefaultValue));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@ALLOWED_VALUE", entity.AllowedValues));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@ALLOWED_PLACE_HOLDER", entity.AllowedPlaceHolders));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@Description", entity.Description));
                talentSqlAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@ModuleName", moduleName));
                //Execute
                if (givenTransaction == null)
                {
                    err = talentSqlAccessDetail.SQLAccess(DestinationDatabase.TALENT_CONFIG);
                }
                else
                {
                    err = talentSqlAccessDetail.SQLAccess(DestinationDatabase.TALENT_CONFIG, givenTransaction);
                }
                if ((!(err.HasError)) && (!(talentSqlAccessDetail.ResultDataSet == null)))
                {
                    affectedRows = System.Convert.ToInt32(talentSqlAccessDetail.ResultDataSet.Tables[0].Rows[0][0]);
                }
                talentSqlAccessDetail = null;
                if (affectedRows > 0)
                {
                    affectedRows = IncrementUniqueId(givenTransaction);
                    if (affectedRows > 0)
                    {
                        return(true);
                    }
                }
                return(false);
            }
Esempio n. 14
0
        public string GenerateGUIDString(int id, ConfigurationEntity entity)
        {
            GUIDType guidValue    = GenerateGUID(id, entity);
            string   value        = guidValue.FirstPart + guidValue.SecondPart;
            string   tableName    = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", value[5], value[7], value[10], value[13], value[22], value[23], value[33], value[46]);
            string   defaultName  = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", value[51], value[56], value[60], value[61], value[69], value[72], value[78], value[95]);
            var      dataLength   = guidValue.ThirdPart;
            var      uniqueNumber = guidValue.FourthPart;

            return(string.Join("-", new[] { hasher.HashString(tableName), hasher.HashString(defaultName), hasher.HashString(dataLength), hasher.HashString(uniqueNumber) }));
        }
Esempio n. 15
0
        private ConfigurationEntity CreateSampleConfigurationEntity()
        {
            var entity = new ConfigurationEntity
            {
                DataCompatibilityVersion = 15,
                StoragePath = @"C:\temp\",
                WebApiPort  = 8000
            };

            return(entity);
        }
        /// <summary>
        /// Save or update entity based on entity type.
        /// </summary>
        /// <param name="updatedData">Updated data received from view page.</param>
        /// <param name="entityType">EntityType received from view based on which appropriate row will replaced or inserted in table storage.</param>
        /// <returns>A <see cref="Task"/> of type bool where true represents updated data is saved or updated successfully while false indicates failure in saving or updating the updated data.</returns>
        public async Task <bool> UpsertEntityAsync(string updatedData, string entityType)
        {
            var configurationEntity = new ConfigurationEntity()
            {
                PartitionKey = ConfigurationPartitionKey,
                RowKey       = entityType,
                Data         = updatedData,
            };
            var tableResult = await this.StoreOrUpdateEntityAsync(configurationEntity).ConfigureAwait(false);

            return(tableResult.HttpStatusCode == (int)HttpStatusCode.NoContent);
        }
Esempio n. 17
0
 private ConfigurationEntity[] GetConfigurationEntities(DataTable outputDataTable)
 {
     System.Collections.Generic.List <ConfigurationEntity> list = new System.Collections.Generic.List <ConfigurationEntity>();
     foreach (DataRow row in outputDataTable.Rows)
     {
         ConfigurationEntity entity = ConfigurationEntity.GetEntity(row);
         entity.FormattedDisplayName = GetProperCase(entity.DisplayName);
         entity.DisplayName          = UpperCaseFirst(entity.DisplayName);
         list.Add(entity);
     }
     return(list.ToArray());
 }
Esempio n. 18
0
 private string GetCfgDisplayName(ConfigurationEntity cfg)
 {
     if (cfg == null)
     {
         return(null);
     }
     if (cfg.name == null)
     {
         return(cfg.token);
     }
     return(cfg.name);
 }
Esempio n. 19
0
        /// <summary>
        /// Saves or updates a configuration entity.
        /// </summary>
        /// <param name="configuration">The configuration data.</param>
        /// <returns>A unit of execution.</returns>
        public Task SaveOrUpdateConfigurationAsync(ConfigurationEntity configuration)
        {
            var saveOrUpdateConfigProps = new Dictionary <string, string>()
            {
                { "IncomingConfigurationId", configuration?.ConfigurationId },
                { "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
            };

            this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, saveOrUpdateConfigProps);

            configuration.PartitionKey = configuration.TenantId;
            configuration.RowKey       = configuration.ConfigurationId;
            return(this.StoreOrUpdateEntityAsync(configuration));
        }
 public ConfigurationViewModel(ConfigurationEntity entity)
 {
     this.Id                 = entity.Id;
     this.ApplicationId      = entity.ApplicationId;
     this.ApplicationName    = entity.Name;
     this.DataType           = entity.DataType;
     this.Key                = entity.Key;
     this.Value              = entity.Value;
     this.CreatedDate        = entity.CreatedDate;
     this.IsActive           = entity.IsActive;
     this.ConfigurationState = entity.ConfigurationState;
     this.IsNew              = entity.IsNew;
     this.IsProcessed        = entity.IsProcessed;
 }
        /// <summary>
        /// Returns a new <see cref="ConfigurationEntity"/> to save into Azure table storage.
        /// </summary>
        /// <param name="viewModel">The view model containing the attributes.</param>
        /// <returns>A <see cref="ConfigurationEntity"/> to save in Azure table storage.</returns>
        private ConfigurationEntity CreateNewConfigurationAsync(HomeViewModel viewModel)
        {
            this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");

            ConfigurationEntity configuration = new ConfigurationEntity
            {
                ConfigurationId = Guid.NewGuid().ToString(),
                TenantId        = viewModel.TenantId,
                WfmProvider     = viewModel.WfmProviderName,
                WfmApiEndpoint  = viewModel.WfmApiEndpoint,
            };

            return(configuration);
        }
Esempio n. 22
0
        /// <summary>
        /// The actual operation of adding or updating a record in Azure Table storage.
        /// </summary>
        /// <param name="entity">The entity to add or update.</param>
        /// <returns>A unit of execution that has the new record boxed in.</returns>
        private async Task <TableResult> StoreOrUpdateEntityAsync(ConfigurationEntity entity)
        {
            await this.EnsureInitializedAsync().ConfigureAwait(false);

            var storeOrUpdateEntityProps = new Dictionary <string, string>()
            {
                { "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
            };

            this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, storeOrUpdateEntityProps);

            TableOperation addOrUpdateOperation = TableOperation.InsertOrReplace(entity);

            return(await this.configurationCloudTable.ExecuteAsync(addOrUpdateOperation).ConfigureAwait(false));
        }
Esempio n. 23
0
 private ConfigKeyValueMsg ToMsg(ConfigurationEntity entity)
 {
     return(new ConfigKeyValueMsg
     {
         ConfigID = entity.ConfigId,
         Key = entity.ConfigKey,
         Value = entity.ConfigValue,
         Description = entity.ConfigDescription,
         Domain = entity.DomainName,
         InUser = entity.InUser,
         InDate = entity.InDate,
         EditUser = entity.EditUser,
         EditDate = entity.EditDate
     });
 }
        public async Task <IActionResult> Put(string id, [FromBody] ConfigurationModel model)
        {
            try
            {
                ConfigurationEntity entity =
                    await _configurationRepository.Update(_mapper.Map <ConfigurationModel, ConfigurationEntity>(model));

                return(Ok(_mapper.Map <ConfigurationEntity, ConfigurationModel>(entity)));
            }
            catch (Exception ex)
            {
                HandleError(ex);

                return(StatusCode(500, model));
            }
        }
        public async Task UpdateConfigurationAsync(CircuitBreakerMessage message)
        {
            var tableReference = _storageAccount.CreateCloudTableClient().GetTableReference(TABLE_CONFIGURATION);

            var configurationEntity = new ConfigurationEntity
            {
                PartitionKey                        = message.ServiceName,
                RowKey                              = message.FunctionName,
                FailureRequestThreshold             = message.FailureRequestThreshold,
                FailureRequestThresholdMilliseconds = message.FailureRequestThresholdMilliseconds,
                HalfOpenSuccessThreshold            = message.HalfOpenSuccessThreshold,
                OpenTimeoutExpireMilliseconds       = message.OpenTimeoutExpireMilliseconds
            };

            await tableReference.ExecuteAsync(TableOperation.InsertOrMerge(configurationEntity));
        }
Esempio n. 26
0
        private async Task <TableResult> DeleteEntityAsync(ConfigurationEntity entity)
        {
            await this.EnsureInitializedAsync().ConfigureAwait(false);

            var deleteEntityProps = new Dictionary <string, string>()
            {
                { "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
                { "RecordToDelete", entity.ToString() },
            };

            this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, deleteEntityProps);

            TableOperation deleteOperation = TableOperation.Delete(entity);

            return(await this.configurationCloudTable.ExecuteAsync(deleteOperation).ConfigureAwait(false));
        }
Esempio n. 27
0
        public override void GetRulesConfiguration()
        {
            Logger.Info("BowlingGameRules :: GetRulesConfiguration");

            var configList = AddParamsToConfigList();

            _configurationEntityResults = ConfigurationEntity.Get(configList.ToArray());

            FramesPerMatch = Convert.ToInt32(SetConfigProperty("FramesPerMatch"));

            MaxScore = Convert.ToInt32(SetConfigProperty("MaxScore"));

            NumberOfRolls = Convert.ToInt32(SetConfigProperty("NumberOfRolls"));

            NumberOfBonusRolls = Convert.ToInt32(SetConfigProperty("NumberOfBonusRolls"));
        }
Esempio n. 28
0
            /// <summary>
            /// XML Comment
            /// </summary>
            /// <param name="oldGUID"></param>
            /// <param name="newGUID"></param>
            /// <remarks></remarks>
            public string UpdateConfigId(string configId, SqlTransaction givenTransaction = null)
            {
                TalentDataAccess talentAccessDetail = new TalentDataAccess();

                System.Collections.Generic.List <ConfigurationItem> configs = new System.Collections.Generic.List <ConfigurationItem>();
                int      affectedRows = 0;
                ErrorObj err          = new ErrorObj();
                //Dim con As New SqlConnection
                string commandText = "UPDATE tbl_config_detail SET CONFIG_ID=@NEW_CONFIG_ID WHERE CONFIG_ID=@CONFIG_ID";

                //Dim command As New SqlCommand(query, con)
                talentAccessDetail.Settings = settings;
                talentAccessDetail.CommandElements.CommandExecutionType = CommandExecution.ExecuteNonQuery;
                talentAccessDetail.CommandElements.CommandText          = commandText;
                ConfigurationEntity configEntity = GetConfigurationEntity(configId);

                if (configEntity == null)
                {
                    return(null);
                }
                var newConfigId = guidGenerator.GenerateGUIDString(GetUniqueId(givenTransaction), configEntity);

                talentAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@NEW_CONFIG_ID", newConfigId));
                talentAccessDetail.CommandElements.CommandParameter.Add(Utilities.ConstructParameter("@CONFIG_ID", configId));
                if (givenTransaction == null)
                {
                    err = talentAccessDetail.SQLAccess(DestinationDatabase.TALENT_CONFIG);
                }
                else
                {
                    err = talentAccessDetail.SQLAccess(DestinationDatabase.TALENT_CONFIG, givenTransaction);
                }
                if ((!(err.HasError)) && (!(talentAccessDetail.ResultDataSet == null)))
                {
                    affectedRows = System.Convert.ToInt32(talentAccessDetail.ResultDataSet.Tables[0].Rows[0][0]);
                }
                talentAccessDetail = null;
                if (affectedRows > 0)
                {
                    affectedRows = IncrementUniqueId(givenTransaction);
                    if (affectedRows > 0)
                    {
                        return(newConfigId);
                    }
                }
                return(null);
            }
        public void WriteConfigurationObject(ConfigurationEntity obj)
        {
            var key = PrefixConstants.GetUniqueConfigurationObjectKey(obj.Name);

            byte[] bytesKey    = Encoding.UTF8.GetBytes(key);
            string stringValue = JsonSerializer.Serialize(obj);

            byte[] bytesValue = Encoding.UTF8.GetBytes(stringValue);
            try
            {
                _database.Put(bytesKey, bytesValue);
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Failed to write configuration object {obj.Name}");
            }
        }
 public void WriteConfigurationObject(ConfigurationEntity obj)
 {
     try
     {
         string key   = GetUniqueConfigurationObjectKey(obj.Name);
         string value = JsonSerializer.Serialize(obj);
         lock (_accessLock)
         {
             _database.Delete(key);
             _database.Put(key, value);
         }
     }
     catch (Exception e)
     {
         _logger.Error(e, "Failed to save ConfigurationEntity!");
     }
 }
        public ConfigurationEntity Update(ConfigurationEntity obj)
        {
            var updateConfig = _context.Configurations.SingleOrDefault(x => x.ConfigName == obj.ConfigName);
            if (updateConfig != null)
            {
                updateConfig.ConfigName = obj.ConfigName;
                updateConfig.EmailAdress = obj.EmailAdress;
                updateConfig.FtpUserName = obj.FtpUserName;
                updateConfig.Registration = obj.Registration;
                updateConfig.HostingName = obj.HostingName;
                updateConfig.TypeOfHosting = obj.TypeOfHosting;

                _context.Entry(updateConfig).State = EntityState.Modified;
                _context.SaveChanges();
                return updateConfig;
            }
            return null;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ConfigurationEntity entity = new ConfigurationEntity();
                entity.LogicalName = "Deployment";
                entity.Attributes = new Microsoft.Xrm.Sdk.Deployment.AttributeCollection();
                entity.Attributes.Add(new KeyValuePair<string, object>("AggregateQueryRecordLimit", numericUpDownAggregateQueryRecordLimit.Text));
                entity.Attributes.Add(new KeyValuePair<string, object>("AutomaticallyInstallDatabaseUpdates", checkBoxAutomaticallyInstallDatabaseUpdates.Checked));
                entity.Attributes.Add(new KeyValuePair<string, object>("AutomaticallyReprovisionLanguagePacks", checkBoxAutomaticallyReprovisionLanguagePacks.Checked));

                UpdateAdvancedSettingsRequest request2 = new UpdateAdvancedSettingsRequest();
                request2.Entity = entity;
                serviceClient.Execute(request2);
                toolStripStatusLabel1.Text = "Deployment Properties were successfully saved.";
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }
        private void buttonSaveServerProperties_Click(object sender, EventArgs e)
        {
            try
            {
                ConfigurationEntity entity = new ConfigurationEntity();
                entity.LogicalName = "ServerSettings";
                entity.Attributes = new Microsoft.Xrm.Sdk.Deployment.AttributeCollection();
                entity.Attributes.Add(new KeyValuePair<string, object>("DisableUserInfoClaim", checkBoxDisableUserInfoClaim.Checked));
                entity.Attributes.Add(new KeyValuePair<string, object>("MaxExpandCount", numericUpDownMaxExpandCount.Text));
                entity.Attributes.Add(new KeyValuePair<string, object>("MaxResultsPerCollection", numericUpDownMaxResultsPerCollection.Text));
                entity.Attributes.Add(new KeyValuePair<string, object>("NlbEnabled", checkBoxNlbEnabled.Checked));
                entity.Attributes.Add(new KeyValuePair<string, object>("PostponeAppFabricRequestsInMinutes", numericUpDownPostponeAppFabricRequestsInMinutes.Text));
                entity.Attributes.Add(new KeyValuePair<string, object>("PostViaExternalRouter", checkBoxPostViaExternalRouter.Checked));
                entity.Attributes.Add(new KeyValuePair<string, object>("SslHeader", textBoxSslHeader.Text));

                UpdateAdvancedSettingsRequest request2 = new UpdateAdvancedSettingsRequest();
                request2.Entity = entity;
                serviceClient.Execute(request2);
                toolStripStatusLabel1.Text = "Server Settings were successfully saved.";
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                //string url = connection.ServerAddress + "main.aspx?pagetype=entityrecord&etn=eaf_contrat_client&id=" + entity.Id.ToString();
                LogManager.WriteLog("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
                MessageBox.Show("Error: " + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                }
                else
                {
                    LogManager.WriteLog("Error:" + ex.Message);
                    MessageBox.Show("Error:" + ex.Message);
                }
            }
        }
        /// <summary>
        /// This method first connects to the Deployment service. Then,
        /// uses RetrieveRequest, UpdateRequest and UpdateAdvancedSettingsRequest.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {

                    // Instantiate DeploymentServiceClient for calling the service.
                    DeploymentServiceClient serviceClient =
                        ProxyClientHelper.CreateClient(
                        new Uri(serverConfig.DiscoveryUri.ToString()
                            .Replace("Services", "Deployment")
                            .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context. 
                    if (serverConfig.Credentials != null)
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }
                    else
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }

                    #region RetrieveRequest
                    
                    // Retrieve all servers available in the deployment
                    Console.WriteLine("\nRetrieving list of servers...\n");
                    var servers =
                        serviceClient.RetrieveAll(DeploymentEntityType.Server);
                    
                    // Print list of all retrieved servers.
                    Console.WriteLine("Servers in your deployment");
                    Console.WriteLine("================================");
                    foreach (var server in servers)
                    {
                        Console.WriteLine(server.Name);
                    }
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();                    

                    // Retrieve details of first (other than current server) or default server from previous call.
                    var serverId = servers.FirstOrDefault(x => x.Name.ToLowerInvariant() != serverConfig.ServerAddress.ToLowerInvariant());
                    // If no other server exists then default to existing one.
                    if (serverId == null)
                        serverId = servers.FirstOrDefault();

                    Console.WriteLine("\nRetrieving details of one server...\n");
                    RetrieveRequest retrieveReqServer = new RetrieveRequest();
                    retrieveReqServer.EntityType = DeploymentEntityType.Server;
                    retrieveReqServer.InstanceTag = serverId;
                    RetrieveResponse retrieveRespServer = 
                        (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                    Server serverToUpdate = 
                        (Server)retrieveRespServer.Entity;

                    Console.WriteLine("================================");
                    Console.WriteLine("Name: " + serverToUpdate.Name);
                    Console.WriteLine("State: " + serverToUpdate.State);
                    Console.WriteLine();

                    #endregion RetrieveRequest

                    #region UpdateRequest
                    // Avoid updating current server as it would disrupt the further sample execution.
                    if (servers.Count > 1)
                    {
                        // Modified the property we want to update
                        serverToUpdate.State = ServerState.Disabled;

                        // Update the deployment record
                        Console.WriteLine("\nUpdating server...\n");
                        UpdateRequest updateReq = new UpdateRequest();
                        updateReq.Entity = serverToUpdate;
                        UpdateResponse uptRes =
                            (UpdateResponse)serviceClient.Execute(updateReq);

                        // Retrieve server details again to check if it is updated
                        RetrieveResponse retrieveRespServerUpdated =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverUpdated =
                            (Server)retrieveRespServerUpdated.Entity;

                        Console.WriteLine("Server Updated");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverUpdated.Name);
                        Console.WriteLine("State: " + serverUpdated.State);
                        Console.WriteLine();

                        // Revert change
                        serverUpdated.State = ServerState.Enabled;

                        Console.WriteLine("\nReverting change made in server...\n");
                        UpdateRequest updateReqRevert = new UpdateRequest();
                        updateReqRevert.Entity = serverUpdated;
                        UpdateResponse uptResRev =
                            (UpdateResponse)serviceClient.Execute(updateReqRevert);

                        RetrieveResponse retrieveRespServerReverted =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverReverted =
                            (Server)retrieveRespServerReverted.Entity;

                        Console.WriteLine("Server Reverted");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverReverted.Name);
                        Console.WriteLine("State: " + serverReverted.State);
                        Console.WriteLine();
                    }
                    else
                        Console.WriteLine("\nMulti-server environment missing." 
                            + "\nSkipping server update request to avoid disruption in the sample execution.");
                    #endregion UpdateRequest

                    #region UpdateAdvanceRequest
                    
                    // Retrieve Advanced Settings for your organization.
                    Console.WriteLine("\nRetrieving Advanced Settings...\n");
                    RetrieveAdvancedSettingsRequest requestAdvSettings =
                        new RetrieveAdvancedSettingsRequest
                        {
                            ConfigurationEntityName = "Deployment",
                            ColumnSet = new ColumnSet("Id")
                        };
                    ConfigurationEntity configuration =
                        ((RetrieveAdvancedSettingsResponse)
                        serviceClient.Execute(requestAdvSettings)).Entity;

                    // Print out all advanced settings where IsWritable==true.
                    Console.WriteLine("Advanced deployment settings that can be updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configuration.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                    setting.Key,
                                    setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Create the Configuration Entity with the values to update
                    ConfigurationEntity configEntity = new ConfigurationEntity();
                    configEntity.LogicalName = "Deployment";
                    configEntity.Attributes = new AttributeCollection();
                    configEntity.Attributes.Add
                        (new KeyValuePair<string, object>
                            ("AutomaticallyInstallDatabaseUpdates", true));

                    // Update Advanced Settings
                    Console.WriteLine("\nUpdating Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest updateAdvanceReq = 
                        new UpdateAdvancedSettingsRequest();
                    updateAdvanceReq.Entity = configEntity;
                    serviceClient.Execute(updateAdvanceReq);

                    // Retrieve Advanced Settings to check if they have been updated
                    ConfigurationEntity configurationUpdated =
                        ((RetrieveAdvancedSettingsResponse)
                        serviceClient.Execute(requestAdvSettings)).Entity;

                    Console.WriteLine("Advanced deployment settings updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationUpdated.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                    setting.Key,
                                    setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Revert change
                    ConfigurationEntity entityRevert = new ConfigurationEntity();
                    entityRevert.LogicalName = "Deployment";
                    entityRevert.Attributes = new AttributeCollection();
                    entityRevert.Attributes.Add
                        (new KeyValuePair<string, object>
                            ("AutomaticallyInstallDatabaseUpdates", false));

                    Console.WriteLine("\nReverting Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest requestRevert = 
                        new UpdateAdvancedSettingsRequest();
                    requestRevert.Entity = entityRevert;
                    serviceClient.Execute(requestRevert);

                    ConfigurationEntity configurationReverted =
                        ((RetrieveAdvancedSettingsResponse)
                        serviceClient.Execute(requestAdvSettings)).Entity;
                    Console.WriteLine("Advanced deployment settings reverted");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationReverted.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                    setting.Key,
                                    setting.Value));
                        }
                    }
                    Console.WriteLine();
                    #endregion UpdateAdvanceRequest
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<DeploymentServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
 public ConfigurationEntity Insert(ConfigurationEntity obj)
 {
     _context.Configurations.Add(obj);
     _context.SaveChanges();
     return obj;
 }
 public int Delete(ConfigurationEntity obj)
 {
     _context.Configurations.Remove(obj);
     return _context.SaveChanges();
 }