From 26e1634e2f2c09bcf304c2fdc893027d6aaa1446 Mon Sep 17 00:00:00 2001 From: "yariv@backand.com" Date: Sun, 29 Oct 2017 09:04:06 +0000 Subject: [PATCH 01/30] save initial changes --- BackAnd.Web.Api/BackAnd.Web.Api.csproj | 6 +- .../Admin/myAppConnectionController.cs | 25 +- .../Controllers/Admin/myAppsController.cs | 35 +- BackAnd.Web.Api/Controllers/apiController.cs | 91 +- .../Controllers/themeController.cs | 67 - BackAnd.Web.Api/Controllers/userController.cs | 8 +- BackAnd.Web.Api/Web.config | 48 +- .../deployment/Sql/Cloud-MySql.sql | 2 +- Durados.DataAccess/Durados.DataAccess.csproj | 2 + Durados.DataAccess/IDataTableAccess.cs | 2 + Durados.DataAccess/MySqlAccess.cs | 253 +- Durados.DataAccess/SqlAccess.cs | 266 +- .../Controllers/AdminController.cs | 14 +- .../MultiTenancy/DnsAliasController.cs | 72 - Durados.Web.Mvc/Durados.Web.Mvc.csproj | 1 - Durados.Web.Mvc/Map.cs | 96 +- Durados.Web.Mvc/Map/DuradosMap.cs | 27 +- Durados.Web.Mvc/Map/Maps.cs | 2594 +++++++++-------- Durados.Web.Mvc/MapDataSet.Designer.cs | 1860 ++++-------- Durados.Web.Mvc/MapDataSet.xsd | 132 +- Durados.Web.Mvc/MapDataSet.xss | 57 +- Durados.Web.Mvc/Services/AccountService.cs | 122 +- Durados.Web.Mvc/UI/Helpers/AppFactory.cs | 99 +- Durados.Web.Mvc/UI/Helpers/RestHelper.cs | 18 +- Durados.Xml/Durados.Xml.csproj | 1 + Durados/Data/ISqlTextBuilder.cs | 8 + 26 files changed, 2769 insertions(+), 3137 deletions(-) delete mode 100644 BackAnd.Web.Api/Controllers/themeController.cs delete mode 100644 Durados.Web.Mvc/Controllers/MultiTenancy/DnsAliasController.cs diff --git a/BackAnd.Web.Api/BackAnd.Web.Api.csproj b/BackAnd.Web.Api/BackAnd.Web.Api.csproj index df5ee711..f823dff4 100644 --- a/BackAnd.Web.Api/BackAnd.Web.Api.csproj +++ b/BackAnd.Web.Api/BackAnd.Web.Api.csproj @@ -95,7 +95,7 @@ False ..\packages\Npgsql.2.2.5\lib\net45\Mono.Security.dll - + False ..\Duradus.Web.Mvc.App\deployment\MySql.Data.dll @@ -177,7 +177,6 @@ - @@ -288,7 +287,6 @@ - @@ -385,7 +383,7 @@ True 5943 / - http://localhost:4110 + http://localhost:8000 True http://localhost:5943 False diff --git a/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs b/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs index eb9f27b0..10d65f20 100644 --- a/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs +++ b/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs @@ -19,6 +19,7 @@ using Durados.Web.Mvc.Webhook; using Durados.Web.Mvc.UI.Helpers.Cloning; using System.Runtime.Caching; +using System.Data.Common; /* HTTP Verb |Entire Collection (e.g. /customers) |Specific Item (e.g. /customers/{id}) ----------------------------------------------------------------------------------------------------------------------------------------------- @@ -1194,11 +1195,12 @@ private void HandleTemplate(string name, string id, MapDataSet.durados_AppRow ap //Maps.Instance.Restart(name); } + /* TODO: Main MySQL depricated private string GetThemePath(int? themeId) { return Maps.Instance.GetTheme(themeId).RelativePath; } - + */ //public Dictionary CreateAppGet2(string template, string name, string title, string server, string catalog, string username, string password, bool usingSsh, bool usingSsl, string sshRemoteHost, string sshUser, string sshPassword, string sshPrivateKey, int sshPort, int productPort, string zone, string characterSetName, string engine, string engineVersion, int? themeId) //{ // Durados.SqlProduct? product = Durados.Web.Mvc.UI.Helpers.RDSNewDatabaseFactory.GetSqlProductfromTemplate(template); @@ -1451,7 +1453,9 @@ private Dictionary CreateApp2(string template, string name, stri values.Add("TemplateFile", string.Empty); values.Add("FK_durados_App_durados_SqlConnection_Security_Parent", string.Empty); values.Add("Basic", basic); - values.Add("FK_durados_App_durados_Theme_Parent", (themeId ?? Maps.DefaultThemeId).ToString()); + /* TODO: Main MySQL depricated + * values.Add("FK_durados_App_durados_Theme_Parent", (themeId ?? Maps.DefaultThemeId).ToString()); + */ if (templateId.HasValue) { string templateIdFieldName = view.GetFieldByColumnNames("TemplateId").Name; @@ -1572,7 +1576,10 @@ private Dictionary CreateApp2(string template, string name, stri } var builder = new UriBuilder(System.Web.HttpContext.Current.Request.Url); - string previewUrl = "http://" + name + Durados.Web.Mvc.Maps.UserPreviewUrl + GetThemePath(themeId); + string previewUrl = "http://" + name + Durados.Web.Mvc.Maps.UserPreviewUrl; + /* TODO: Main MySQL depricated + * +GetThemePath(themeId); + */ return new Dictionary() { { "Success", true }, { "Url", Maps.GetAppUrl(name) }, { "previewUrl", previewUrl } }; } @@ -2838,8 +2845,8 @@ public string GetConnection(string serverName, string catalog, bool? integratedS { string connectionString = null; - System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(); - builder.ConnectionString = Map.connectionString; + DbConnectionStringBuilder builder = Maps.GetMapsConnectionStringBuilder(); ; + //builder.ConnectionString = Map.connectionString; bool hasServer = !string.IsNullOrEmpty(serverName); bool hasCatalog = !string.IsNullOrEmpty(catalog); @@ -2853,7 +2860,7 @@ public string GetConnection(string serverName, string catalog, bool? integratedS { if (!hasServer) { - serverName = builder.DataSource; + serverName = builder.Server(); } connectionString = "Data Source={0};Initial Catalog={1};Integrated Security=True;"; @@ -2897,7 +2904,7 @@ public string GetConnection(string serverName, string catalog, bool? integratedS if (!hasServer) { if (Maps.AllowLocalConnection) - serverName = builder.DataSource; + serverName = builder.Server(); else throw new Durados.DuradosException("Server Name is missing"); } @@ -2905,7 +2912,7 @@ public string GetConnection(string serverName, string catalog, bool? integratedS if (!hasUsername) { if (Maps.AllowLocalConnection) - username = builder.UserID; + username = builder.UserId(); else throw new Durados.DuradosException("Username Name is missing"); } @@ -2913,7 +2920,7 @@ public string GetConnection(string serverName, string catalog, bool? integratedS if (!hasPassword) { if (Maps.AllowLocalConnection) - password = builder.Password; + password = builder.Password(); else throw new Durados.DuradosException("Password Name is missing"); } diff --git a/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs b/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs index 4119863d..8170bb34 100644 --- a/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs +++ b/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs @@ -19,6 +19,7 @@ using Durados.Data; using Durados.Web.Mvc.Webhook; using BackAnd.Web.Api.Controllers.Admin; +using System.Data; /* HTTP Verb |Entire Collection (e.g. /customers) |Specific Item (e.g. /customers/{id}) ----------------------------------------------------------------------------------------------------------------------------------------------- @@ -368,6 +369,7 @@ public virtual IHttpActionResult Post() const string Name = "Name"; const string Title = "Title"; const string Environment = "Environment"; + if (values.ContainsKey(Name)) @@ -405,6 +407,7 @@ public virtual IHttpActionResult Post() values.Add(Creator, view.Database.GetUserID()); values.Add(DatabaseStatus, (int)OnBoardingStatus.NotStarted); + appName = values[Name].ToString(); string key = view.Create(values, false, view_BeforeCreate, view_BeforeCreateInDatabase, view_AfterCreateBeforeCommit, view_AfterCreateAfterCommit); @@ -413,6 +416,7 @@ public virtual IHttpActionResult Post() return Ok(new { __metadata = new { id = key, appName = appName } }); } + // TODO : Mysql deprecated catch (System.Data.SqlClient.SqlException exception) { const int DuplicateUniqueIndex = 2601; @@ -463,8 +467,8 @@ private int GetNextUserAppNameNumber(string appNamePrefix) private string[] GetAppNamesWithPrefix(string appNamePrefix) { - SqlAccess sqlAccess = new SqlAccess(); - string sql = "select name from durados_app where name like '" + appNamePrefix + "%'"; + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + string sql = Maps.GetMainAppSqlSchema().GetAppNamesWithPrefixSql(appNamePrefix); System.Data.DataTable table = sqlAccess.ExecuteTable(Maps.Instance.DuradosMap.connectionString, sql, null, System.Data.CommandType.Text); List list = new List(); @@ -784,8 +788,12 @@ protected override void AfterDeleteBeforeCommit(Durados.DeleteEventArgs e) { int id = Convert.ToInt32(e.PrimaryKey); - System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(Maps.Instance.ConnectionString); - string mapServer = scsb.DataSource; + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + SqlSchema sqlSchema = sqlAccess.GetNewSqlSchema(); + + + string mapServer = sqlSchema.GetServerName(Maps.Instance.ConnectionString); + MapDataSet.durados_SqlConnectionRow systemConnectionRow = ((MapDataSet.durados_AppRow)e.PrevRow).durados_SqlConnectionRowByFK_durados_App_durados_SqlConnection_System; if (systemConnectionRow != null) { @@ -829,9 +837,13 @@ protected override void AfterDeleteBeforeCommit(Durados.DeleteEventArgs e) private bool HasOtherConnectios(string appDatabase) { - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + ISqlMainSchema sqlSchema= Maps.GetMainAppSqlSchema(); + string sql = sqlSchema.GetHasOtherConnectiosSql(appDatabase); + + using (IDbConnection connection = sqlSchema.GetNewConnection(Maps.Instance.ConnectionString)) { - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("select count(*) from dbo.durados_SqlConnection where [Catalog] = N'" + appDatabase + "'", connection)) + + using (IDbCommand command = sqlSchema.GetNewCommand( sql,connection)) { connection.Open(); object scalar = command.ExecuteScalar(); @@ -845,12 +857,17 @@ private bool HasOtherConnectios(string appDatabase) private void DropDatabase(string name) { - System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(Maps.Instance.ConnectionString); + + //System.Data.Common.DbConnectionStringBuilder scsb = Maps.GetMapsConnectionStringBuilder(Maps.Instance.ConnectionString); //scsb.InitialCatalog = null; - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(scsb.ConnectionString)) + + ISqlMainSchema sqlSchema = Maps.GetMainAppSqlSchema(); + string sql = sqlSchema.GetDropDatabaseSql(name); + using (IDbConnection connection = sqlSchema.GetNewConnection(Maps.Instance.ConnectionString)) { - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("ALTER DATABASE " + name + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE; drop database " + name, connection)) + + using (IDbCommand command = sqlSchema.GetNewCommand(sql, connection)) { connection.Open(); command.ExecuteNonQuery(); diff --git a/BackAnd.Web.Api/Controllers/apiController.cs b/BackAnd.Web.Api/Controllers/apiController.cs index 88a49399..93c85ddd 100644 --- a/BackAnd.Web.Api/Controllers/apiController.cs +++ b/BackAnd.Web.Api/Controllers/apiController.cs @@ -19,11 +19,12 @@ using BackAnd.Web.Api.Controllers.Filters; using System.Threading.Tasks; using System.Collections; -using System.Data.SqlClient; +using System.Data.Common; using Durados.Web.Mvc.Infrastructure; using Durados.Web.Mvc.Farm; using System.Runtime.Caching; + /* HTTP Verb |Entire Collection (e.g. /customers) |Specific Item (e.g. /customers/{id}) ----------------------------------------------------------------------------------------------------------------------------------------------- @@ -584,16 +585,18 @@ protected void UpdateLogModelException(Exception exception) { if (logModelId.HasValue) { - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.DuradosMap.connectionString)) + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + using (IDbConnection connection = sqlMain.GetNewConnection(Maps.Instance.ConnectionString)) { connection.Open(); - string sql = "update [backand_model] set errorMessage = @errorMessage, errorTrace = @errorTrace where id=@id"; + string sql = sqlMain.GetUpdateLogModelExceptionSql(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection)) + using (IDbCommand command = sqlMain.GetNewCommand(sql, connection)) { - command.Parameters.AddWithValue("errorMessage", exception.Message); - command.Parameters.AddWithValue("errorTrace", exception.StackTrace); - command.Parameters.AddWithValue("id", logModelId.Value); + GetDataParameter("errorMessage",exception.Message, command); + GetDataParameter("errorTrace", exception.StackTrace, command); + GetDataParameter("id", logModelId.Value, command); + command.ExecuteNonQuery(); } @@ -609,30 +612,39 @@ protected void UpdateLogModelException(Exception exception) } } + protected static void GetDataParameter(string name,object val, IDbCommand command) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = name; + parameter.Value = val; + command.Parameters.Add(parameter); + } + protected int? logModelId = null; private void LogModel(string appName, string username, DateTime timestamp, string input, string output, string valid, string action) { - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.DuradosMap.connectionString)) + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + using (IDbConnection connection = sqlMain.GetNewConnection(Maps.Instance.ConnectionString)) { connection.Open(); - string sql = "insert into [backand_model] ([appName], [username], [timestamp], [input], [output], [valid], [action]) values (@appName, @username, @timestamp, @input, @output, @valid, @action); SELECT IDENT_CURRENT(N'backand_model') AS ID"; + string sql = sqlMain.GetLogModelSql(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection)) + using (IDbCommand command = sqlMain.GetNewCommand(sql, connection)) { try { - command.Parameters.AddWithValue("appName", appName); - command.Parameters.AddWithValue("username", username); - command.Parameters.AddWithValue("timestamp", timestamp); - command.Parameters.AddWithValue("input", input); - command.Parameters.AddWithValue("output", output); - command.Parameters.AddWithValue("valid", valid); - command.Parameters.AddWithValue("action", action); + GetDataParameter("appName", appName,command); + GetDataParameter("username", username, command); + GetDataParameter("timestamp", timestamp, command); + GetDataParameter("input", input, command); + GetDataParameter("output", output, command); + GetDataParameter("valid", valid, command); + GetDataParameter("action", action, command); object scalar = command.ExecuteScalar(); logModelId = Convert.ToInt32(scalar); } - catch (SqlException e) + catch (DbException e) { Maps.Instance.DuradosMap.Logger.Log("Model", "Validate", "LogModel", e, 1, command.CommandText + "; " + connection.ConnectionString); @@ -1096,6 +1108,7 @@ private void HandleSpecialDefaults(Durados.Web.Mvc.View view, Dictionary values) { HandleCurrentUserDefault(view, values, false); @@ -1113,7 +1126,7 @@ private void HandleCurrentUserDefault(Durados.Web.Mvc.View view, Dictionary values, bool import) { var fields = view.Fields.Values.Where(f => f.FieldType == FieldType.Parent && f.DefaultValue != null && f.DefaultValue.ToString().ToLower() == Durados.Web.Mvc.Database.UserPlaceHolder.ToLower()); @@ -1138,6 +1151,7 @@ private void HandleCurrentUserDefault(Durados.Web.Mvc.View view, Dictionary values) { @@ -1962,24 +1976,25 @@ protected virtual void AfterEditAfterCommit(EditEventArgs e) wfe.PerformActions(this, e.View, TriggerDataAction.AfterEdit, e.Values, e.PrimaryKey, e.PrevRow, Map.Database.ConnectionString, Convert.ToInt32(((Durados.Web.Mvc.Database)e.View.Database).GetUserID()), ((Durados.Web.Mvc.Database)e.View.Database).GetUserRole(), e.Command, e.SysCommand); wfe.Notifier.Notify((Durados.Web.Mvc.View)e.View, 1, GetUsername(), e.OldNewValues, e.PrimaryKey, e.PrevRow, this, e.Values, GetSiteWithoutQueryString(), GetMainSiteWithoutQueryString()); - - const string Active = "Active"; - if (e.View.Name == "Durados_Language") - { - bool prevActive = !e.PrevRow.IsNull(Active) && Convert.ToBoolean(e.PrevRow[Active]); - bool currActive = e.Values.ContainsKey(Active) && Convert.ToBoolean(e.Values[Active]); - - if (!prevActive && currActive) - { - string code = e.PrevRow["Code"].ToString(); - string scriptFile = Maps.GetDeploymentPath("Sql/Localization/" + code + "pack.sql"); + /* TODO: Main MySql deprectaed + const string Active = "Active"; + + if (e.View.Name == "Durados_Language") + { + bool prevActive = !e.PrevRow.IsNull(Active) && Convert.ToBoolean(e.PrevRow[Active]); + bool currActive = e.Values.ContainsKey(Active) && Convert.ToBoolean(e.Values[Active]); - SqlAccess sqlAcces = new SqlAccess(); - sqlAcces.RunScriptFile(scriptFile, Map.GetLocalizationDatabase().ConnectionString); - Map.Database.Localizer.SetCurrentUserLanguageCode(code); - } - } + if (!prevActive && currActive) + { + string code = e.PrevRow["Code"].ToString(); + string scriptFile = Maps.GetDeploymentPath("Sql/Localization/" + code + "pack.sql"); + SqlAccess sqlAcces = new SqlAccess(); + sqlAcces.RunScriptFile(scriptFile, Map.GetLocalizationDatabase().ConnectionString); + Map.Database.Localizer.SetCurrentUserLanguageCode(code); + } + } + */ if (e.View.Name == "durados_Cloud") { RefreshConfigCache(); @@ -2081,8 +2096,8 @@ protected virtual void AfterDeleteBeforeCommit(DeleteEventArgs e) { int userId = Maps.Instance.DuradosMap.Database.GetUserID(deletedUsername); string appId = Map.Id; - SqlAccess sqlAccess = new SqlAccess(); - sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, string.Format("delete durados_UserApp where UserId = {0} and AppId = {1}", userId, appId)); + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, Maps.GetMainAppSqlSchema().GetDeleteUserSql( userId, appId)); } } catch { } diff --git a/BackAnd.Web.Api/Controllers/themeController.cs b/BackAnd.Web.Api/Controllers/themeController.cs deleted file mode 100644 index 65e87d67..00000000 --- a/BackAnd.Web.Api/Controllers/themeController.cs +++ /dev/null @@ -1,67 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Formatting; -using System.Net.Http.Headers; -using System.Threading.Tasks; -using System.Web.Http; - - -namespace BackAnd.Web.Api.Controllers -{ - - public class themeController : apiController - { - public HttpResponseMessage Get(string id = null) - { - try - { - if (id == null) - { - id = GetAppName(); - } - string path = Durados.Web.Mvc.Maps.Instance.GetAppThemePath(id); - //if (!path.StartsWith("/")) - // path = "/" + path; - string responseBody = string.Format(@" location.replace('{0}') ", path); - - HttpResponseMessage response = Request.CreateResponse(System.Net.HttpStatusCode.OK, responseBody, new TextPlainFormatter()); - response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/javascript"); - response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); - response.Content.Headers.ContentDisposition.Name = "theme"; - response.Content.Headers.ContentDisposition.FileName = "theme.js"; - - return response; - } - catch (Exception exception) - { - throw new BackAndApiUnexpectedResponseException(exception, this); - } - } - - private string GetAppName() - { - try - { - return System.Web.HttpContext.Current.Request.UrlReferrer.Authority.Split('.')[0]; - } - catch - { - try - { - return Durados.Web.Mvc.Maps.GetCurrentAppName(); - } - catch - { - return null; - } - } - } - } - - -} diff --git a/BackAnd.Web.Api/Controllers/userController.cs b/BackAnd.Web.Api/Controllers/userController.cs index a7ec0c88..56d09296 100644 --- a/BackAnd.Web.Api/Controllers/userController.cs +++ b/BackAnd.Web.Api/Controllers/userController.cs @@ -1303,26 +1303,28 @@ private void RegisterUserToMainApp(string email, string appName, string firstNam account.InviteAdminAfterSignUp(email); AccountService.SendRegistrationRequest(firstName, lastName, email, string.Empty, email, string.Empty, Maps.Instance.DuradosMap, DontSend); + /* TODO: Main MySQL depricated try { - AccountService.UpdateWebsiteUsers(email, Convert.ToInt32(Maps.Instance.GetMap(appName).Database.GetUserID())); + //AccountService.UpdateWebsiteUsers(email, Convert.ToInt32(Maps.Instance.GetMap(appName).Database.GetUserID())); } catch (Exception ex) { Maps.Instance.DuradosMap.Logger.Log("user", "SignUp", "SignUp", ex, 1, "failed to update websiteusercookie with userid"); } - + //Insert into website users try { - AccountService.InsertContactUsUsers(email, firstName + " " + lastName, null, string.Empty, 10, 100, null); //10=welcome email + //AccountService.InsertContactUsUsers(email, firstName + " " + lastName, null, string.Empty, 10, 100, null); //10=welcome email } catch (Exception ex) { Maps.Instance.DuradosMap.Logger.Log("user", "SignUp", "SignUp", ex, 1, "failed to update websiteuser in ContactUs"); } + * */ } diff --git a/BackAnd.Web.Api/Web.config b/BackAnd.Web.Api/Web.config index f802a331..3664a0ad 100644 --- a/BackAnd.Web.Api/Web.config +++ b/BackAnd.Web.Api/Web.config @@ -155,7 +155,7 @@ - + @@ -210,13 +210,14 @@ =======--> + - + @@ -230,8 +231,8 @@ - - + + @@ -242,9 +243,22 @@ - + >>>>>> Stashed changes--> - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - +--> - + + + + - + - + - - + + - + - - - - + + + - + 870 @@ -36,7 +35,7 @@ - + 1576 @@ -48,7 +47,7 @@ - + 887 @@ -72,7 +71,7 @@ - + 494 @@ -84,7 +83,7 @@ - + 400 @@ -100,7 +99,7 @@ - + 494 @@ -112,7 +111,7 @@ - + 494 @@ -124,7 +123,7 @@ - + 1037 @@ -144,7 +143,7 @@ - + 494 @@ -156,7 +155,7 @@ - + 1576 @@ -168,7 +167,7 @@ - + 1576 @@ -204,19 +203,7 @@ - - - - 726 - 533 - - - 887 - 533 - - - - + 887 @@ -228,7 +215,7 @@ - + 259 @@ -244,7 +231,7 @@ - + 887 diff --git a/Durados.Web.Mvc/Services/AccountService.cs b/Durados.Web.Mvc/Services/AccountService.cs index d0ae7c55..c3d5c3e7 100644 --- a/Durados.Web.Mvc/Services/AccountService.cs +++ b/Durados.Web.Mvc/Services/AccountService.cs @@ -6,7 +6,7 @@ using System; using System.Collections.Generic; using System.Data; -using System.Data.SqlClient; +//using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; @@ -57,15 +57,16 @@ public string GetEmailBySocialId(string provider, string socialId, int appId) //int rowCount = -1; //DataView dataView = view.FillPage(1, 1, new Dictionary() { { "Provider", provider }, { "SocialId", socialId } }, null, null, out rowCount, null, null); - SqlAccess sa = new SqlAccess(); + SqlAccess sa = Maps.GetMainAppSqlAccess(); - string sql = "select UserId from durados_UserSocial where Provider = @Provider and SocialId = @SocialId and AppId = @AppId"; + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + string sql = sqlMain.GetEmailBySocialIdSql(); object scalar = sa.ExecuteScalar(view.ConnectionString, sql, new Dictionary() { { "Provider", provider }, { "SocialId", socialId }, { "AppId", appId } }); if (scalar == null) { - sql = "select UserId from durados_UserSocial where Provider = @Provider and SocialId = @SocialId and AppId is null"; + sql = sqlMain.GetEmailBySocialIdSql2(); scalar = sa.ExecuteScalar(view.ConnectionString, sql, new Dictionary() { { "Provider", provider }, { "SocialId", socialId } }); } @@ -91,6 +92,8 @@ public string GetEmailBySocialId(string provider, string socialId, int appId) return GetDuradosMap().Database.GetUsernameById(userId); } + + public string GetSocialIdlByEmail(string provider, string email, string appName) { int appId = Convert.ToInt32(Maps.Instance.GetMap(appName).Id); @@ -145,16 +148,18 @@ public static string GetRandomPassword(int chars) public string GetSocialIdlByEmail(string provider, int userId, int appId) { View view = GetUserSocialView(); - - SqlAccess sa = new SqlAccess(); - string sql = "select SocialId from durados_UserSocial WITH(NOLOCK) where Provider = @Provider and UserId = @UserId and AppId = @AppId"; + SqlAccess sa = Maps.GetMainAppSqlAccess(); + + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + + string sql = sqlMain.GetSocialIdlByEmail(); object scalar = sa.ExecuteScalar(view.ConnectionString, sql, new Dictionary() { { "Provider", provider }, { "UserId", userId }, { "AppId", appId } }); if (scalar == null) { - sql = "select SocialId from durados_UserSocial WITH(NOLOCK) where Provider = @Provider and UserId = @UserId and AppId is null"; + sql = sqlMain.GetSocialIdlByEmail2(); scalar = sa.ExecuteScalar(view.ConnectionString, sql, new Dictionary() { { "Provider", provider }, { "UserId", userId } }); } @@ -343,7 +348,10 @@ public Dictionary SignUpToBackand(string username, string passwo bool DontSend = false; try { - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + Dictionary parameters = new Dictionary(); string email = username.Trim(); @@ -396,7 +404,7 @@ public Dictionary SignUpToBackand(string username, string passwo Guid guid = Guid.NewGuid(); parameters.Add("@Guid", guid); - sql.ExecuteNonQuery(Maps.Instance.DuradosMap.Database.ConnectionString, "if NOT EXISTS (Select [Username] From [" + GetDuradosMap().Database.GetUserView().GetTableName() + "] WHERE [Username] = @Username) begin INSERT INTO [durados_User] ([Username],[FirstName],[LastName],[Email],[Role],[Guid]) VALUES (@Username,@FirstName,@LastName,@Email,@Role,@Guid) end", parameters, CreateMembershipCallback); + sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.Database.ConnectionString, sqlMain.InsertNewUserSql(GetDuradosMap().Database.GetUserView().GetTableName(), "durados_User"), sqlAccess.GetSqlProduct(), parameters, CreateMembershipCallback); //System.Web.Security.MembershipUser user = System.Web.Security.Membership.Provider.GetUser(username, true); //if (user != null) @@ -420,6 +428,8 @@ public Dictionary SignUpToBackand(string username, string passwo if (sendEmail) SendRegistrationRequest(fullname, lastName, email, guid.ToString(), username, password, Maps.Instance.DuradosMap, DontSend); + /* + * TODO: Main MySQL depricated try { Durados.Web.Mvc.UI.Helpers.AccountService.UpdateWebsiteUsers(username, identity); @@ -440,6 +450,7 @@ public Dictionary SignUpToBackand(string username, string passwo Maps.Instance.DuradosMap.Logger.Log("account", "SignUpToBackand", "SignUp", ex, 1, "failed to update websiteuser in ContactUs"); } + */ } catch (DuradosException exception) @@ -459,6 +470,7 @@ public Dictionary SignUpToBackand(string username, string passwo //return Json(new { Success = true, Message = "Success", identity = identity, DemoDefaults = GetDefaultDemo(identity) }); } + protected virtual string CreateMembershipCallback(Dictionary paraemeters) { string username = paraemeters["@Username"].ToString(); @@ -832,14 +844,17 @@ protected virtual void Activate(string username, string appName) protected virtual void Activate(string username, string appName, string role) { Map map = GetMap(appName); - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); Dictionary parameters = new Dictionary(); parameters.Add("@UserId", map.Database.GetUserID(username)); parameters.Add("@AppId", map.Id); parameters.Add("@Role", role); - sql.ExecuteNonQuery(Maps.Instance.DuradosMap.Database.ConnectionString, "INSERT INTO [durados_UserApp] ([UserId],[AppId],[Role]) VALUES (@UserId,@AppId,@Role)", parameters, null); + sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.Database.ConnectionString, sqlMain.GetInsertUserAppSql(), parameters, null); } + + public virtual void ActivateAdmin(string username, string appName) { bool isAuthenticated = IsAuthenticated(username, null); @@ -850,20 +865,20 @@ public virtual void ActivateAdmin(string username, string appName) } else { - InviteAdminBeforeAignUp(username, appName); + InviteAdminBeforeSignUp(username, appName); } } - private void InviteAdminBeforeAignUp(string username, string appName) + private void InviteAdminBeforeSignUp(string username, string appName) { - SqlAccess sqlAccess = new SqlAccess(); - + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); try { Map map = GetDuradosMap(); string appId = GetMap(appName).Id; - sqlAccess.ExecuteNonQuery(map.connectionString, string.Format("insert into durados_Invite (username, appId) values ('{0}', {1})", username, appId)); + sqlAccess.ExecuteNonQuery(map.connectionString,sqlMain.GetInviteAdminBeforeSignUpSql(username, appId) ); } catch (Exception exception) { @@ -912,9 +927,11 @@ public static void SendRegistrationRequest(string firstName, string lastName, st /// /// /// + /// + /* TODO: Main MySQL depricated public static void UpdateWebsiteUsers(string username, int userId) { - SqlAccess sqlAccess = new SqlAccess(); + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); string sql = @"INSERT INTO [website_UsersCookie]([UserId],[CookieGuid],[CreateDate]) VALUES(@UserId,@CookieGuid,@CreateDate)"; Dictionary parameters = new Dictionary(); @@ -937,7 +954,7 @@ public static void UpdateWebsiteUsers(string username, int userId) /// public static void InsertContactUsUsers(string email, string fullname, string comments, string phone, int requestSubjectId, int? dbType, string dbOther) { - SqlAccess sqlAccess = new SqlAccess(); + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); Dictionary parameters = new Dictionary(); parameters.Add("@Email", email); if (fullname == null) @@ -972,7 +989,7 @@ public static void InsertContactUsUsers(string email, string fullname, string co sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, "dbo.website_AddEditUser @Email,@FullName,@Comments,@CookieGuid,@Phone,@RequestSubject,@DBtype,@DBother", parameters, null); } - + /// /// Retrun the GUID stored in the tracking cookie /// @@ -986,7 +1003,7 @@ public static object GetTrackingCookieGuid() return trackingCookie.Values["guid"]; } - + */ public virtual void InviteAdminAfterSignUp(string username) { try @@ -994,21 +1011,25 @@ public virtual void InviteAdminAfterSignUp(string username) Map map = GetDuradosMap(); int userId = GetDuradosMap().Database.GetUserID(username); - using (SqlConnection connection = new SqlConnection(map.connectionString)) + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + using (IDbConnection connection = sqlAccess.GetNewSqlSchema().GetConnection(map.connectionString)) { connection.Open(); - - SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); + + IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); try { - using (SqlCommand command = new SqlCommand()) + + + using (IDbCommand command = sqlAccess.GetNewCommand()) { command.Connection = connection; command.Transaction = transaction; - command.CommandText = string.Format("select appId from durados_Invite where username = '{0}'", username); + command.CommandText = sqlMain.GetInviteAdminAfterSignupSql(username); List apps = new List(); using (IDataReader reader = command.ExecuteReader()) { @@ -1022,10 +1043,10 @@ public virtual void InviteAdminAfterSignUp(string username) foreach (string appId in apps) { - command.CommandText = string.Format("insert into durados_UserApp (UserId, AppId, Role) values ({0},{1},'{2}')", userId, appId, "Admin"); + command.CommandText = sqlMain.GetInviteAdminAfterSignupSql(userId,appId,"Admin"); command.ExecuteNonQuery(); } - command.CommandText = string.Format("delete durados_Invite where username = '{0}'", username); + command.CommandText = sqlMain.GetDeleteInviteUser(username); command.ExecuteNonQuery(); transaction.Commit(); @@ -1159,8 +1180,11 @@ protected virtual void AddToAuthenticatedUsers(string appName, string firstName, parameters.Add("Role", role); parameters.Add("Guid", Guid.NewGuid()); parameters.Add("AppName", appName); - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); - sql.ExecuteNonQuery(GetDuradosMap().Database.GetUserView().ConnectionString, "if NOT EXISTS (Select [Username] From [" + GetDuradosMap().Database.GetUserView().GetTableName() + "] WHERE [Username] = @Username) begin INSERT INTO [" + GetDuradosMap().Database.GetUserView().GetTableName() + "] ([Username],[FirstName],[LastName],[Email],[Role],[Guid]) VALUES (@Username,@FirstName,@LastName,@Email,@Role,@Guid) end", parameters, AddToAuthenticatedUsersCallback); + + Map map = GetDuradosMap(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + sqlAccess.ExecuteNonQuery(map.Database.GetUserView().ConnectionString, sqlMain.InsertNewUserSql(GetDuradosMap().Database.GetUserView().GetTableName() , GetDuradosMap().Database.GetUserView().GetTableName() ), parameters, AddToAuthenticatedUsersCallback); } @@ -1603,12 +1627,12 @@ public static string GetUserGuid(string userName) { try { - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); Dictionary parameters = new Dictionary(); parameters.Add("@username", userName); - object guid = sql.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 [durados_user].[guid] FROM durados_user WITH(NOLOCK) WHERE [durados_user].[username]=@username", parameters); + object guid = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 [durados_user].[guid] FROM durados_user WITH(NOLOCK) WHERE [durados_user].[username]=@username", parameters); if (guid == null || guid == DBNull.Value) throw new DuradosException("Username has no unique guid, cannot reset password."); @@ -1626,12 +1650,14 @@ public static int GetUserId(string userName) { try { - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); Dictionary parameters = new Dictionary(); parameters.Add("@username", userName); - object id = sql.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 [durados_user].[id] FROM durados_user WITH(NOLOCK) WHERE [durados_user].[username]=@username", parameters); + object id = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sqlMain.GetUserSql(), parameters); if (id == null || id == DBNull.Value) throw new DuradosException("Username has no unique username."); @@ -1652,12 +1678,14 @@ public static string GetUserTempToken(string username) { string guid = GetUserGuid(username); - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); Dictionary parameters = new Dictionary(); parameters.Add("@UserGuid", guid); - object tempGuid = sql.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 Id FROM [durados_ValidGuid] WITH(NOLOCK) WHERE UserGuid=@UserGuid and Used=0", parameters); + object tempGuid = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sqlMain.GetUserTempTokenSql() , parameters); if (tempGuid == null || tempGuid == DBNull.Value) throw new DuradosException("Temp token not found for " + username); @@ -1709,13 +1737,15 @@ private void SetAppNameByToken(string token, string appName) private string GetUsername(string guid) { - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); Dictionary parameters = new Dictionary(); parameters.Add("@guid", guid); - string sqlDuradosSys = string.Format("SELECT TOP 1 username FROM durados_user WITH(NOLOCK) WHERE guid=@guid"); + string sqlDuradosSys = sqlMain.GetUserNameByGuidSql(); return sqlAccess.ExecuteScalar(Maps.Instance.ConnectionString, sqlDuradosSys, parameters); } @@ -1733,13 +1763,14 @@ public void DeleteUser(string username, string appName) if (Maps.Instance.DuradosMap.Database.GetUserRow() == null) throw new DuradosException("user does not exist"); - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); Dictionary parameters = new Dictionary(); parameters.Add("@username", username); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); - string sql = string.Format("delete FROM durados_user WHERE [username]=@username"); + string sql = sqlMain.GetDeleteUserSql(); if (appName != null && appName != Maps.DuradosAppName) { @@ -1766,14 +1797,15 @@ public bool UserBelongToMoreThanOneApp(string username, string appName) appId = Convert.ToInt32(map.Id); } - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); Dictionary parameters = new Dictionary(); parameters.Add("@appid", appId); parameters.Add("@userid", id); - string sql = string.Format("select id FROM durados_userapp WHERE [userid]=@userid and appid<>@appid"); + string sql = sqlMain.GetUserBelongToMoreThanOneAppSql(); return !sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sql, parameters).Equals(string.Empty); @@ -1785,13 +1817,13 @@ private bool UserHasApps(string username) { int id = Maps.Instance.DuradosMap.Database.GetUserID(username); - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); - + Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); Dictionary parameters = new Dictionary(); parameters.Add("@id", id); - string sql = string.Format("SELECT TOP 1 id FROM durados_app WITH(NOLOCK) WHERE creator=@id"); + string sql = sqlMain.GetHasAppsSql(); return !sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sql, parameters).Equals(string.Empty); } diff --git a/Durados.Web.Mvc/UI/Helpers/AppFactory.cs b/Durados.Web.Mvc/UI/Helpers/AppFactory.cs index a5428992..72a65eb8 100644 --- a/Durados.Web.Mvc/UI/Helpers/AppFactory.cs +++ b/Durados.Web.Mvc/UI/Helpers/AppFactory.cs @@ -4,6 +4,7 @@ using System.Text; using System.Threading.Tasks; using Durados.DataAccess; +using System.Data.Common; namespace Durados.Web.Mvc.UI.Helpers { @@ -15,13 +16,9 @@ public class AppFactory public NewDatabaseParameters GetNewExternalDBParameters(Durados.SqlProduct sqlProduct, string id, out string server,out int port,string sampleApp)//, out string catalog { - // set all the database parameters for the createapp - - Durados.Web.Mvc.UI.Helpers.NewDatabaseParameters newDbParameters = new Durados.Web.Mvc.UI.Helpers.RDSNewDatabaseFactory().GetNewParameters(sqlProduct, id); - //catalog = newDbParameters.DbName; + Durados.Web.Mvc.UI.Helpers.NewDatabaseParameters newDbParameters = new Durados.Web.Mvc.UI.Helpers.RDSNewDatabaseFactory().GetNewParameters(sqlProduct, id); + CreateNewSchemaAndUser(sqlProduct, out server,out port, newDbParameters,sampleApp); - //server = newDbParameters.InstanceName; //System.Configuration.ConfigurationManager.AppSettings["AWSServer"]??".";//aws database server - //catalog = sqlProduct == Durados.SqlProduct.SqlServer ? newDbParameters.InstanceName : newDbParameters.DbName; return newDbParameters; } @@ -116,7 +113,7 @@ public string GetExternalAvailableInstanceConnectionString(SqlProduct product,ou port = 0; string spName = "durados_GetExternalAvailableInstance"; int? connectionId= null; - using (System.Data.IDbConnection cnn = Durados.DataAccess.DataAccessObject.GetNewConnection(SqlProduct.SqlServer, Maps.Instance.ConnectionString)) + using (System.Data.IDbConnection cnn = Maps.GetMainAppSqlSchema().GetNewConnection(Maps.Instance.ConnectionString)) { using (DuradosCommand command = new DuradosCommand(GetSystemProduct())) { @@ -135,19 +132,44 @@ public string GetExternalAvailableInstanceConnectionString(SqlProduct product,ou throw new Exception("No connection to main database", ex); } } + var parameter = command.CreateParameter(); + parameter.ParameterName = "productId"; + parameter.Value = 3; + command.Parameters.Add(parameter); System.Data.IDataReader reader = command.ExecuteReader(); if (reader.Read()) connectionId = reader.GetInt32(reader.GetOrdinal("SqlConnectionId")); } } - + Durados.Web.Mvc.View view = GetView(ConnectionViewName); if (!connectionId.HasValue) { - Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "GetExternalAvailableInstanceConnection", null, 1, "Failed to retrive available external instance = connection id has no value"); - throw new Exception("Failed to retrive available external instance = connection id has no value"); + string newConnection = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["AppsConnectionString"].ConnectionString; + DbConnectionStringBuilder builder = GetConnectionStringBuilder(Maps.Instance.ConnectionString); + + Dictionary connectionParameters = new Dictionary{ + {"Password",builder.Password()}, + {"Username",builder.UserId()}, + {"ServerName",builder.Server()}, + {"Catalog",builder.Database()}, + {"ProductPort",builder.Port()} + }; + //password = Convert.ToString(connectionRow["Password"]); + //username = Convert.ToString(connectionRow[""]); + //server = Convert.ToString(connectionRow[""]); + //catalog = Convert.ToString(connectionRow[""]); + //port = Convert.ToInt32(connectionRow[""]) + string pk = view.Create(connectionParameters); + int tmpId; + if (string.IsNullOrEmpty(pk) || !int.TryParse(pk,out tmpId)) + { + Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "GetExternalAvailableInstanceConnection", null, 1, "Failed to retrive available external instance = connection id has no value"); + throw new Exception("Failed to retrive available external instance = connection id has no value"); + } + connectionId = tmpId; } - Durados.Web.Mvc.View view = GetView(ConnectionViewName); + //Durados.Web.Mvc.View view = GetView(ConnectionViewName); System.Data.DataRow connectionRow = view.GetDataRow(connectionId.Value.ToString()); //Dictionary values = new Dictionary(); //values.Add("Id", "&&%&=&&%& " + connectionId.Value.ToString()); @@ -199,14 +221,14 @@ protected virtual View GetView(string viewName) } private SqlProduct GetSystemProduct() { - return SqlProduct.SqlServer; + return Maps.Instance.DuradosMap.SqlProduct; ; } public static string GetConnectionString(string serverName, string catalog, bool? integratedSecurity, string username, string password, string duradosuserId, Durados.SqlProduct sqlProduct, int localPort, bool usesSsh, bool usesSsl) { string connectionString = null; - System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(); - builder.ConnectionString = Maps.Instance.ConnectionString; + DbConnectionStringBuilder cnnBuilder = GetConnectionStringBuilder(Maps.Instance.ConnectionString); + bool hasServer = !string.IsNullOrEmpty(serverName); bool hasCatalog = !string.IsNullOrEmpty(catalog); @@ -220,7 +242,7 @@ public static string GetConnectionString(string serverName, string catalog, bool { if (!hasServer) { - serverName = builder.DataSource; + serverName = cnnBuilder.Server(); } connectionString = "Data Source={0};Initial Catalog={1};Integrated Security=True;"; @@ -264,7 +286,7 @@ public static string GetConnectionString(string serverName, string catalog, bool if (!hasServer) { if (Maps.AllowLocalConnection) - serverName = builder.DataSource; + serverName = cnnBuilder.Server(); else throw new Durados.DuradosException("Server Name is missing"); } @@ -272,7 +294,7 @@ public static string GetConnectionString(string serverName, string catalog, bool if (!hasUsername) { if (Maps.AllowLocalConnection) - username = builder.UserID; + username = cnnBuilder.UserId(); else throw new Durados.DuradosException("Username is missing"); } @@ -280,7 +302,7 @@ public static string GetConnectionString(string serverName, string catalog, bool if (!hasPassword) { if (Maps.AllowLocalConnection) - password = builder.Password; + password = cnnBuilder.Password(); else throw new Durados.DuradosException("Password is missing"); } @@ -372,6 +394,47 @@ private Dictionary GetConnectionFromConnectionId(List connI return connStrs; } + public static DbConnectionStringBuilder GetConnectionStringBuilder(string connectionString) + { + if (MySqlAccess.IsMySqlConnectionString(connectionString)) + return new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(connectionString); + return new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString); + } + } + public static class DbStringBuilderExtention + { + public static string Server( this DbConnectionStringBuilder builder){ + if(builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return builder["server"].ToString(); + return builder["Data Source"].ToString(); + } + + public static string Database(this DbConnectionStringBuilder builder) + { + if (builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return builder["database"].ToString(); + return builder["Initial Catalog"].ToString(); + } + + public static string UserId(this DbConnectionStringBuilder builder) + { + if (builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return builder["uid"].ToString(); + return builder["User ID"].ToString(); + } + + public static string Password(this DbConnectionStringBuilder builder) + { + if (builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return builder["password"].ToString(); + return builder["Password"].ToString(); + } + public static string Port(this DbConnectionStringBuilder builder) + { + if (builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return builder["port"].ToString(); + return builder["port"].ToString(); + } } } diff --git a/Durados.Web.Mvc/UI/Helpers/RestHelper.cs b/Durados.Web.Mvc/UI/Helpers/RestHelper.cs index c2bc9e68..9b609e82 100644 --- a/Durados.Web.Mvc/UI/Helpers/RestHelper.cs +++ b/Durados.Web.Mvc/UI/Helpers/RestHelper.cs @@ -6625,20 +6625,10 @@ private bool ShouldBeUsed() private int? FindAndUpdateAppInMain(string appName, string title, int creator, int poolCreator, string connectionString, int? templateId) { - string sql = - "begin tran getFromPool " + - "declare @appId int " + - "select top(1) @appId = id from durados_App with(UPDLOCK) where TemplateId " + (templateId.HasValue ? " = " + templateId.Value : " is null ").ToString() + " and creator = @poolCreator and DatabaseStatus = 1 order by id asc; " + - "delete from durados_App where [Name] = @Name; " + - "update durados_App " + - "set creator = @creator, " + - "[CreatedDate] = @CreatedDate, " + - "[Name] = @Name, " + - "[Title] = @Title " + - "where id = @appId; " + - "select @appId " + - "commit tran getFromPool"; - string scalar = new SqlAccess().ExecuteScalar(connectionString, sql, new Dictionary() { { "poolCreator", poolCreator }, { "creator", creator }, { "CreatedDate", DateTime.Now }, { "Name", appName }, { "Title", title } }); + SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + string varConnectionString = string.Format("{0}{1};", connectionString,"Allow User Variables=True"); + string sql = Maps.GetMainAppSqlSchema().GetFindAndUpdateAppInMainSql(templateId); + string scalar = sqlAccess.ExecuteScalar(varConnectionString, sql, new Dictionary() { { "poolCreator", poolCreator }, { "creator", creator }, { "CreatedDate", DateTime.Now }, { "Name", appName }, { "Title", title } }); if (!string.IsNullOrEmpty(scalar)) { return Convert.ToInt32(scalar); diff --git a/Durados.Xml/Durados.Xml.csproj b/Durados.Xml/Durados.Xml.csproj index 7c6d3bba..d59233d4 100644 --- a/Durados.Xml/Durados.Xml.csproj +++ b/Durados.Xml/Durados.Xml.csproj @@ -135,6 +135,7 @@ + diff --git a/Durados/Data/ISqlTextBuilder.cs b/Durados/Data/ISqlTextBuilder.cs index e15b7846..3a88f9c6 100644 --- a/Durados/Data/ISqlTextBuilder.cs +++ b/Durados/Data/ISqlTextBuilder.cs @@ -69,4 +69,12 @@ string FromDual(); string GetPointFieldStatement(string tableName, string columnName); + + string GetEncryptedColumnsStatement(string encryptedName, string databaseNames); + + string GetCloseCertificatesStatement(); + + string GetOpenCertificatesStatement(); + + string GetDbEncrypytedColumnSql(string p, string columnName); } \ No newline at end of file From 05bb6b716d586fb18c9187e655afbaf3f78d691a Mon Sep 17 00:00:00 2001 From: "yariv@backand.com" Date: Sun, 5 Nov 2017 09:11:27 +0000 Subject: [PATCH 02/30] fix bugs , remove message board and DBS alias from xsd, fix password decryption and encryption for Mysql Main DB --- BackAnd.Web.Api/BackAnd.Web.Api.csproj | 2 + .../Controllers/AccountController.cs | 19 +- .../Controllers/Admin/limitsController.cs | 13 +- .../Admin/myAppConnectionController.cs | 150 +- .../Controllers/Admin/myAppsController.cs | 55 +- .../Filters/BackAndAuthorizeAttribute.cs | 26 +- .../Filters/TokenAuthorizeAttribute .cs | 15 +- BackAnd.Web.Api/Controllers/apiController.cs | 19 +- BackAnd.Web.Api/Controllers/wfController.cs | 10 +- BackAnd.Web.Api/Web.config | 9 +- Durados.DataAccess/ISqlMainSchema.cs | 163 + Durados.DataAccess/MySqlAccess.cs | 299 +- Durados.DataAccess/SqlAccess.cs | 299 +- .../Controllers/AccountController.cs | 60 +- Durados.Web.Mvc/Database.cs | 2 +- .../Infrastructure/ProductMaintenance.cs | 105 +- Durados.Web.Mvc/Map.cs | 28 +- Durados.Web.Mvc/Map/DuradosMap.cs | 42 +- Durados.Web.Mvc/Map/Maps.cs | 132 +- Durados.Web.Mvc/Map/SqlPersistency.cs | 34 +- Durados.Web.Mvc/MapDataSet.Designer.cs | 9251 +++++++---------- Durados.Web.Mvc/MapDataSet.xsd | 212 +- Durados.Web.Mvc/MapDataSet.xss | 74 +- Durados.Web.Mvc/Services/AccountService.cs | 70 +- Durados.Web.Mvc/Stat/Measurement.cs | 6 +- Durados.Web.Mvc/UI/Helpers/AppFactory.cs | 190 +- Durados.Web.Mvc/UI/Helpers/PlugInHelper.cs | 4170 ++++---- Durados.Web.Mvc/UI/Helpers/RestHelper.cs | 19 +- Durados.Web.Mvc/UI/Helpers/SecurityHelper.cs | 647 +- Durados.Workflow/ApprovalProcess.cs | 779 +- Durados.Workflow/Engine.cs | 8 +- Durados.Workflow/Notifier.cs | 331 +- Durados/Data/ISqlTextBuilder.cs | 8 +- Durados/Database.cs | 2 + Durados/View.cs | 15 +- 35 files changed, 8004 insertions(+), 9260 deletions(-) create mode 100644 Durados.DataAccess/ISqlMainSchema.cs diff --git a/BackAnd.Web.Api/BackAnd.Web.Api.csproj b/BackAnd.Web.Api/BackAnd.Web.Api.csproj index f823dff4..1297940d 100644 --- a/BackAnd.Web.Api/BackAnd.Web.Api.csproj +++ b/BackAnd.Web.Api/BackAnd.Web.Api.csproj @@ -184,6 +184,7 @@ + @@ -275,6 +276,7 @@ + diff --git a/BackAnd.Web.Api/Controllers/AccountController.cs b/BackAnd.Web.Api/Controllers/AccountController.cs index 05ab6dbc..1dbfe507 100644 --- a/BackAnd.Web.Api/Controllers/AccountController.cs +++ b/BackAnd.Web.Api/Controllers/AccountController.cs @@ -129,7 +129,7 @@ private string GetUserDetail(string guid, string userField) private string GetUserFieldsForSelect() { string select; - select = string.Format("[{0}],[{1}],[{2}],[{3}],[{4}]", Map.Database.UserGuidFieldName, Map.Database.UsernameFieldName, "FirstName", "LastName", "Email"); + select = string.Format(Durados.Web.Mvc.Maps.MainAppSchema.GetUserFieldsForSelectSql(), Map.Database.UserGuidFieldName, Map.Database.UsernameFieldName, "FirstName", "LastName", "Email"); return select; } @@ -148,13 +148,13 @@ protected string PWResetNotAllowedMessage } private void LoadUserData(string guid) { - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Durados.Web.Mvc.Maps.MainAppSqlAccess; Dictionary parameters = new Dictionary(); parameters.Add("@guid", guid); - string sqlDuradosSys = string.Format("SELECT TOP 1 username FROM durados_user WITH(NOLOCK) WHERE guid=@guid"); + string sqlDuradosSys = Durados.Web.Mvc.Maps.MainAppSchema.GetLoadUserDataByGuidSql(); object duradosSysUser = sqlAccess.ExecuteScalar(Durados.Web.Mvc.Maps.Instance.ConnectionString, sqlDuradosSys, parameters); @@ -165,7 +165,7 @@ private void LoadUserData(string guid) parameters.Add("@username", duradosSysUser.ToString()); - string sql = string.Format("SELECT TOP 1 {0} FROM {1} WITH(NOLOCK) WHERE {2}=@username", GetUserFieldsForSelect(), Map.Database.UserViewName, Map.Database.UsernameFieldName); + string sql = Durados.Web.Mvc.Maps.MainAppSchema.GetLoadUserDataByUsernameSql( GetUserFieldsForSelect(), Map.Database.UserViewName, Map.Database.UsernameFieldName); object dataTable = sqlAccess.ExecuteTable(Map.Database.GetUserView().ConnectionString, sql, parameters, System.Data.CommandType.Text); @@ -308,13 +308,14 @@ private string GetUserGuid(string userName) { try { - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); + Durados.DataAccess.SqlAccess sql = Durados.Web.Mvc.Maps.MainAppSqlAccess; Dictionary parameters = new Dictionary(); parameters.Add("@username", userName); string userViewName = Map.Database.UserViewName; - object guid = sql.ExecuteScalar(Durados.Web.Mvc.Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 [durados_user].[guid] FROM durados_user WITH(NOLOCK) WHERE [durados_user].[username]=@username", parameters); + + object guid = sql.ExecuteScalar(Durados.Web.Mvc.Maps.Instance.DuradosMap.connectionString, Durados.Web.Mvc.Maps.MainAppSchema.GetUserGuidSql(), parameters); if (guid == null || guid == DBNull.Value) throw new Durados.DuradosException(Map.Database.Localizer.Translate("Username has no uniqe guid ,password canot be reset.")); @@ -545,12 +546,12 @@ private void ApproveUser(string appName, string username) Dictionary parameters2 = new Dictionary(); parameters2.Add("@UserId", userId); parameters2.Add("@AppId", mapId); - Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); - if (string.IsNullOrEmpty(sql.ExecuteScalar(Durados.Web.Mvc.Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 [ID] FROM [durados_UserApp] WHERE [UserId]=@UserId AND [AppId]=@AppId", parameters2))) + Durados.DataAccess.SqlAccess sqlAccess = Durados.Web.Mvc.Maps.MainAppSqlAccess; + if (string.IsNullOrEmpty(sqlAccess.ExecuteScalar(Durados.Web.Mvc.Maps.Instance.DuradosMap.connectionString, Durados.Web.Mvc.Maps.MainAppSchema.GetUserAappIdSql(), parameters2))) { parameters2.Add("@newUser", username); parameters2.Add("@appName", appName); - sql.ExecuteNonQuery(Durados.Web.Mvc.Maps.Instance.DuradosMap.Database.ConnectionString, "durados_AssignPendingApps @newUser,@appName", parameters2, AssignPendingAppsCallback); + sqlAccess.ExecuteNonQuery(Durados.Web.Mvc.Maps.Instance.DuradosMap.Database.ConnectionString, "durados_AssignPendingApps @newUser,@appName", parameters2, AssignPendingAppsCallback); } } diff --git a/BackAnd.Web.Api/Controllers/Admin/limitsController.cs b/BackAnd.Web.Api/Controllers/Admin/limitsController.cs index 2d34a00d..240829a9 100644 --- a/BackAnd.Web.Api/Controllers/Admin/limitsController.cs +++ b/BackAnd.Web.Api/Controllers/Admin/limitsController.cs @@ -140,16 +140,9 @@ public IHttpActionResult Put(string appName = null) int limit = System.Convert.ToInt32(values[key]); - SqlAccess sa = new SqlAccess(); - - string sql = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; " + - "BEGIN TRANSACTION; " + - "UPDATE dbo.durados_AppLimits SET Limit = " + limit + " WHERE AppId = " + id + " and Name = '" + limits.ToString() + "';" + - " IF @@ROWCOUNT = 0 " + - "BEGIN " + - "INSERT into dbo.durados_AppLimits (Name, Limit, AppId) values ('" + limits.ToString() + "'," + limit + "," + id.Value + "); " + - "END " + - "COMMIT TRANSACTION;"; + SqlAccess sa = Maps.MainAppSqlAccess; + + string sql = Maps.MainAppSchema.GetInsertLimitsSql(limits, limit, id); sa.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql); } diff --git a/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs b/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs index 10d65f20..9042057e 100644 --- a/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs +++ b/BackAnd.Web.Api/Controllers/Admin/myAppConnectionController.cs @@ -20,6 +20,7 @@ using Durados.Web.Mvc.UI.Helpers.Cloning; using System.Runtime.Caching; using System.Data.Common; +using System.Data; /* HTTP Verb |Entire Collection (e.g. /customers) |Specific Item (e.g. /customers/{id}) ----------------------------------------------------------------------------------------------------------------------------------------------- @@ -196,7 +197,10 @@ private string GetPostDataForCreateNewRdsDatabase(string callbackUrl) private string GetNewAppGuid(Durados.CreateEventArgs e) { Guid guid; - string sql = "Select [Guid] from durados_app with(nolock) where id=" + e.PrimaryKey; + string sql = Maps.MainAppSchema.GetAppGuidById(); + var parameter = e.Command.CreateParameter(); + parameter.ParameterName = "Id"; + parameter.Value = e.PrimaryKey; e.Command.CommandText = sql; object scalar = e.Command.ExecuteScalar(); @@ -228,12 +232,12 @@ protected override void BeforeCreate(Durados.CreateEventArgs e) { if (IsTempAppBelongToCreator(e, out tempAppId)) { - string sqlDeleteTempApp = "delete durados_App with (rowlock) where Id = " + tempAppId.Value; + string sqlDeleteTempApp = Maps.MainAppSchema.GetDeleteAppById(tempAppId.Value); e.Command.CommandText = sqlDeleteTempApp; //lock (locker1) // { - Durados.SmartRun.RunWithRetry.Run(() => + Durados.SmartRun.RunWithRetry.Run(() => { e.Command.ExecuteNonQuery(); }, 8, 2000); @@ -359,9 +363,8 @@ protected void BeforeCreate2(Durados.CreateEventArgs e) if (string.IsNullOrEmpty(e.PrimaryKey)) throw new Durados.DuradosException("Failed to save new app."); string callbackUrl = string.Format("{0}/admin/myAppConnection/rdsResponse?appguid={1}&appname={2}", Maps.ApiUrls[0], GetNewAppGuid(e), e.Values["Name"].ToString()); - - - string url = System.Configuration.ConfigurationManager.AppSettings["nodeServicesUrl"] + "/createRDSInstance"; + + // string url = System.Configuration.ConfigurationManager.AppSettings["nodeServicesUrl"] + "/createRDSInstance"; ///{"instanceName":"yrvtest23","dbName":"yrvtest23","instanceClass":"db.t1.micro","storageSize":"5","IPRange":["0.0.0.0/32"],"engine":"MySQL","engineVersion":"5.6.21","username":"yariv","password":"123456789","region":"us-east-1","characterSetName":"ASCII","callbackUrl":"http://backand-dev3.cloudapp.net:4109/admin/myAppConnection/rdsResponse?appguid=86bec9ad-3319-423d-8125-9860ccd535c4&appname=test1&success=true","authToken":"123456789","securityGroup":"bknd-Allcustomers"} string postData = GetPostDataForCreateNewRdsDatabase(callbackUrl); @@ -376,8 +379,8 @@ protected void BeforeCreate2(Durados.CreateEventArgs e) } else { - string response = Durados.Web.Mvc.Infrastructure.Http.PostWebRequest(url, postData); - json = Durados.Web.Mvc.UI.Json.JsonSerializer.Deserialize(response); + //string response = Durados.Web.Mvc.Infrastructure.Http.PostWebRequest(url, postData); + //json = Durados.Web.Mvc.UI.Json.JsonSerializer.Deserialize(response); } } catch (Exception exception) @@ -392,7 +395,9 @@ protected void BeforeCreate2(Durados.CreateEventArgs e) } private string GetServerName(string connectionString) { - return new MySqlSchema().GetServerName(connectionString); + if (MySqlAccess.IsMySqlConnectionString(Maps.Instance.SystemConnectionString)) + return new MySqlSchema().GetServerName(connectionString); + return new SqlSchema().GetServerName(connectionString); } private Durados.SqlProduct GetSystemSqlProduct() @@ -549,13 +554,18 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) string dataSourceTypeId = e.Values[dataSourceTypeFieldName].ToString(); string name = e.Values[nameFieldName].ToString(); - System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(); - builder.ConnectionString = Map.connectionString; + DbConnectionStringBuilder builder = Maps.GetMapsConnectionStringBuilder(); + + string server = builder.Server(); + string userId = builder.UserId(); + string password = builder.Password(); + bool integratedSecurity = builder.IntegratedSecurity(); + string pk = e.PrimaryKey; string cleanName = GetCleanName(name); - Durados.SqlProduct sqlProduct = Durados.SqlProduct.SqlServer; + Durados.SqlProduct sqlProduct = Map.SqlProduct; if (dataSourceTypeId == "1")// || dataSourceTypeId == "4") // blank or template { @@ -570,7 +580,7 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) { sqlAccess.ExecuteNoneQueryStoredProcedure(Maps.Instance.ConnectionString, "durados_CreateNewDatabase", values); } - catch (System.Data.SqlClient.SqlException exception) + catch (DbException exception) { throw new Durados.DuradosException(exception.Message, exception); } @@ -590,9 +600,10 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) string duradosUser = Map.Database.GetUserID(); string newPassword = new Durados.Web.Mvc.Controllers.AccountMembershipService().GetRandomPassword(12); string newUsername = appCatalog + "User"; + try { - CreateDatabaseUser(builder.DataSource, appCatalog, builder.UserID, builder.Password, builder.IntegratedSecurity, newUsername, newPassword, false); + CreateDatabaseUser(server, appCatalog, userId, password, integratedSecurity, newUsername, newPassword, false); sqlAccess.CreateDatabaseUserWithoutLogin(Map.connectionString, sysCatalog, newUsername, newPassword, "db_owner"); } catch (Exception exception) @@ -600,23 +611,24 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), "CreateApp", exception.Source, exception, 1, "Failed to create database user. username=" + newUsername); throw new Durados.DuradosException("Failed to create database user"); } - int? appConnId = SaveConnection(builder.DataSource, appCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); + int? appConnId = SaveConnection(server, appCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); - int? sysConnId = SaveConnection(builder.DataSource, sysCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); + int? sysConnId = SaveConnection(server, sysCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); //values = new Dictionary(); //values.Add("FK_durados_App_durados_SqlConnection_Parent", appConnId); //values.Add("FK_durados_App_durados_SqlConnection_System_Parent", sysConnId); //e.View.Edit(values, e.PrimaryKey, null, null, null, null); + + string sql = Maps.MainAppSchema.GetUpdateAppConnectionsSql(appConnId,sysConnId, e.PrimaryKey); - string sql = "update durados_App set SqlConnectionId = " + appConnId + ", SystemSqlConnectionId = " + sysConnId + " where id = " + e.PrimaryKey; - - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + using (IDbConnection connection = GetNewConnection(Maps.Instance.DuradosMap.SqlProduct,Maps.Instance.ConnectionString)) { connection.Open(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection)) + using (IDbCommand command = connection.CreateCommand()) { + command.CommandText = sql; command.ExecuteNonQuery(); } } @@ -645,10 +657,10 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) { try { - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + using (IDbConnection connection = GetNewConnection(Maps.Instance.DuradosMap.SqlProduct,Maps.Instance.ConnectionString)) { connection.Open(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand()) + using (IDbCommand command = connection.CreateCommand()) { command.Connection = connection; sqlAccess.ExecuteNonQuery(e.View, command, "create database " + sysCatalog, null); @@ -663,14 +675,14 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) try { - CreateDatabaseUser(builder.DataSource, sysCatalog, builder.UserID, builder.Password, builder.IntegratedSecurity, newUsername, newPassword, false); + CreateDatabaseUser(server, sysCatalog, userId, password, integratedSecurity, newUsername, newPassword, false); } catch (Exception exception) { Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), "CreateApp", exception.Source, exception, 1, "Failed to create database user. username=" + newUsername); throw new Durados.DuradosException("Failed to create database user"); } - sysConnId = SaveConnection(builder.DataSource, sysCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); + sysConnId = SaveConnection(server, sysCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); } else if (systemSqlProduct == Durados.SqlProduct.MySql) @@ -696,13 +708,14 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) //values.Add("FK_durados_App_durados_SqlConnection_System_Parent", sysConnId); //e.View.Edit(values, e.PrimaryKey, null, null, null, null); - string sql = "update durados_App set SystemSqlConnectionId = " + sysConnId + " where id = " + e.PrimaryKey; + string sql = Maps.MainAppSchema.GetUpdateAppSystemConnectionSql(sysConnId, e.PrimaryKey); - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + using (IDbConnection connection = GetNewConnection(Map.SqlProduct, Maps.Instance.ConnectionString)) { connection.Open(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection)) + using (IDbCommand command = connection.CreateCommand()) { + command.CommandText = sql; command.ExecuteNonQuery(); } } @@ -737,19 +750,21 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) try { + string sql =Maps.MainAppSchema.GetExecCreateDB(sysCatalog) ; if (!sysExists) { - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + using (IDbConnection connection = GetNewConnection(Maps.Instance.DuradosMap.SqlProduct,Maps.Instance.ConnectionString)) { connection.Open(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("exec('create database " + sysCatalog + "')", connection)) + using (IDbCommand command = connection.CreateCommand()) { + command.CommandText = sql; command.ExecuteNonQuery(); } } } } - catch (System.Data.SqlClient.SqlException exception) + catch (DbException exception) { throw new Durados.DuradosException("Could not create system database: " + sysCatalog + "; Additional info: " + exception.Message, exception); } @@ -758,17 +773,19 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) { if (!appExists) { - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + string sql = Maps.MainAppSchema.GetExecCreateDB(appCatalog); + using (IDbConnection connection = GetNewConnection(Maps.Instance.DuradosMap.SqlProduct,Maps.Instance.ConnectionString)) { connection.Open(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("exec('create database " + appCatalog + "')", connection)) + using (IDbCommand command = connection.CreateCommand()) { + command.CommandText = sql; command.ExecuteNonQuery(); } } } } - catch (System.Data.SqlClient.SqlException exception) + catch (DbException exception) { throw new Durados.DuradosException("Could not create app database: " + appCatalog + "; Additional info: " + exception.Message, exception); } @@ -781,7 +798,7 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) { if (!appExists) { - CreateDatabaseUser(builder.DataSource, appCatalog, builder.UserID, builder.Password, builder.IntegratedSecurity, newUsername, newPassword, false); + CreateDatabaseUser(server, appCatalog, userId, password, integratedSecurity, newUsername, newPassword, false); if (!sysExists) { sqlAccess.CreateDatabaseUserWithoutLogin(Map.connectionString, sysCatalog, newUsername, newPassword, "db_owner"); @@ -793,7 +810,7 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) { sqlAccess.CreateDatabaseUser(Map.connectionString, sysCatalog, newUsername, newPassword, "db_owner"); } - catch (System.Data.SqlClient.SqlException) + catch (DbException) { sqlAccess.CreateDatabaseUserWithoutLogin(Map.connectionString, sysCatalog, newUsername, newPassword, "db_owner"); } @@ -808,13 +825,13 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) int? appConnId = null; if (!appExists) - appConnId = SaveConnection(builder.DataSource, appCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); + appConnId = SaveConnection(server, appCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); else appConnId = Convert.ToInt32(e.Values[appconnstrFieldName]); int? sysConnId = null; if (!sysExists) - sysConnId = SaveConnection(builder.DataSource, sysCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); + sysConnId = SaveConnection(server, sysCatalog, newUsername, newPassword, duradosUser, Durados.SqlProduct.SqlServer); else sysConnId = Convert.ToInt32(e.Values[sysconnstrFieldName]); @@ -824,13 +841,15 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) //e.View.Edit(values, e.PrimaryKey, null, null, null, null); - string sql2 = "update durados_App set SqlConnectionId = " + appConnId + ", SystemSqlConnectionId = " + sysConnId + " where id = " + e.PrimaryKey; + string sql2 = Maps.MainAppSchema.GetUpdateAppConnectionsSql(appConnId, sysConnId, e.PrimaryKey); + - using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(Maps.Instance.ConnectionString)) + using (IDbConnection connection = GetConnection(Maps.Instance.DuradosMap.SqlProduct,Maps.Instance.ConnectionString)) { connection.Open(); - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql2, connection)) + using (IDbCommand command = connection.CreateCommand()) { + command.CommandText = sql2; command.ExecuteNonQuery(); } } @@ -877,7 +896,7 @@ protected override void AfterCreateAfterCommit(Durados.CreateEventArgs e) //values = new Dictionary(); //values.Add(e.View.GetFieldByColumnNames("SqlConnectionId").Name, newConnectionId); //e.View.Edit(values, e.PrimaryKey, null, null, null, null); - string sql = "update durados_App set SqlConnectionId = " + newConnectionId + ",Image= '" + image + "', DataSourceTypeId=2 where Id = " + e.PrimaryKey; + string sql = Maps.MainAppSchema.GetUpdateAppConnectionAndProductSql(newConnectionId, image,e.PrimaryKey); sqlAccess.ExecuteNonQuery(e.View.ConnectionString, sql); } sqlProduct = sqlConnectionRow.IsNull("SqlProductId") ? Durados.SqlProduct.SqlServer : (Durados.SqlProduct)sqlConnectionRow["SqlProductId"]; @@ -1015,7 +1034,7 @@ private void ValidateConnection(string server, string catalog, string username, ValidateConnection(server, catalog, username, password, Durados.SqlProduct.SqlServer, 0, false, false, null, null, null, null, null, 0, 0); } - SqlAccess sqlAccess = new SqlAccess(); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; private string CreateDatabase(string server, string catalog, string username, string password, string source, string template) { @@ -1129,13 +1148,13 @@ protected virtual void SendError(int logType, Exception exception, string contro protected int? SaveConnection(string server, string catalog, string username, string password, string userId, Durados.SqlProduct sqlProduct, bool usingSsh, bool usingSsl, string sshRemoteHost, string sshUser, string sshPassword, string sshPrivateKey, int sshPort, int productPort) { View view = GetView("durados_SqlConnection"); - + Dictionary values = new Dictionary(); values.Add("ServerName", server); values.Add("Catalog", catalog); values.Add("Username", username); values.Add("IntegratedSecurity", false); - values.Add("Password", password); + values.Add("Password", Maps.Instance.DuradosMap.Encrypt(password)); values.Add(view.GetFieldByColumnNames("SqlProductId").Name, ((int)sqlProduct).ToString()); values.Add(view.GetFieldByColumnNames("DuradosUser").Name, userId); @@ -1486,9 +1505,9 @@ private Dictionary CreateApp2(string template, string name, stri } } - catch (System.Data.SqlClient.SqlException exception) + catch (DbException exception) { - if (exception.Number == 2601) + if (exception is System.Data.SqlClient.SqlException && (exception as System.Data.SqlClient.SqlException).Number == 2601) { Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), "CreateApp", exception.Source, exception, 6, "App name already exists"); return new Dictionary() { { "Success", false }, { "Message", "Application name already exists, please enter a different name." } }; @@ -1927,8 +1946,8 @@ private void UpdateProductType(string appName, int productType) return; string sql = - "update durados_App set productType = @productType where Name = @name"; - new SqlAccess().ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql, new Dictionary() { { "productType", productType }, { "name", appName } }, null); + Maps.MainAppSchema.GetUpdateAppProduct(); + Maps.MainAppSqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql, new Dictionary() { { "productType", productType }, { "name", appName } }, null); } @@ -2010,8 +2029,8 @@ public void HandleError(Exception exception) { Maps.Instance.DuradosMap.Logger.Log("myAppConnection", "CreateApp", exception.Source, exception, 1, null); - string sql = "Update durados_App set DatabaseStatus = " + (int)OnBoardingStatus.Error + " where id = " + appId; - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); + string sql = Maps.MainAppSchema.GetUpdateDBStatusSql((int)OnBoardingStatus.Error, appId); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql); @@ -2085,9 +2104,9 @@ private void CopyApp(int sourceAppId, int targetAppId, CopyOptions copyOptions) private int GetAppId(int templateId) { - string sql = - "select AppId from durados_Template with(NOLOCK) where id = " + templateId; - string scalar = new SqlAccess().ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sql); + string sql = Maps.MainAppSchema.GetAppIdSql(templateId); + + string scalar = Maps.MainAppSqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sql); if (!string.IsNullOrEmpty(scalar)) { return Convert.ToInt32(scalar); @@ -2268,8 +2287,8 @@ private Template GetTemplateFromCache(string appName) private void UpdateDatabaseStatus(int appId, OnBoardingStatus onBoardingStatus) { - string sql = "Update durados_App set DatabaseStatus = " + (int)onBoardingStatus + " where id = " + appId; - Durados.DataAccess.SqlAccess sqlAccess = new Durados.DataAccess.SqlAccess(); + string sql = Maps.MainAppSchema.GetUpdateDBStatusSql((int)onBoardingStatus, appId); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; try { sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql); @@ -2473,6 +2492,9 @@ public virtual IHttpActionResult Put(string id) if (!values.ContainsKey("ProductPort")) values.Add("ProductPort", productPort); + if (Maps.Instance.DuradosMap.SqlProduct == Durados.SqlProduct.MySql && values.ContainsKey("password") && !string.IsNullOrEmpty((values["password"] ?? string.Empty).ToString())) + values["password"] = map.Encrypt(values["password"].ToString()); + view.Update(values, connectionId.ToString(), false, view_BeforeEdit, view_BeforeEditInDatabase, view_AfterEditBeforeCommit, view_AfterEditAfterCommit); try @@ -2533,7 +2555,7 @@ private void UpdateProductCache(int id, Durados.SqlProduct sqlProduct, System.Da private string[] GetAppsName(int id, System.Data.IDbCommand command) { - command.CommandText = "SELECT dbo.durados_App.Name FROM dbo.durados_App with(nolock) INNER JOIN dbo.durados_SqlConnection with(nolock) ON dbo.durados_App.SqlConnectionId = dbo.durados_SqlConnection.Id WHERE (dbo.durados_SqlConnection.Id = 1)"; + command.CommandText = Maps.MainAppSchema.GetAppsNameSql(); List apps = new List(); @@ -2592,7 +2614,10 @@ private void ValidateConnectionString(Durados.DataActionEventArgs e) //connectionString = GetConnection(serverName, catalog, integratedSecurity, username, password, duradosUserId); //SqlConnection connection = new SqlConnection(connectionString); - + if(Maps.Instance.DuradosMap.SqlProduct == sqlProduct) + { + password = map.Decrypt(password); + } connectionString = GetConnection(serverName, catalog, integratedSecurity, username, password, duradosUserId, sqlProduct, localPort, usesSsh, usesSsl); System.Data.IDbConnection connection = GetNewConnection(sqlProduct, connectionString); @@ -3051,6 +3076,17 @@ protected void NotifyNewDatabase(string server, string catalog, string newUser, Durados.Cms.DataAccess.Email.Send(host, Map.Database.UseSmtpDefaultCredentials, port, username, password, false, to.Split(';'), new string[0], new string[1] { from }, subject, message, from, null, null, false, null, Map.Database.Logger); } + protected internal override void view_AfterSelect(object sender, Durados.SelectEventArgs e) + { + if(sender is MySqlAccess && e.View != null && e.View.Name == ConnectionViewName) + { + foreach (DataRow row in (e.DataTable.AsEnumerable())) + { + if(row["Password"] != null) + row["Password"] = map.Decrypt(row["Password"].ToString()); + } + } + } } public class InvalidSchemaException : Durados.DuradosException diff --git a/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs b/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs index 8170bb34..910d1897 100644 --- a/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs +++ b/BackAnd.Web.Api/Controllers/Admin/myAppsController.cs @@ -20,6 +20,7 @@ using Durados.Web.Mvc.Webhook; using BackAnd.Web.Api.Controllers.Admin; using System.Data; +using System.Data.Common; /* HTTP Verb |Entire Collection (e.g. /customers) |Specific Item (e.g. /customers/{id}) ----------------------------------------------------------------------------------------------------------------------------------------------- @@ -417,10 +418,10 @@ public virtual IHttpActionResult Post() return Ok(new { __metadata = new { id = key, appName = appName } }); } // TODO : Mysql deprecated - catch (System.Data.SqlClient.SqlException exception) + catch (DbException exception) { const int DuplicateUniqueIndex = 2601; - if (exception.Number == DuplicateUniqueIndex) + if ( exception is System.Data.SqlClient.SqlException && ((System.Data.SqlClient.SqlException)exception).Number == DuplicateUniqueIndex) { return ResponseMessage(Request.CreateResponse(HttpStatusCode.Conflict, string.Format(Messages.AppNameAlreadyExists, appName))); } @@ -467,8 +468,8 @@ private int GetNextUserAppNameNumber(string appNamePrefix) private string[] GetAppNamesWithPrefix(string appNamePrefix) { - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - string sql = Maps.GetMainAppSqlSchema().GetAppNamesWithPrefixSql(appNamePrefix); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; + string sql = Maps.MainAppSchema.GetAppNamesWithPrefixSql(appNamePrefix); System.Data.DataTable table = sqlAccess.ExecuteTable(Maps.Instance.DuradosMap.connectionString, sql, null, System.Data.CommandType.Text); List list = new List(); @@ -660,19 +661,7 @@ private void UpdateAnonymousUserRole(Map map, string role) } - //private void UpdateIsAuthApp(Map map, bool isAuthApp) - //{ - // UpdateIsAuthApp(Convert.ToInt32(map.Id), isAuthApp); - // map.IsAuthApp = isAuthApp; - //} - - //private void UpdateIsAuthApp(int id, bool isAuthApp) - //{ - // string sql = "update durados_App set IsAuthApp = @isAuthApp where id = @id"; - // (new SqlAccess()).ExecuteNonQuery(map.Database.SystemConnectionString, sql, Durados.SqlProduct.SqlServer, new Dictionary() { { "id", id }, { "IsAuthApp", isAuthApp } }, null); - - //} - + private string GetAnonymousRole(Dictionary databaseSettings) { string key = "defaultGuestRole"; @@ -695,26 +684,10 @@ protected override void AfterEditAfterCommit(Durados.EditEventArgs e) string newName = e.Values["Name"].ToString(); if (!oldName.Equals(newName)) { - //Maps.Instance.ChangeName(oldName, newName); - //CreateDns(newName); + Maps.Instance.Restart(oldName); } - //SqlProduct product = Maps.GetSqlProduct(newName); - - //if (product == SqlProduct.MySql) - //{ - // string url = Maps.GetAppUrl(newName); - // string[] split = url.Split(':'); - // url = split[0] + ":" + split[1] + ":" + Maps.ProductsPort[product] + "/Admin/Restart?id=" + Map.Database.GetUserGuid(); - - // Infrastructure.Http.CallWebRequest(url); - - //} - //else - //{ - //Maps.Instance.Restart(oldName); - //} } } @@ -788,7 +761,7 @@ protected override void AfterDeleteBeforeCommit(Durados.DeleteEventArgs e) { int id = Convert.ToInt32(e.PrimaryKey); - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; SqlSchema sqlSchema = sqlAccess.GetNewSqlSchema(); @@ -837,7 +810,7 @@ protected override void AfterDeleteBeforeCommit(Durados.DeleteEventArgs e) private bool HasOtherConnectios(string appDatabase) { - ISqlMainSchema sqlSchema= Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlSchema= Maps.MainAppSchema; string sql = sqlSchema.GetHasOtherConnectiosSql(appDatabase); using (IDbConnection connection = sqlSchema.GetNewConnection(Maps.Instance.ConnectionString)) @@ -862,7 +835,7 @@ private void DropDatabase(string name) //scsb.InitialCatalog = null; - ISqlMainSchema sqlSchema = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlSchema = Maps.MainAppSchema; string sql = sqlSchema.GetDropDatabaseSql(name); using (IDbConnection connection = sqlSchema.GetNewConnection(Maps.Instance.ConnectionString)) { @@ -899,11 +872,11 @@ public virtual IHttpActionResult Delete(string id) { return ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, string.Format(Messages.ItemWithIdNotFound, id, AppViewName))); } - + /* TODO: Mysql Main string guid = GetMasterGuid(); string qstring = "id=" + guid; - + */ try { @@ -946,8 +919,8 @@ public virtual IHttpActionResult Delete(string id) } catch { } - string sql = "delete durados_App where name = '" + id + "'"; - (new SqlAccess()).ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql); + string sql = Maps.MainAppSchema.GetDeleteAppByName(id); + Maps.MainAppSqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql); Maps.Instance.DuradosMap.Logger.Log("myApps", "delete", "", null, 1, "The app " + id + " was deleted"); diff --git a/BackAnd.Web.Api/Controllers/Filters/BackAndAuthorizeAttribute.cs b/BackAnd.Web.Api/Controllers/Filters/BackAndAuthorizeAttribute.cs index 5566e42a..37f0c06c 100644 --- a/BackAnd.Web.Api/Controllers/Filters/BackAndAuthorizeAttribute.cs +++ b/BackAnd.Web.Api/Controllers/Filters/BackAndAuthorizeAttribute.cs @@ -744,13 +744,16 @@ private void SetAppByTokenToCache(string anonymousToken, string appName) private string GetAppByTokenFromDb(string anonymousToken) { - string sql = "SELECT [Name] FROM [durados_app] WITH(NOLOCK) WHERE [AnonymousToken] =@AnonymousToken"; - using (System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection(Maps.Instance.DuradosMap.Database.ConnectionString)) + string sql = Maps.MainAppSchema.GetAppNameByTokenSql(Database.AnonymousToken); + using (IDbConnection cnn = Maps.MainAppSchema.GetNewConnection(Maps.Instance.DuradosMap.Database.ConnectionString)) { - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, cnn)) + using (IDbCommand command = cnn.CreateCommand()) { - - command.Parameters.AddWithValue(Database.AnonymousToken, anonymousToken); + command.CommandText = sql; + var parameter = command.CreateParameter(); + parameter.ParameterName ="token"; + parameter.Value = anonymousToken; + command.Parameters.Add(parameter); cnn.Open(); object scalar = command.ExecuteScalar(); if (scalar == null || scalar == DBNull.Value) @@ -821,13 +824,16 @@ private bool IsServerAuthorizedForRDScallback(System.Web.Http.Controllers.HttpAc private string GetAppGuid(string appName) { - string sql = "SELECT [Guid] FROM [durados_app] WITH(NOLOCK) WHERE [Name] =@appName"; - using (System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection(Maps.Instance.DuradosMap.Database.ConnectionString)) + string sql = Maps.MainAppSchema.GetAppGuidByName(); + using (IDbConnection cnn = Maps.MainAppSchema.GetNewConnection(Maps.Instance.DuradosMap.Database.ConnectionString)) { - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, cnn)) + using (IDbCommand command = cnn.CreateCommand()) { - - command.Parameters.AddWithValue("appName", appName); + command.CommandText = sql; + var parameter= command.CreateParameter(); + parameter.ParameterName = "appName"; + parameter.Value = appName; + command.Parameters.Add(parameter); cnn.Open(); object scalar = command.ExecuteScalar(); if (scalar == null || scalar == DBNull.Value) diff --git a/BackAnd.Web.Api/Controllers/Filters/TokenAuthorizeAttribute .cs b/BackAnd.Web.Api/Controllers/Filters/TokenAuthorizeAttribute .cs index 7cc49d87..7e2bd7cb 100644 --- a/BackAnd.Web.Api/Controllers/Filters/TokenAuthorizeAttribute .cs +++ b/BackAnd.Web.Api/Controllers/Filters/TokenAuthorizeAttribute .cs @@ -7,6 +7,8 @@ using System.Web.Http; using System.Net; using Durados.Web.Mvc; +using System.Data; + namespace BackAnd.Web.Api.Controllers.Filters { @@ -53,13 +55,16 @@ private bool IsGuid(string token) protected virtual string GetAppName(string token) { - string sql = string.Format("SELECT [Name] FROM [durados_app] WITH(NOLOCK) WHERE [{0}] = @token", HeaderToken.ToString()); - using (System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection(Maps.Instance.DuradosMap.Database.ConnectionString)) + string sql = Maps.MainAppSchema.GetAppNameByTokenSql(HeaderToken.ToString()); + using (IDbConnection cnn = Maps.MainAppSchema.GetNewConnection(Maps.Instance.ConnectionString))//Getc(Maps.Instance.DuradosMap.Database.ConnectionString)) { - using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, cnn)) + using (IDbCommand command = cnn.CreateCommand()) { - - command.Parameters.AddWithValue("token", token); + command.CommandText = sql; + var parameter = command.CreateParameter(); + parameter.ParameterName = "token"; + parameter.Value = token; + command.Parameters.Add(parameter); cnn.Open(); object scalar = command.ExecuteScalar(); if (scalar == null || scalar == DBNull.Value) diff --git a/BackAnd.Web.Api/Controllers/apiController.cs b/BackAnd.Web.Api/Controllers/apiController.cs index 93c85ddd..77e8e267 100644 --- a/BackAnd.Web.Api/Controllers/apiController.cs +++ b/BackAnd.Web.Api/Controllers/apiController.cs @@ -585,13 +585,13 @@ protected void UpdateLogModelException(Exception exception) { if (logModelId.HasValue) { - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); - using (IDbConnection connection = sqlMain.GetNewConnection(Maps.Instance.ConnectionString)) + + using (IDbConnection connection = Maps.MainAppSchema.GetNewConnection(Maps.Instance.ConnectionString)) { connection.Open(); - string sql = sqlMain.GetUpdateLogModelExceptionSql(); + string sql = Maps.MainAppSchema.GetUpdateLogModelExceptionSql(); - using (IDbCommand command = sqlMain.GetNewCommand(sql, connection)) + using (IDbCommand command = Maps.MainAppSchema.GetNewCommand(sql, connection)) { GetDataParameter("errorMessage",exception.Message, command); GetDataParameter("errorTrace", exception.StackTrace, command); @@ -624,7 +624,7 @@ protected static void GetDataParameter(string name,object val, IDbCommand comman private void LogModel(string appName, string username, DateTime timestamp, string input, string output, string valid, string action) { - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; using (IDbConnection connection = sqlMain.GetNewConnection(Maps.Instance.ConnectionString)) { connection.Open(); @@ -733,7 +733,7 @@ protected virtual ArrayList GetBackandToObject(string token) private static bool RefreshOldAdminFailure = false; protected virtual void RefreshOldAdmin(string appName) { - if (RefreshOldAdminFailure) + if (!Maps.ExistsOldAdmin || RefreshOldAdminFailure) return; string id = GetMasterGuid(); @@ -909,7 +909,8 @@ protected virtual string GetMasterGuid() { string currentUser = Maps.SuperDeveloper; System.Data.DataRow userRow = Maps.Instance.DuradosMap.Database.GetUserRow(currentUser); - string guid = userRow["Guid"].ToString(); + string guid = (userRow == null) ? Maps.MasterOpsAuth : userRow["Guid"].ToString(); + return SecurityHelper.GetTmpUserGuidFromGuid(guid); } @@ -2096,8 +2097,8 @@ protected virtual void AfterDeleteBeforeCommit(DeleteEventArgs e) { int userId = Maps.Instance.DuradosMap.Database.GetUserID(deletedUsername); string appId = Map.Id; - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, Maps.GetMainAppSqlSchema().GetDeleteUserSql( userId, appId)); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; + sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, Maps.MainAppSchema.GetDeleteUserSql( userId, appId)); } } catch { } diff --git a/BackAnd.Web.Api/Controllers/wfController.cs b/BackAnd.Web.Api/Controllers/wfController.cs index fe2884a7..f90143ff 100644 --- a/BackAnd.Web.Api/Controllers/wfController.cs +++ b/BackAnd.Web.Api/Controllers/wfController.cs @@ -59,11 +59,11 @@ public string GetUrlAction(Durados.View view, string pk) return string.Empty; } - - public virtual string SaveInMessageBoard(Dictionary parameters, Durados.View view, Dictionary values, System.Data.DataRow prevRow, string pk, string siteWithoutQueryString, string urlAction, string subject, string message, int currentUserId, string currentUserRole, Dictionary recipients) - { - return SaveInMessageBoard(parameters, (View)view, values, prevRow, pk, siteWithoutQueryString, urlAction, subject, message, currentUserId, recipients); - } + //TODO : Main Mysql + //public virtual string SaveInMessageBoard(Dictionary parameters, Durados.View view, Dictionary values, System.Data.DataRow prevRow, string pk, string siteWithoutQueryString, string urlAction, string subject, string message, int currentUserId, string currentUserRole, Dictionary recipients) + //{ + // return SaveInMessageBoard(parameters, (View)view, values, prevRow, pk, siteWithoutQueryString, urlAction, subject, message, currentUserId, recipients); + //} public virtual void SaveMessageAction(View view, string pk, Durados.Web.Mvc.UI.Json.Field jsonField, Durados.Web.Mvc.Controllers.MessageBoardAction messageBoardAction) { diff --git a/BackAnd.Web.Api/Web.config b/BackAnd.Web.Api/Web.config index 3664a0ad..f1b61be1 100644 --- a/BackAnd.Web.Api/Web.config +++ b/BackAnd.Web.Api/Web.config @@ -155,7 +155,7 @@ - + @@ -212,7 +212,7 @@ =======--> - + @@ -243,7 +243,7 @@ - + >>>>>> Stashed changes--> @@ -260,6 +260,9 @@ + + + - + - - - - - - - - - - - + + + + + + + + + - + 870 @@ -35,7 +33,7 @@ - + 1576 @@ -47,7 +45,7 @@ - + 887 @@ -71,7 +69,7 @@ - + 494 @@ -83,7 +81,7 @@ - + 400 @@ -99,7 +97,7 @@ - + 494 @@ -111,7 +109,7 @@ - + 494 @@ -123,7 +121,7 @@ - + 1037 @@ -143,7 +141,7 @@ - + 494 @@ -155,7 +153,7 @@ - + 1576 @@ -167,7 +165,7 @@ - + 1576 @@ -179,19 +177,7 @@ - - - - 887 - 324 - - - 519 - 324 - - - - + 1503 @@ -203,19 +189,7 @@ - - - - 887 - 533 - - - 334 - 533 - - - - + 259 @@ -231,7 +205,7 @@ - + 887 diff --git a/Durados.Web.Mvc/Services/AccountService.cs b/Durados.Web.Mvc/Services/AccountService.cs index c3d5c3e7..9ac9e5a2 100644 --- a/Durados.Web.Mvc/Services/AccountService.cs +++ b/Durados.Web.Mvc/Services/AccountService.cs @@ -57,16 +57,16 @@ public string GetEmailBySocialId(string provider, string socialId, int appId) //int rowCount = -1; //DataView dataView = view.FillPage(1, 1, new Dictionary() { { "Provider", provider }, { "SocialId", socialId } }, null, null, out rowCount, null, null); - SqlAccess sa = Maps.GetMainAppSqlAccess(); + SqlAccess sa = Maps.MainAppSqlAccess; - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); - string sql = sqlMain.GetEmailBySocialIdSql(); + //ISqlMainSchema sqlMain = ; + string sql = Maps.MainAppSchema.GetEmailBySocialIdSql(); object scalar = sa.ExecuteScalar(view.ConnectionString, sql, new Dictionary() { { "Provider", provider }, { "SocialId", socialId }, { "AppId", appId } }); if (scalar == null) { - sql = sqlMain.GetEmailBySocialIdSql2(); + sql = Maps.MainAppSchema.GetEmailBySocialIdSql2(); scalar = sa.ExecuteScalar(view.ConnectionString, sql, new Dictionary() { { "Provider", provider }, { "SocialId", socialId } }); } @@ -149,9 +149,9 @@ public string GetSocialIdlByEmail(string provider, int userId, int appId) { View view = GetUserSocialView(); - SqlAccess sa = Maps.GetMainAppSqlAccess(); + SqlAccess sa = Maps.MainAppSqlAccess; - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; string sql = sqlMain.GetSocialIdlByEmail(); @@ -344,13 +344,13 @@ public static bool IsValidRole(string appName, string role) public Dictionary SignUpToBackand(string username, string password, string send, string phone, string fullname, string dbtype, string dbother) { - int identity = -1; + bool DontSend = false; try { - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); @@ -359,7 +359,7 @@ public Dictionary SignUpToBackand(string username, string passwo parameters.Add("@Email", email); parameters.Add("@Username", username); - //if (sql.ExecuteScalar(Maps.Instance.DuradosMap.Database.ConnectionString, "SELECT TOP 1 [Username] FROM [durados_User] WHERE [Username]=@Username", parameters) != string.Empty) + System.Web.Security.MembershipUser user = System.Web.Security.Membership.Provider.GetUser(username, false); if (user != null) { @@ -844,8 +844,8 @@ protected virtual void Activate(string username, string appName) protected virtual void Activate(string username, string appName, string role) { Map map = GetMap(appName); - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); parameters.Add("@UserId", map.Database.GetUserID(username)); parameters.Add("@AppId", map.Id); @@ -872,8 +872,8 @@ public virtual void ActivateAdmin(string username, string appName) private void InviteAdminBeforeSignUp(string username, string appName) { - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; + ISqlMainSchema sqlMain = Maps.MainAppSchema; try { Map map = GetDuradosMap(); @@ -931,7 +931,7 @@ public static void SendRegistrationRequest(string firstName, string lastName, st /* TODO: Main MySQL depricated public static void UpdateWebsiteUsers(string username, int userId) { - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; string sql = @"INSERT INTO [website_UsersCookie]([UserId],[CookieGuid],[CreateDate]) VALUES(@UserId,@CookieGuid,@CreateDate)"; Dictionary parameters = new Dictionary(); @@ -954,7 +954,7 @@ public static void UpdateWebsiteUsers(string username, int userId) /// public static void InsertContactUsUsers(string email, string fullname, string comments, string phone, int requestSubjectId, int? dbType, string dbOther) { - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; Dictionary parameters = new Dictionary(); parameters.Add("@Email", email); if (fullname == null) @@ -1011,8 +1011,8 @@ public virtual void InviteAdminAfterSignUp(string username) Map map = GetDuradosMap(); int userId = GetDuradosMap().Database.GetUserID(username); - SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + SqlAccess sqlAccess = Maps.MainAppSqlAccess; + ISqlMainSchema sqlMain = Maps.MainAppSchema; using (IDbConnection connection = sqlAccess.GetNewSqlSchema().GetConnection(map.connectionString)) { connection.Open(); @@ -1182,8 +1182,8 @@ protected virtual void AddToAuthenticatedUsers(string appName, string firstName, parameters.Add("AppName", appName); Map map = GetDuradosMap(); - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; + ISqlMainSchema sqlMain = Maps.MainAppSchema; sqlAccess.ExecuteNonQuery(map.Database.GetUserView().ConnectionString, sqlMain.InsertNewUserSql(GetDuradosMap().Database.GetUserView().GetTableName() , GetDuradosMap().Database.GetUserView().GetTableName() ), parameters, AddToAuthenticatedUsersCallback); } @@ -1627,12 +1627,12 @@ public static string GetUserGuid(string userName) { try { - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; Dictionary parameters = new Dictionary(); parameters.Add("@username", userName); - object guid = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, "SELECT TOP 1 [durados_user].[guid] FROM durados_user WITH(NOLOCK) WHERE [durados_user].[username]=@username", parameters); + object guid = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, Maps.MainAppSchema.GetUserGuidSql(), parameters); if (guid == null || guid == DBNull.Value) throw new DuradosException("Username has no unique guid, cannot reset password."); @@ -1650,14 +1650,14 @@ public static int GetUserId(string userName) { try { - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); parameters.Add("@username", userName); - object id = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sqlMain.GetUserSql(), parameters); + object id = sqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.connectionString, sqlMain.GetUserIdFromUsernameSql(), parameters); if (id == null || id == DBNull.Value) throw new DuradosException("Username has no unique username."); @@ -1678,9 +1678,9 @@ public static string GetUserTempToken(string username) { string guid = GetUserGuid(username); - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); @@ -1737,9 +1737,9 @@ private void SetAppNameByToken(string token, string appName) private string GetUsername(string guid) { - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); @@ -1763,12 +1763,12 @@ public void DeleteUser(string username, string appName) if (Maps.Instance.DuradosMap.Database.GetUserRow() == null) throw new DuradosException("user does not exist"); - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; Dictionary parameters = new Dictionary(); parameters.Add("@username", username); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + ISqlMainSchema sqlMain = Maps.MainAppSchema; string sql = sqlMain.GetDeleteUserSql(); @@ -1797,8 +1797,8 @@ public bool UserBelongToMoreThanOneApp(string username, string appName) appId = Convert.ToInt32(map.Id); } - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); parameters.Add("@appid", appId); @@ -1817,8 +1817,8 @@ private bool UserHasApps(string username) { int id = Maps.Instance.DuradosMap.Database.GetUserID(username); - Durados.DataAccess.SqlAccess sqlAccess = Maps.GetMainAppSqlAccess(); - ISqlMainSchema sqlMain = Maps.GetMainAppSqlSchema(); + Durados.DataAccess.SqlAccess sqlAccess = Maps.MainAppSqlAccess; + ISqlMainSchema sqlMain = Maps.MainAppSchema; Dictionary parameters = new Dictionary(); parameters.Add("@id", id); diff --git a/Durados.Web.Mvc/Stat/Measurement.cs b/Durados.Web.Mvc/Stat/Measurement.cs index d8997ef9..f80cc8bc 100644 --- a/Durados.Web.Mvc/Stat/Measurement.cs +++ b/Durados.Web.Mvc/Stat/Measurement.cs @@ -193,20 +193,20 @@ public virtual void Persist(DateTime date, object value, SqlCommand command) int sqlConnId = appRow.durados_SqlConnectionRowByFK_durados_App_durados_SqlConnection_System.Id; command.Parameters.Clear(); - command.CommandText = "select Id from modubiz_LogStats2 with(nolock) where SqlConId = @SqlConId and LogDate = @LogDate"; + command.CommandText = "SELECT Id FROM modubiz_LogStats2 WITH(NOLOCK) WHERE SqlConId = @SqlConId and LogDate = @LogDate"; command.Parameters.AddWithValue("SqlConId", sqlConnId); command.Parameters.AddWithValue("LogDate", date); object scalar = command.ExecuteScalar(); if (scalar == null || scalar == DBNull.Value) { - command.CommandText = "insert into modubiz_LogStats2 (SqlConId, LogDate) values (@SqlConId, @LogDate); SELECT IDENT_CURRENT(N'[modubiz_LogStats2]') AS ID; "; + command.CommandText = "INSERT INTO modubiz_LogStats2 (SqlConId, LogDate) VALUES (@SqlConId, @LogDate); SELECT IDENT_CURRENT(N'[modubiz_LogStats2]') AS ID; "; scalar = command.ExecuteScalar(); } command.Parameters.Clear(); - command.CommandText = "update modubiz_LogStats2 set " + MeasurementType.ToString() + " = @value where Id = @Id"; + command.CommandText = "UPDATE modubiz_LogStats2 set " + MeasurementType.ToString() + " = @value WHERE Id = @Id"; command.Parameters.AddWithValue("value", value is ulong ? System.Convert.ToInt64(value) : value); command.Parameters.AddWithValue("Id", scalar); command.ExecuteNonQuery(); diff --git a/Durados.Web.Mvc/UI/Helpers/AppFactory.cs b/Durados.Web.Mvc/UI/Helpers/AppFactory.cs index 72a65eb8..ce90bfe4 100644 --- a/Durados.Web.Mvc/UI/Helpers/AppFactory.cs +++ b/Durados.Web.Mvc/UI/Helpers/AppFactory.cs @@ -111,62 +111,11 @@ public string GetExternalAvailableInstanceConnectionString(SqlProduct product,ou string password = null; server = null; port = 0; - string spName = "durados_GetExternalAvailableInstance"; - int? connectionId= null; - using (System.Data.IDbConnection cnn = Maps.GetMainAppSqlSchema().GetNewConnection(Maps.Instance.ConnectionString)) - { - using (DuradosCommand command = new DuradosCommand(GetSystemProduct())) - { - command.Connection = cnn; - command.CommandText = spName; - command.CommandType = System.Data.CommandType.StoredProcedure; - if (command.Connection.State == System.Data.ConnectionState.Closed) - { - try - { - command.Connection.Open(); - } - catch(Exception ex) - { - Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "GetExternalAvailableInstanceConnection", null, 1, "No connection to main database"); - throw new Exception("No connection to main database", ex); - } - } - var parameter = command.CreateParameter(); - parameter.ParameterName = "productId"; - parameter.Value = 3; - command.Parameters.Add(parameter); - System.Data.IDataReader reader = command.ExecuteReader(); - if (reader.Read()) - connectionId = reader.GetInt32(reader.GetOrdinal("SqlConnectionId")); - } - } + int? connectionId = GetConnectionFromExternalTable(); Durados.Web.Mvc.View view = GetView(ConnectionViewName); if (!connectionId.HasValue) { - string newConnection = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["AppsConnectionString"].ConnectionString; - DbConnectionStringBuilder builder = GetConnectionStringBuilder(Maps.Instance.ConnectionString); - - Dictionary connectionParameters = new Dictionary{ - {"Password",builder.Password()}, - {"Username",builder.UserId()}, - {"ServerName",builder.Server()}, - {"Catalog",builder.Database()}, - {"ProductPort",builder.Port()} - }; - //password = Convert.ToString(connectionRow["Password"]); - //username = Convert.ToString(connectionRow[""]); - //server = Convert.ToString(connectionRow[""]); - //catalog = Convert.ToString(connectionRow[""]); - //port = Convert.ToInt32(connectionRow[""]) - string pk = view.Create(connectionParameters); - int tmpId; - if (string.IsNullOrEmpty(pk) || !int.TryParse(pk,out tmpId)) - { - Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "GetExternalAvailableInstanceConnection", null, 1, "Failed to retrive available external instance = connection id has no value"); - throw new Exception("Failed to retrive available external instance = connection id has no value"); - } - connectionId = tmpId; + connectionId = InsertConnectionFromConfig(connectionId, view); } //Durados.Web.Mvc.View view = GetView(ConnectionViewName); @@ -184,7 +133,9 @@ public string GetExternalAvailableInstanceConnectionString(SqlProduct product,ou try { + password = Convert.ToString(connectionRow["Password"]); + password = Maps.Instance.DuradosMap.Decrypt(password); username = Convert.ToString(connectionRow["Username"]); server = Convert.ToString(connectionRow["ServerName"]); catalog = Convert.ToString(connectionRow["Catalog"]); @@ -202,6 +153,120 @@ public string GetExternalAvailableInstanceConnectionString(SqlProduct product,ou + } + + private int? InsertConnectionFromConfig(int? connectionId, Durados.Web.Mvc.View view) + { + string newConnection = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["AppsConnectionString"].ConnectionString; + DbConnectionStringBuilder builder = GetConnectionStringBuilder(Maps.Instance.ConnectionString); + string serverName = builder.Server(); + string catalogName = builder.Database(); + string password = builder.Password(); + password = Maps.Instance.DuradosMap.Encrypt(password); + Dictionary connectionParameters = new Dictionary{ + {"Password", password}, + {"Username",builder.UserId()}, + {"ServerName",serverName}, + {"Catalog",builder.Database()}, + {"ProductPort",builder.Port()}, + {"durados_SqlProduct_durados_SqlConnection_Parent",builder.ProductId()} + }; + + string pk = view.Create(connectionParameters); + int tmpId; + if (string.IsNullOrEmpty(pk) || !int.TryParse(pk, out tmpId)) + { + Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "GetExternalAvailableInstanceConnection", null, 1, "Failed to retrive available external instance = connection id has no value"); + throw new Exception("Failed to retrive available external instance = connection id has no value"); + } + + connectionId = tmpId; + + // + return SaveExternalInstanceToDb(connectionId, serverName, catalogName); + } + + private int? SaveExternalInstanceToDb(int? connectionId,string serverName, string catalogName) + { + //ISqlMainSchema sqlSchema = Maps.MainAppSchema; + string sql = Maps.MainAppSchema.InsertNewConnectionToExternalServerTable(); + + using (System.Data.IDbConnection cnn = Maps.MainAppSchema.GetNewConnection(Maps.Instance.ConnectionString)) + { + using (System.Data.IDbCommand command = cnn.CreateCommand()) + { + command.CommandText = sql; + command.CommandType = System.Data.CommandType.Text; + if (command.Connection.State == System.Data.ConnectionState.Closed) + { + try + { + command.Connection.Open(); + } + catch (Exception ex) + { + Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "InsertExternalAvailableInstanceConnection", null, 1, "New connection to main database"); + throw new Exception("New connection to main database", ex); + } + } + GetNewDbParameter(serverName, command, "serverName"); + GetNewDbParameter(catalogName, command, "catalog"); + GetNewDbParameter(1, command, "IsActive"); + GetNewDbParameter(connectionId, command, "SqlConnectionId"); + object scalar = command.ExecuteScalar(); + + if (scalar == null || scalar == DBNull.Value) + { + throw new DuradosException("Fail to insert new external connection"); + } + + } + // + return connectionId; + } + } + + private static void GetNewDbParameter(object connectionId, System.Data.IDbCommand command,string parameterName) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = parameterName; + parameter.Value = connectionId; + command.Parameters.Add(parameter); + } + + private int? GetConnectionFromExternalTable() + { + string spName = "durados_GetExternalAvailableInstance"; + int? connectionId = null; + using (System.Data.IDbConnection cnn = Maps.MainAppSchema.GetNewConnection(Maps.Instance.ConnectionString)) + { + using (DuradosCommand command = new DuradosCommand(GetSystemProduct())) + { + command.Connection = cnn; + command.CommandText = spName; + command.CommandType = System.Data.CommandType.StoredProcedure; + if (command.Connection.State == System.Data.ConnectionState.Closed) + { + try + { + command.Connection.Open(); + } + catch (Exception ex) + { + Maps.Instance.DuradosMap.Logger.Log("AppFactory", null, "GetExternalAvailableInstanceConnection", null, 1, "No connection to main database"); + throw new Exception("No connection to main database", ex); + } + } + var parameter = command.CreateParameter(); + parameter.ParameterName = "productId"; + parameter.Value = 3; + command.Parameters.Add(parameter); + System.Data.IDataReader reader = command.ExecuteReader(); + if (reader.Read()) + connectionId = reader.GetInt32(reader.GetOrdinal("SqlConnectionId")); + } + } + return connectionId; } public void CreateNewSystemSchemaAndUser(string connectionString, NewDatabaseParameters newDbParameters) { @@ -327,10 +392,10 @@ public Dictionary GetExternalInstanceConnection() private List GetExternalConnectionIds() { List conIds = new List(); - string sql = "SELECT SqlConnectionId FROM durados_ExternaInstance WITH(NOLOCK) INNER JOIN durados_SqlConnection WITH(NOLOCK) on durados_SqlConnection.Id = durados_ExternaInstance.SqlConnectionId"; - using (System.Data.IDbConnection cnn = Durados.DataAccess.DataAccessObject.GetNewConnection(SqlProduct.SqlServer, Maps.Instance.ConnectionString)) + string sql = Maps.MainAppSchema.GetExternalConnectionIdsSql(); + using (System.Data.IDbConnection cnn = Maps.MainAppSchema.GetNewConnection(Maps.Instance.ConnectionString) ) { - using (DuradosCommand command = new DuradosCommand(GetSystemProduct())) + using (System.Data.IDbCommand command = cnn.CreateCommand()) { command.Connection = cnn; command.CommandText = sql; @@ -436,5 +501,18 @@ public static string Port(this DbConnectionStringBuilder builder) return builder["port"].ToString(); return builder["port"].ToString(); } + public static bool IntegratedSecurity(this DbConnectionStringBuilder builder) + { + if (builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return false; + return Convert.ToBoolean(builder["IntegratedSecurity"]); + } + public static int ProductId(this DbConnectionStringBuilder builder) + { + if (builder is MySql.Data.MySqlClient.MySqlConnectionStringBuilder) + return (int)SqlProduct.MySql; + return (int)SqlProduct.SqlServer; + } + } } diff --git a/Durados.Web.Mvc/UI/Helpers/PlugInHelper.cs b/Durados.Web.Mvc/UI/Helpers/PlugInHelper.cs index fa9cfd5a..63267e02 100644 --- a/Durados.Web.Mvc/UI/Helpers/PlugInHelper.cs +++ b/Durados.Web.Mvc/UI/Helpers/PlugInHelper.cs @@ -1,2080 +1,2090 @@ -using System; -using System.Data; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Durados.Web.Mvc.UI.Json; -using System.Web; -using System.Web.Mvc; - -using Durados.DataAccess; -using System.Data.SqlClient; -using System.IO; -using Durados.Web.Mvc.Controllers; -using System.Configuration; - -namespace Durados.Web.Mvc.UI.Helpers -{ - public static class PlugInHelper - { - public static readonly int FreePlan = 3; - - public static void UpdateSiteInfo(this Database database, string siteId, string siteInfo, string url) - { - try - { - string sql = "update durados_PlugInSite set Url = @Url, Info = @Info where siteId = @SiteId "; - - - if (url.Length > 500) - { - url = url.Substring(0, 500); - } - - if (siteInfo.Length > 4000) - { - siteInfo = siteInfo.Substring(0, 4000); - } - - Dictionary parameters = new Dictionary(); - parameters.Add("@Url", url); - parameters.Add("@Info", string.Empty); - parameters.Add("@SiteId", siteId); - - SqlAccess.ExecuteNonQuery(database.ConnectionString, sql, parameters, null); - } - catch (Exception exception) - { - database.Logger.Log("PlugIn", "UpdateSiteInfo", "update durados_PlugInSite", exception, 1, "Failed to update site info. siteId: " + siteId + ", url: " + url); - - } - } - - public static void UpdatePlan(this Database database, int appId, int planId, string siteId) - { - bool newPlan = IsNewPlan(database, planId, siteId); - - int id = UpdateSiteApp(database, appId, planId, siteId); - - if (newPlan) - { - int[] appIds = GetSiteApps(database, id); - - foreach (int appId2 in appIds) - { - UpdatePlan(database, appId2, planId, true); - } - } - else - { - UpdatePlan(database, appId, planId, true); - } - } - - private static int[] GetSiteApps(Database database, int id) - { - string sql = string.Format("select appId from durados_PlugInSiteApp where PlugInSiteId = {0}", id); - DataTable table = SqlAccess.ExecuteTable(database.ConnectionString, sql, null, CommandType.Text); - List ids = new List(); - - foreach (DataRow row in table.Rows) - { - ids.Add((int)row[0]); - } - - return ids.ToArray(); - } - - private static int UpdateSiteApp(Database database, int appId, int planId, string siteId) - { - int id = UpdateSite(database, appId, planId, siteId); - - string sql = string.Format("if not exists (select top(1) appId from durados_PlugInSiteApp WITH (NOLOCK) where appId='{0}') insert into durados_PlugInSiteApp (appId, PlugInSiteId) values ({0}, {1}) ", appId, id); - - SqlAccess.ExecuteNonQuery(database.ConnectionString, sql); - - return id; - } - - private static int UpdateSite(Database database, int appId, int planId, string siteId) - { - string sql = string.Format("if not exists (select top(1) siteId from durados_PlugInSite WITH (NOLOCK) where siteId='{0}') insert into durados_PlugInSite (siteId, planId) values ('{0}', {1}) else update durados_PlugInSite set planId = {1} where siteId = '{0}' ", siteId, planId); - - SqlAccess.ExecuteNonQuery(database.ConnectionString, sql); - - sql = string.Format("select id from durados_PlugInSite where siteId = '{0}'", siteId); - - object scalar = SqlAccess.ExecuteScalar(database.ConnectionString, sql); - - return Convert.ToInt32(scalar); - } - - private static bool IsNewPlan(Database database, int planId, string siteId) - { - string sql = string.Format("select id from durados_PlugInSite WITH (NOLOCK) where SiteId = '{0}' and PlanId = {1}", siteId, planId); - - object scalar = SqlAccess.ExecuteScalar(database.ConnectionString, sql); - - return (scalar == null || scalar == DBNull.Value); - - } - - public static void UpdatePlan(this Database database, int appId, int planId, bool updateCache) - { - string sql = "if not exists (select * from (select top(1) PlanId from durados_AppPlan WITH (NOLOCK) where Appid=" + appId + " order by PurchaseDate desc) as a where PlanId=" + planId + ") insert into durados_AppPlan (AppId, PlanId) values(" + appId + "," + planId + ")"; - - SqlAccess.ExecuteNonQuery(database.ConnectionString, sql); - - if (updateCache) - { - string appName = Maps.Instance.GetAppRow(appId).Name; - - Map map = Maps.Instance.GetMap(appName); - - map.Plan = planId; - } - } - - public static Option[] GetViewNameDisplayList(this Database database) - { - List