private void Page_Load(object sender, System.EventArgs e) { Utils.SetPageTitle(Page, L10n.Term(".moduleList." + m_sMODULE)); // 06/04/2006 Paul. Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. this.Visible = (SplendidCRM.Security.GetUserAccess(m_sMODULE, "edit") >= 0); if (!this.Visible) { return; } try { // 06/09/2006 Paul. Remove data binding in the user controls. Binding is required, but only do so in the ASPX pages. //Page.DataBind(); gID = Sql.ToGuid(Request["ID"]); if (!IsPostBack) { CURRENCY_ID.DataSource = SplendidCache.Currencies(); CURRENCY_ID.DataBind(); TAXRATE_ID.DataSource = SplendidCache.TaxRates(); TAXRATE_ID.DataBind(); TAXRATE_ID.Items.Insert(0, new ListItem(L10n.Term(".LBL_NONE"), "")); SHIPPER_ID.DataSource = SplendidCache.Shippers(); SHIPPER_ID.DataBind(); SHIPPER_ID.Items.Insert(0, new ListItem(L10n.Term(".LBL_NONE"), "")); Guid gDuplicateID = Sql.ToGuid(Request["DuplicateID"]); if (!Sql.IsEmptyGuid(gID) || !Sql.IsEmptyGuid(gDuplicateID)) { DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { string sSQL; sSQL = "select * " + ControlChars.CrLf + " from vwQUOTES_Edit" + ControlChars.CrLf + " where ID = @ID " + ControlChars.CrLf; using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = sSQL; if (!Sql.IsEmptyGuid(gDuplicateID)) { Sql.AddParameter(cmd, "@ID", gDuplicateID); gID = Guid.Empty; } else { Sql.AddParameter(cmd, "@ID", gID); } con.Open(); #if DEBUG Page.RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd)); #endif using (IDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (rdr.Read()) { ctlModuleHeader.Title = Sql.ToString(rdr["NAME"]); Utils.SetPageTitle(Page, L10n.Term(".moduleList." + m_sMODULE) + " - " + ctlModuleHeader.Title); Utils.UpdateTracker(Page, m_sMODULE, gID, ctlModuleHeader.Title); ViewState["ctlModuleHeader.Title"] = ctlModuleHeader.Title; ViewState["BILLING_ACCOUNT_ID"] = Sql.ToGuid(rdr["BILLING_ACCOUNT_ID"]); ViewState["SHIPPING_ACCOUNT_ID"] = Sql.ToGuid(rdr["SHIPPING_ACCOUNT_ID"]); this.AppendEditViewFields(m_sMODULE + ".EditView", tblMain, rdr); this.AppendEditViewFields(m_sMODULE + ".EditAddress", tblAddress, rdr); this.AppendEditViewFields(m_sMODULE + ".EditDescription", tblDescription, rdr); new DynamicControl(this, "SHOW_LINE_NUMS").Checked = Sql.ToBoolean(rdr["SHOW_LINE_NUMS"]); new DynamicControl(this, "CALC_GRAND_TOTAL").Checked = Sql.ToBoolean(rdr["CALC_GRAND_TOTAL"]); try { new DynamicControl(this, "CURRENCY_ID").SelectedValue = Sql.ToString(rdr["CURRENCY_ID"]); } catch { } try { new DynamicControl(this, "TAXRATE_ID").SelectedValue = Sql.ToString(rdr["TAXRATE_ID"]); } catch { } try { new DynamicControl(this, "SHIPPER_ID").SelectedValue = Sql.ToString(rdr["SHIPPER_ID"]); } catch { } } } } } } else { this.AppendEditViewFields(m_sMODULE + ".EditView", tblMain, null); this.AppendEditViewFields(m_sMODULE + ".EditAddress", tblAddress, null); this.AppendEditViewFields(m_sMODULE + ".EditDescription", tblDescription, null); // 06/08/2006 Paul. Prepopulate the Account. Guid gPARENT_ID = Sql.ToGuid(Request["PARENT_ID"]); if (!Sql.IsEmptyGuid(gPARENT_ID)) { string sMODULE = String.Empty; string sPARENT_TYPE = String.Empty; string sPARENT_NAME = String.Empty; SqlProcs.spPARENT_Get(ref gPARENT_ID, ref sMODULE, ref sPARENT_TYPE, ref sPARENT_NAME); if (!Sql.IsEmptyGuid(gPARENT_ID) && sMODULE == "Accounts") { UpdateAccount(gPARENT_ID, true, true); } if (!Sql.IsEmptyGuid(gPARENT_ID) && sMODULE == "Contacts") { UpdateContact(gPARENT_ID, true, true); } else if (!Sql.IsEmptyGuid(gPARENT_ID) && sMODULE == "Opportunities") { new DynamicControl(this, "OPPORTUNITY_ID").ID = gPARENT_ID; new DynamicControl(this, "OPPORTUNITY_NAME").Text = sPARENT_NAME; } } } } else { // 12/02/2005 Paul. When validation fails, the header title does not retain its value. Update manually. ctlModuleHeader.Title = Sql.ToString(ViewState["ctlModuleHeader.Title"]); Utils.SetPageTitle(Page, L10n.Term(".moduleList." + m_sMODULE) + " - " + ctlModuleHeader.Title); DynamicControl ctlBILLING_ACCOUNT_ID = new DynamicControl(this, "BILLING_ACCOUNT_ID"); DynamicControl ctlSHIPPING_ACCOUNT_ID = new DynamicControl(this, "SHIPPING_ACCOUNT_ID"); if (Sql.ToGuid(ViewState["BILLING_ACCOUNT_ID"]) != ctlBILLING_ACCOUNT_ID.ID) { UpdateAccount(ctlBILLING_ACCOUNT_ID.ID, true, true); ViewState["BILLING_ACCOUNT_ID"] = ctlBILLING_ACCOUNT_ID.ID; ViewState["SHIPPING_ACCOUNT_ID"] = ctlBILLING_ACCOUNT_ID.ID; } if (Sql.ToGuid(ViewState["SHIPPING_ACCOUNT_ID"]) != ctlSHIPPING_ACCOUNT_ID.ID) { UpdateAccount(ctlSHIPPING_ACCOUNT_ID.ID, false, true); ViewState["SHIPPING_ACCOUNT_ID"] = ctlSHIPPING_ACCOUNT_ID.ID; } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); ctlEditButtons.ErrorText = ex.Message; } }
public Database(string connStr) : this(connStr, DbProviderFactories.GetFactory("System.Data.SqlClient")) { }
private static bool IsValidProviderName(string providerName) { return(DbProviderFactories.GetFactoryClasses().Rows.Find(providerName) != null); }
/// <summary> /// Bind parameters to the SQL statement /// </summary> /// <param name="sql">SQL command</param> protected override void _Prepare(string sql) { var provider = DbProviderFactories.GetFactory(_db.Adapter()); var cmd = provider.CreateCommand(); // Oracle.DataAccess.Client (and managed) bind by position by default(!) // So we need to force it to bind by name if used var bindByName = cmd.GetType().GetProperty("BindByName"); bindByName?.SetValue(cmd, true, null); // Need to reliably get the primary key value if (_type == "insert" && _pkey != null) { // Add a returning parameter statement into an output parameter sql += " RETURNING " + _ProtectIdentifiers(_pkey[0]) + " INTO :dtvalue"; } cmd.CommandText = sql; cmd.Connection = _db.Conn(); cmd.Transaction = _db.DbTransaction; // Need to reliably get the primary key value if (_type == "insert" && _pkey != null) { // Determine the parameter type var pkeyCmd = provider.CreateCommand(); pkeyCmd.CommandText = "SELECT data_type, data_length FROM all_tab_columns WHERE table_name = upper(:t) AND column_name = upper(:c)"; pkeyCmd.Connection = _db.Conn(); pkeyCmd.Transaction = _db.DbTransaction; var pkeyByName = pkeyCmd.GetType().GetProperty("BindByName"); pkeyByName?.SetValue(pkeyCmd, true, null); var tableParam = pkeyCmd.CreateParameter(); tableParam.ParameterName = ":t"; tableParam.Value = _table[0]; pkeyCmd.Parameters.Add(tableParam); var pkeyParam = pkeyCmd.CreateParameter(); pkeyParam.ParameterName = ":c"; pkeyParam.Value = _pkey[0]; pkeyCmd.Parameters.Add(pkeyParam); using (var dr = pkeyCmd.ExecuteReader()) { // If the table doesn't have a primary key field, we can't get // the inserted pkey! if (dr.HasRows && dr.Read()) { var dataType = dr["data_type"]; var dataLength = dr["data_length"]; var outParam = cmd.CreateParameter(); outParam.ParameterName = ":dtvalue"; outParam.Direction = ParameterDirection.Output; if ((string)dataType == "NUMBER") { outParam.DbType = DbType.Int32; } else if ((string)dataType == "DATE") { outParam.DbType = DbType.Date; } else if ((string)dataType == "DATETIME") { outParam.DbType = DbType.DateTime; } else { outParam.DbType = DbType.String; } cmd.Parameters.Add(outParam); cmd.UpdatedRowSource = UpdateRowSource.OutputParameters; } else { // Best effort var outParam = cmd.CreateParameter(); outParam.ParameterName = ":dtvalue"; outParam.Direction = ParameterDirection.Output; outParam.DbType = DbType.Int32; cmd.Parameters.Add(outParam); cmd.UpdatedRowSource = UpdateRowSource.OutputParameters; } } } // Bind values for (int i = 0, ien = _bindings.Count; i < ien; i++) { var binding = _bindings[i]; var param = cmd.CreateParameter(); param.ParameterName = binding.Name; param.Value = binding.Value ?? DBNull.Value; if (binding.Type != null) { param.DbType = binding.Type; } cmd.Parameters.Add(param); } _stmt = cmd; _db.DebugInfo(sql, _bindings); }
public void Run(string csproj, string[] args) { var projectDir = Path.GetDirectoryName(csproj); var outFile = GetOption(args, "o").TrimToNull(); var connectionKey = GetOption(args, "c").TrimToNull(); var table = GetOption(args, "t").TrimToNull(); var what = GetOption(args, "w").TrimToNull(); var module = GetOption(args, "m").TrimToNull(); var identifier = GetOption(args, "i").TrimToNull(); var permissionKey = GetOption(args, "p").TrimToNull(); if (identifier != null) { CodeFileHelper.Overwrite = true; } var config = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json")); var connectionStringOptions = new ConnectionStringOptions(); if (!string.IsNullOrEmpty(config.CustomTemplates)) { Templates.TemplatePath = Path.Combine(projectDir, config.CustomTemplates); } foreach (var x in config.Connections.Where(x => !x.ConnectionString.IsEmptyOrNull())) { connectionStringOptions[x.Key] = new ConnectionStringEntry { ConnectionString = x.ConnectionString, ProviderName = x.ProviderName, Dialect = x.Dialect }; } foreach (var name in config.AppSettingFiles) { var path = Path.Combine(projectDir, name); if (File.Exists(name)) { var appSettings = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(path).TrimToNull() ?? "{}"); if (appSettings.Data != null) { foreach (var data in appSettings.Data) { // not so nice fix for relative paths, e.g. sqlite etc. if (data.Value.ConnectionString.Contains("../../..", StringComparison.Ordinal)) { data.Value.ConnectionString = data.Value .ConnectionString.Replace("../../..", Path.GetDirectoryName(csproj), StringComparison.Ordinal); } else if (data.Value.ConnectionString.Contains(@"..\..\..\", StringComparison.Ordinal)) { data.Value.ConnectionString = data.Value.ConnectionString.Replace(@"..\..\..\", Path.GetDirectoryName(csproj), StringComparison.Ordinal); } connectionStringOptions[data.Key] = data.Value; } } } } if (connectionStringOptions.Count == 0) { Console.Error.WriteLine("No connections in appsettings files or sergen.json!"); Environment.Exit(1); } var connectionKeys = connectionStringOptions.Keys.OrderBy(x => x).ToArray(); if (outFile == null && connectionKey == null) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("=== Table Code Generation ==="); Console.WriteLine(""); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Available Connections:"); Console.ResetColor(); foreach (var x in connectionKeys) { Console.WriteLine(x); } Console.ResetColor(); Console.WriteLine(); } else if (connectionKey == null) { File.WriteAllText(outFile, JSON.Stringify(connectionStringOptions.Keys.OrderBy(x => x))); Environment.Exit(0); } string userInput = null; if (outFile == null && connectionKey == null) { userInput = connectionKeys.Length == 1 ? connectionKeys[0] : null; while (connectionKey == null || !connectionKeys.Contains(connectionKey, StringComparer.OrdinalIgnoreCase)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Connection: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; connectionKey = Hinter.ReadHintedLine(connectionKeys, userInput: userInput); userInput = connectionKey; if (connectionKey == "!") { Console.ResetColor(); return; } } } userInput = connectionKey; if (!connectionStringOptions.ContainsKey(userInput)) { Console.Error.WriteLine("Can't find connection with key: " + userInput + "!"); Environment.Exit(1); } if (outFile == null) { Console.ResetColor(); Console.WriteLine(); } DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", Microsoft.Data.SqlClient.SqlClientFactory.Instance); DbProviderFactories.RegisterFactory("System.Data.SqlClient", Microsoft.Data.SqlClient.SqlClientFactory.Instance); DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite", Microsoft.Data.Sqlite.SqliteFactory.Instance); DbProviderFactories.RegisterFactory("Npgsql", Npgsql.NpgsqlFactory.Instance); DbProviderFactories.RegisterFactory("FirebirdSql.Data.FirebirdClient", FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance); DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlConnector.MySqlConnectorFactory.Instance); var sqlConnections = new DefaultSqlConnections( new DefaultConnectionStrings(connectionStringOptions)); ISchemaProvider schemaProvider; List <TableName> tableNames; using (var connection = sqlConnections.NewByKey(connectionKey)) { schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType); tableNames = schemaProvider.GetTableNames(connection).ToList(); } var tables = tableNames.Select(x => x.Tablename).ToList(); var confConnection = config.Connections.FirstOrDefault(x => string.Compare(x.Key, connectionKey, StringComparison.OrdinalIgnoreCase) == 0); if (outFile == null && table == null) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Available Tables:"); Console.ResetColor(); foreach (var x in tables) { Console.WriteLine(x); } } else if (table == null) { File.WriteAllText(outFile, JSON.Stringify(tableNames.Select(x => { var xct = confConnection == null ? null : confConnection.Tables.FirstOrDefault(z => string.Compare(z.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0); return(new { name = x.Tablename, module = xct == null || xct.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : xct.Module, permission = xct == null || xct.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : xct.PermissionKey, identifier = xct == null || xct.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(x.Table) : xct.Identifier, }); }))); Environment.Exit(0); } userInput = tables.Count == 1 ? tables[0] : null; if (userInput == null && schemaProvider.DefaultSchema != null && tables.Any(x => x.StartsWith(schemaProvider.DefaultSchema + ".", StringComparison.Ordinal))) { userInput = schemaProvider.DefaultSchema + "."; } if (outFile == null) { Console.WriteLine(); while (table == null || !tables.Contains(table, StringComparer.OrdinalIgnoreCase)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; table = Hinter.ReadHintedLine(tables, userInput: userInput); userInput = table; if (table == "!") { Console.ResetColor(); return; } } } userInput = table; var tableName = tableNames.First(x => string.Compare(x.Tablename, userInput, StringComparison.OrdinalIgnoreCase) == 0); if (tableName == null) { Console.Error.WriteLine("Can't find table with name: " + userInput + "!"); Environment.Exit(1); } var confTable = confConnection == null ? null : confConnection.Tables.FirstOrDefault(x => string.Compare(x.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0); if (module == null) { userInput = confTable == null || confTable.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : confTable.Module; Console.WriteLine(); while (module.IsTrimmedEmpty()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Module name for table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; module = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput); userInput = module; if (module == "!") { Console.ResetColor(); return; } } } if (identifier == null) { userInput = confTable == null || confTable.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(tableName.Table) : confTable.Identifier; Console.WriteLine(); while (identifier.IsTrimmedEmpty()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a class Identifier for table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; identifier = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput); userInput = identifier; if (identifier == "!") { Console.ResetColor(); return; } } } if (permissionKey == null) { userInput = confTable == null || confTable.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : confTable.PermissionKey; Console.WriteLine(); while (permissionKey.IsTrimmedEmpty()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Permission Key for table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; permissionKey = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput); userInput = permissionKey; if (permissionKey == "!") { Console.ResetColor(); return; } } } if (what == null) { Console.WriteLine(); userInput = "RSUC"; while (what.IsEmptyOrNull()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Choose What to Generate (R:Row, S:Repo+Svc, U=UI, C=Custom)"); Console.ForegroundColor = ConsoleColor.Yellow; what = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput); userInput = what; if (what == "!") { Console.ResetColor(); return; } } } config.GenerateRow = what.IndexOf("R", StringComparison.OrdinalIgnoreCase) >= 0; config.GenerateService = what.IndexOf("S", StringComparison.OrdinalIgnoreCase) >= 0; config.GenerateUI = what.IndexOf("U", StringComparison.OrdinalIgnoreCase) >= 0; config.GenerateCustom = what.IndexOf("C", StringComparison.OrdinalIgnoreCase) >= 0; Console.ResetColor(); Console.WriteLine(); if (confConnection == null) { confConnection = new GeneratorConfig.Connection { Key = connectionKey }; config.Connections.Add(confConnection); } if (confTable == null) { confTable = new GeneratorConfig.Table { Identifier = identifier, Module = module, PermissionKey = permissionKey, Tablename = tableName.Tablename }; confConnection.Tables.Add(confTable); } else { confTable.Identifier = identifier; confTable.Module = module; confTable.PermissionKey = permissionKey; } File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson()); using (var connection = sqlConnections.NewByKey(connectionKey)) { connection.Open(); var csprojContent = File.ReadAllText(csproj); var net5Plus = !new Regex(@"\<TargetFramework\>.*netcoreapp.*\<\/TargetFramework\>", RegexOptions.Multiline | RegexOptions.Compiled) .IsMatch(csprojContent); var rowModel = RowGenerator.GenerateModel(connection, tableName.Schema, tableName.Table, module, connectionKey, identifier, permissionKey, config, net5Plus); rowModel.AspNetCore = true; rowModel.NET5Plus = net5Plus; var kdiff3Paths = new[] { config.KDiff3Path }; CodeFileHelper.Kdiff3Path = kdiff3Paths.FirstOrDefault(File.Exists); CodeFileHelper.TSCPath = config.TSCPath ?? "tsc"; new EntityCodeGenerator(rowModel, config, csproj).Run(); } }
public List <SIListModel> FillSISSearchGrid(SIListModel model) { ShomaRMEntities db = new ShomaRMEntities(); List <SIListModel> lstData = new List <SIListModel>(); try { DataTable dtTable = new DataTable(); using (var cmd = db.Database.Connection.CreateCommand()) { db.Database.Connection.Open(); cmd.CommandText = "usp_GetServiceIssuePaginationAndSearchData"; cmd.CommandType = CommandType.StoredProcedure; DbParameter paramC = cmd.CreateParameter(); paramC.ParameterName = "Criteria"; paramC.Value = model.Criteria; cmd.Parameters.Add(paramC); DbParameter paramPN = cmd.CreateParameter(); paramPN.ParameterName = "PageNumber"; paramPN.Value = model.PageNumber; cmd.Parameters.Add(paramPN); DbParameter paramNOR = cmd.CreateParameter(); paramNOR.ParameterName = "NumberOfRows"; paramNOR.Value = model.NumberOfRows; cmd.Parameters.Add(paramNOR); DbParameter param5 = cmd.CreateParameter(); param5.ParameterName = "SortBy"; param5.Value = model.SortBy; cmd.Parameters.Add(param5); DbParameter param6 = cmd.CreateParameter(); param6.ParameterName = "OrderBy"; param6.Value = model.OrderBy; cmd.Parameters.Add(param6); DbDataAdapter da = DbProviderFactories.GetFactory("System.Data.SqlClient").CreateDataAdapter(); da.SelectCommand = cmd; da.Fill(dtTable); db.Database.Connection.Close(); } foreach (DataRow dr in dtTable.Rows) { SIListModel usm = new SIListModel(); usm.IssueID = int.Parse(dr["IssueID"].ToString()); usm.CausingIssueID = int.Parse(dr["CausingIssueID"].ToString()); usm.CausingIssue = dr["CausingIssue"].ToString(); usm.ServiceIssueID = int.Parse(dr["ServiceIssueID"].ToString()); usm.ServiceIssue = dr["ServiceIssue"].ToString(); usm.Issue = dr["Issue"].ToString(); usm.NumberOfPages = int.Parse(dr["NumberOfPages"].ToString()); lstData.Add(usm); } db.Dispose(); return(lstData.ToList()); } catch (Exception ex) { db.Database.Connection.Close(); throw ex; } }
protected void Page_Command(object sender, CommandEventArgs e) { try { if (e.CommandName == "Search") { // 10/13/2005 Paul. Make sure to clear the page index prior to applying search. grdMain.CurrentPageIndex = 0; grdMain.ApplySort(); grdMain.DataBind(); } // 12/14/2007 Paul. We need to capture the sort event from the SearchView. else if (e.CommandName == "SortGrid") { grdMain.SetSortFields(e.CommandArgument as string[]); } else if (e.CommandName == "MassUpdate") { string[] arrID = Request.Form.GetValues("chkMain"); if (arrID != null) { // 10/26/2007 Paul. Use a stack to run the update in blocks of under 200 IDs. //string sIDs = Utils.ValidateIDs(arrID); System.Collections.Stack stk = Utils.FilterByACL_Stack(m_sMODULE, "edit", arrID, "INVOICES"); if (stk.Count > 0) { DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { con.Open(); using (IDbTransaction trn = con.BeginTransaction()) { try { while (stk.Count > 0) { string sIDs = Utils.BuildMassIDs(stk); // 07/09/2006 Paul. The date conversion was moved out of the MassUpdate control. // 09/11/2007 Paul. Mass update of teams is now available. SqlProcs.spINVOICES_MassUpdate(sIDs, ctlMassUpdate.ASSIGNED_USER_ID, ctlMassUpdate.PAYMENT_TERMS, ctlMassUpdate.INVOICE_STAGE, T10n.ToServerTime(ctlMassUpdate.DUE_DATE), ctlMassUpdate.TEAM_ID, trn); } trn.Commit(); } catch (Exception ex) { trn.Rollback(); throw(new Exception(ex.Message, ex.InnerException)); } } } Response.Redirect("default.aspx"); } } } else if (e.CommandName == "MassDelete") { string[] arrID = Request.Form.GetValues("chkMain"); if (arrID != null) { // 10/26/2007 Paul. Use a stack to run the update in blocks of under 200 IDs. //string sIDs = Utils.ValidateIDs(arrID); System.Collections.Stack stk = Utils.FilterByACL_Stack(m_sMODULE, "delete", arrID, "INVOICES"); if (stk.Count > 0) { DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { con.Open(); using (IDbTransaction trn = con.BeginTransaction()) { try { while (stk.Count > 0) { string sIDs = Utils.BuildMassIDs(stk); SqlProcs.spINVOICES_MassDelete(sIDs, trn); } trn.Commit(); } catch (Exception ex) { trn.Rollback(); throw(new Exception(ex.Message, ex.InnerException)); } } } Response.Redirect("default.aspx"); } } } else if (e.CommandName == "Export") { // 11/03/2006 Paul. Apply ACL rules to Export. int nACLACCESS = SplendidCRM.Security.GetUserAccess(m_sMODULE, "export"); if (nACLACCESS >= 0) { if (nACLACCESS == ACL_ACCESS.OWNER) { vwMain.RowFilter = "ASSIGNED_USER_ID = '" + Security.USER_ID.ToString() + "'"; } string[] arrID = Request.Form.GetValues("chkMain"); SplendidExport.Export(vwMain, m_sMODULE, ctlExportHeader.ExportFormat, ctlExportHeader.ExportRange, grdMain.CurrentPageIndex, grdMain.PageSize, arrID); } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); lblError.Text = ex.Message; } }
public void Run(string csproj, string[] args) { var projectDir = Path.GetDirectoryName(csproj); var outFile = GetOption(args, "o").TrimToNull(); var connectionKey = GetOption(args, "c").TrimToNull(); var table = GetOption(args, "t").TrimToNull(); var what = GetOption(args, "w").TrimToNull(); var module = GetOption(args, "m").TrimToNull(); var identifier = GetOption(args, "i").TrimToNull(); var permissionKey = GetOption(args, "p").TrimToNull(); if (identifier != null) { CodeFileHelper.Overwrite = true; } var config = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json")); var connectionKeys = config.Connections .Where(x => !x.ConnectionString.IsEmptyOrNull()) .Select(x => x.Key).ToList(); var appSettingsFile = Path.Combine(projectDir, "appsettings.json"); AppSettingsFormat appSettings; if (File.Exists(appSettingsFile)) { appSettings = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(appSettingsFile).TrimToNull() ?? "{}"); } else { appSettings = new AppSettingsFormat(); } connectionKeys.AddRange(appSettings.Data.Keys); var appSettingsFile2 = Path.Combine(projectDir, "appsettings.machine.json"); if (File.Exists(appSettingsFile2)) { var appSettings2 = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(appSettingsFile2).TrimToNull() ?? "{}"); foreach (var pair in appSettings2.Data) { appSettings.Data[pair.Key] = pair.Value; } } connectionKeys.AddRange(appSettings.Data.Keys); connectionKeys = connectionKeys.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList(); if (connectionKeys.Count == 0) { Console.Error.WriteLine("No connections in appsettings.json or sergen.json!"); Environment.Exit(1); } if (outFile == null && connectionKey == null) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("=== Table Code Generation ==="); Console.WriteLine(""); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Available Connections:"); Console.ResetColor(); foreach (var x in connectionKeys) { Console.WriteLine(x); } Console.ResetColor(); Console.WriteLine(); } else if (connectionKey == null) { File.WriteAllText(outFile, JSON.Stringify(connectionKeys)); Environment.Exit(0); } string userInput = null; if (outFile == null && connectionKey == null) { userInput = connectionKeys.Count == 1 ? connectionKeys[0] : null; while (connectionKey == null || !connectionKeys.Contains(connectionKey, StringComparer.OrdinalIgnoreCase)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Connection: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; connectionKey = Hinter.ReadHintedLine(connectionKeys, userInput: userInput); userInput = connectionKey; if (connectionKey == "!") { Console.ResetColor(); return; } } } userInput = connectionKey; connectionKey = connectionKeys.Find(x => string.Compare(x, userInput, StringComparison.OrdinalIgnoreCase) == 0); if (connectionKey == null) { Console.Error.WriteLine("Can't find connection with key: " + userInput + "!"); Environment.Exit(1); } if (outFile == null) { Console.ResetColor(); Console.WriteLine(); } var dataConnection = appSettings.Data.ContainsKey(connectionKey) ? appSettings.Data[connectionKey] : null; var confConnection = config.Connections.FirstOrDefault(x => string.Compare(x.Key, connectionKey, StringComparison.OrdinalIgnoreCase) == 0); var connectionString = dataConnection != null?dataConnection.ConnectionString.TrimToNull() : null; if (connectionString == null && confConnection != null) { connectionString = confConnection.ConnectionString.TrimToNull(); } var providerName = dataConnection != null?dataConnection.ProviderName.TrimToNull() : null; if (providerName == null && confConnection != null) { providerName = confConnection.ProviderName.TrimToNull(); } providerName = providerName ?? "System.Data.SqlClient"; #if COREFX DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance); DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite", Microsoft.Data.Sqlite.SqliteFactory.Instance); DbProviderFactories.RegisterFactory("Npgsql", Npgsql.NpgsqlFactory.Instance); DbProviderFactories.RegisterFactory("FirebirdSql.Data.FirebirdClient", FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance); DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySql.Data.MySqlClient.MySqlClientFactory.Instance); #endif if (connectionString.IndexOf("../../..") >= 0) { connectionString = connectionString.Replace("../../..", Path.GetDirectoryName(csproj)); } else if (connectionString.IndexOf(@"..\..\..\") >= 0) { connectionString = connectionString.Replace(@"..\..\..\", Path.GetDirectoryName(csproj)); } ISchemaProvider schemaProvider; List <TableName> tableNames; using (var connection = SqlConnections.New(connectionString, providerName)) { schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType); tableNames = schemaProvider.GetTableNames(connection).ToList(); } var tables = tableNames.Select(x => x.Tablename).ToList(); if (outFile == null && table == null) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Available Tables:"); Console.ResetColor(); foreach (var x in tables) { Console.WriteLine(x); } } else if (table == null) { File.WriteAllText(outFile, JSON.Stringify(tableNames.Select(x => { var xct = confConnection == null ? null : confConnection.Tables.FirstOrDefault(z => string.Compare(z.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0); return(new { name = x.Tablename, module = xct == null || xct.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : xct.Module, permission = xct == null || xct.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : xct.PermissionKey, identifier = xct == null || xct.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(x.Table) : xct.Identifier, }); }))); Environment.Exit(0); } userInput = tables.Count == 1 ? tables[0] : null; if (userInput == null && schemaProvider.DefaultSchema != null && tables.Any(x => x.StartsWith(schemaProvider.DefaultSchema + "."))) { userInput = schemaProvider.DefaultSchema + "."; } if (outFile == null) { Console.WriteLine(); while (table == null || !tables.Contains(table, StringComparer.OrdinalIgnoreCase)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; table = Hinter.ReadHintedLine(tables, userInput: userInput); userInput = table; if (table == "!") { Console.ResetColor(); return; } } } userInput = table; var tableName = tableNames.First(x => string.Compare(x.Tablename, userInput, StringComparison.OrdinalIgnoreCase) == 0); if (tableName == null) { Console.Error.WriteLine("Can't find table with name: " + userInput + "!"); Environment.Exit(1); } var confTable = confConnection == null ? null : confConnection.Tables.FirstOrDefault(x => string.Compare(x.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0); if (module == null) { userInput = confTable == null || confTable.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : confTable.Module; Console.WriteLine(); while (module.IsTrimmedEmpty()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Module name for table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; module = Hinter.ReadHintedLine(new string[0], userInput: userInput); userInput = module; if (module == "!") { Console.ResetColor(); return; } } } if (identifier == null) { userInput = confTable == null || confTable.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(tableName.Table) : confTable.Identifier; Console.WriteLine(); while (identifier.IsTrimmedEmpty()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a class Identifier for table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; identifier = Hinter.ReadHintedLine(new string[0], userInput: userInput); userInput = identifier; if (identifier == "!") { Console.ResetColor(); return; } } } if (permissionKey == null) { userInput = confTable == null || confTable.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : confTable.PermissionKey; Console.WriteLine(); while (permissionKey.IsTrimmedEmpty()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Enter a Permission Key for table: ('!' to abort)"); Console.ForegroundColor = ConsoleColor.Yellow; permissionKey = Hinter.ReadHintedLine(new string[0], userInput: userInput); userInput = permissionKey; if (permissionKey == "!") { Console.ResetColor(); return; } } } if (what == null) { Console.WriteLine(); userInput = "RSU"; while (what.IsEmptyOrNull()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Choose What to Generate (R:Row, S:Repo+Svc, U=Cols+Form+Page+Grid+Dlg+Css)"); Console.ForegroundColor = ConsoleColor.Yellow; what = Hinter.ReadHintedLine(new string[0], userInput: userInput); userInput = what; if (what == "!") { Console.ResetColor(); return; } } } config.GenerateRow = what.IndexOf("R", StringComparison.OrdinalIgnoreCase) >= 0; config.GenerateService = what.IndexOf("S", StringComparison.OrdinalIgnoreCase) >= 0; config.GenerateUI = what.IndexOf("U", StringComparison.OrdinalIgnoreCase) >= 0; Console.ResetColor(); Console.WriteLine(); if (confConnection == null) { confConnection = new GeneratorConfig.Connection { Key = connectionKey }; config.Connections.Add(confConnection); } if (confTable == null) { confTable = new GeneratorConfig.Table { Identifier = identifier, Module = module, PermissionKey = permissionKey, Tablename = tableName.Tablename }; confConnection.Tables.Add(confTable); } else { confTable.Identifier = identifier; confTable.Module = module; confTable.PermissionKey = permissionKey; } File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson()); using (var connection = SqlConnections.New(connectionString, providerName)) { connection.Open(); var rowModel = RowGenerator.GenerateModel(connection, tableName.Schema, tableName.Table, module, connectionKey, identifier, permissionKey, config); new EntityCodeGenerator(rowModel, config, csproj).Run(); } }
private void Page_Load(object sender, System.EventArgs e) { SetPageTitle(L10n.Term("Terminology.LBL_LIST_FORM_TITLE")); // 06/04/2006 Paul. Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. this.Visible = SplendidCRM.Security.IS_ADMIN; if (!this.Visible) { return; } try { DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { string sSQL; sSQL = "select * " + ControlChars.CrLf + " from vwTERMINOLOGY_List" + ControlChars.CrLf + " where 1 = 1 " + ControlChars.CrLf; using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = sSQL; // 01/12/2006 Paul. ctlSearch.LANGUAGE is not working. if (!IsPostBack) { Sql.AppendParameter(cmd, L10N.NormalizeCulture(L10n.NAME), 10, Sql.SqlFilterMode.Exact, "LANG"); //ctlSearch.LANGUAGE = L10n.NAME; } else { ctlSearch.SqlSearchClause(cmd); } if (ctlSearch.GLOBAL_TERMS) { cmd.CommandText += " and MODULE_NAME is null" + ControlChars.CrLf; } if (!ctlSearch.INCLUDE_LISTS) { cmd.CommandText += " and LIST_NAME is null" + ControlChars.CrLf; } if (bDebug) { RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd)); } using (DbDataAdapter da = dbf.CreateDataAdapter()) { ((IDbDataAdapter)da).SelectCommand = cmd; using (DataTable dt = new DataTable()) { da.Fill(dt); vwMain = dt.DefaultView; grdMain.DataSource = vwMain; if (!IsPostBack) { // 12/14/2007 Paul. Only set the default sort if it is not already set. It may have been set by SearchView. if (String.IsNullOrEmpty(grdMain.SortColumn)) { grdMain.SortColumn = "NAME"; grdMain.SortOrder = "asc"; } grdMain.ApplySort(); grdMain.DataBind(); } } } } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); lblError.Text = ex.Message; } if (!IsPostBack) { // 06/09/2006 Paul. Remove data binding in the user controls. Binding is required, but only do so in the ASPX pages. //Page.DataBind(); } }
public void ConstructDatabaseWithNullConnectionStringThrows() { DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); new TestDatabase(null, factory); }
public ConnectionFactory(ConnectionStringSettings settings) { _providerFactory = DbProviderFactories.GetFactory(settings.ProviderName); _connectionString = settings.ConnectionString; }
protected override bool LoadObjects() { DbConnection cnn = null; DbCommand cmd = null; DbDataReader rdr = null; try { DbProviderFactory factory = DbProviderFactories.GetFactory( connection.Provider.InvariantName); cnn = factory.CreateConnection(); cnn.ConnectionString = connection.ConnectionString; cnn.Open(); cmd = factory.CreateCommand(); cmd.Connection = cnn; cmd.CommandText = "SELECT C.TABLE_SCHEMA, C.TABLE_NAME, T.TABLE_TYPE, " + "C.COLUMN_NAME, C.DATA_TYPE, C.CHARACTER_MAXIMUM_LENGTH " + "FROM INFORMATION_SCHEMA.COLUMNS C INNER JOIN " + "INFORMATION_SCHEMA.TABLES T ON " + "T.TABLE_SCHEMA = C.TABLE_SCHEMA AND " + "T.TABLE_NAME = C.TABLE_NAME"; rdr = cmd.ExecuteReader(); while (rdr.Read()) { /* * Need to make keys lowercase for case-insensitive * matching but retain case for object properties. */ string schemaName = rdr.GetString(0); string schemaNameNC = schemaName.ToLower(); schemaNameNC = schemaNameNC.Replace(' ', '~'); string tableName = rdr.GetString(1); string tableNameNC = tableName.ToLower(); tableNameNC = tableNameNC.Replace(' ', '~'); bool isView = (rdr.GetString(2) == "VIEW"); string columnName = rdr.GetString(3); string columnType = rdr.GetString(4); int columnSize = (rdr.IsDBNull(5) ? -1 : rdr.GetInt32(5)); string columnTypeName = GetColumnTypeName( columnType, columnSize); if (!schemata.ContainsKey(schemaNameNC)) { schemata[schemaNameNC] = new Schema(schemaName); } if (!schemata[schemaNameNC].Tables.ContainsKey(tableNameNC)) { schemata[schemaNameNC].Tables[tableNameNC] = new Table(tableName, schemaName, isView); } schemata[schemaNameNC].Tables[tableNameNC].Columns.Add( new TableColumn(columnName, columnTypeName)); } return(true); } catch { return(false); } finally { if (rdr != null) { rdr.Dispose(); } if (cnn != null) { cnn.Dispose(); } } }
/// <summary> /// 默认构造函数 /// </summary> static DBVisitor3() { Params = new ParameterCollection(); DataFactory = DbProviderFactories.GetFactory(ConnectionString.ProviderName); }
protected void Page_Command(Object sender, CommandEventArgs e) { // 06/08/2006 Paul. Redirect to parent if that is where the note was originated. Guid gPARENT_ID = Sql.ToGuid(Request["PARENT_ID"]); string sMODULE = String.Empty; string sPARENT_TYPE = String.Empty; string sPARENT_NAME = String.Empty; try { SqlProcs.spPARENT_Get(ref gPARENT_ID, ref sMODULE, ref sPARENT_TYPE, ref sPARENT_NAME); } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); // The only possible error is a connection failure, so just ignore all errors. gPARENT_ID = Guid.Empty; } if (e.CommandName == "Save") { SplendidDynamic.ValidateEditViewFields(m_sMODULE + ".EditView", this); SplendidDynamic.ValidateEditViewFields(m_sMODULE + ".EditAddress", this); SplendidDynamic.ValidateEditViewFields(m_sMODULE + ".EditDescription", this); if (Page.IsValid) { string sCUSTOM_MODULE = "QUOTES"; DataTable dtCustomFields = SplendidCache.FieldsMetaData_Validated(sCUSTOM_MODULE); DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { con.Open(); using (IDbTransaction trn = con.BeginTransaction()) { try { SqlProcs.spQUOTES_Update (ref gID , new DynamicControl(this, "ASSIGNED_USER_ID").ID , new DynamicControl(this, "NAME").Text , new DynamicControl(this, "OPPORTUNITY_ID").ID , new DynamicControl(this, "QUOTE_TYPE").SelectedValue , new DynamicControl(this, "PAYMENT_TERMS").SelectedValue , new DynamicControl(this, "ORDER_STAGE").SelectedValue , new DynamicControl(this, "QUOTE_STAGE").SelectedValue , new DynamicControl(this, "PURCHASE_ORDER_NUM").Text , new DynamicControl(this, "ORIGINAL_PO_DATE").DateValue , new DynamicControl(this, "DATE_QUOTE_CLOSED").DateValue , new DynamicControl(this, "DATE_QUOTE_EXPECTED_CLOSED").DateValue , new DynamicControl(this, "DATE_ORDER_SHIPPED").DateValue , new DynamicControl(this, "SHOW_LINE_NUMS").Checked , new DynamicControl(this, "CALC_GRAND_TOTAL").Checked , new DynamicControl(this, "CURRENCY_ID").ID , new DynamicControl(this, "TAXRATE_ID").ID , new DynamicControl(this, "SHIPPER_ID").ID , new DynamicControl(this, "SUBTOTAL").DecimalValue , new DynamicControl(this, "SHIPPING").DecimalValue , new DynamicControl(this, "TAX").DecimalValue , new DynamicControl(this, "TOTAL").DecimalValue , new DynamicControl(this, "BILLING_ACCOUNT_ID").ID , new DynamicControl(this, "BILLING_CONTACT_ID").ID , new DynamicControl(this, "BILLING_ADDRESS_STREET").Text , new DynamicControl(this, "BILLING_ADDRESS_CITY").Text , new DynamicControl(this, "BILLING_ADDRESS_STATE").Text , new DynamicControl(this, "BILLING_ADDRESS_POSTALCODE").Text , new DynamicControl(this, "BILLING_ADDRESS_COUNTRY").Text , new DynamicControl(this, "SHIPPING_ACCOUNT_ID").ID , new DynamicControl(this, "SHIPPING_CONTACT_ID").ID , new DynamicControl(this, "SHIPPING_ADDRESS_STREET").Text , new DynamicControl(this, "SHIPPING_ADDRESS_CITY").Text , new DynamicControl(this, "SHIPPING_ADDRESS_STATE").Text , new DynamicControl(this, "SHIPPING_ADDRESS_POSTALCODE").Text , new DynamicControl(this, "SHIPPING_ADDRESS_COUNTRY").Text , new DynamicControl(this, "DESCRIPTION").Text , trn ); SplendidDynamic.UpdateCustomFields(this, trn, gID, sCUSTOM_MODULE, dtCustomFields); trn.Commit(); } catch (Exception ex) { trn.Rollback(); SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); ctlEditButtons.ErrorText = ex.Message; return; } } } if (!Sql.IsEmptyGuid(gPARENT_ID)) { Response.Redirect("~/" + sMODULE + "/view.aspx?ID=" + gPARENT_ID.ToString()); } else { Response.Redirect("view.aspx?ID=" + gID.ToString()); } } } else if (e.CommandName == "Cancel") { if (!Sql.IsEmptyGuid(gPARENT_ID)) { Response.Redirect("~/" + sMODULE + "/view.aspx?ID=" + gPARENT_ID.ToString()); } else if (Sql.IsEmptyGuid(gID)) { Response.Redirect("default.aspx"); } else { Response.Redirect("view.aspx?ID=" + gID.ToString()); } } }
private static DbProviderFactory CreateDbProviderFactory() { return(DbProviderFactories.GetFactory(ProviderName)); }
private void Page_Load(object sender, System.EventArgs e) { Utils.SetPageTitle(Page, L10n.Term(".moduleList." + m_sMODULE)); // 06/04/2006 Paul. Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. this.Visible = (SplendidCRM.Security.GetUserAccess(m_sMODULE, "edit") >= 0); if (!this.Visible) { return; } try { gID = Sql.ToGuid(Request["ID"]); if (!IsPostBack) { // 07/29/2005 Paul. SugarCRM 3.0 does not allow the NONE option. //lstPARENT_TYPE .Items.Insert(0, new ListItem(L10n.Term(".LBL_NONE"), "")); Guid gDuplicateID = Sql.ToGuid(Request["DuplicateID"]); if (!Sql.IsEmptyGuid(gID) || !Sql.IsEmptyGuid(gDuplicateID)) { DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { string sSQL; sSQL = "select * " + ControlChars.CrLf + " from vwTASKS_Edit" + ControlChars.CrLf + " where ID = @ID " + ControlChars.CrLf; using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = sSQL; if (!Sql.IsEmptyGuid(gDuplicateID)) { Sql.AddParameter(cmd, "@ID", gDuplicateID); gID = Guid.Empty; } else { Sql.AddParameter(cmd, "@ID", gID); } con.Open(); #if DEBUG Page.RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd)); #endif using (IDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (rdr.Read()) { ctlModuleHeader.Title = Sql.ToString(rdr["NAME"]); Utils.SetPageTitle(Page, L10n.Term(".moduleList." + m_sMODULE) + " - " + ctlModuleHeader.Title); Utils.UpdateTracker(Page, m_sMODULE, gID, ctlModuleHeader.Title); ViewState["ctlModuleHeader.Title"] = ctlModuleHeader.Title; this.AppendEditViewFields(m_sMODULE + ".EditView", tblMain, rdr); // 07/15/2006 Paul. Contacts are not valid parents for a Task. // Manually remove them as the list record_type_display is common across all other parents. DropDownList lstPARENT_TYPE = FindControl("PARENT_TYPE") as DropDownList; if (lstPARENT_TYPE != null) { lstPARENT_TYPE.Items.Remove("Contacts"); } // 03/04/2006 Paul. The close button on the Tasks List is used to edit and set STATUS to Completed. // 06/21/2006 Paul. Change parameter to Close so that the same parameter can be used for Calls, Meetings and Tasks. // 08/08/2006 Paul. SugarCRM uses Completed in its URL, so we will do the same. if (Sql.ToString(Request["Status"]) == "Completed") { new DynamicControl(this, "STATUS").SelectedValue = "Completed"; } } } } } } else { this.AppendEditViewFields(m_sMODULE + ".EditView", tblMain, null); // 07/15/2006 Paul. Contacts are not valid parents for a Task. // Manually remove them as the list record_type_display is common across all other parents. DropDownList lstPARENT_TYPE = FindControl("PARENT_TYPE") as DropDownList; if (lstPARENT_TYPE != null) { lstPARENT_TYPE.Items.Remove("Contacts"); } Guid gPARENT_ID = Sql.ToGuid(Request["PARENT_ID"]); Guid gCONTACT_ID = Sql.ToGuid(Request["CONTACT_ID"]); if (!Sql.IsEmptyGuid(gPARENT_ID)) { string sMODULE = String.Empty; string sPARENT_TYPE = String.Empty; string sPARENT_NAME = String.Empty; SqlProcs.spPARENT_Get(ref gPARENT_ID, ref sMODULE, ref sPARENT_TYPE, ref sPARENT_NAME); if (!Sql.IsEmptyGuid(gPARENT_ID)) { // 07/15/2006 Paul. If the parent is a contact, then convert to a contact. if (sPARENT_TYPE == "Contacts") { gCONTACT_ID = gPARENT_ID; } else { new DynamicControl(this, "PARENT_ID").ID = gPARENT_ID; new DynamicControl(this, "PARENT_NAME").Text = sPARENT_NAME; new DynamicControl(this, "PARENT_TYPE").SelectedValue = sPARENT_TYPE; } } } if (!Sql.IsEmptyGuid(gCONTACT_ID)) { string sMODULE = String.Empty; string sCONTACT_TYPE = String.Empty; string sCONTACT_NAME = String.Empty; SqlProcs.spPARENT_Get(ref gCONTACT_ID, ref sMODULE, ref sCONTACT_TYPE, ref sCONTACT_NAME); if (!Sql.IsEmptyGuid(gCONTACT_ID)) { new DynamicControl(this, "CONTACT_ID").ID = gCONTACT_ID; new DynamicControl(this, "CONTACT_NAME").Text = sCONTACT_NAME; } } try { // 12/04/2005 Paul. Default value is Medium. new DynamicControl(this, "PRIORITY").SelectedValue = "Medium"; } catch (Exception ex) { SplendidError.SystemWarning(new StackTrace(true).GetFrame(0), ex.Message); } try { // 12/04/2005 Paul. Default value is Not Started. new DynamicControl(this, "STATUS").SelectedValue = "Not Started"; } catch (Exception ex) { SplendidError.SystemWarning(new StackTrace(true).GetFrame(0), ex.Message); } } } else { // 12/02/2005 Paul. When validation fails, the header title does not retain its value. Update manually. ctlModuleHeader.Title = Sql.ToString(ViewState["ctlModuleHeader.Title"]); Utils.SetPageTitle(Page, L10n.Term(".moduleList." + m_sMODULE) + " - " + ctlModuleHeader.Title); } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); ctlEditButtons.ErrorText = ex.Message; } }
private AdoParameterFactory GetFactory() { var factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); return(new AdoParameterFactory(factory.CreateCommand())); }
protected void Page_Command(Object sender, CommandEventArgs e) { // 08/21/2005 Paul. Redirect to parent if that is where the note was originated. Guid gPARENT_ID = Sql.ToGuid(Request["PARENT_ID"]); Guid gCONTACT_ID = Sql.ToGuid(Request["CONTACT_ID"]); string sMODULE = String.Empty; string sPARENT_TYPE = String.Empty; string sPARENT_NAME = String.Empty; try { SqlProcs.spPARENT_Get(ref gPARENT_ID, ref sMODULE, ref sPARENT_TYPE, ref sPARENT_NAME); } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); // The only possible error is a connection failure, so just ignore all errors. gPARENT_ID = Guid.Empty; } if (e.CommandName == "Save") { // 01/16/2006 Paul. Enable validator before validating page. SplendidDynamic.ValidateEditViewFields(m_sMODULE + ".EditView", this); if (Page.IsValid) { string sCUSTOM_MODULE = "TASKS"; DataTable dtCustomFields = SplendidCache.FieldsMetaData_Validated(sCUSTOM_MODULE); DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { con.Open(); using (IDbTransaction trn = con.BeginTransaction()) { try { SqlProcs.spTASKS_Update (ref gID , new DynamicControl(this, "ASSIGNED_USER_ID").ID , new DynamicControl(this, "NAME").Text , new DynamicControl(this, "STATUS").SelectedValue , new DynamicControl(this, "DATE_DUE").DateValue , new DynamicControl(this, "DATE_START").DateValue , new DynamicControl(this, "PARENT_TYPE").SelectedValue , new DynamicControl(this, "PARENT_ID").ID , new DynamicControl(this, "CONTACT_ID").ID , new DynamicControl(this, "PRIORITY").SelectedValue , new DynamicControl(this, "DESCRIPTION").Text , trn ); SplendidDynamic.UpdateCustomFields(this, trn, gID, sCUSTOM_MODULE, dtCustomFields); trn.Commit(); } catch (Exception ex) { trn.Rollback(); SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); ctlEditButtons.ErrorText = ex.Message; return; } } } if (!Sql.IsEmptyGuid(gPARENT_ID)) { Response.Redirect("~/" + sMODULE + "/view.aspx?ID=" + gPARENT_ID.ToString()); } else if (!Sql.IsEmptyGuid(gCONTACT_ID)) { Response.Redirect("~/Contacts/view.aspx?ID=" + gCONTACT_ID.ToString()); } else { Response.Redirect("view.aspx?ID=" + gID.ToString()); } } } else if (e.CommandName == "Cancel") { if (!Sql.IsEmptyGuid(gPARENT_ID)) { Response.Redirect("~/" + sMODULE + "/view.aspx?ID=" + gPARENT_ID.ToString()); } else if (!Sql.IsEmptyGuid(gCONTACT_ID)) { Response.Redirect("~/Contacts/view.aspx?ID=" + gCONTACT_ID.ToString()); } else if (Sql.IsEmptyGuid(gID)) { Response.Redirect("default.aspx"); } else { Response.Redirect("view.aspx?ID=" + gID.ToString()); } } }
private void Page_Load(object sender, System.EventArgs e) { SetPageTitle(L10n.Term(m_sMODULE + ".LBL_LIST_FORM_TITLE")); // 06/04/2006 Paul. Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. this.Visible = (SplendidCRM.Security.GetUserAccess(m_sMODULE, "list") >= 0); if (!this.Visible) { return; } try { if (this.IsMobile && grdMain.Columns.Count > 0) { grdMain.Columns[0].Visible = false; } DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { string sSQL; sSQL = "select * " + ControlChars.CrLf + " from vwINVOICES_List" + ControlChars.CrLf; using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = sSQL; // 11/24/2006 Paul. Use new Security.Filter() function to apply Team and ACL security rules. Security.Filter(cmd, m_sMODULE, "list"); ctlSearchView.SqlSearchClause(cmd); if (bDebug) { RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd)); } using (DbDataAdapter da = dbf.CreateDataAdapter()) { ((IDbDataAdapter)da).SelectCommand = cmd; using (DataTable dt = new DataTable()) { da.Fill(dt); vwMain = dt.DefaultView; grdMain.DataSource = vwMain; if (!IsPostBack) { // 12/14/2007 Paul. Only set the default sort if it is not already set. It may have been set by SearchView. if (String.IsNullOrEmpty(grdMain.SortColumn)) { grdMain.SortColumn = "NAME"; grdMain.SortOrder = "asc"; } grdMain.ApplySort(); grdMain.DataBind(); } } } } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); lblError.Text = ex.Message; } if (!IsPostBack) { // 06/09/2006 Paul. Remove data binding in the user controls. Binding is required, but only do so in the ASPX pages. //Page.DataBind(); } }
public void TestSetUp() { _runner = QueryRunner.Create(DbProviderFactories.GetFactory("System.Data.SqlClient"), _conn, true, 30); }
static void Main(string[] args) { try { //Для подключения к SQLite, создается один раз SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite"); Console.WriteLine("Сгенерировать новую БД SQLite? (y/n)"); ConsoleKeyInfo keyInfo = Console.ReadKey(false); if (keyInfo.KeyChar == 'y' || keyInfo.KeyChar == 'у' || keyInfo.KeyChar == 'д') { //генерация новой БД Console.WriteLine("Запись данных в БД SQLite"); WriteSQLite(factory); Console.WriteLine("Нажмите любую клавишу для продолжения..."); Console.ReadKey(true); } //чтение БД Console.WriteLine("Чтение данных из БД SQLite"); List <FullRow> rows = ReadSQLite(factory); string str_data = JsonConvert.SerializeObject(rows); // подключаемся к удаленному хосту IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(address), port); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(ipPoint); Console.WriteLine("Шифрование данных"); // получаем публичный ключ RSA byte[] data_rsa = new byte[2048]; // буфер для ответа int bytes = socket.Receive(data_rsa, data_rsa.Length, 0); string serial_rsa = Encoding.Unicode.GetString(data_rsa, 0, bytes); RSAParameters rsaParams = JsonConvert.DeserializeObject <RSAParameters>(serial_rsa); //шифруем симметричным шифрованием данные Rijndael cipher = Rijndael.Create(); string encrypted = Encrypt(str_data, cipher.Key, cipher.IV); //string decrypted = Decrypt(encrypted, cipher.Key, cipher.IV); //шифруем RSA ключ симметричного шифрования byte[] encrypted_key = RSAEncrypt(cipher.Key, rsaParams); //byte[] decrypted_key = RSAEncrypt(encrypted_key, RSA.ExportParameters(true)); //удаляем из памяти экземпляр класса симметричного шифрования byte[] iv = cipher.IV; cipher.Dispose(); Console.WriteLine("Пересылка данных"); //отправляем зашифрованный ключ симметричного шифрования socket.Send(encrypted_key); // получаем подтверждение byte[] data = new byte[256]; // буфер для ответа bytes = socket.Receive(data, data.Length, 0); string answer = Encoding.Unicode.GetString(data, 0, bytes); if (!answer.Equals("ready")) { throw new Exception("Получены некорректные данные"); } //отправляем инициализующий вектор симметричного шифрования в открытом виде socket.Send(iv); //получаем подтверждение data = new byte[256]; // буфер для ответа bytes = socket.Receive(data, data.Length, 0); answer = Encoding.Unicode.GetString(data, 0, bytes); if (!answer.Equals("ready")) { throw new Exception("Получены некорректные данные"); } //отправляем размер данных byte[] data_rows = Encoding.Unicode.GetBytes(encrypted); string message = "отправка " + data_rows.Length; data = Encoding.Unicode.GetBytes(message); socket.Send(data); // получаем подтверждение data = new byte[256]; // буфер для ответа bytes = socket.Receive(data, data.Length, 0); answer = Encoding.Unicode.GetString(data, 0, bytes); if (!answer.Equals("ready")) { throw new Exception("Получены некорректные данные"); } //отправляем зашифрованные данные socket.Send(data_rows); // получаем количество доставленных байт data = new byte[256]; // буфер для ответа bytes = socket.Receive(data, data.Length, 0); answer = Encoding.Unicode.GetString(data, 0, bytes); //отображаем отчет string[] res = answer.Split(' '); if (res.Length != 2 || !res[0].Equals("доставлено")) { throw new Exception("Получены некорректные данные"); } int count = int.Parse(res[1]); Console.WriteLine("Отправлено {0} байт.\nДоставлено {1} байт", data_rows.Length, count); // закрываем сокет socket.Shutdown(SocketShutdown.Both); socket.Close(); } catch (Exception ex) { Console.WriteLine("Произошла ошибка {0}. Приложение будет закрыто.", ex.Message); } Console.WriteLine("Нажмите любую клавишу для выхода..."); Console.ReadKey(true); Environment.Exit(0); }
public void No_connection_expects_error_on_Execute() { _runner = new QueryRunner(DbProviderFactories.GetFactory("System.Data.SqlClient"), null, true, 30); _runner.ExecuteQuery(" "); }
private void Page_Load(object sender, System.EventArgs e) { Utils.SetPageTitle(Page, L10n.Term(m_sMODULE + ".LBL_LIST_FORM_TITLE")); // 06/04/2006 Paul. Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. this.Visible = (SplendidCRM.Security.GetUserAccess(m_sMODULE, "list") >= 0); if (!this.Visible) { return; } try { DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { string sSQL; sSQL = "select * " + ControlChars.CrLf + " from vwPROJECTS_List" + ControlChars.CrLf + " where 1 = 1 " + ControlChars.CrLf; using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = sSQL; int nACLACCESS = Security.GetUserAccess(m_sMODULE, "list"); if (nACLACCESS == ACL_ACCESS.OWNER) { Sql.AppendParameter(cmd, Security.USER_ID, "ASSIGNED_USER_ID", false); } ctlSearch.SqlSearchClause(cmd); #if DEBUG Page.RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd)); #endif using (DbDataAdapter da = dbf.CreateDataAdapter()) { ((IDbDataAdapter)da).SelectCommand = cmd; using (DataTable dt = new DataTable()) { da.Fill(dt); vwMain = dt.DefaultView; grdMain.DataSource = vwMain; if (!IsPostBack) { grdMain.SortColumn = "NAME"; grdMain.SortOrder = "asc"; grdMain.ApplySort(); grdMain.DataBind(); } } } } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message); lblError.Text = ex.Message; } if (!IsPostBack) { // 06/09/2006 Paul. Remove data binding in the user controls. Binding is required, but only do so in the ASPX pages. //Page.DataBind(); } }
/// <summary> /// 创建一个数据提供程序实例 /// </summary> /// <param name="connectionStringName"></param> /// <returns></returns> public static Database Create(string connectionStringName) { CheckUtil.ArgumentNotNullOrEmpty(connectionStringName, "connectionStringName"); ConnectionStringSettings css = ConfigurationManager.ConnectionStrings[connectionStringName]; if (css == null) { throw new Exception(string.Format(Resources.Data.ConnectionStringNameNotFound, connectionStringName)); } string connectionString = css.ConnectionString; string providerName = css.ProviderName; Database db = new SqlServerDatabase(connectionString); DbProviderFactory providerFactory = null; if (string.IsNullOrEmpty(providerName)) { return(db); } //if (css.ProviderName == "System.Data.OleDb") //{ // providerFactory = OleDbFactory.Instance; //} //else //{ // providerFactory = DbProviderFactories.GetFactory(css.ProviderName); //} //if (providerFactory == null) throw new Exception(string.Format(Resources.Data.DataProviderNotFound, css.ProviderName)); switch (providerName) { //case "System.Data.SqlClient": // break; case "System.Data.Odbc": db = new OdbcDatabase(connectionString); break; case "System.Data.OleDb": db = new OleDbDatabase(connectionString); break; case "System.Data.OracleClient": db = new OracleDatabase(connectionString); break; case "Devart.Data.Oracle": //http://evget.com/zh-CN/product/954/feature.aspx http://www.devart.com/ case "DDTek.Oracle": //http://www.datadirect.com/index.html providerFactory = DbProviderFactories.GetFactory(providerName); db = new OracleDatabase(connectionString, providerFactory); break; case "System.Data.SQLite": providerFactory = DbProviderFactories.GetFactory(providerName); db = new SQLiteDatabase(connectionString, providerFactory); break; case "MySql.Data.MySqlClient": providerFactory = DbProviderFactories.GetFactory(providerName); db = new MySqlDatabase(connectionString, providerFactory); break; case "IBM.Data.DB2": providerFactory = DbProviderFactories.GetFactory(providerName); db = new DB2Database(connectionString, providerFactory); break; case "FirebirdSql.Data.FirebirdClient": providerFactory = DbProviderFactories.GetFactory(providerName); db = new FirebirdDatabase(connectionString, providerFactory); break; default: break; } return(db); }
internal void RegisterDatabase(string databaseId, string providerInvariantName, string connectionString) { RegisterDatabase(databaseId, DbProviderFactories.GetFactory(providerInvariantName), connectionString); }
/// <summary> /// Asynchronous function that accepts the client and processes its requests /// </summary> public async void Connect() { try { DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); factory.CreateConnection(); using (SqlConnection conn = new SqlConnection(ServConnect.strConnectionString)) { TcpListener serv = new TcpListener(IPAddress.Any, 10000); serv.Start(); while (true) { conn.ConnectionString = ServConnect.strConnectionString; conn.Open(); DbCommand comm = factory.CreateCommand(); comm.Connection = conn; TcpClient client = await Task.Run(() => serv.AcceptTcpClient()); byte[] buf = new byte[4096]; var iRead = client.GetStream().Read(buf, 0, buf.Length); string[] stringSeparators = new string[] { "\r\n" }; string str = Encoding.Unicode.GetString(buf, 0, iRead); int codding = int.Parse(str.Remove(3)); str = str.Remove(0, 3); Console.WriteLine("\r\n" + codding + " " + str); /// login to the program with a username and password if (codding == 001) { try { string[] log_pass = str.Split(stringSeparators, StringSplitOptions.None); string log = log_pass[0]; string pass = log_pass[1]; Console.WriteLine(log + " " + pass); comm.CommandText = string.Format("Select id,name,surname from Users where Users.login='******' AND Users.pass = '******'", log, pass); DbDataReader reader = comm.ExecuteReader(); int id_user = 0; string Name_user = null; string Surname_user = null; while (reader.Read()) { id_user = int.Parse(reader.GetValue(0).ToString()); Name_user = reader.GetValue(1).ToString(); Surname_user = reader.GetValue(2).ToString(); } buf = Encoding.Unicode.GetBytes(string.Format("{0}\r\n{1}\r\n{2}", id_user, Name_user, Surname_user)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// New User Registration if (codding == 002) { try { string[] name_surname_log_pass = str.Split(stringSeparators, StringSplitOptions.None); string name = name_surname_log_pass[0]; string surname = name_surname_log_pass[1]; string log = name_surname_log_pass[2]; string pass = name_surname_log_pass[3]; comm.CommandText = string.Format("Select login from Users where Users.login='******'", log); string logg = null; DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { logg = reader.GetValue(0).ToString(); } reader.Close(); reader = null; if (logg != null) { throw new Exception("Пользователь с таким лоогином уже существует"); } comm.CommandText = string.Format("INSERT INTO Users (name, surname, login, pass) VALUES ('{0}', '{1}', '{2}', '{3}');", name, surname, log, pass); DbDataReader reader1 = comm.ExecuteReader(); reader1.Close(); reader1 = null; comm.CommandText = string.Format("Select id,name,surname from Users where Users.login='******' AND Users.pass = '******'", log, pass); DbDataReader proverka = comm.ExecuteReader(); int id_user = 0; string Name_user = null; string Surname_user = null; while (proverka.Read()) { id_user = int.Parse(proverka.GetValue(0).ToString()); Name_user = proverka.GetValue(1).ToString(); Surname_user = proverka.GetValue(2).ToString(); } if (id_user == 0 || Name_user == null || Surname_user == null) { throw new Exception("Не удалось зарегестрировать пользователя"); } proverka.Close(); proverka = null; comm.CommandText = string.Format("CREATE TABLE Friends{0} (id INT NOT NULL PRIMARY KEY,name nchar(15) NOT NULL,surname nchar(15) NOT NULL)", id_user); DbDataReader CreatreTable = comm.ExecuteReader(); CreatreTable.Close(); CreatreTable = null; comm.CommandText = string.Format("CREATE TABLE Rooms{0} (id_Friend INT NOT NULL PRIMARY KEY)", id_user); DbDataReader CreatreTableMessage = comm.ExecuteReader(); CreatreTableMessage.Close(); CreatreTableMessage = null; buf = Encoding.Unicode.GetBytes("Поздравляем, вы успешно зарегестрировались"); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// Sending a list of friends to the user if (codding == 003) { try { comm.CommandText = string.Format("Select id,name,surname from Friends{0}", str); string lstfriens = null; DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { lstfriens += string.Format("{0} {1} {2}\r\n", reader.GetValue(0).ToString().Trim(' '), reader.GetValue(1).ToString().Trim(' '), reader.GetValue(2).ToString().Trim(' ')); } if (lstfriens == null) { lstfriens = "0"; } buf = Encoding.Unicode.GetBytes(lstfriens); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); reader.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// search for new friends if (codding == 004) { try { string[] log_pass = str.Split(stringSeparators, StringSplitOptions.None); int codSerch = int.Parse(log_pass[0]); if (codSerch == 0) { int id_serch = int.Parse(log_pass[1]); Console.WriteLine(codSerch + " " + id_serch); comm.CommandText = string.Format("Select id,name,surname from Users where Users.id='{0}'", id_serch); } else if (codSerch == 1) { string name_serch = log_pass[1]; Console.WriteLine(codSerch + " " + name_serch); comm.CommandText = string.Format("Select id,name,surname from Users where Users.name='{0}'", name_serch); } else if (codSerch == 2) { string surname_serch = log_pass[1]; Console.WriteLine(codSerch + " " + surname_serch); comm.CommandText = string.Format("Select id,name,surname from Users where Users.surname='{0}'", surname_serch); } else if (codSerch == 3) { string[] name_surname = log_pass[1].Split(' '); string name = name_surname[0]; string surname = name_surname[1]; Console.WriteLine(codSerch + " " + name + " " + surname); comm.CommandText = string.Format("Select id,name,surname from Users where Users.name='{0}' AND Users.surname = '{1}'", name, surname); } string lstfriens = null; DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { lstfriens += string.Format("{0} {1} {2}\r\n", reader.GetValue(0).ToString().Trim(' '), reader.GetValue(1).ToString().Trim(' '), reader.GetValue(2).ToString().Trim(' ')); } if (lstfriens == null) { lstfriens = "0"; } buf = Encoding.Unicode.GetBytes(lstfriens); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); reader.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// add user to friends if (codding == 005) { try { string[] log_pass = str.Split(stringSeparators, StringSplitOptions.None); string id_friend = log_pass[0]; string my_id = log_pass[1]; Console.WriteLine(id_friend + " " + my_id); comm.CommandText = string.Format("Select name from Friends{0} where id='{1}'", my_id, id_friend); string Name_friend = null; string Surname_friend = null; DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { Name_friend = reader.GetValue(0).ToString(); } reader.Close(); reader = null; if (Name_friend != null) { throw new Exception("Этот пользователь уже находится у вас в списке друзей"); } comm.CommandText = string.Format("Select id,name,surname from Users where Users.id='{0}'", id_friend); reader = comm.ExecuteReader(); while (reader.Read()) { id_friend = reader.GetValue(0).ToString(); Name_friend = reader.GetValue(1).ToString(); Surname_friend = reader.GetValue(2).ToString(); } reader.Close(); reader = null; comm.CommandText = string.Format("INSERT INTO Friends{3} (id,name, surname) VALUES ('{0}', '{1}', '{2}');", id_friend, Name_friend, Surname_friend, my_id); reader = comm.ExecuteReader(); reader.Close(); reader = null; buf = Encoding.Unicode.GetBytes(string.Format("Пользователь {0} {1} успешно добавлен в список друзей", Name_friend.Trim(' '), Surname_friend.Trim(' '))); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// creating a "room" of two users for communication if (codding == 006) { try { string[] log_pass = str.Split(stringSeparators, StringSplitOptions.None); string my_id = log_pass[0]; string friend_id = log_pass[1]; Console.WriteLine(my_id + " " + friend_id); string id = null; comm.CommandText = string.Format("Select id_Friend from Rooms{0} where id_Friend='{1}'", my_id, friend_id); DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { id = reader.GetValue(0).ToString(); } reader.Close(); reader = null; string name_table_message = null; if (id != null) { try { if (int.Parse(my_id) < int.Parse(friend_id)) { throw new Exception(name_table_message = "Message_" + my_id + "_" + friend_id); } else { throw new Exception(name_table_message = "Message_" + friend_id + "_" + my_id); } } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format(ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } comm.CommandText = string.Format("INSERT INTO Rooms{0} (id_Friend) VALUES ('{1}');", my_id, friend_id); DbDataReader reader1 = comm.ExecuteReader(); reader1.Close(); reader1 = null; comm.CommandText = string.Format("INSERT INTO Rooms{0} (id_Friend) VALUES ('{1}');", friend_id, my_id); DbDataReader reader2 = comm.ExecuteReader(); reader2.Close(); reader2 = null; if (int.Parse(my_id) < int.Parse(friend_id)) { comm.CommandText = string.Format("CREATE TABLE Message_{0}_{1} (id_Message INT NOT NULL PRIMARY KEY IDENTITY,Text nvarchar(1000) NOT NULL,id_sender int NOT NULL)", my_id, friend_id); name_table_message = "Message_" + my_id + "_" + friend_id; } else { comm.CommandText = string.Format("CREATE TABLE Message_{0}_{1} (id_Message INT NOT NULL PRIMARY KEY IDENTITY,Text nvarchar(1000) NOT NULL,id_sender int NOT NULL)", friend_id, my_id); } name_table_message = "Message_" + friend_id + "_" + my_id; DbDataReader CreatreTableMessage = comm.ExecuteReader(); CreatreTableMessage.Close(); CreatreTableMessage = null; buf = Encoding.Unicode.GetBytes(name_table_message); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// return the user a list of all his chat rooms if (codding == 007) { try { string lstfriens = null; comm.CommandText = string.Format("Select id_Friend from Rooms{0}", str); DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { lstfriens += string.Format("{0} ", reader.GetValue(0).ToString().Trim(' ')); } reader.Close(); reader = null; if (lstfriens == null) { throw new Exception("0"); } string[] lstfriendinroom = lstfriens.Split(' '); lstfriens = null; for (int i = 0; i < lstfriendinroom.Length - 1; i++) { comm.CommandText = string.Format("Select id,name,surname from Users where id='{0}'", lstfriendinroom[i]); reader = comm.ExecuteReader(); while (reader.Read()) { lstfriens += string.Format("{0} {1} {2}\r\n", reader.GetValue(0).ToString().Trim(' '), reader.GetValue(1).ToString().Trim(' '), reader.GetValue(2).ToString().Trim(' ')); } reader.Close(); reader = null; } buf = Encoding.Unicode.GetBytes(lstfriens); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// send a chat history to the user if (codding == 008) { try { string[] log_pass = str.Split(stringSeparators, StringSplitOptions.None); string NameChat = log_pass[0]; string lstMessage = null; comm.CommandText = string.Format("Select Text,id_sender from {0}", NameChat); DbDataReader reader = comm.ExecuteReader(); while (reader.Read()) { lstMessage += string.Format("{0}_{1}\\", reader.GetValue(0).ToString(), reader.GetValue(1).ToString()); } reader.Close(); reader = null; buf = Encoding.Unicode.GetBytes(lstMessage); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } /// chat room posting if (codding == 009) { try { string[] log_pass = str.Split('\\'); string NameChat = log_pass[0]; string id_user = log_pass[1]; string text = log_pass[2]; Console.WriteLine(codding + " " + NameChat); comm.CommandText = string.Format("INSERT INTO {0} (Text,id_sender) VALUES ('{1}', '{2}');", NameChat, text, id_user); DbDataReader reader = comm.ExecuteReader(); reader.Close(); reader = null; buf = Encoding.Unicode.GetBytes("1"); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } catch (Exception ex) { buf = Encoding.Unicode.GetBytes(string.Format("Произошла ошибка: {0}", ex.Message)); client.GetStream().Write(buf, 0, buf.Length); conn.Close(); } } } } } catch (Exception ex) { Console.WriteLine(ex); } }
protected override void InitializeTarget() { base.InitializeTarget(); #pragma warning disable 618 if (UseTransactions.HasValue) #pragma warning restore 618 { InternalLogger.Warn("DatabaseTarget(Name={0}): UseTransactions property is obsolete and will not be used - will be removed in NLog 6", Name); } bool foundProvider = false; string providerName = string.Empty; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim())) { ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim()); } providerName = cs.ProviderName?.Trim() ?? string.Empty; } #endif if (ConnectionString != null) { try { var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent()); var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue)) { // Special Entity Framework Connection String if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue)) { // Provider was overriden by ConnectionString providerName = providerValue.ToString()?.Trim() ?? string.Empty; } // ConnectionString was overriden by ConnectionString :) ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString()); } } catch (Exception ex) { #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse '{1}' ConnectionString", Name, ConnectionStringName); } else #endif InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse ConnectionString", Name); } } #if !NETSTANDARD if (string.IsNullOrEmpty(providerName)) { string dbProvider = DBProvider?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(dbProvider)) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase)) { providerName = invariantname; break; } } } } if (!string.IsNullOrEmpty(providerName)) { try { ProviderFactory = DbProviderFactories.GetFactory(providerName); foundProvider = true; } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): DbProviderFactories failed to get factory from ProviderName={1}", Name, providerName); throw; } } #endif if (!foundProvider) { try { SetConnectionType(); if (ConnectionType == null) { InternalLogger.Warn("DatabaseTarget(Name={0}): No ConnectionType created from DBProvider={1}", Name, DBProvider); } } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): Failed to create ConnectionType from DBProvider={1}", Name, DBProvider); throw; } } }
public DataSource(string connectionString, string providerName) { this.providerFactory = DbProviderFactories.GetFactory(providerName); this.connectionString = connectionString; }
////public static SqlCommand CreateDeleteCommand(SqlConnection connection, IIdentifier id, IImmutableDictionary<string, object> where) ////{ //// /* //// DELETE FROM [dbo].[Setting] WHERE [Name] LIKE 'baz%' AND [Environment] = 'boz' //// */ //// var sql = new StringBuilder(); //// var dbProviderFactory = DbProviderFactories.GetFactory(connection); //// using (var commandBuilder = dbProviderFactory.CreateCommandBuilder()) //// { //// string Sanitize(string identifier) => commandBuilder.QuoteIdentifier(identifier); //// var table = $"{Sanitize(_tableMetadata.SchemaName)}.{Sanitize(_tableMetadata.TableName)}"; //// sql.Append($"DELETE FROM {table}").AppendLine(); //// sql.Append(where.Keys.Aggregate( //// $"WHERE ([{EntityProperty.Name}] = @{EntityProperty.Name} OR [{EntityProperty.Name}] LIKE @{EntityProperty.Name} + N'[[]%]')", //// (result, next) => $"{result} AND {Sanitize(next)} = @{next} ") //// ); //// } //// var command = connection.CreateCommand(); //// command.CommandType = CommandType.Text; //// command.CommandText = sql.ToString(); //// // --- add parameters & values //// (command, _tableMetadata).AddParameter( //// ImmutableDictionary<string, object>.Empty //// .Add(EntityProperty.Name, id.ToString()) //// .AddRange(where) //// ); //// return command; ////} public static SqlCommand CreateUpdateCommand(this SqlConnection connection, SqlServer datastore, ISetting setting) { /* * * UPDATE [Setting] * SET [Value] = 'Hallo update!' * WHERE [Name]='baz' AND [Environment] = 'boz' * IF @@ROWCOUNT = 0 * INSERT INTO [Setting]([Name], [Value], [Environment]) * VALUES ('baz', 'Hallo insert!', 'boz') * */ var sql = new StringBuilder(); var dbProviderFactory = DbProviderFactories.GetFactory(connection); using (var commandBuilder = dbProviderFactory.CreateCommandBuilder()) { string Sanitize(string identifier) => commandBuilder.QuoteIdentifier(identifier); var table = $"{Sanitize(datastore.Schema)}.{Sanitize(datastore.Table)}"; sql.Append($"UPDATE {table}").AppendLine(); sql.Append($"SET [{nameof(ISetting.Value)}] = @{nameof(ISetting.Value)}").AppendLine(); sql.Append(datastore.Where.Aggregate( $"WHERE [{nameof(ISetting.Name)}] = @{nameof(ISetting.Name)}", (result, next) => $"{result} AND {Sanitize(next.Key)} = @{next.Key} ") ).AppendLine(); sql.Append($"IF @@ROWCOUNT = 0").AppendLine(); var columns = datastore.Where.Keys.Select(Sanitize).Aggregate( $"[{nameof(ISetting.Name)}], [{nameof(ISetting.Value)}]", (result, next) => $"{result}, {next}" ); sql.Append($"INSERT INTO {table}({columns})").AppendLine(); var parameterNames = datastore.Where.Keys.Aggregate( $"@{nameof(ISetting.Name)}, @{nameof(ISetting.Value)}", (result, next) => $"{result}, @{next}" ); sql.Append($"VALUES ({parameterNames})"); } var command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = sql.ToString(); // --- add parameters command.Parameters.AddWithValue(nameof(ISetting.Name), setting.Name.ToString()); command.Parameters.AddWithValue(nameof(ISetting.Value), setting.Value); command.AddParameters(datastore.Where); return(command); }
private void Page_Load(object sender, System.EventArgs e) { SetPageTitle(L10n.Term(m_sMODULE + ".LBL_LIST_FORM_TITLE")); // 06/04/2006 Paul. Visibility is already controlled by the ASPX page, but it is probably a good idea to skip the load. this.Visible = (SplendidCRM.Security.GetUserAccess(m_sMODULE, "list") >= 0); if (!this.Visible) { return; } nACLACCESS_Export = Security.GetUserAccess(m_sMODULE, "export"); try { sMODULE_NAME = Sql.ToString(Request["MODULE_NAME"]); ctlListHeaderMySaved.Title = ".saved_reports_dom." + sMODULE_NAME; ctlListHeaderPublished.Title = ".published_reports_dom." + sMODULE_NAME; DbProviderFactory dbf = DbProviderFactories.GetFactory(); using (IDbConnection con = dbf.CreateConnection()) { string sSQL; sSQL = "select * " + ControlChars.CrLf + " from vwREPORTS_List" + ControlChars.CrLf + " where 1 = 1 " + ControlChars.CrLf; using (IDbCommand cmd = con.CreateCommand()) { cmd.CommandText = sSQL; Sql.AppendParameter(cmd, sMODULE_NAME, "MODULE_NAME"); if (bDebug) { RegisterClientScriptBlock("SQLCode", Sql.ClientScriptBlock(cmd)); } using (DbDataAdapter da = dbf.CreateDataAdapter()) { ((IDbDataAdapter)da).SelectCommand = cmd; using (DataTable dt = new DataTable()) { da.Fill(dt); // 06/18/2006 Paul. Translate the report type. foreach (DataRow row in dt.Rows) { row["REPORT_TYPE"] = L10n.Term(".dom_report_types.", row["REPORT_TYPE"]); } vwMySaved = new DataView(dt); vwMySaved.RowFilter = "PUBLISHED = 0 and ASSIGNED_USER_ID = '" + Security.USER_ID.ToString() + "'"; grdMySaved.DataSource = vwMySaved; if (!IsPostBack) { grdMySaved.SortColumn = "NAME"; grdMySaved.SortOrder = "asc"; grdMySaved.ApplySort(); grdMySaved.DataBind(); } vwPublished = new DataView(dt); // 05/18/2006 Paul. Lets include unassigned so that they don't get lost. vwPublished.RowFilter = "PUBLISHED = 1 or ASSIGNED_USER_ID is null"; grdPublished.DataSource = vwPublished; if (!IsPostBack) { grdPublished.SortColumn = "NAME"; grdPublished.SortOrder = "asc"; grdPublished.ApplySort(); grdPublished.DataBind(); } } } } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); lblError.Text = ex.Message; } if (!IsPostBack) { // 06/09/2006 Paul. Remove data binding in the user controls. Binding is required, but only do so in the ASPX pages. //Page.DataBind(); } }