protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { string user_name = Request.Form["user_name"]; string first_name = Request.Form["first_name"]; string last_name = Request.Form["last_name"]; string password = Request.Form["password"]; string male = Request.Form["male"]; string email = Request.Form["email"]; SqlUtility util = new SqlUtility(); if (util.CreateUser(user_name, first_name, last_name, password, male, email)) { Session["username"] = user_name; Response.Redirect("profilepage.aspx"); } else { Response.Write("<script type=\"text/javascript\">alert('user already exists')</script>"); } }//if }
/// <summary> /// When the client gets connected to the server the server will create an instance of the ChatClient and pass the TcpClient /// </summary> /// <param name="client"></param> public ChatClient(TcpClient client) { sql = new SqlUtility(); _client = client; // Read data from the client async data = new byte[_client.ReceiveBufferSize]; //Makenull(log); // BeginRead will begin async read from the NetworkStream // This allows the server to remain responsive and continue accepting new connections from other clients // When reading complete control will be transfered to the ReviveMessage() function. _client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(_client.ReceiveBufferSize), ReceiveMessage, null); }
public static string GetColumnName(this ReferencePropertyInfo info) { return(SqlUtility.Identifier(info.Name + "ID")); }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { string azureToken = request.DataStore.GetJson("AzureToken", "access_token"); string subscription = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); string webserviceFile = request.DataStore.GetValue("WebServiceFile"); string webserviceName = request.DataStore.GetValue("WebServiceName"); string commitmentPlanName = request.DataStore.GetValue("CommitmentPlan"); string resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); string storageAccountName = request.DataStore.GetValue("StorageAccountName"); string storageAccountKey = request.DataStore.GetValue("StorageAccountKey"); string responseType = request.DataStore.GetValue("IsRequestResponse"); bool isRequestResponse = false; if (responseType != null) { isRequestResponse = bool.Parse(responseType); } ServiceClientCredentials creds = new TokenCredentials(azureToken); AzureMLWebServicesManagementClient client = new AzureMLWebServicesManagementClient(creds); AzureMLCommitmentPlansManagementClient commitmentClient = new AzureMLCommitmentPlansManagementClient(creds); client.SubscriptionId = subscription; commitmentClient.SubscriptionId = subscription; // Create commitment plan var commitmentPlan = new Azure.Management.MachineLearning.CommitmentPlans.Models.CommitmentPlan(); commitmentPlan.Sku = new ResourceSku() { Capacity = 1, Name = "S1", Tier = "Standard" }; commitmentPlan.Location = "South Central US"; var createdCommitmentPlan = await commitmentClient.CommitmentPlans.CreateOrUpdateAsync(commitmentPlan, resourceGroup, commitmentPlanName); request.Logger.LogResource(request.DataStore, createdCommitmentPlan.Name, DeployedResourceType.MlWebServicePlan, CreatedBy.BPST, DateTime.UtcNow.ToString("o"), createdCommitmentPlan.Id, commitmentPlan.Sku.Tier); // Get webservicedefinition string sqlConnectionString = request.DataStore.GetValueAtIndex("SqlConnectionString", "SqlServerIndex"); SqlCredentials sqlCredentials; string jsonDefinition = File.ReadAllText(request.Info.App.AppFilePath + "/" + webserviceFile); if (!string.IsNullOrWhiteSpace(sqlConnectionString)) { sqlCredentials = SqlUtility.GetSqlCredentialsFromConnectionString(sqlConnectionString); jsonDefinition = ReplaceSqlPasswords(sqlCredentials, jsonDefinition); } // Create WebService - fixed to southcentralus WebService webService = ModelsSerializationUtil.GetAzureMLWebServiceFromJsonDefinition(jsonDefinition); webService.Properties.StorageAccount = new StorageAccount { Key = storageAccountKey, Name = storageAccountName }; webService.Properties.CommitmentPlan = new CommitmentPlan(createdCommitmentPlan.Id); // A little bit of juggling to change the name webService = new WebService(webService.Location, webService.Properties, null, webserviceName, webService.Type, webService.Tags); webService.Validate(); WebService result = null; try { result = client.WebServices.CreateOrUpdate(resourceGroup, webserviceName, webService); var keys = client.WebServices.ListKeys(resourceGroup, webserviceName); var swaggerLocation = result.Properties.SwaggerLocation; string url = swaggerLocation.Replace("swagger.json", "jobs?api-version=2.0"); if (isRequestResponse) { url = swaggerLocation.Replace("swagger.json", "execute?api-version=2.0&format=swagger"); } string serviceKey = keys.Primary; request.DataStore.AddToDataStore("AzureMLUrl", url); request.DataStore.AddToDataStore("AzureMLKey", serviceKey); } catch (CloudException e) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromStringValue(e.Message), e, "DefaultError", ((CloudException)e).Response.Content)); } request.Logger.LogResource(request.DataStore, result.Name, DeployedResourceType.MlWebService, CreatedBy.BPST, DateTime.UtcNow.ToString("o"), result.Id); return(new ActionResponse(ActionStatus.Success)); }
public void BuildCommand(IDbCommand command, SqlQuery sqlQuery) { if (command == null) { throw new ArgumentNullException("command"); } if (sqlQuery == null) { throw new ArgumentNullException("sqlQuery"); } if (log.IsDebug) { log.Debug(LogMessages.DbDialect_BuildingCommand); } var parameterNames = SqlUtility.GetParameterNames(sqlQuery.CommandText); if (parameterNames.Count == 0 && sqlQuery.Arguments.Count > 0) { parameterNames = Enumerable.Range(0, sqlQuery.Arguments.Count) .Select(c => "Parameter" + c.ToString(CultureInfo.InvariantCulture)) .ToArray(); } if (parameterNames.Count != sqlQuery.Arguments.Count) { throw new MicroLiteException(ExceptionMessages.DbDriver_ArgumentsCountMismatch.FormatWith(parameterNames.Count.ToString(CultureInfo.InvariantCulture), sqlQuery.Arguments.Count.ToString(CultureInfo.InvariantCulture))); } if (command.CommandText != sqlQuery.CommandText) { command.CommandText = this.GetCommandText(sqlQuery.CommandText); command.CommandType = this.GetCommandType(sqlQuery.CommandText); command.Parameters.Clear(); } for (int i = 0; i < parameterNames.Count; i++) { var parameterName = parameterNames[i]; var sqlArgument = sqlQuery.Arguments[i]; IDbDataParameter parameter; if (command.Parameters.Contains(parameterName)) { parameter = (IDbDataParameter)command.Parameters[parameterName]; } else { parameter = command.CreateParameter(); command.Parameters.Add(parameter); } this.BuildParameter(parameter, parameterName, sqlArgument); } if (this.SupportsCommandTimeout) { command.CommandTimeout = sqlQuery.Timeout; } }
public string CreateDatabaseStructure(IConceptInfo conceptInfo) { var info = (BinaryPropertyInfo)conceptInfo; PropertyDatabaseDefinition.RegisterColumnMetadata(_conceptMetadata, info, SqlUtility.Identifier(info.Name), Sql.Get("BinaryPropertyDatabaseDefinition_DataType")); if (info.DataStructure is EntityInfo) { return(PropertyDatabaseDefinition.AddColumn(_conceptMetadata, info)); } return(""); }
public void SingleQuote_EscapeSequenceTest() { Assert.AreEqual("'ab''c'", SqlUtility.QuoteText("ab'c")); }
private static DateTime DbTime(RhetosTestContainer container) { return(SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>())); }
public void ActivePropertyValueDoesNotHaveToBeDefinedOnUpdate() { using (var container = new RhetosTestContainer()) { var id1 = Guid.NewGuid(); var id2 = Guid.NewGuid(); var id3 = Guid.NewGuid(); var id4 = Guid.NewGuid(); container.Resolve <ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestDeactivatable.BasicEnt", "INSERT INTO TestDeactivatable.BasicEnt (ID, Name) VALUES (" + SqlUtility.QuoteGuid(id1) + ", 'a')", "INSERT INTO TestDeactivatable.BasicEnt (ID, Name, Active) VALUES (" + SqlUtility.QuoteGuid(id2) + ", 'b', 0)", "INSERT INTO TestDeactivatable.BasicEnt (ID, Name) VALUES (" + SqlUtility.QuoteGuid(id3) + ", 'c')", "INSERT INTO TestDeactivatable.BasicEnt (ID, Name, Active) VALUES (" + SqlUtility.QuoteGuid(id4) + ", 'd', 1)", }); var repository = container.Resolve <Common.DomRepository>(); Assert.AreEqual( "a , b False, c , d True", TestUtility.DumpSorted(repository.TestDeactivatable.BasicEnt.Query(), item => item.Name + " " + item.Active)); var e1 = new BasicEnt { ID = id1, Name = "a2", Active = false }; var e2 = new BasicEnt { ID = id2, Name = "b2" }; var e3 = new BasicEnt { ID = id3, Name = "c2" }; var e4 = new BasicEnt { ID = id4, Name = "d2" }; repository.TestDeactivatable.BasicEnt.Update(new[] { e1, e2, e3, e4 }); var afterUpdate = repository.TestDeactivatable.BasicEnt.Query(); Assert.AreEqual( "a2 False, b2 False, c2 True, d2 True", TestUtility.DumpSorted(afterUpdate, item => item.Name + " " + item.Active)); } }
public static string GetConstraintName(DataStructureExtendsInfo info) { return(SqlUtility.Identifier(Sql.Format("DataStructureExtendsDatabaseDefinition_ConstraintName", info.Extension.Name, info.Base.Name))); }
public string CreateDatabaseStructure(IConceptInfo conceptInfo) { var info = (DataStructureExtendsInfo)conceptInfo; if (ShouldCreateConstraint(info)) { return(Sql.Format("DataStructureExtendsDatabaseDefinition_Create", SqlUtility.Identifier(info.Extension.Module.Name) + "." + SqlUtility.Identifier(info.Extension.Name), GetConstraintName(info), ForeignKeyUtility.GetSchemaTableForForeignKey(info.Base), ForeignKeyConstraintOptions.Evaluate(info))); } // TODO: else - Generate a Filter+InvalidData validation in the server application that checks for invalid items. return(""); }
public void UndoDataMigrationScripts(List <string> createdTags) { _sqlExecuter.ExecuteSql(createdTags.Select(tag => "UPDATE Rhetos.DataMigrationScript SET Active = 0 WHERE Tag = " + SqlUtility.QuoteText(tag))); }
public string UploadImage(List <UploadImage> insertImage) { string status = string.Empty; DataTable dt = new DataTable(); //dt.Columns.AddRange(new DataColumn[5] { // new DataColumn("ImageName",typeof(string)), // new DataColumn("FileType",typeof(char)), // new DataColumn("FrontBWImg",typeof(byte[])), // new DataColumn("BackBWImg",typeof(byte[])), // new DataColumn("FrontGrayImg",typeof(byte[])), // }); foreach (UploadImage item in insertImage) { var Parameters = new DynamicParameters(); try { //_memorystream.Seek(0, SeekOrigin.Begin); Parameters.Add("@FileType", item.FileType); Parameters.Add("@ImageName", item.ImageName); Parameters.Add("@FrontGrayImg", item.FrontGrayImg, DbType.Binary, ParameterDirection.Input, -1); //Parameters.Add("@Photo", SqlDbType.VarBinary, -1).Value = DBNull.Value; Parameters.Add("@BackBWImg", item.BackBWImg, DbType.Binary, ParameterDirection.Input, -1); Parameters.Add("@FrontBWImg", item.FrontBWImg, DbType.Binary, ParameterDirection.Input, -1); //Parameters.Add("@BackBWImg", item.BackBWImg); //A.Add("@A", anexoBytes, dbType: DbType.Binary, direction: ParameterDirection.Input); //A.Get<DbType>("@A"); //Parameters.Add("@BackBWImg", item.BackBWImg,dbType: DbType.Binary, direction: ParameterDirection.Input); using (sqlConnection = SqlUtility.GetConnection()) { var res = sqlConnection.Query <int>("USP_ImageUpdate", Parameters, commandType: CommandType.StoredProcedure).FirstOrDefault(); status = AppUtility.AppUtility.getStatus(Convert.ToInt32(res)).ToString(); } } catch (Exception ex) { throw ex; } //dt.Rows.Add(item.ImageName, item.FileType, item.FrontBWImg, item.BackBWImg, item.FrontGrayImg); } //var Parameters = new DynamicParameters(); // Parameters.Add("@SOURCE", dt.AsTableValuedParameter("UDT_UploadImage1")); //try //{ // using (sqlConnection = SqlUtility.GetConnection()) // { // var res = sqlConnection.Query<int>("USP_ImageUpload", Parameters, commandType: CommandType.StoredProcedure).FirstOrDefault(); // status = AppUtility.getStatus(Convert.ToInt32(res)).ToString(); // } //} //catch (Exception ex) //{ // throw ex; //} return(status); }
public string RemoveDatabaseStructure(IConceptInfo conceptInfo) { var info = (UniqueReferenceInfo)conceptInfo; if (IsSupported(info)) { return(Sql.Format("UniqueReferenceDatabaseDefinition_Remove", SqlUtility.Identifier(info.Extension.Module.Name) + "." + SqlUtility.Identifier(info.Extension.Name), GetConstraintName(info))); } return(""); }
public static string GetConstraintName(UniqueReferenceInfo info) { return(SqlUtility.Identifier(Sql.Format("UniqueReferenceDatabaseDefinition_ConstraintName", info.Extension.Name, info.Base.Name))); }
public void ExecuteGenerators(bool deployDatabaseOnly) { _deployPackagesLogger.Trace("SQL connection string: " + SqlUtility.MaskPassword(SqlUtility.ConnectionString)); ValidateDbConnection(); _deployPackagesLogger.Trace("Preparing Rhetos database."); PrepareRhetosDatabase(); _deployPackagesLogger.Trace("Parsing DSL scripts."); int dslModelConceptsCount = _dslModel.Concepts.Count(); _deployPackagesLogger.Trace("Application model has " + dslModelConceptsCount + " statements."); if (deployDatabaseOnly) { _deployPackagesLogger.Info("Skipped code generators (DeployDatabaseOnly)."); } else { _deployPackagesLogger.Trace("Compiling DOM assembly."); int generatedTypesCount = _domGenerator.Assembly.GetTypes().Length; if (generatedTypesCount == 0) { _deployPackagesLogger.Error("WARNING: Empty assembly is generated."); } else { _deployPackagesLogger.Trace("Generated " + generatedTypesCount + " types."); } var generators = GetSortedGenerators(); foreach (var generator in generators) { _deployPackagesLogger.Trace("Executing " + generator.GetType().Name + "."); generator.Generate(); } if (!generators.Any()) { _deployPackagesLogger.Trace("No additional generators."); } } _deployPackagesLogger.Trace("Cleaning old migration data."); _databaseCleaner.RemoveRedundantMigrationColumns(); _databaseCleaner.RefreshDataMigrationRows(); _deployPackagesLogger.Trace("Executing data migration scripts."); var dataMigrationReport = _dataMigration.ExecuteDataMigrationScripts(); _deployPackagesLogger.Trace("Upgrading database."); try { _databaseGenerator.UpdateDatabaseStructure(); } catch (Exception ex) { try { _dataMigration.UndoDataMigrationScripts(dataMigrationReport.CreatedTags); } catch (Exception undoException) { _deployPackagesLogger.Error(undoException.ToString()); } ExceptionsUtility.Rethrow(ex); } _deployPackagesLogger.Trace("Deleting redundant migration data."); _databaseCleaner.RemoveRedundantMigrationColumns(); _databaseCleaner.RefreshDataMigrationRows(); _deployPackagesLogger.Trace("Uploading DSL scripts."); UploadDslScriptsToServer(); }
private void WriteSqlStatement(StreamWriter writer, int languageId, string labelName, string labelValue) { if (!string.IsNullOrWhiteSpace(labelName) && !string.IsNullOrWhiteSpace(labelValue)) { writer.WriteLine(string.Format("EXEC spRoll_InsertUpdateVariableAndVariableTranslation '{0}', {1}, N'{2}', {3}, {4}", labelName, languageId, SqlUtility.SqlEncode(labelValue), 88, 384)); } }
public string RemoveDatabaseStructure(IConceptInfo conceptInfo) { var info = (DataStructureExtendsInfo)conceptInfo; if (ShouldCreateConstraint(info)) { return(Sql.Format("DataStructureExtendsDatabaseDefinition_Remove", SqlUtility.Identifier(info.Extension.Module.Name) + "." + SqlUtility.Identifier(info.Extension.Name), GetConstraintName(info))); } return(""); }
/// <summary> /// /// </summary> /// <param name="pageSize"></param> /// <param name="sessionType"></param> /// <param name="searchKeyword"></param> /// <returns></returns> public List <Session> GetSessionOnFilter(int pageSize, int sessionType, string searchKeyword) { List <Session> sessions = new List <Session>(); var prms = new List <SqlParameter> { SqlUtility.CreateParameter(SPGetSessionsOnFilter.PARAM_KEYWORD, SqlDbType.NVarChar, searchKeyword), SqlUtility.CreateParameter(SPGetSessionsOnFilter.PARAM_PAGESIZE, SqlDbType.Int, pageSize), SqlUtility.CreateParameter(SPGetSessionsOnFilter.PARAM_SESSIONTYPE, SqlDbType.Int, sessionType), }; try { var dt = SqlUtility.ExecuteAndGetTable(SPGetSessionsOnFilter.NAME, CommandType.StoredProcedure, SPGetSessionsOnFilter.TABLE_NAME, prms); foreach (DataRow row in dt.Rows) { // var sessionID = Convert.ToInt32(row["SessionId"]); if (sessions.All(x => x.Id != Convert.ToInt32(row["SessionId"]))) { sessions.Add(new Session { Title = row["Title"].ToString(), Id = Convert.ToInt32(row["SessionId"]), Date = Convert.ToDateTime(row["SessionDate"]), Description = row["Description"].ToString(), PresenterFullName = row["PresenterFullName"].ToString(), Presenter = Convert.ToInt32(row["Presenter"]), SessionAttendees = new List <User>() }); } int userId; var objSession = sessions.FirstOrDefault(x => x.Id == Convert.ToInt32(row["SessionId"])); if (objSession == null || !Int32.TryParse(row["UserId"].ToString(), out userId)) { continue; } User objUser = new User { UserId = Convert.ToInt32(row["UserId"]), FirstName = row["FirstName"].ToString(), LastName = row["LastName"].ToString() }; objSession.SessionAttendees.Add(objUser); } //sessions.AddRange(from DataRow row in // select new Session // { // Title = row["Title"].ToString() , // Id = Convert.ToInt32(row["SessionId"]), // Date = Convert.ToDateTime(row["SessionDate"]), // Description = row["Description"].ToString(), // PresenterFullName =row["PresenterFullName"].ToString(), // Presenter = Convert.ToInt32(row["Presenter"]) // }); } catch (Exception ex) { LogUtility.ErrorRoutine(ex); } return(sessions); }
public void UndoDataMigrationScripts(List <string> createdTags) { _sqlExecuter.ExecuteSql(createdTags.Select(tag => "DELETE FROM Rhetos.DataMigrationScript WHERE Tag = " + SqlUtility.QuoteText(tag))); }
public static void UpdateCodesWithoutCache <TEntity>( ISqlExecuter sqlExecuter, string entityName, string propertyName, IList <AutoCodeItem <TEntity, string> > autoCodeItems, Action <TEntity, string> setCode, string groupColumnName = null, bool groupTypeQuoted = false) where TEntity : IEntity { foreach (var autoCodeItem in autoCodeItems) { if (autoCodeItem.Code == null) { autoCodeItem.Code = "+"; } } var autoCodeGroups = OrganizeToAutoCodeGroups(autoCodeItems, entityName, propertyName); // UpdateCodesWithoutCache does not need to update cache, so it is interested only in the items that require a generated code. autoCodeGroups = autoCodeGroups.Where(acg => acg.ItemsToGenerateCode.Count > 0).ToList(); if (autoCodeGroups.Count > 0) { Lock(sqlExecuter, entityName); } foreach (var autoCodeGroup in autoCodeGroups) { string groupFilter; if (groupColumnName == null) { groupFilter = ""; } else { groupFilter = "AND " + GetGroupFilter(groupColumnName, autoCodeGroup.Grouping, groupTypeQuoted); } string quotedPrefix = SqlUtility.QuoteText(autoCodeGroup.Prefix); int prefixLength = autoCodeGroup.Prefix.Length; string sql = $@"SELECT TOP 1 MaxSuffixNumber = CONVERT(INT, SUBSTRING({propertyName}, {prefixLength} + 1, 256 )), MaxSuffixLength = LEN({propertyName}) - {prefixLength} FROM {entityName} WHERE {propertyName} LIKE {quotedPrefix} + '%' AND ISNUMERIC(SUBSTRING({propertyName}, {prefixLength} + 1, 256)) = 1 AND CHARINDEX('.', SUBSTRING({propertyName}, {prefixLength} + 1, 256)) = 0 AND CHARINDEX('e', SUBSTRING({propertyName}, {prefixLength} + 1, 256)) = 0 {groupFilter} ORDER BY -- Find maximal numeric suffix: CONVERT(INT, SUBSTRING({propertyName}, {prefixLength} + 1, 256)) DESC, -- If there are more than one suffixes with same value, take the longest code: LEN({propertyName}) - {prefixLength} DESC"; int maxSuffixNumber = 0; // Default, if there are no matching records. int maxSuffixLength = 1; sqlExecuter.ExecuteReader(sql, reader => { maxSuffixNumber = reader.GetInt32(0); maxSuffixLength = reader.GetInt32(1); }); // If there are newly inserted records greater then the existing records: if (autoCodeGroup.MaxProvidedCode != null && autoCodeGroup.MaxProvidedCode > maxSuffixNumber) { maxSuffixNumber = autoCodeGroup.MaxProvidedCode.Value; maxSuffixLength = autoCodeGroup.MinDigits; } SetNewCodes(autoCodeGroup, maxSuffixNumber + autoCodeGroup.ItemsToGenerateCode.Count, Math.Max(maxSuffixLength, autoCodeGroup.MinDigits), setCode); } }
private static string ConstraintName(MoneyPropertyInfo info) { return(SqlUtility.Identifier(Sql.Format("MoneyPropertyDatabaseDefinition_CheckConstraintName", info.DataStructure.Name, info.Name))); }
private static DateTime DbTime(UnitOfWorkScope scope) { return(SqlUtility.GetDatabaseTime(scope.Resolve <ISqlExecuter>())); }
public string CreateDatabaseStructure(IConceptInfo conceptInfo) { var info = (MoneyPropertyInfo)conceptInfo; SqlUtility.Identifier(info.Name); PropertyDatabaseDefinition.RegisterColumnMetadata(_conceptMetadata, info, SqlUtility.Identifier(info.Name), Sql.Get("MoneyPropertyDatabaseDefinition_DataType")); if (info.DataStructure is EntityInfo) { return(PropertyDatabaseDefinition.AddColumn(_conceptMetadata, info, Sql.Format("MoneyPropertyDatabaseDefinition_CreateCheckConstraint", ConstraintName(info), SqlUtility.Identifier(info.Name)))); } return(""); }
public void SingleQuote_SimpleTest() { Assert.AreEqual("'abc'", SqlUtility.QuoteText("abc")); }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { List <Task <ActionResponse> > task = new List <Task <ActionResponse> >(); var token = request.DataStore.GetJson("AzureToken", "access_token"); var subscription = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); var resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); string postDeploymentPipelineType = request.DataStore.GetValue("postDeploymentPipelineType"); string pipelineFrequency = request.DataStore.GetValue("pipelineFrequency"); string pipelineInterval = request.DataStore.GetValue("pipelineInterval"); string pipelineType = request.DataStore.GetValue("pipelineType"); string connString = request.DataStore.GetValue("SqlConnectionString"); if (!string.IsNullOrWhiteSpace(postDeploymentPipelineType)) { pipelineFrequency = request.DataStore.GetValue("postDeploymentPipelineFrequency"); pipelineType = postDeploymentPipelineType; pipelineInterval = request.DataStore.GetValue("postDeploymentPipelineInterval"); } string adfJsonData = request.DataStore.GetValue("ADFPipelineJsonData"); var sqlCreds = SqlUtility.GetSqlCredentialsFromConnectionString(connString); var obj = JsonConvert.DeserializeObject(adfJsonData, typeof(DeserializedADFPayload)) as DeserializedADFPayload; foreach (var o in obj.fields) { var deploymentName = string.Concat("ADFDataset", pipelineType, o.Item1); dynamic datasetParam = new AzureArmParameterGenerator(); datasetParam.AddStringParam("dataFactoryName", resourceGroup + "SalesforceCopyFactory"); datasetParam.AddStringParam("targetSqlTable", o.Item1); datasetParam.AddStringParam("targetSalesforceTable", o.Item1); datasetParam.AddStringParam("sliceFrequency", pipelineFrequency); datasetParam.AddStringParam("sliceInterval", pipelineInterval); datasetParam.AddStringParam("pipelineType", pipelineType); var armTemplate = JsonUtility.GetJsonObjectFromJsonString(System.IO.File.ReadAllText(Path.Combine(request.Info.App.AppFilePath, "Service/ADF/datasets.json"))); var armParamTemplate = JsonUtility.GetJObjectFromObject(datasetParam.GetDynamicObject()); armTemplate.Remove("parameters"); armTemplate.Add("parameters", armParamTemplate["parameters"]); string tableFields = JsonConvert.SerializeObject(o.Item2); StringBuilder query = CreateQuery(o, tableFields); string stringTemplate = ReplaceTableFieldsAndQuery(tableFields, query, armTemplate); var creds = new TokenCloudCredentials(subscription, token); var client = new ResourceManagementClient(creds); var deployment = new Microsoft.Azure.Management.Resources.Models.Deployment() { Properties = new DeploymentPropertiesExtended() { Template = stringTemplate, Parameters = JsonUtility.GetEmptyJObject().ToString() } }; var validate = client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result; if (!validate.IsValid) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(validate), null, DefaultErrorCodes.DefaultErrorCode, $"Azure:{validate.Error.Message} Details:{validate.Error.Details}")); } task.Add(new Task <ActionResponse>(() => { var deploymentItem = client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result; var helper = new DeploymentHelper(); return(helper.WaitForDeployment(resourceGroup, deploymentName, client)); })); } foreach (var t in task) { t.Start(); } Task.WaitAll(task.ToArray()); foreach (var t in task) { if (t.Result.Status != ActionStatus.Success) { return(new ActionResponse(ActionStatus.Failure, t.Result.ExceptionDetail.FriendlyErrorMessage)); } } return(new ActionResponse(ActionStatus.Success)); }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { var azureToken = request.DataStore.GetJson("AzureToken", "access_token"); var subscription = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); var resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); var location = request.DataStore.GetLastValue("SqlLocation") ?? "westus"; var databaseTier = request.DataStore.GetLastValue("SqlSku") ?? "S1"; string server = request.DataStore.GetJson("SqlCredentials").SelectToken("Server")?.ToString(); string user = request.DataStore.GetJson("SqlCredentials").SelectToken("User")?.ToString(); string password = request.DataStore.GetJson("SqlCredentials").SelectToken("Password")?.ToString(); var database = request.DataStore.GetJson("SqlCredentials").SelectToken("Database")?.ToString(); string serverWithoutExtension = server.Replace(".database.windows.net", string.Empty); var param = new AzureArmParameterGenerator(); param.AddStringParam("SqlServerName", serverWithoutExtension); param.AddStringParam("SqlDatabaseName", database); param.AddStringParam("Username", user); param.AddParameter("Password", "securestring", password); param.AddStringParam("Sku", databaseTier); param.AddStringParam("SqlLocation", location); var armTemplate = JsonUtility.GetJObjectFromJsonString(System.IO.File.ReadAllText(Path.Combine(request.ControllerModel.SiteCommonFilePath, "Service/Arm/sqlserveranddatabase.json"))); var armParamTemplate = JsonUtility.GetJObjectFromObject(param.GetDynamicObject()); armTemplate.Remove("parameters"); armTemplate.Add("parameters", armParamTemplate["parameters"]); SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription, azureToken); ResourceManagementClient client = new ResourceManagementClient(creds); var deployment = new Microsoft.Azure.Management.Resources.Models.Deployment() { Properties = new DeploymentPropertiesExtended() { Template = armTemplate.ToString(), Parameters = JsonUtility.GetEmptyJObject().ToString() } }; string deploymentName = "SqlDatabaseDeployment"; var validate = await client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()); if (!validate.IsValid) { return(new ActionResponse( ActionStatus.Failure, JsonUtility.GetJObjectFromObject(validate), null, DefaultErrorCodes.DefaultErrorCode, $"Azure:{validate.Error.Message} Details:{validate.Error.Details}")); } var deploymentItem = await client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()); // Wait for deployment while (true) { Thread.Sleep(5000); var status = await client.Deployments.GetAsync(resourceGroup, deploymentName, new CancellationToken()); var operations = await client.DeploymentOperations.ListAsync(resourceGroup, deploymentName, new DeploymentOperationsListParameters()); var provisioningState = status.Deployment.Properties.ProvisioningState; if (provisioningState == "Accepted" || provisioningState == "Running") { continue; } if (provisioningState == "Succeeded") { break; } var operation = operations.Operations.First(p => p.Properties.ProvisioningState == ProvisioningState.Failed); var operationFailed = await client.DeploymentOperations.GetAsync(resourceGroup, deploymentName, operation.OperationId); return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(operationFailed), null, DefaultErrorCodes.DefaultErrorCode, operationFailed.Operation.Properties.StatusMessage)); } SqlCredentials credentials = new SqlCredentials() { Server = server, Username = user, Password = password, Authentication = SqlAuthentication.SQL, Database = database }; request.Logger.LogResource(request.DataStore, server, DeployedResourceType.SqlServer, CreatedBy.BPST, DateTime.UtcNow.ToString("o")); request.Logger.LogResource(request.DataStore, server + "\\" + database, DeployedResourceType.SqlDatabase, CreatedBy.BPST, DateTime.UtcNow.ToString("o"), string.Empty, databaseTier); var connectionStringResponse = SqlUtility.GetConnectionString(credentials); return(new ActionResponse(ActionStatus.Success, JsonUtility.CreateJObjectWithValueFromObject(connectionStringResponse), true)); }
public IEnumerable <IConceptInfo> CreateNewConcepts(PropertyLoggingInfo conceptInfo, IDslModel existingConcepts) { var newConcepts = new List <IConceptInfo>(); var reference = conceptInfo.Property as ReferencePropertyInfo; if (reference != null && reference.Referenced is EntityInfo && existingConcepts.FindByReference <ReferenceDetailInfo>(d => d.Reference, reference).Any() && existingConcepts.FindByReference <EntityLoggingInfo>(l => l.Entity, reference.Referenced).Any()) { newConcepts.Add(new LoggingRelatedItemInfo { Logging = conceptInfo.EntityLogging, Table = SqlUtility.Identifier(reference.Referenced.Module.Name) + "." + SqlUtility.Identifier(reference.Referenced.Name), Column = reference.Name + "ID", Relation = "Detail" }); } return(newConcepts); }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { List <Task <ActionResponse> > task = new List <Task <ActionResponse> >(); var token = request.DataStore.GetJson("AzureToken", "access_token"); var subscription = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); var resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); string connString = request.DataStore.GetValue("SqlConnectionString"); string schema = "dbo"; var coreObjects = request.DataStore.GetValue("ObjectTables").SplitByCommaSpaceTabReturnList(); string postDeploymentPipelineType = request.DataStore.GetValue("postDeploymentPipelineType"); string pipelineFrequency = request.DataStore.GetValue("pipelineFrequency"); string pipelineInterval = request.DataStore.GetValue("pipelineInterval"); string pipelineType = request.DataStore.GetValue("pipelineType"); string pipelineStart = request.DataStore.GetValue("pipelineStart"); string pipelineEnd = request.DataStore.GetValue("pipelineEnd"); bool historicalOnly = Convert.ToBoolean(request.DataStore.GetValue("historicalOnly")); string dataFactoryName = resourceGroup.Replace("_", string.Empty) + "SalesforceCopyFactory"; if (!string.IsNullOrWhiteSpace(postDeploymentPipelineType)) { pipelineFrequency = request.DataStore.GetValue("postDeploymentPipelineFrequency"); pipelineType = postDeploymentPipelineType; pipelineInterval = request.DataStore.GetValue("postDeploymentPipelineInterval"); pipelineStart = DateTime.UtcNow.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); pipelineEnd = new DateTime(9999, 12, 31, 23, 59, 59).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } if (string.IsNullOrWhiteSpace(pipelineStart)) { pipelineStart = DateTime.UtcNow.AddYears(-3).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } if (string.IsNullOrWhiteSpace(pipelineEnd)) { pipelineEnd = DateTime.UtcNow.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } var adfJsonData = request.DataStore.GetValue("ADFPipelineJsonData"); var obj = JsonConvert.DeserializeObject(adfJsonData, typeof(DeserializedADFPayload)) as DeserializedADFPayload; obj = ReorderObjects(obj); for (int i = 0; i < obj.fields.Count(); i++) { var o = obj.fields[i]; string deploymentName = string.Concat("ADFPipeline", pipelineType, o.Item1); var sqlCreds = SqlUtility.GetSqlCredentialsFromConnectionString(connString); var param = new AzureArmParameterGenerator(); param.AddStringParam("dataFactoryName", dataFactoryName); param.AddStringParam("targetSqlSchema", schema); param.AddStringParam("targetSqlTable", o.Item1.ToLowerInvariant()); param.AddStringParam("targetSalesforceTable", o.Item1); param.AddStringParam("pipelineName", o.Item1 + "_CopyPipeline"); param.AddStringParam("sqlWritableTypeName", o.Item1.ToLowerInvariant() + "type"); param.AddStringParam("sqlWriterStoredProcedureName", "spMerge" + o.Item1.ToLowerInvariant()); param.AddStringParam("pipelineStartDate", pipelineStart); param.AddStringParam("pipelineEndDate", pipelineEnd); param.AddStringParam("pipelineType", pipelineType); param.AddStringParam("sliceFrequency", pipelineFrequency); param.AddStringParam("sliceInterval", pipelineInterval); var armTemplate = JsonUtility.GetJsonObjectFromJsonString(System.IO.File.ReadAllText(Path.Combine(request.Info.App.AppFilePath, "Service/ADF/pipeline.json"))); var armParamTemplate = JsonUtility.GetJObjectFromObject(param.GetDynamicObject()); armTemplate.Remove("parameters"); armTemplate.Add("parameters", armParamTemplate["parameters"]); if (i >= 1) { armTemplate = CreatePipelineDependency(pipelineType, obj, armTemplate, i - 1); } string tableFields = JsonConvert.SerializeObject(o.Item2); StringBuilder query; if (o.Item1 != "Opportunity" && o.Item1 != "Lead" && o.Item1 != "OpportunityLineItem" && pipelineType == "PreDeployment" && coreObjects.Contains(o.Item1)) { query = CreateQuery(o, tableFields, true, pipelineStart, pipelineEnd); armTemplate = CreateOneTimePipeline(armTemplate); } else { query = CreateQuery(o, tableFields, false); } if (historicalOnly && pipelineType == "PostDeployment") { armTemplate = this.PausePipeline(armTemplate); } string stringTemplate = ReplaceTableFieldsAndQuery(tableFields, query, armTemplate); SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription, token); ResourceManagementClient client = new ResourceManagementClient(creds); var deployment = new Microsoft.Azure.Management.Resources.Models.Deployment() { Properties = new DeploymentPropertiesExtended() { Template = stringTemplate, Parameters = JsonUtility.GetEmptyJObject().ToString() } }; var validate = client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result; if (!validate.IsValid) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(validate), null, DefaultErrorCodes.DefaultErrorCode, $"Azure:{validate.Error.Message} Details:{validate.Error.Details}")); } task.Add(new Task <ActionResponse>(() => { var deploymentItem = client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result; var helper = new DeploymentHelper(); return(helper.WaitForDeployment(client, resourceGroup, deploymentName).Result); })); } foreach (var t in task) { t.Start(); } var results = Task.WhenAll(task.ToArray()); foreach (var t in results.Result) { if (t.Status != ActionStatus.Success) { return(new ActionResponse(ActionStatus.Failure, t.ExceptionDetail.FriendlyErrorMessage)); } } return(new ActionResponse(ActionStatus.Success, JsonUtility.GetJObjectFromStringValue(dataFactoryName))); }
public async static Task <List <Mitarbeiter> > LoadAllAsync(string[] Fields, ISqlHandler Sql) { SqlDataSet data = await Sql.SelectAsync(Table, SqlUtility.AppendWithCommas(Fields)); List <Mitarbeiter> mitarbeiter = new List <Mitarbeiter>(); foreach (List <object> singleData in data.Data) { Mitarbeiter mit = new Mitarbeiter(); for (int i = 0; i < data.FieldCount; i++) { string f = data.FieldNames[i]; object o = singleData[i]; if (o is DBNull) { o = default(object); } if (f == FieldId) { mit.Id = (int)o; } else if (f == FieldKennung) { mit.Kennung = (string)o; } else if (f == FieldName) { mit.Name = (string)o; } else if (f == FieldVorname) { mit.Vorname = (string)o; } else if (f == FieldFähigkeiten) { mit.Fähigkeiten = (string)o; } else if (f == FieldSchicht) { mit.Schicht.Id = (int)o; } else if (f == FieldTelefon) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.FestnetzPrivat)); } else if (f == FieldMobil) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.MobilDienst)); } else if (f == FieldTelefonIntern) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.FestnetzIntern)); } else if (f == FieldFaxIntern) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.FaxIntern)); } else if (f == FieldEMail) { mit.Kontakt.EMail = (string)o; } } mitarbeiter.Add(mit); } return(mitarbeiter); }
public async static Task <Mitarbeiter> LoadAsync(ISqlHandler Sql, string[] fields, int Id) { SqlDataSet data = await Sql.SelectWhereAsync(Table, SqlUtility.AppendWithCommas(fields), SqlUtility.Equal(FieldId, Id)); Mitarbeiter mit = new Mitarbeiter(); for (int i = 0; i < data.FieldCount; i++) { string f = data.FieldNames[i]; object o = data.Data[0][i]; if (o is DBNull) { o = default(object); } if (f == FieldId) { mit.Id = (int)o; } else if (f == FieldKennung) { mit.Kennung = (string)o; } else if (f == FieldName) { mit.Name = (string)o; } else if (f == FieldVorname) { mit.Vorname = (string)o; } else if (f == FieldFähigkeiten) { mit.Fähigkeiten = (string)o; } else if (f == FieldSchicht) { mit.Schicht.Id = (int)o; } else if (f == FieldTelefon) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.FestnetzPrivat)); } else if (f == FieldMobil) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.MobilDienst)); } else if (f == FieldTelefonIntern) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.FestnetzIntern)); } else if (f == FieldFaxIntern) { mit.Kontakt.Rufnummern.Add(new Rufnummer((string)o, RufnummerTyp.FaxIntern)); } else if (f == FieldEMail) { mit.Kontakt.EMail = (string)o; } } return(mit); }
public static string GetConstraintName(PropertyInfo info) { return(SqlUtility.Identifier(Sql.Format("SqlDefaultPropertyDatabaseDefinition_ConstraintName", info.DataStructure.Name, info.Name))); }