/// <summary>
        /// Executes this command against the specified database connection and returns the auto-increment value of the inserted row, or null if it is not an
        /// auto-increment table.
        /// </summary>
        public object Execute( DBConnection cn )
        {
            var cmd = cn.DatabaseInfo.CreateCommand();
            cmd.CommandText = "INSERT INTO " + table;
            if( columnModifications.Count == 0 )
                cmd.CommandText += " DEFAULT VALUES";
            else {
                cmd.CommandText += "( ";
                foreach( var columnMod in columnModifications )
                    cmd.CommandText += columnMod.ColumnName + ", ";
                cmd.CommandText = cmd.CommandText.Substring( 0, cmd.CommandText.Length - 2 );
                cmd.CommandText += " ) VALUES( ";
                foreach( var columnMod in columnModifications ) {
                    var parameter = columnMod.GetParameter();
                    cmd.CommandText += parameter.GetNameForCommandText( cn.DatabaseInfo ) + ", ";
                    cmd.Parameters.Add( parameter.GetAdoDotNetParameter( cn.DatabaseInfo ) );
                }
                cmd.CommandText = cmd.CommandText.Substring( 0, cmd.CommandText.Length - 2 );
                cmd.CommandText += " )";
            }
            cn.ExecuteNonQueryCommand( cmd );

            if( !cn.DatabaseInfo.LastAutoIncrementValueExpression.Any() )
                return null;
            var autoIncrementRetriever = cn.DatabaseInfo.CreateCommand();
            autoIncrementRetriever.CommandText = "SELECT {0}".FormatWith( cn.DatabaseInfo.LastAutoIncrementValueExpression );
            var autoIncrementValue = cn.ExecuteScalarCommand( autoIncrementRetriever );
            return autoIncrementValue != DBNull.Value ? autoIncrementValue : null;
        }
 public List<String> getListOfForums()
 {
     DBConnection myConnection = new DBConnection();
     myConnection.connect("LILY-PC", "projectdb1", "admin", "123");
     String query = "SELECT f_title FROM [projectdb1].[dbo].[Forum]";
     return myConnection.getResultsList(query, "f_title");
 }
Exemplo n.º 3
0
        public Company Get(int id, string lang)
        {
            DBConnection dbConnection = new DBConnection(lang);
            company = dbConnection.GetCompanyById(id);
            //company.licenceList = new List<Licence>();

            //if (company != null && company.company_id > 0)
            //{
            //    var licenceList = dbConnection.GetAllLicenceByCompanyId(company.company_id, "active");
            //    if (licenceList != null && licenceList.Count > 0)
            //    {
            //       company.licenceList = licenceList;

            //        foreach (var licence in company.licenceList)
            //        {
            //            licence.deviceList = new List<Device>();
            //            //Get Device
            //            var deviceList = dbConnection.GetAllDevice("", "", licence.original_licence_no);
            //            if (deviceList != null && deviceList.Count > 0)
            //            {
            //                licence.deviceList = deviceList;
            //            }
            //        }
            //    }
            //}
            return company;
        }
Exemplo n.º 4
0
 public Artist GetArtistById(int? id)
 {
     using (var db = new DBConnection())
     {
         return db.Artists.FirstOrDefault(x => x.id == id);
     }
 }
Exemplo n.º 5
0
 private bool CheckEEP_ExecutingServiceStateTable(string sProjectID)
 {
     bool blExistence = false;
     DBConnection cDBConnection;
     try
     {
         cDBConnection = new DBConnection();
         DataTable dtt = new DataTable();
         DataRow[] dtwSelection;
         string cmdSQL = "select name from SysObjects order by name";
         dtt = cDBConnection.execDataTable(cmdSQL, gsEEPDB);
         dtwSelection = dtt.Select("name = 'EEP_ExecutingServiceState'");
         switch (dtwSelection.Length)
         {
             case 1: // have being the table.
                 blExistence = true;
                 gLogger.Trace("已經有EEP_ExecutingServiceState的Table");
                 break;
             case 0://Create a new table
                 cmdSQL = "CREATE TABLE dbo.EEP_ExecutingServiceState (ProjectID NVARCHAR (50) NOT NULL, ServiceName NVARCHAR (50) NOT NULL, RecTime DATETIME NOT NULL, AlarmIntervalMinute INT NOT NULL, CONSTRAINT PK_EEP_ExecutingServiceState PRIMARY KEY (ProjectID, ServiceName));";
                 //cmdSQL = string.Format("CREATE TABLE [dbo].[RMC_HistoryData_{0}_{1}]([EquipmentID] [nvarchar](50) NULL, [PointID] [nvarchar](50) NULL, [PointValue] [nvarchar](50) NULL, [RecTime] [datetime] NULL) ON [PRIMARY]", sProjectID, DateTime.Now.ToString("yyyyMM"));
                 cDBConnection.execNonQuery(cmdSQL, gsEEPDB);
                 blExistence = true;
                 gLogger.Trace("產生新的EEP_ExecutingServiceState的Table");
                 break;
         }
     }
     catch (Exception ex)
     {
         gLogger.ErrorException("UpdateServiceTime.CheckEEP_ExecutingServiceStateTable", ex);
     }
     return blExistence;
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            DBConnection bindComboBox = new DBConnection();
            City cities = new City();
            DataTable DT = new DataTable();
            DT = bindComboBox.BindDropdown(cities.SearchCities(), "City_Name", "City_Number");
            CityDDL.DataSource = DT;
            CityDDL.DataValueField = "City_Number";
            CityDDL.DataTextField = "City_Name";

            CityDDL.DataBind();

            GenderDDL.Items.Add("Male");
            GenderDDL.Items.Add("Female");

            //EmployeeType
            EmployeeType empType = new EmployeeType();
            DT = bindComboBox.BindDropdown(empType.SearchEmployeeTypes(), "Employee_Type_Name", "Employee_Type_Number");

            EmployeeTypeDDL.DataSource = DT;
            EmployeeTypeDDL.DataValueField = "Employee_Type_Name";
            EmployeeTypeDDL.DataTextField = "Employee_Type_Number";

            EmployeeTypeDDL.DataBind();
        }
 public frmEditFunctionSettings(SpecialFunction _function, DBConnection _dbCon, string _tableName)
 {
     InitializeComponent();
     function = _function;
     dbCon = _dbCon;
     tableName = _tableName;
 }
Exemplo n.º 8
0
        private string gsProjectID = ConfigurationManager.AppSettings.Get("ProjectID"); //從AppConfig讀取「ProjectID」參數

        #endregion Fields

        #region Methods

        /// <summary>
        /// 紀錄WindowServic運作時間
        /// 用來判斷WindowService是否有正常作動
        /// </summary>
        public void Update_Time()
        {
            DBConnection cDBConnection;
            bool blFlag;
            string cmdSQL = string.Empty;
            string sServiceName = gsProjectID + ".ModbusTCP.Adapter(" + gsIP + ":" + gsPort + ")";
            try
            {
                cDBConnection = new DBConnection();
                blFlag = false;
                blFlag = CheckEEP_ExecutingServiceStateTable(gsProjectID);
                if (blFlag == false)
                {
                    gLogger.Error("產生EEP_ExecutingServiceState Table失敗");
                }
                cmdSQL = string.Format("SELECT * FROM EEP_ExecutingServiceState WHERE ProjectID = '{0}' AND ServiceName = '{1}'", gsProjectID, sServiceName);
                DataTable dttExecutingServiceState = cDBConnection.execDataTable(cmdSQL, gsEEPDB);
                if (dttExecutingServiceState.Rows.Count > 0)
                {
                    cmdSQL = string.Format("UPDATE EEP_ExecutingServiceState SET RecTime = '{2}', AlarmIntervalSecond = '{3}' WHERE ProjectID = '{0}' AND ServiceName = '{1}'", gsProjectID, sServiceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), dttExecutingServiceState.Rows[0]["AlarmIntervalSecond"].ToString());
                    cDBConnection.execNonQuery(cmdSQL, gsEEPDB);
                    gLogger.Trace("更新WindowService監控時間成功");
                }
                else
                {
                    cmdSQL = string.Format("INSERT INTO EEP_ExecutingServiceState (ProjectID, ServiceName, RecTime, AlarmIntervalSecond) VALUES ('{0}', '{1}', '{2}', '{3}')", gsProjectID, sServiceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), giSystemRunTimeRecord);
                    cDBConnection.execNonQuery(cmdSQL, gsEEPDB);
                }
            }
            catch (Exception ex)
            {
                gLogger.ErrorException("UpdateServiceTime.Update_Time", ex);
            }
        }
        internal static void Generate(
            DBConnection cn, TextWriter writer, string baseNamespace, Database database, Configuration.SystemDevelopment.Database configuration)
        {
            if( configuration.queries == null )
                return;

            info = cn.DatabaseInfo;
            writer.WriteLine( "namespace " + baseNamespace + "." + database.SecondaryDatabaseName + "Retrieval {" );

            foreach( var query in configuration.queries ) {
                List<Column> columns;
                try {
                    columns = validateQueryAndGetColumns( cn, query );
                }
                catch( Exception e ) {
                    throw new UserCorrectableException( "Column retrieval failed for the " + query.name + " query.", e );
                }

                CodeGenerationStatics.AddSummaryDocComment( writer, "This object holds the values returned from a " + query.name + " query." );
                writer.WriteLine( "public static partial class " + query.name + "Retrieval {" );

                // Write nested classes.
                DataAccessStatics.WriteRowClasses( writer, columns, localWriter => { } );
                writeCacheClass( writer, database, query );

                writer.WriteLine( "private const string selectFromClause = @\"" + query.selectFromClause + " \";" );
                foreach( var postSelectFromClause in query.postSelectFromClauses )
                    writeQueryMethod( writer, database, query, postSelectFromClause );
                writer.WriteLine( "static partial void updateSingleRowCaches( Row row );" );
                writer.WriteLine( "}" ); // class
            }
            writer.WriteLine( "}" ); // namespace
        }
Exemplo n.º 10
0
 public List<Genre> GetAllGenres()
 {
     using (var db = new DBConnection())
     {
         return db.Genres.ToList();
     }
 }
Exemplo n.º 11
0
 public Genre GetGenreById(int? id)
 {
     using (var db = new DBConnection())
     {
         return db.Genres.FirstOrDefault(x => x.id == id);
     }
 }
Exemplo n.º 12
0
        public void FillSession(string usuario)
        {
            DBConnection dbconnectionObj = new DBConnection();
            string query = @"select
            u.id as usuario_id,
            u.usuario as usuario,
            p.id as empleado_id,
            p.num_placa,
            p.nombre as nombre_personal,
            p.delegacion_id
            from
            usuarios as u inner join personal as p on u.empleado_id = p.id
            where u.usuario = @usuario";

            DataTable dt = dbconnectionObj.Select(query,
                new SqlParameter("@usuario", usuario)
                );
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Sesion.usuario_id = int.Parse(row["usuario_id"].ToString());
                    Sesion.empleado_id = int.Parse(row["empleado_id"].ToString());
                    Sesion.nombre_personal = row["nombre_personal"].ToString();
                    Sesion.num_placa = row["num_placa"].ToString();
                    Sesion.delegacion_id = int.Parse(row["delegacion_id"].ToString());
                }
            }
        }
Exemplo n.º 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Get database connection information from DBConnection.cs
            DBConnection conString = new DBConnection();
            string dbConnString;
            conString.MyProperty = "";
            dbConnString = conString.MyProperty;

            //Check all fields from SafeInsert.cs
            SafeInsert safeInsert = new SafeInsert();
            string phoneIn = safeInsert.cityFix(phoneNumberIn.Text);

            try
            {
                MySqlConnection connection = new MySqlConnection(dbConnString);
                connection.Open(); //open connection

                MySqlDataAdapter MyDa = new MySqlDataAdapter();
                string SqlSelectAll = "Select * from customerdetails;";
                MyDa.SelectCommand = new MySqlCommand(SqlSelectAll, connection);

                DataTable table = new DataTable(); //Setup Bindings to attach to DataGrid
                MyDa.Fill(table);
                BindingSource bSource = new BindingSource();
                bSource.DataSource = table;

                //Fill grid
                dgView.DataSource = bSource;
            }

            catch (Exception)
            {
                MessageBox.Show("Error Connecting");
            }
        }
 internal static string GetClassName( DBConnection cn, string table, bool isRevisionHistoryTable, bool isRevisionHistoryClass )
 {
     return
         EwlStatics.GetCSharpSafeClassName(
             isRevisionHistoryTable && !isRevisionHistoryClass
                 ? "Direct" + table.TableNameToPascal( cn ) + "ModificationWithRevisionBypass"
                 : table.TableNameToPascal( cn ) + "Modification" );
 }
Exemplo n.º 15
0
 public void UpdateArtist(Artist artist)
 {
     using (var db = new DBConnection())
     {
         db.Entry(artist).State = EntityState.Modified;
         db.SaveChanges();
     }
 }
Exemplo n.º 16
0
 public void DeleteGenre(int id)
 {
     using (var db = new DBConnection())
     {
         db.Genres.Remove(db.Genres.FirstOrDefault(x=>x.id == id));
         db.SaveChanges();
     }
 }
Exemplo n.º 17
0
 public void Update(Album album)
 {
     using (var db = new DBConnection())
     {
         db.Entry(album).State = EntityState.Modified;
         db.SaveChanges();
     }
 }
Exemplo n.º 18
0
 public void UpdateGenre(Genre genre)
 {
    using (var db = new DBConnection())
     {
         db.Entry(genre).State = EntityState.Modified;
         db.SaveChanges();
     }
 }
Exemplo n.º 19
0
 public void CreateGenre(Genre genre)
 {
     using (var db = new DBConnection())
     {
         db.Genres.Add(genre);
         db.SaveChanges();
     }
 }
Exemplo n.º 20
0
 public void CreateAlbum(Album album)
 {
     using (var db = new DBConnection())
     {
         db.Albums.Add(album);
         db.SaveChanges();
     }
 }
        public void FirstConnectToDBTest()
        {
            DBConnection dbConnection = new DBConnection();

            var connectionSuccessFlag = dbConnection.ConnectToDB();
            Assert.AreEqual(true, connectionSuccessFlag);
            Assert.AreEqual(true, dbConnection.IsConnectedToDB);
        }
Exemplo n.º 22
0
 private void btnCreateConnection_Click(object sender, EventArgs e)
 {
     DBConnection con = new DBConnection((string)cboxServ.SelectedItem, (string)cboxDatabase.SelectedItem, txtUser.Text, txtPass.Text);
     frmManagerMain main = new frmManagerMain(con);
     this.Hide();
     main.ShowDialog();
     this.Show();
 }
 public String getForumID(String forumName)
 {
     List<String> myList = new List<string>();
     DBConnection myConnection = new DBConnection();
     myConnection.connect("LILY-PC", "projectdb1", "admin", "123");
     String query = String.Format("SELECT f_id FROM [projectdb1].[dbo].[Forum] WHERE f_title = '{0}'", forumName);
     myList = myConnection.getResultsList(query, "f_id");
     return myList.First();
 }
 public DataTable getInfo(String id)
 {
     DataTable myTable = new DataTable();
     DBConnection myConnection = new DBConnection();
     myConnection.connect("LILY-PC", "projectdb1", "admin", "123");
     String query = String.Format("SELECT c.f_name AS 'First Name' ,c.m_name AS 'Middle Name', c.l_name AS 'Last Name', c.prs_email AS 'Personal Email', c.company AS 'Company',c.cmp_add_no AS 'C.A.No',c.cmp_add_street AS 'C.A.St',c.cmp_add_town AS 'C.A.tw',c.cmp_email AS 'Cm.Email',p.phone AS 'Pers Phone',b.phone AS 'Bus Phone'  FROM Manager AS c, PrsPhone AS p, BusPhone AS b WHERE c.u_id=p.u_id AND c.u_id=b.u_id AND c.u_id={0}", id);
     myTable = myConnection.executeReturningQuery(query);
     return myTable;
 }
 public DataTable getCV(String id)
 {
     DataTable myTable = new DataTable();
     DBConnection myConnection = new DBConnection();
     myConnection.connect("LILY-PC", "projectdb1", "admin", "123");
     String query = String.Format("SELECT c.f_name AS 'First Name' ,c.m_name AS 'Middle Name', c.l_name AS 'Last Name', c.dob AS 'Date of Birth', c.age AS 'Age', c.gender AS 'Gender', c.maritual_status AS 'Marital Status', c.add_no AS 'Number',c.add_street AS 'Street', c.add_town AS 'Town',c.email AS 'Email', p.phone AS 'Phone', s.school AS 'School'  FROM [Candidate] AS c, PrsPhone AS p, CanSchool AS s WHERE c.u_id=p.u_id AND c.u_id=s.u_id AND c.u_id={0}", id);
     myTable = myConnection.executeReturningQuery(query);
     return myTable;
 }
        internal TableColumns( DBConnection cn, string table, bool forRevisionHistoryLogic )
        {
            try {
                // NOTE: Cache this result.
                AllColumns = Column.GetColumnsInQueryResults( cn, "SELECT * FROM " + table, true );

                foreach( var col in AllColumns ) {
                    // This hack allows code to be generated against a database that is configured for ASP.NET Application Services.
                    var isAspNetApplicationServicesTable = table.StartsWith( "aspnet_" );

                    if( !( cn.DatabaseInfo is OracleInfo ) && col.DataTypeName == typeof( string ).ToString() && col.AllowsNull && !isAspNetApplicationServicesTable )
                        throw new UserCorrectableException( "String column " + col.Name + " allows null, which is not allowed." );
                }

                // Identify key, identity, and non identity columns.
                var nonIdentityColumns = new List<Column>();
                foreach( var col in AllColumns ) {
                    if( col.IsKey )
                        keyColumns.Add( col );
                    if( col.IsIdentity ) {
                        if( identityColumn != null )
                            throw new UserCorrectableException( "Only one identity column per table is supported." );
                        identityColumn = col;
                    }
                    else
                        nonIdentityColumns.Add( col );
                }
                if( !keyColumns.Any() )
                    throw new UserCorrectableException( "The table must contain a primary key or other means of uniquely identifying a row." );

                // If the table has a composite key, try to use the identity as the key instead since this will enable InsertRow to return a value.
                if( identityColumn != null && keyColumns.Count > 1 ) {
                    keyColumns.Clear();
                    keyColumns.Add( identityColumn );
                }

                RowVersionColumn = AllColumns.SingleOrDefault( i => i.IsRowVersion );
                AllColumnsExceptRowVersion = AllColumns.Where( i => !i.IsRowVersion ).ToArray();
                AllNonIdentityColumnsExceptRowVersion = nonIdentityColumns.Where( i => !i.IsRowVersion ).ToArray();

                if( forRevisionHistoryLogic ) {
                    if( keyColumns.Count != 1 ) {
                        throw new UserCorrectableException(
                            "A revision history modification class can only be created for tables with exactly one primary key column, which is assumed to also be a foreign key to the revisions table." );
                    }
                    primaryKeyAndRevisionIdColumn = keyColumns.Single();
                    if( primaryKeyAndRevisionIdColumn.IsIdentity )
                        throw new UserCorrectableException( "The revision ID column of a revision history table must not be an identity." );
                }

                dataColumns = AllColumns.Where( col => !col.IsIdentity && !col.IsRowVersion && col != primaryKeyAndRevisionIdColumn ).ToArray();
            }
            catch( Exception e ) {
                throw UserCorrectableException.CreateSecondaryException( "An exception occurred while getting columns for table " + table + ".", e );
            }
        }
Exemplo n.º 27
0
 public DataTable Get()
 {
     DataTable dt = new DataTable();
     DBConnection dbconnectionObj = new DBConnection();
     string query = @"
     select id, nombre from roles
     ";
     dt = dbconnectionObj.Select(query, null);
     return dt;
 }
Exemplo n.º 28
0
 public bool Exists(string usuario)
 {
     DataTable dt = new DataTable();
     DBConnection dbconnectionObj = new DBConnection();
     string query = @"select id from usuarios where usuario = @usuario";
     dt = dbconnectionObj.Select(query,
         new SqlParameter("@usuario", usuario)
         );
     return dt.Rows.Count > 0 ? true : false;
 }
Exemplo n.º 29
0
 protected void VehicleDDL_SelectedIndexChanged(object sender, EventArgs e)
 {
     DBConnection db = new DBConnection();
     ClientVehicle ClientV = new ClientVehicle();
     DateDDL.DataTextField = "Project_StartDateTime";
     DateDDL.DataValueField = "Project_Number";
     DateDDL.DataSource = db.BindDropdown("SELECT Project.Project_Number, Project.Project_StartDateTime, Project.Project_TotalCost FROM Project WHERE Client_Vehicle_Number = " + VehicleDDL.SelectedItem.Value, "Project_StartDateTime", "Project_Number");
     DateDDL.DataBind();
     DateDDL.Items.Insert(0, "");
 }
        internal static void Generate( DBConnection cn, TextWriter writer, string baseNamespace, Database database )
        {
            writer.WriteLine( "namespace " + baseNamespace + " {" );
            writer.WriteLine( "public static class " + database.SecondaryDatabaseName + "Procedures {" );
            foreach( var procedure in database.GetProcedures() ) {
                var parameters = database.GetProcedureParameters( procedure );

                // header
                CodeGenerationStatics.AddSummaryDocComment( writer, "Executes the " + procedure + " procedure." );
                var parameterDeclarations =
                    parameters.Select(
                        i => ( i.Direction == ParameterDirection.Output ? "out " : i.Direction == ParameterDirection.InputOutput ? "ref " : "" ) + i.DataTypeName + " " + i.Name );
                writer.WriteLine( "public static void " + procedure + "( " + StringTools.ConcatenateWithDelimiter( ", ", parameterDeclarations.ToArray() ) + " ) {" );

                // body
                writer.WriteLine( "var cmd = new SprocExecution( \"" + procedure + "\" );" );
                foreach( var parameter in parameters ) {
                    if( parameter.Direction == ParameterDirection.Input )
                        writer.WriteLine( "cmd.AddParameter( " + getDbCommandParameterCreationExpression( parameter ) + " );" );
                    else {
                        writer.WriteLine( "var " + parameter.Name + "Parameter = " + getDbCommandParameterCreationExpression( parameter ) + ";" );
                        writer.WriteLine(
                            parameter.Name + "Parameter.GetAdoDotNetParameter( " + DataAccessStatics.GetConnectionExpression( database ) +
                            ".DatabaseInfo ).Direction = ParameterDirection." + parameter.Direction + ";" );
                        writer.WriteLine( "cmd.AddParameter( " + parameter.Name + "Parameter );" );
                    }
                }
                foreach( var parameter in parameters.Where( parameter => parameter.Direction != ParameterDirection.Input ) )
                    writer.WriteLine( parameter.DataTypeName + " " + parameter.Name + "Local = default( " + parameter.DataTypeName + " );" );
                writer.WriteLine( "cmd.ExecuteReader( " + DataAccessStatics.GetConnectionExpression( database ) + ", r => {" );
                foreach( var parameter in parameters.Where( parameter => parameter.Direction != ParameterDirection.Input ) ) {
                    var adoDotNetParameterValueExpression = "{0}Parameter.GetAdoDotNetParameter( {1}.DatabaseInfo ).Value".FormatWith(
                        parameter.Name,
                        DataAccessStatics.GetConnectionExpression( database ) );

                    // We are not sure if this is handling null correctly. When a null comes back via an "out" parameter, we're not sure whether it is represented with
                    // DBNull.Value or in another way. This issue can be resolved as soon as we have a system with stored procedures that we can use for testing.

                    // NOTE: This is a hack. We would like to use a simple cast to convert the value of the database parameter to the method parameter's type, but we
                    // can't because the types in Oracle.DataAccess.Types, like OracleDecimal, do not support any kind of conversion to .NET types when they are boxed.
                    writer.WriteLine(
                        "{0}Local = {1};".FormatWith(
                            parameter.Name,
                            parameter.GetIncomingValueConversionExpression(
                                "EwlStatics.ChangeType( {0}.ToString(), typeof( {1} ) )".FormatWith( adoDotNetParameterValueExpression, parameter.UnconvertedDataTypeName ) ) ) );
                    //writer.WriteLine( "{0}Local = {1};".FormatWith( parameter.Name, parameter.GetIncomingValueConversionExpression( adoDotNetParameterValueExpression ) ) );
                }
                writer.WriteLine( "} );" );
                foreach( var parameter in parameters.Where( parameter => parameter.Direction != ParameterDirection.Input ) )
                    writer.WriteLine( parameter.Name + " = " + parameter.Name + "Local;" );
                writer.WriteLine( "}" );
            }
            writer.WriteLine( "}" );
            writer.WriteLine( "}" );
        }
Exemplo n.º 31
0
        public static void delObject(
            string sessionGuid_in,
            string ip_forLogPurposes_in,

            long idAuthor_in,

            out int[] errors_out
            )
        {
            List <int>  _errorlist;
            Guid        _sessionguid;
            Sessionuser _sessionuser;

            #region check...
            if (!SBO_CRD_Authentication.isSessionGuid_valid(
                    sessionGuid_in,
                    ip_forLogPurposes_in,
                    out _sessionguid,
                    out _sessionuser,
                    out _errorlist,
                    out errors_out
                    ))
            {
                //// no need!
                //errors_out = _errors.ToArray();

                return;
            }
            #endregion
            #region check Permissions...
            if (
                !_sessionuser.hasPermission(
                    PermissionType.Author__delete
                    )
                )
            {
                _errorlist.Add(ErrorType.author__lack_of_permissions_to_delete);
                errors_out = _errorlist.ToArray();
                return;
            }
            #endregion
            #region check existence...
            SO_NWS_Author _author;
            if (
                idAuthor_in <= 0
                ||
                (
                    (_author = DO_NWS_Author.getObject(
                         idAuthor_in
                         )) == null
                )
                )
            {
                _errorlist.Add(ErrorType.data__not_found);
                errors_out = _errorlist.ToArray();
                return;
            }
            #endregion
            #region check Permissions... (more)
            if (
                // is approved
                (
                    !_author.IFUser__Approved_isNull
                    ||
                    !_author.Approved_date_isNull
                )
                &&
                // and no permission to approve
                !_sessionuser.hasPermission(
                    PermissionType.Author__approve
                    )
                )
            {
                _errorlist.Add(ErrorType.author__lack_of_permissions_to_delete_approved);
                errors_out = _errorlist.ToArray();
                return;
            }
            #endregion
            #region check References...
            if (
                (DO_NWS_ContentAuthor.getCount_inRecord_byAuthor(
                     idAuthor_in
                     ) > 0)
                )
            {
                _errorlist.Add(ErrorType.data__constraint_violation);
                errors_out = _errorlist.ToArray();
                return;
            }
            #endregion

            Exception _exception = null;
            #region DBConnection _con = DO__Utilities.DBConnection_createInstance(...);
            DBConnection _con = DO__Utilities.DBConnection_createInstance(
                DO__Utilities.DBServerType,
                DO__Utilities.DBConnectionstring,
                DO__Utilities.DBLogfile
                );
            #endregion
            try {
                //_con.Open();
                //_con.Transaction.Begin();

                DO_NWS_Author.delObject(
                    idAuthor_in,

                    _con
                    );

                _errorlist.Add(ErrorType.author__successfully_deleted__WARNING);

                #region _con.Transaction.Commit();
                if (
                    _con.IsOpen
                    &&
                    _con.Transaction.InTransaction
                    )
                {
                    _con.Transaction.Commit();
                }
                #endregion
            } catch (Exception _ex) {
                #region _con.Transaction.Rollback();
                if (
                    _con.IsOpen
                    &&
                    _con.Transaction.InTransaction
                    )
                {
                    _con.Transaction.Rollback();
                }
                #endregion

                _exception = _ex;
            } finally {
                #region _con.Transaction.Terminate(); _con.Close(); _con.Dispose();
                if (_con.IsOpen)
                {
                    if (_con.Transaction.InTransaction)
                    {
                        _con.Transaction.Terminate();
                    }
                    _con.Close();
                }

                _con.Dispose();
                #endregion
            }
            if (_exception != null)
            {
                #region SBO_LOG_Log.Log(ErrorType.data);
                OGen.NTier.Kick.Libraries.BusinessLayer.SBO_LOG_Log.log(
                    _sessionuser,
                    LogType.error,
                    ErrorType.data,
                    -1L,
                    _sessionuser.IDApplication,
                    "{0}",
                    new string[] {
                    _exception.Message
                }
                    );
                #endregion
                _errorlist.Add(ErrorType.data);
            }

            errors_out = _errorlist.ToArray();
        }
    protected void SubmitButton_Click(object sender, System.EventArgs e)
    {
        if (!IsValid)
        {
            return;
        }

        MainDataSet.Tables["Users"].Rows[0]["Email"]            = EmailAddress.Text;
        MainDataSet.Tables["Users"].Rows[0]["FirstName"]        = FirstName.Text;
        MainDataSet.Tables["Users"].Rows[0]["LastName"]         = LastName.Text;
        MainDataSet.Tables["Users"].Rows[0]["CompanyName"]      = CompanyName.Text;
        MainDataSet.Tables["Users"].Rows[0]["Address"]          = Address.Text;
        MainDataSet.Tables["Users"].Rows[0]["City"]             = City.Text;
        MainDataSet.Tables["Users"].Rows[0]["State"]            = State.Text;
        MainDataSet.Tables["Users"].Rows[0]["Zip"]              = Zip.Text;
        MainDataSet.Tables["Users"].Rows[0]["Country"]          = ddlCountries.SelectedItem.Text;
        MainDataSet.Tables["Users"].Rows[0]["PrimaryTelephone"] = PrimaryTelephone.Text;
        MainDataSet.Tables["Users"].Rows[0]["EveningTelephone"] = EveningTelephone.Text;
        MainDataSet.Tables["Users"].Rows[0]["DaytimeTelephone"] = DaytimeTelephone.Text;
        MainDataSet.Tables["Users"].Rows[0]["MobileTelephone"]  = MobileTelephone.Text;
        MainDataSet.Tables["Users"].Rows[0]["dateModified"]     = DateTime.Today.ToString();

        if (Website.Text.Length > 0)
        {
            if (!Website.Text.StartsWith("http://"))
            {
                Website.Text = "http://" + Website.Text;
            }
            MainDataSet.Tables["Users"].Rows[0]["Website"] = Website.Text;
        }
        else
        {
            MainDataSet.Tables["Users"].Rows[0]["Website"] = "";
        }

        MainDataSet.Tables["Users"].Rows[0]["Registered"]        = Registered.Text;
        MainDataSet.Tables["Users"].Rows[0]["IfPayTravelAgents"] = PayTravelAgents.Checked;

        int referredby = -1;

        try
        {
            referredby = Convert.ToInt32(Agents.SelectedValue);
        }
        catch (Exception)
        {
        }
        if (referredby != -1)
        {
            MainDataSet.Tables["Users"].Rows[0]["ReferredByID"] = referredby;
        }
        else
        {
            MainDataSet.Tables["Users"].Rows[0]["ReferredByID"] = DBNull.Value;
        }

        if (ReservationSame.Checked)
        {
            MainDataSet.Tables["Users"].Rows[0]["IfReservationSame"]    = true;
            MainDataSet.Tables["Users"].Rows[0]["ReservationEmail"]     = MainDataSet.Tables["Users"].Rows[0]["Email"];
            MainDataSet.Tables["Users"].Rows[0]["ReservationFirstName"] = MainDataSet.Tables["Users"].Rows[0]["FirstName"];
            MainDataSet.Tables["Users"].Rows[0]["ReservationLastName"]  = MainDataSet.Tables["Users"].Rows[0]["LastName"];
        }
        else
        {
            MainDataSet.Tables["Users"].Rows[0]["IfReservationSame"]    = false;
            MainDataSet.Tables["Users"].Rows[0]["ReservationEmail"]     = ReservationEmail.Text;
            MainDataSet.Tables["Users"].Rows[0]["ReservationFirstName"] = ReservationFirstName.Text;
            MainDataSet.Tables["Users"].Rows[0]["ReservationLastName"]  = ReservationLastName.Text;
        }

        if (AuthenticationManager.IfAdmin && IfAdmin.Visible)
        {
            MainDataSet.Tables["Users"].Rows[0]["IfAdmin"] = IfAdmin.Items[IfAdmin.SelectedIndex].Text == "Yes";
        }


        DBConnection obj = new DBConnection();
        DataTable    dt  = new DataTable();

        try
        {
//lock (CommonFunctions.Connection)
            MainAdapter.Update(MainDataSet, "Users");

            dt = VADBCommander.NewsletterListByEmail(EmailAddress.Text);
            if (dt.Rows.Count == 0)
            {
                string strFullName = FirstName.Text + " " + LastName.Text;
                VADBCommander.NewsLetterEmailShortAdd(EmailAddress.Text, strFullName);
            }
        }
        catch (Exception ex) { lblInfo.Text = ex.Message; }
        finally { obj.CloseConnection(); }

        Response.Redirect(CommonFunctions.PrepareURL("listings.aspx"));
    }
Exemplo n.º 33
0
 private void mostrarInventarioToolStripMenuItem_Click(object sender, EventArgs e)
 {
     dgvResultados.DataSource = DBConnection.GetItemStock();
 }
Exemplo n.º 34
0
        public static void update(Guid id, Guid gradeID, Guid productID, Guid productWidthID, Guid lengthUnitID, Guid colorID, int qty, int orderLotQty, string poNotes, string notes)
        {
            InventoryStockLevel objOld = new InventoryStockLevel(id);

            //generate log description
            string  logDescription = "";
            Product product        = new Product(productID);

            if (objOld.ProductStoreNameID != product.StoreNameID)
            {
                logDescription = Tools.append(logDescription, String.Format("Product Store Name: '{0}' to '{1}'", objOld.ProductStoreName, product.StoreName), ",");
            }
            if (objOld.GradeID != gradeID)
            {
                logDescription = Tools.append(logDescription, String.Format("Grade: '{0}' to '{1}'", objOld.GradeID, new Grade(gradeID).Name), ",");
            }
            if (objOld.ProductWidthID != productWidthID)
            {
                logDescription = Tools.append(logDescription, String.Format("Product Width: '{0}' to '{1}'", objOld.ProductWidthName, new ProductWidth(productWidthID).Name), ",");
            }
            if (objOld.LengthUnitID != lengthUnitID)
            {
                logDescription = Tools.append(logDescription, String.Format("Length Unit: '{0}' to '{1}'", objOld.LengthUnitID, new LengthUnit(lengthUnitID).Name), ",");
            }
            if (objOld.VendorName != product.VendorName)
            {
                logDescription = Tools.append(logDescription, String.Format("Vendor: '{0}' to '{1}'", objOld.VendorName, product.VendorName), ",");
            }
            if (objOld.OrderLotQty != orderLotQty)
            {
                logDescription = Tools.append(logDescription, String.Format("Lot qty: '{0}' to '{1}'", objOld.OrderLotQty, orderLotQty), ",");
            }
            if (objOld.Qty != qty)
            {
                logDescription = Tools.append(logDescription, String.Format("Qty: '{0}' to '{1}'", objOld.Qty, qty), ",");
            }
            if (objOld.PONotes != poNotes)
            {
                logDescription = Tools.append(logDescription, String.Format("PO Notes: '{0}' to '{1}'", objOld.PONotes, poNotes), ",");
            }
            if (objOld.Notes != notes)
            {
                logDescription = Tools.append(logDescription, String.Format("Notes: '{0}' to '{1}'", objOld.Notes, notes), ",");
            }

            if (!string.IsNullOrEmpty(logDescription))
            {
                SqlQueryResult result = DBConnection.query(
                    false,
                    DBConnection.ActiveSqlConnection,
                    QueryTypes.ExecuteNonQuery,
                    "inventorystocklevel_update",
                    new SqlQueryParameter(COL_DB_ID, SqlDbType.UniqueIdentifier, id),
                    new SqlQueryParameter(COL_DB_GRADEID, SqlDbType.UniqueIdentifier, gradeID),
                    new SqlQueryParameter(COL_DB_PRODUCTID, SqlDbType.UniqueIdentifier, productID),
                    new SqlQueryParameter(COL_DB_PRODUCTWIDTHID, SqlDbType.UniqueIdentifier, productWidthID),
                    new SqlQueryParameter(COL_DB_LENGTHUNITID, SqlDbType.UniqueIdentifier, lengthUnitID),
                    new SqlQueryParameter(COL_DB_COLORID, SqlDbType.UniqueIdentifier, colorID),
                    new SqlQueryParameter(COL_DB_ORDERLOTQTY, SqlDbType.Int, orderLotQty),
                    new SqlQueryParameter(COL_DB_QTY, SqlDbType.Int, qty),
                    new SqlQueryParameter(COL_DB_PONOTES, SqlDbType.VarChar, Util.wrapNullable(poNotes)),
                    new SqlQueryParameter(COL_DB_NOTES, SqlDbType.VarChar, Util.wrapNullable(notes))
                    );

                if (result.IsSuccessful)
                {
                    ActivityLog.submitUpdate(id, logDescription);
                }
            }
        }
Exemplo n.º 35
0
    public static ReturnObject AddShift(string current)
    {
        masters_manage_shift page_object   = new masters_manage_shift();
        DBConnection         db_connection = new DBConnection();
        ReturnObject         return_object = new ReturnObject();
        string shift_code = string.Empty;
        string shift_name = string.Empty;
        int    count      = 0;

        if (HttpContext.Current.Session["username"] == null)  // checking session expired or not
        {
            return_object = page_object.DoLogout();
        }
        else
        {
            try
            {
                JObject current_data = JObject.Parse(current);
                shift_code = current_data["shift_code"].ToString();
                shift_name = current_data["shift_desc"].ToString();

                count = page_object.CheckShiftCode(shift_code);
                if (count > 0)
                {
                    return_object.status      = "error";
                    return_object.return_data = "Shift Code has been taken. Please try again with a different Code.";

                    return(return_object);
                }

                count = page_object.CheckShiftName(shift_name);
                if (count > 0)
                {
                    return_object.status      = "error";
                    return_object.return_data = "Shift Name has been taken. Please try again with a different Name.";

                    return(return_object);
                }

                page_object.UpdateDatabase(current_data, "I");

                return_object.status      = "success";
                return_object.return_data = "Shift added successfully!";
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, page, "ADD_SHIFT");

                return_object.status      = "error";
                return_object.return_data = "An error occurred while saving Shift details. Please try again. If the error persists, please contact Support.";

                throw;
            }
            finally
            {
                page_object.Dispose();
            }
        }

        return(return_object);
    }
Exemplo n.º 36
0
    private void PrepareDataForExport(string filters, string branches)
    {
        DBConnection db_connection     = new DBConnection();
        Hashtable    filter_conditions = new Hashtable();
        JObject      filters_data      = new JObject();
        JArray       branch_data       = new JArray();

        string
            from_date, to_date, user_name,
            employee_name, employee_id, current_user_id,
            where_clause = string.Empty, company_name, category_name, employee_status,
            department_name, shift_name, branch_list = string.Empty;

        int
            user_access_level, i = 0;

        filters_data    = JObject.Parse(filters);
        company_name    = filters_data["company_name"].ToString();
        department_name = filters_data["department"].ToString();
        shift_name      = filters_data["shift"].ToString();
        category_name   = filters_data["category"].ToString();
        employee_status = filters_data["status"].ToString();
        employee_id     = filters_data["employee_id"].ToString();
        employee_name   = filters_data["employee_name"].ToString();

        from_date = DateTime.ParseExact(filters_data["from_date"].ToString(), "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
        to_date   = DateTime.ParseExact(filters_data["to_date"].ToString(), "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

        // Get current logged in user data from the Session variable
        user_name         = HttpContext.Current.Session["username"].ToString();
        user_access_level = Convert.ToInt32(HttpContext.Current.Session["access_level"]);
        current_user_id   = HttpContext.Current.Session["employee_id"].ToString();

        // process branch IDs
        branch_data = JArray.Parse(branches);
        for (i = 0; i < branch_data.Count; i++)
        {
            branch_list += "'" + branch_data[i].ToString() + "',";
        }

        where_clause += " where m.punchdate between '" + from_date + "' and '" + to_date + "' ";

        if (company_name != "select")
        {
            // where_clause = where_clause + " and c.Companyname = '" + company_name + "'";

            if (!string.IsNullOrEmpty(branch_list))
            {
                branch_list  = branch_list.Remove(branch_list.Length - 1, 1);
                where_clause = where_clause + " and b.branchname in (" + branch_list + ")";
            }

            if (department_name != "select")
            {
                where_clause = where_clause + " and d.DeptName = '" + department_name + "'";
            }

            if (shift_name != "select")
            {
                where_clause = where_clause + " and s.Shift_Desc = '" + shift_name + "'";
            }


            if (category_name != "select")
            {
                where_clause = where_clause + " and ecm.EmpCategoryName='" + category_name + "'";
            }

            // Checking to see if an employee ID has been selected in the filters.
            if (employee_id != "") // If YES then we pull results only for the selected employee ID.
            {
                where_clause = where_clause + " and m.EmpId = '" + employee_id + "'";
            }
            else
            {
                where_clause += " and m.EmpId in (select EmpID from [FetchEmployees] ('" + current_user_id + "','" + employee_status + "'))";
            }
            if (employee_name != "")
            {
                where_clause = where_clause + " and e.Emp_Name like '%" + employee_name + "%'";
            }

            filter_conditions.Add("where", where_clause);

            db_connection.ExecuteStoredProcedureWithHashtable_WithoutReturn("DailyPunchReport1", filter_conditions);
        }
    }
Exemplo n.º 37
0
        private void DeliverRecordDatabaseExecute()
        {
            int succ = 0;

            try
            {
                DBConnection.OpenConnection();

                DBConnection.cmd.CommandType = CommandType.StoredProcedure;
                DBConnection.cmd.CommandText = "sp_insertFollowUP";


                #region create Parameters
                DBConnection.cmd.Parameters.Add(new SqlParameter("@DecisionNO", SqlDbType.BigInt));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@LastConnection", SqlDbType.DateTime));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@Notice", SqlDbType.NText));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@Comment", SqlDbType.NText));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@ReceivedDate", SqlDbType.Date));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@VisitDate", SqlDbType.Date));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@DeliverDate", SqlDbType.Date));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@Distance", SqlDbType.TinyInt));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@FStatus", SqlDbType.TinyInt));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@Scribe_ssn", SqlDbType.BigInt));
                DBConnection.cmd.Parameters.Add(new SqlParameter("@Observer_ssn", SqlDbType.BigInt));


                DBConnection.cmd.Parameters.Add(new SqlParameter("@Success", SqlDbType.Int));
                #endregion

                #region set value in parameters
                DBConnection.cmd.Parameters["@DecisionNO"].Value     = long.Parse(DecisionNO);
                DBConnection.cmd.Parameters["@LastConnection"].Value = DBNull.Value;
                DBConnection.cmd.Parameters["@Notice"].Value         = DBNull.Value;
                DBConnection.cmd.Parameters["@Comment"].Value        = DBNull.Value;
                DBConnection.cmd.Parameters["@ReceivedDate"].Value   = ReceivedDate;
                DBConnection.cmd.Parameters["@VisitDate"].Value      = DBNull.Value;
                DBConnection.cmd.Parameters["@DeliverDate"].Value    = DBNull.Value;

                DBConnection.cmd.Parameters["@Distance"].Value = Distance;
                DBConnection.cmd.Parameters["@FStatus"].Value  = 0;

                DBConnection.cmd.Parameters["@Scribe_ssn"].Value   = Properties.Settings.Default.EmpNo;
                DBConnection.cmd.Parameters["@Observer_ssn"].Value = employee.Ssn;



                #endregion

                DBConnection.cmd.Parameters["@Success"].Direction = ParameterDirection.Output;

                DBConnection.cmd.ExecuteNonQuery();

                succ = (int)DBConnection.cmd.Parameters["@Success"].Value;

                #region messge box
                // It Was Stored in Database
                if (succ == 1)
                {
                    MessageBox.Show("تم تحويل المحضر للمتابعة بنجاح", "", MessageBoxButton.OK, MessageBoxImage.None,
                                    MessageBoxResult.OK, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
                }
                //record is not exist
                else if (succ == 2)
                {
                    MessageBox.Show("رقم المحضر غير موجود", "", MessageBoxButton.OK, MessageBoxImage.Error,
                                    MessageBoxResult.OK, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
                }
                // follow up Already exist
                else if (succ == 3)
                {
                    MessageBox.Show("المحظر حول للمتابعة بالفعل", "", MessageBoxButton.OK, MessageBoxImage.Error,
                                    MessageBoxResult.OK, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
                }
                // EMPLOYEE is not exist
                else if (succ == 4)
                {
                    MessageBox.Show("رقم المتابع غير موجود", "", MessageBoxButton.OK, MessageBoxImage.Error,
                                    MessageBoxResult.OK, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
                }
                // It is not Stored in Database
                else
                {
                    MessageBox.Show("لم يتم  تحويل المحضر للمتابعة الرجاء التاكد من البيانات", "", MessageBoxButton.OK, MessageBoxImage.Error,
                                    MessageBoxResult.OK, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("لم يتم  تحويل المحضر للمتابعة الرجاء التاكد من الاتصال بالسيرفر" + Environment.NewLine + "الخطأ : " + ex.Message.ToString(), "", MessageBoxButton.OK, MessageBoxImage.Error,
                                MessageBoxResult.OK, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
            }
            finally
            {
                DBConnection.CloseConnection();
            }
        }
 public LocationsController(DBConnection context)
 {
     _context = context;
 }
Exemplo n.º 39
0
    public static ReturnObject DeleteHoliday(string current)
    {
        masters_holiday page_object   = new masters_holiday();
        DBConnection    db_connection = new DBConnection();
        ReturnObject    return_object = new ReturnObject();
        string          query         = string.Empty;
        int             count         = 0;

        string
            company_code       = string.Empty,
            holiday_group_code = string.Empty,
            holiday_code       = string.Empty,
            holiday_from       = string.Empty,
            holiday_to         = string.Empty,
            holiday_type       = string.Empty;

        if (HttpContext.Current.Session["username"] == null)  // checking session expired or not
        {
            return_object = page_object.DoLogout();
        }
        else
        {
            try
            {
                JObject current_data = JObject.Parse(current);
                holiday_code = current_data["holiday_code"].ToString();
                holiday_from = current_data["holiday_from"].ToString();
                holiday_to   = current_data["holiday_to"].ToString();
                company_code = current_data["company_code"].ToString();
                holiday_type = current_data["holiday_type"].ToString();

                query = "select count(*) from HolidayListDetails where holcode in(select distinct holcode from HolidayMaster where holcode = '" + holiday_code + "')";
                count = db_connection.GetRecordCount(query);
                if (count > 0)
                {
                    return_object.status      = "error";
                    return_object.return_data = "Holidays have been mapped to Holiday Group List. Please unassign the holidays from the Holiday Group List and try again.";
                }
                else
                {
                    page_object.UpdateDatabase(holiday_code, null, holiday_from, holiday_to, company_code, "0", holiday_code, "D", holiday_type);

                    return_object.status      = "success";
                    return_object.return_data = "Holiday deleted successfully!";
                }
            }
            catch (Exception Ex)
            {
                Logger.LogException(Ex, page, "DELETE_HOLIDAY");

                return_object.status      = "error";
                return_object.return_data = "An error occurred while performing this operation. Please try again. If the error persists, please contact Support";

                throw;
            }
            finally
            {
                page_object.Dispose();
            }
        }

        return(return_object);
    }
Exemplo n.º 40
0
    public static ReturnObject EditHoliday(string current, string previous)
    {
        masters_holiday page_object           = new masters_holiday();
        DBConnection    db_connection         = new DBConnection();
        ReturnObject    return_object         = new ReturnObject();
        string          query                 = string.Empty;
        string          holiday_code          = string.Empty;
        string          holiday_name          = string.Empty;
        string          holiday_from          = string.Empty;
        string          holiday_to            = string.Empty;
        string          company_code          = string.Empty;
        string          holiday_type          = string.Empty;
        string          original_holiday_name = string.Empty;
        string          original_holiday_from = string.Empty;
        string          original_holiday_to   = string.Empty;
        int             count                 = 0;

        if (HttpContext.Current.Session["username"] == null)  // checking session expired or not
        {
            return_object = page_object.DoLogout();
        }
        else
        {
            try
            {
                JObject current_data  = JObject.Parse(current);
                JObject original_data = JObject.Parse(previous);

                holiday_code = current_data["holiday_code"].ToString();
                holiday_name = current_data["holiday_name"].ToString();
                holiday_from = current_data["holiday_from"].ToString();
                holiday_to   = current_data["holiday_to"].ToString();
                company_code = current_data["company_code"].ToString();
                holiday_type = current_data["holiday_type"].ToString();

                original_holiday_name = original_data["holiday_name"].ToString();
                original_holiday_from = original_data["holiday_from"].ToString();
                original_holiday_to   = original_data["holiday_to"].ToString();

                if (original_holiday_name != holiday_name)
                {
                    count = page_object.CheckHolidayName(holiday_name, company_code);
                    if (count > 0)
                    {
                        return_object.status      = "error";
                        return_object.return_data = "A Holiday with the same Name has been created. Please try again with a different Holiday Name.";

                        return(return_object);
                    }
                }
                Debug.Write(original_holiday_from + " " + holiday_from);
                if (original_holiday_from != holiday_from || original_holiday_to != holiday_to)
                {
                    count = page_object.CheckHolidayDates(holiday_from, holiday_to);
                    if (count > 0)
                    {
                        return_object.status      = "error";
                        return_object.return_data = "The selected From and To Dates have been mapped to another Holiday. Please try again with different Dates";

                        return(return_object);
                    }
                }

                page_object.UpdateDatabase(holiday_code, holiday_name, holiday_from, holiday_to, company_code, "0", holiday_code, "U", holiday_type);

                return_object.status      = "success";
                return_object.return_data = "Holiday edited successfully!";
            }
            catch (Exception Ex)
            {
                Logger.LogException(Ex, page, "EDIT_HOLIDAY");

                return_object.status      = "error";
                return_object.return_data = "An error occurred while performing this operation. Please try again. If the error persists, please contact Support";

                throw;
            }
            finally
            {
                page_object.Dispose();
            }
        }
        return(return_object);
    }
Exemplo n.º 41
0
 /// <summary>
 /// Making the use of Database Transactions possible on a sequence of operations across multiple DataObjects.
 /// </summary>
 /// <param name="connection_in">opened Database connection with an initiated Transaction</param>
 public DO_Word(DBConnection connection_in) : base(connection_in)
 {
 }
        protected void Button1_Click(object sender, EventArgs e)
        {
            bool methodCheck = true;
            //check a requirement password format
            Regex RK = new Regex("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{4,12}$");

            if (InputValidation.ValidationPassword(TextBox6.Text, TextBox7.Text) == false)
            {
                methodCheck = false;
            }

            if (!RK.IsMatch(TextBox6.Text))
            {
                methodCheck = false;
            }

            if (methodCheck == true)
            {
                Dbm.ConnectDB();
                query = "Select email, Fname FROM USERTABLE WHERE email = @email AND Fname = @Fname";
                Dbm.GetCommend(query);

                Dbm.AddVal("@email", TextBox1.Text);
                Dbm.AddVal("@Fname", TextBox5.Text);

                SqlDataReader reader = Dbm.ExeReader();

                if (reader.HasRows && reader.Read())
                {
                    Dbm.CloseDB();
                    DBConnection Db2 = new DBConnection();
                    Db2.ConnectDB();

                    query = "UPDATE USERTABLE Set Password = @Password";
                    Db2.GetCommend(query);

                    //process to hash password to store in sql
                    String saltHashReturned = PasswordHash.CreateHash(TextBox6.Text);
                    int    commaIndex       = saltHashReturned.IndexOf(":");
                    String extractedString  = saltHashReturned.Substring(0, commaIndex);
                    commaIndex      = saltHashReturned.IndexOf(":");
                    extractedString = saltHashReturned.Substring(commaIndex + 1);
                    commaIndex      = extractedString.IndexOf(":");
                    String salt = extractedString.Substring(0, commaIndex);

                    commaIndex      = extractedString.IndexOf(":");
                    extractedString = extractedString.Substring(commaIndex + 1);
                    String hash = extractedString;

                    //from the first : to the second is a salt
                    //from the second " to the end is a hash
                    Db2.AddVal("@Password", saltHashReturned);


                    //sql execute
                    Db2.ExeQuery();
                    Response.Redirect("index.aspx");
                    Db2.CloseDB();
                }

                else
                {
                    Label1.Visible = true;
                    Label1.Text    = "Username and Name is not matching";
                }
            }

            if (methodCheck == false)
            {
                Label1.Visible = true;
                Label1.Text    = "At least one upper case English letter." + " <br /> " +
                                 "At least one lower case English letter," + "<br />" +
                                 "At least one digit." + "<br />" +
                                 "At least one special character." + "<br />" +
                                 "Minimum 4 and maximum 12 in length . ";
            }
        }
Exemplo n.º 43
0
 public VentanaMantenimientoDao(IConfiguration config)
 {
     _db = new DBConnection(config);
 }
Exemplo n.º 44
0
        public void OnRoundEnd(RoundEndEvent ev)
        {
            if (ConfigManager.Manager.Config.GetBoolValue("rank_enabled", true))
            {
                DBConnection db = new DBConnection(main);
                switch (ev.Status)
                {
                case Smod2.API.ROUND_END_STATUS.CI_VICTORY:
                    foreach (Player p in PluginManager.Manager.Server.GetPlayers())
                    {
                        switch (p.TeamRole.Team)
                        {
                        case Smod2.API.Team.CLASSD:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_ci_classd"));
                            break;

                        case Smod2.API.Team.CHAOS_INSURGENCY:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_ci_ci"));
                            break;

                        case Smod2.API.Team.SPECTATOR:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_ci_spectator"));
                            break;
                        }
                    }

                    return;

                case Smod2.API.ROUND_END_STATUS.MTF_VICTORY:

                    foreach (Player p in PluginManager.Manager.Server.GetPlayers())
                    {
                        switch (p.TeamRole.Team)
                        {
                        case Smod2.API.Team.NINETAILFOX:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_mtf_mtf"));
                            break;

                        case Smod2.API.Team.SCIENTIST:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_mtf_scient"));
                            break;

                        case Smod2.API.Team.SPECTATOR:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_mtf_spectator"));
                            break;
                        }
                    }

                    return;

                case Smod2.API.ROUND_END_STATUS.SCP_CI_VICTORY:

                    foreach (Player p in PluginManager.Manager.Server.GetPlayers())
                    {
                        switch (p.TeamRole.Team)
                        {
                        case Smod2.API.Team.SCP:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_scpci_scp"));
                            break;

                        case Smod2.API.Team.CHAOS_INSURGENCY:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_scpci_ci"));
                            break;

                        case Smod2.API.Team.SPECTATOR:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_scpci_spectator"));
                            break;
                        }
                    }

                    return;

                case Smod2.API.ROUND_END_STATUS.SCP_VICTORY:

                    foreach (Player p in PluginManager.Manager.Server.GetPlayers())
                    {
                        switch (p.TeamRole.Team)
                        {
                        case Smod2.API.Team.SCP:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_scp_scp"));
                            break;

                        case Smod2.API.Team.SPECTATOR:
                            db.AddPoint(p.SteamId, main.GetConfigInt("rank_point_win_scp_spectator"));
                            break;
                        }
                    }

                    return;
                }
            }
        }
Exemplo n.º 45
0
 public VentanaMantenimientoDao(IConfiguration config, string con)
 {
     _db = new DBConnection(config, con);
 }
Exemplo n.º 46
0
        public void OnPost(int id, int currentBooks, int addedBooks)
        {
            // Connect to Database
            DBConnection  dbstring     = new DBConnection();
            string        DbConnection = dbstring.DbString();
            SqlConnection conn         = new SqlConnection(DbConnection);

            conn.Open();

            // SQL Query
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = conn;

                if (currentBooks == 0)
                {
                    // First read PreloanBook Table as we need to know if any customers have preloaned the book  as they will instantly loan the book
                    command.CommandText = @"SELECT TOP(@BFirst) UsernameId FROM PreLoanedBook WHERE BookId = @BId ORDER BY DatePreLoaned";
                    command.Parameters.AddWithValue("@BFirst", addedBooks);
                    command.Parameters.AddWithValue("@BId", id);

                    SqlDataReader reader = command.ExecuteReader(); // read records

                    PreLoanedBooks = new List <PreLoanedBook>();

                    // Get each username who pre-loan the book
                    while (reader.Read())
                    {
                        PreLoanedBook PreLoanedBook = new PreLoanedBook();
                        PreLoanedBook.CustomerId = reader.GetInt32(0);

                        PreLoanedBooks.Add(PreLoanedBook);
                    }

                    reader.Close();

                    // If the Book List is empty then no one has pre-loaned that book
                    if (PreLoanedBooks.Count != 0)
                    {
                        // Delete the records from the table for that book as the users who have the earliest date take priority
                        command.CommandText = @"DELETE FROM PreLoanedBook WHERE Id IN(SELECT TOP(@BFirst) Id FROM PreLoanedBook WHERE BookId = @BId ORDER BY DatePreLoaned)";
                        command.ExecuteNonQuery();

                        for (int i = 0; i < PreLoanedBooks.Count; i++)
                        {
                            // Add those records to LoanedBook Table & add the Dates
                            command.CommandText = @"INSERT INTO LoanedBook (UsernameId, BookId, DateLoaned, DateReturned) VALUES (@CId" + i + ", @BId, @DLoaned" + i + ", @DReturned" + i + ")";
                            command.Parameters.AddWithValue("@CId" + i, PreLoanedBooks[i].CustomerId);

                            // already defined BookId earlier on, so automatically added

                            DateTime currentDate = DateTime.Now;                                       // get the current time

                            command.Parameters.AddWithValue("@DLoaned" + i, currentDate);              // they now loan the book as of now
                            command.Parameters.AddWithValue("@DReturned" + i, currentDate.AddDays(7)); // this is the returned due date

                            command.ExecuteNonQuery();
                        }

                        // change the value - people who preloan the book take priorty
                        currentBooks = addedBooks - PreLoanedBooks.Count;
                    }

                    else
                    {
                        // If no one has preloaned the book we  can just simply add it on
                        currentBooks += addedBooks;
                    }
                }


                else
                {
                    // If no one has preloaned the book we  can just simply add it on
                    currentBooks += addedBooks;
                }

                // Update the quantity
                command.CommandText = @"UPDATE Book SET Quantity = @BQuantity WHERE Id = @BookId";
                command.Parameters.AddWithValue("@BookId", id);
                command.Parameters.AddWithValue("@BQuantity", currentBooks);

                command.ExecuteNonQuery();
            }
            // Update the page
            OnGet();
        }
Exemplo n.º 47
0
        public static async Task AddWarningAsync(IUser User, DBConnection dbCon, bool ban = false)
        {
            ulong userid = User.Id;
            bool  Found  = false;

            string query = "SELECT * FROM user_profiles WHERE user_id = @userid;";
            var    cmd   = new MySqlCommand(query, dbCon.Connection);

            cmd.Parameters.Add("@userid", MySqlDbType.UInt64).Value = userid;
            var reader = await cmd.ExecuteReaderAsync();

            while (await reader.ReadAsync() && Found == false)
            {
                int warnings = reader.GetInt32(6) + 1;
                if (warnings < 3 && ban == false)
                {
                    // Warn them
                    cmd.Dispose();
                    reader.Close();

                    await User.SendMessageAsync("A global chat moderator has warned you for your actions. Please keep the chat mature!");

                    query = "UPDATE user_profiles SET count_warnings = @count_warnings WHERE user_id = @userid";
                    cmd   = new MySqlCommand(query, dbCon.Connection);
                    cmd.Parameters.Add("@userid", MySqlDbType.UInt64).Value         = userid;
                    cmd.Parameters.Add("@count_warnings", MySqlDbType.UInt32).Value = warnings;

                    try
                    {
                        Console.WriteLine("Warned user " + User.Username + ".");
                        Found = true;
                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.Message);
                        cmd.Dispose();
                    }
                }
                else
                {
                    // Blacklist them
                    cmd.Dispose();
                    reader.Close();

                    await User.SendMessageAsync("A global chat moderator has warned you for your actions. You have been blacklisted!");

                    query = "UPDATE user_profiles SET count_warnings = @count_warnings, user_blacklisted = @blacklisted WHERE user_id = @userid";
                    cmd   = new MySqlCommand(query, dbCon.Connection);
                    cmd.Parameters.Add("@userid", MySqlDbType.UInt64).Value         = userid;
                    cmd.Parameters.Add("@count_warnings", MySqlDbType.UInt32).Value = 3;
                    cmd.Parameters.Add("@blacklisted", MySqlDbType.UInt32).Value    = 1;

                    try
                    {
                        Console.WriteLine("Blacklisted user " + User.Username + ".");
                        Found = true;
                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.Message);
                        cmd.Dispose();
                    }
                }
            }
            dbCon.Close();
        }
Exemplo n.º 48
0
        public static long insObject(
            string sessionGuid_in,
            string ip_forLogPurposes_in,

            SO_NWS_Attachment attachment_in,
            SO_DIC__TextLanguage[] tx_Name_in,
            SO_DIC__TextLanguage[] tx_Description_in,

            bool selectIdentity_in,

            out string guid_out,

            out int[] errors_out
            )
        {
            guid_out = "";
            long _output = -1L;

            Guid        _sessionguid;
            Sessionuser _sessionuser;

            #region check...
            List <int> _errorlist;
            if (!check(
                    sessionGuid_in,
                    ip_forLogPurposes_in,

                    ref attachment_in,

                    out _sessionguid,
                    out _sessionuser,
                    out _errorlist
                    ))
            {
                errors_out = _errorlist.ToArray();
                return(_output);
            }
            #endregion
            #region check Existence . . .
            if (
                (attachment_in.IFContent <= 0)
                ||
                !DO_NWS_Content.isObject(attachment_in.IFContent)
                )
            {
                _errorlist.Add(ErrorType.data__not_found);
                errors_out = _errorlist.ToArray();
                return(_output);
            }
            #endregion

            // ToDos: here! should mark Content to be re-Approved!
            // ToDos: here! or not allow if no approve permission

            attachment_in.GUID
                  = guid_out
                  = Guid.NewGuid().ToString("N");
            attachment_in.Order = DateTime.Now.Ticks;

            Exception _exception = null;
            #region DBConnection _con = DO__Utilities.DBConnection_createInstance(...);
            DBConnection _con = DO__Utilities.DBConnection_createInstance(
                DO__Utilities.DBServerType,
                DO__Utilities.DBConnectionstring,
                DO__Utilities.DBLogfile
                );
            #endregion
            try {
                //if (
                //    (
                //        (tx_Name_in != null)
                //        &&
                //        (tx_Name_in.Length != 0))
                //    ||
                //    (
                //        (tx_Description_in != null)
                //        &&
                //        (tx_Description_in.Length != 0)
                //    )
                //) {
                _con.Open();
                _con.Transaction.Begin();
                //}

                #region content_in.TX_Name = ...;
                if (
                    (tx_Name_in == null)
                    ||
                    (tx_Name_in.Length == 0)
                    )
                {
                    attachment_in.TX_Name_isNull = true;
                }
                else
                {
                    attachment_in.TX_Name = SBO_DIC_Dic.insObject(
                        _con,

                        _sessionuser.IDApplication,
                        OGen.NTier.Kick.Libraries.BusinessLayer.Shared.TableFieldSource.NWS_ATTACHMENT__TX_NAME,

                        tx_Name_in
                        );
                }
                #endregion
                #region content_in.TX_Description = ...;
                if (
                    (tx_Description_in == null)
                    ||
                    (tx_Description_in.Length == 0)
                    )
                {
                    attachment_in.TX_Description_isNull = true;
                }
                else
                {
                    attachment_in.TX_Description = SBO_DIC_Dic.insObject(
                        _con,

                        _sessionuser.IDApplication,
                        OGen.NTier.Kick.Libraries.BusinessLayer.Shared.TableFieldSource.NWS_ATTACHMENT__TX_DESCRIPTION,

                        tx_Description_in
                        );
                }
                #endregion

                _output = DO_NWS_Attachment.insObject(
                    attachment_in,
                    selectIdentity_in,

                    _con
                    );
                _errorlist.Add(ErrorType.news__attachment__successfully_created__WARNING);

                #region _con.Transaction.Commit();
                if (
                    _con.IsOpen
                    &&
                    _con.Transaction.InTransaction
                    )
                {
                    _con.Transaction.Commit();
                }
                #endregion
            } catch (Exception _ex) {
                #region _con.Transaction.Rollback();
                if (
                    _con.IsOpen
                    &&
                    _con.Transaction.InTransaction
                    )
                {
                    _con.Transaction.Rollback();
                }
                #endregion

                _exception = _ex;
            } finally {
                #region _con.Transaction.Terminate(); _con.Close(); _con.Dispose();
                if (_con.IsOpen)
                {
                    if (_con.Transaction.InTransaction)
                    {
                        _con.Transaction.Terminate();
                    }
                    _con.Close();
                }

                _con.Dispose();
                #endregion
            }
            if (_exception != null)
            {
                #region SBO_LOG_Log.Log(ErrorType.data);
                OGen.NTier.Kick.Libraries.BusinessLayer.SBO_LOG_Log.log(
                    _sessionuser,
                    LogType.error,
                    ErrorType.data,
                    -1L,
                    _sessionuser.IDApplication,
                    "{0}",
                    new string[] {
                    _exception.Message
                }
                    );
                #endregion
                _errorlist.Add(ErrorType.data);
            }

            errors_out = _errorlist.ToArray();
            return(_output);
        }
Exemplo n.º 49
0
    private void UpdateDatabase(JObject data, string mode)
    {
        DBConnection db_connection                = new DBConnection();
        Hashtable    shift_data                   = new Hashtable();
        string       company_code                 = data["company_code"].ToString();
        string       shift_code                   = data["shift_code"].ToString();
        string       shift_name                   = data["shift_desc"].ToString();
        int          check_normal_shift           = Convert.ToInt32(data["check_if_normal_shift"]);
        DateTime     start_time                   = new DateTime();
        string       break_out                    = data["break_out"].ToString();
        string       break_in                     = data["break_in"].ToString();
        DateTime     end_time                     = new DateTime();
        string       normal_shift_grace_in        = data["in_grace"].ToString();
        string       normal_shift_grace_break_out = data["break_out_grace"].ToString();
        string       normal_shift_grace_break_in  = data["break_in_grace"].ToString();
        string       normal_shift_grace_out       = data["out_grace"].ToString();
        string       ramdan_start_time            = data["ramadan_in_time"].ToString();
        string       ramdan_end_time              = data["ramadan_out_time"].ToString();
        int          check_night_shift            = Convert.ToInt32(data["status_night_shift"]);
        string       night_shift                  = data["max_shift_end_cut_off_time"].ToString();
        string       night_shift_grace_in         = data["grace_in"].ToString();
        string       night_shift_grace_out        = data["grace_out"].ToString();
        string       night_shift_grace_break_in   = data["grace_break_in"].ToString();
        string       night_shift_grace_break_out  = data["grace_break_out"].ToString();
        int          check_overtime               = Convert.ToInt32(data["overtime"]);
        string       min_overtime                 = data["min_overtime"].ToString();
        string       max_overtime                 = data["max_overtime"].ToString();
        int          check_half_day               = Convert.ToInt32(data["status_half_day"]);
        string       half_day                     = data["half_day"].ToString();
        string       half_day_start               = data["start_time_half_day"].ToString();
        string       half_day_end                 = data["end_time_half_day"].ToString();
        string       week_off_1                   = data["weekly_off1"].ToString();
        string       week_off_2                   = data["weekly_off2"].ToString();
        string       Branch_Code                  = data["branch"].ToString();
        string       Employee_Category_Code       = data["category"].ToString();
        int          IsAutoShiftEligible          = Convert.ToInt32(data["auto_checked"].ToString());
        int          IsActive                     = Convert.ToInt32(data["is_active"].ToString());


        // The mode of the DB operation to be performed.
        // I = Insert
        // U = Update
        shift_data.Add("Mode", mode);
        // Basic data regarding the shift and settings.
        shift_data.Add("CompanyCode", company_code);
        shift_data.Add("ShiftCode ", shift_code.ToUpper());
        shift_data.Add("ShiftName", shift_name);

        DateTime.TryParse(data["in_time"].ToString(), out start_time);
        shift_data.Add("StartTime", start_time);
        DateTime.TryParse(data["out_time"].ToString(), out end_time);
        shift_data.Add("EndTime", end_time);

        shift_data.Add("HalfDayendtime", half_day_end == string.Empty ? Convert.ToDateTime(Convert.ToDateTime(DateTime.Today.ToShortDateString())) : Convert.ToDateTime(half_day_end));

        if (Convert.ToInt32(data["status_night_shift"]) == 0)
        {
            shift_data.Add("MaxOverTime", "");
        }
        else
        {
            shift_data.Add("MaxOverTime", night_shift);
        }

        if (half_day == "select")
        {
            half_day = null;
        }
        shift_data.Add("HalfDay", half_day);

        if (Convert.ToInt32(data["overtime"]) == 0)
        {
            shift_data.Add("MaxWorkTime", "");
            shift_data.Add("minovertime", "");
        }
        else
        {
            shift_data.Add("MaxWorkTime", max_overtime);
            shift_data.Add("minovertime", min_overtime);
        }

        // Processing Weekly Off data and settings.
        if (week_off_1 == "select")
        {
            week_off_1 = null;
        }
        shift_data.Add("WeakOff1", week_off_1);

        if (week_off_2 == "select")
        {
            week_off_2 = null;
        }
        shift_data.Add("WeakOff2", week_off_2);

        shift_data.Add("breakout", break_out);
        shift_data.Add("breakin", break_in);

        shift_data.Add("sgrace", normal_shift_grace_in);
        shift_data.Add("boutgrace", normal_shift_grace_break_out);
        shift_data.Add("bingrace", normal_shift_grace_break_in);
        shift_data.Add("egrace", normal_shift_grace_out);

        shift_data.Add("InGrace", night_shift_grace_in == string.Empty ? "0" : night_shift_grace_in);
        shift_data.Add("OutGrace", night_shift_grace_out == string.Empty ? "0" : night_shift_grace_out);
        shift_data.Add("Bin_Grace", night_shift_grace_break_in == string.Empty ? "0" : night_shift_grace_break_in);
        shift_data.Add("Bout_Grace", night_shift_grace_break_out == string.Empty ? "0" : night_shift_grace_break_out);

        DateTime ramdan_start = Convert.ToDateTime(ramdan_start_time == string.Empty ? Convert.ToDateTime(Convert.ToDateTime(DateTime.Today.ToShortDateString())) : Convert.ToDateTime(ramdan_start_time));

        shift_data.Add("Ramadan_StartTime", ramdan_start);
        DateTime ramdan_end = Convert.ToDateTime(ramdan_end_time == string.Empty ? Convert.ToDateTime(Convert.ToDateTime(DateTime.Today.ToShortDateString())) : Convert.ToDateTime(ramdan_end_time));

        shift_data.Add("Ramadan_EndTime", ramdan_end);
        shift_data.Add("ifNormalShift", check_normal_shift.ToString());

        //for autoshift
        shift_data.Add("Branch_Code", Branch_Code);
        shift_data.Add("Employee_Category_Code", Employee_Category_Code);
        shift_data.Add("IsAutoShiftEligible", IsAutoShiftEligible);
        shift_data.Add("IsActive", IsActive);


        shift_data.Add("HalfDaystarttime", half_day_start == string.Empty ? Convert.ToDateTime(Convert.ToDateTime(DateTime.Today.ToShortDateString())) : Convert.ToDateTime(half_day_start));

        db_connection.ExecuteStoredProcedureWithHashtable_WithoutReturn("General", shift_data);
    }
Exemplo n.º 50
0
        public static void updObject(
            string sessionGuid_in,
            string ip_forLogPurposes_in,

            SO_NWS_Attachment attachment_in,
            SO_DIC__TextLanguage[] tx_Name_in,
            SO_DIC__TextLanguage[] tx_Description_in,

            out int[] errors_out
            )
        {
            Guid        _sessionguid;
            Sessionuser _sessionuser;

            #region check...
            List <int> _errorlist;
            if (!check(
                    sessionGuid_in,
                    ip_forLogPurposes_in,

                    ref attachment_in,

                    out _sessionguid,
                    out _sessionuser,
                    out _errorlist
                    ))
            {
                errors_out = _errorlist.ToArray();
                return;
            }
            #endregion

            #region check existence . . .
            SO_NWS_Attachment _attachment;
            if (
                attachment_in.IDAttachment <= 0
                ||
                (
                    (_attachment = DO_NWS_Attachment.getObject(
                         attachment_in.IDAttachment
                         )) == null
                )
                )
            {
                _errorlist.Add(ErrorType.data__not_found);
                errors_out = _errorlist.ToArray();
                return;
            }
            #endregion

            // ToDos: here! should mark Content to be re-Approved!
            // ToDos: here! or not allow if no approve permission

            Exception _exception = null;
            #region DBConnection _con = DO__Utilities.DBConnection_createInstance(...);
            DBConnection _con = DO__Utilities.DBConnection_createInstance(
                DO__Utilities.DBServerType,
                DO__Utilities.DBConnectionstring,
                DO__Utilities.DBLogfile
                );
            #endregion
            try {
                _con.Open();
                _con.Transaction.Begin();

                #region TX_Name . . .
                if ((tx_Name_in != null) && (tx_Name_in.Length != 0))
                {
                    if (_attachment.TX_Name_isNull)
                    {
                        _attachment.TX_Name = SBO_DIC_Dic.insObject(
                            _con,
                            _sessionuser.IDApplication,
                            OGen.NTier.Kick.Libraries.BusinessLayer.Shared.TableFieldSource.NWS_ATTACHMENT__TX_NAME,
                            tx_Name_in
                            );
                    }
                    else
                    {
                        SBO_DIC_Dic.updObject(
                            _con,
                            _attachment.TX_Name,
                            tx_Name_in
                            );
                    }
                }
                #endregion
                #region TX_Description . . .
                if ((tx_Description_in != null) && (tx_Description_in.Length != 0))
                {
                    if (_attachment.TX_Description_isNull)
                    {
                        _attachment.TX_Description = SBO_DIC_Dic.insObject(
                            _con,
                            _sessionuser.IDApplication,
                            OGen.NTier.Kick.Libraries.BusinessLayer.Shared.TableFieldSource.NWS_ATTACHMENT__TX_DESCRIPTION,
                            tx_Description_in
                            );
                    }
                    else
                    {
                        SBO_DIC_Dic.updObject(
                            _con,
                            _attachment.TX_Description,
                            tx_Description_in
                            );
                    }
                }
                #endregion

                //_attachment.??? = attachment_in.???;
                DO_NWS_Attachment.updObject(
                    _attachment,
                    true,

                    _con
                    );
                _errorlist.Add(ErrorType.news__attachment__successfully_updated__WARNING);

                #region _con.Transaction.Commit();
                if (
                    _con.IsOpen
                    &&
                    _con.Transaction.InTransaction
                    )
                {
                    _con.Transaction.Commit();
                }
                #endregion
            } catch (Exception _ex) {
                #region _con.Transaction.Rollback();
                if (
                    _con.IsOpen
                    &&
                    _con.Transaction.InTransaction
                    )
                {
                    _con.Transaction.Rollback();
                }
                #endregion

                _exception = _ex;
            } finally {
                #region _con.Transaction.Terminate(); _con.Close(); _con.Dispose();
                if (_con.IsOpen)
                {
                    if (_con.Transaction.InTransaction)
                    {
                        _con.Transaction.Terminate();
                    }
                    _con.Close();
                }

                _con.Dispose();
                #endregion
            }
            if (_exception != null)
            {
                #region SBO_LOG_Log.Log(ErrorType.data);
                OGen.NTier.Kick.Libraries.BusinessLayer.SBO_LOG_Log.log(
                    _sessionuser,
                    LogType.error,
                    ErrorType.data,
                    -1L,
                    _sessionuser.IDApplication,
                    "{0}",
                    new string[] {
                    _exception.Message
                }
                    );
                #endregion
                _errorlist.Add(ErrorType.data);
            }

            errors_out = _errorlist.ToArray();
        }
Exemplo n.º 51
0
        /// <summary>
        /// Selects FRM_Question values from Database and assigns them to the appropriate DO_FRM_Question property.
        /// </summary>
        /// <param name="IDQuestion_in">IDQuestion</param>
        /// <param name="dbConnection_in">Database connection, making the use of Database Transactions possible on a sequence of operations across the same or multiple DataObjects</param>
        /// <returns>null if FRM_Question doesn't exists at Database</returns>
        public static SO_FRM_Question getObject(
            long IDQuestion_in,
            DBConnection dbConnection_in
            )
        {
            SO_FRM_Question _output = null;

            DBConnection _connection = (dbConnection_in == null)
                                ? DO__Utilities.DBConnection_createInstance(
                DO__Utilities.DBServerType,
                DO__Utilities.DBConnectionstring,
                DO__Utilities.DBLogfile
                )
                                : dbConnection_in;

            IDbDataParameter[] _dataparameters = new IDbDataParameter[] {
                _connection.newDBDataParameter("IDQuestion_", DbType.Int64, ParameterDirection.InputOutput, IDQuestion_in, 0),
                _connection.newDBDataParameter("IFQuestion__parent_", DbType.Int64, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("IFQuestiontype_", DbType.Int32, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("TX_Question_", DbType.Int64, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("TX_Details_", DbType.Int64, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("IsRequired_", DbType.Boolean, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("IsTemplate_", DbType.Boolean, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("IFApplication_", DbType.Int32, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("IFUser__audit_", DbType.Int64, ParameterDirection.Output, null, 0),
                _connection.newDBDataParameter("Date__audit_", DbType.DateTime, ParameterDirection.Output, null, 0)
            };
            _connection.Execute_SQLFunction("sp0_FRM_Question_getObject", _dataparameters);
            if (dbConnection_in == null)
            {
                _connection.Dispose();
            }

            if (_dataparameters[0].Value != DBNull.Value)
            {
                _output = new SO_FRM_Question();

                if (_dataparameters[0].Value == System.DBNull.Value)
                {
                    _output.IDQuestion = 0L;
                }
                else
                {
                    _output.IDQuestion = (long)_dataparameters[0].Value;
                }
                if (_dataparameters[1].Value == System.DBNull.Value)
                {
                    _output.IFQuestion__parent_isNull = true;
                }
                else
                {
                    _output.IFQuestion__parent = (long)_dataparameters[1].Value;
                }
                if (_dataparameters[2].Value == System.DBNull.Value)
                {
                    _output.IFQuestiontype_isNull = true;
                }
                else
                {
                    _output.IFQuestiontype = (int)_dataparameters[2].Value;
                }
                if (_dataparameters[3].Value == System.DBNull.Value)
                {
                    _output.TX_Question_isNull = true;
                }
                else
                {
                    _output.TX_Question = (long)_dataparameters[3].Value;
                }
                if (_dataparameters[4].Value == System.DBNull.Value)
                {
                    _output.TX_Details_isNull = true;
                }
                else
                {
                    _output.TX_Details = (long)_dataparameters[4].Value;
                }
                if (_dataparameters[5].Value == System.DBNull.Value)
                {
                    _output.IsRequired_isNull = true;
                }
                else
                {
                    _output.IsRequired = (bool)_dataparameters[5].Value;
                }
                if (_dataparameters[6].Value == System.DBNull.Value)
                {
                    _output.IsTemplate_isNull = true;
                }
                else
                {
                    _output.IsTemplate = (bool)_dataparameters[6].Value;
                }
                if (_dataparameters[7].Value == System.DBNull.Value)
                {
                    _output.IFApplication_isNull = true;
                }
                else
                {
                    _output.IFApplication = (int)_dataparameters[7].Value;
                }
                if (_dataparameters[8].Value == System.DBNull.Value)
                {
                    _output.IFUser__audit = 0L;
                }
                else
                {
                    _output.IFUser__audit = (long)_dataparameters[8].Value;
                }
                if (_dataparameters[9].Value == System.DBNull.Value)
                {
                    _output.Date__audit = new DateTime(1900, 1, 1);
                }
                else
                {
                    _output.Date__audit = (DateTime)_dataparameters[9].Value;
                }

                _output.HasChanges = false;
                return(_output);
            }

            return(null);
        }
    protected void Page_Load(object sender, System.EventArgs e)
    {
        //CommonFunctions.Connection.Open ();

        MainAdapter = CommonFunctions.PrepareAdapter(CommonFunctions.GetConnection(), "SELECT * FROM Users WHERE ID = @UserID", SqlDbType.Int);

        CountriesAdapter = CommonFunctions.PrepareAdapter(CommonFunctions.GetConnection(), "SELECT DISTINCT(Country) AS Country " +
                                                          "FROM Users WHERE (IfAgent = 1) AND (LEN(Country) > 0) AND NOT (ID = @UserID)", SqlDbType.Int);

        AgentsAdapter = CommonFunctions.PrepareAdapter(CommonFunctions.GetConnection(), "SELECT -1 AS ID, 'Not referred by anyone' AS FullName " +
                                                       "UNION SELECT ID, LastName + ', ' + FirstName AS FullName FROM Users WHERE (Country = @Country) AND" +
                                                       " (IfAgent = 1) AND NOT (ID = @UserID)", SqlDbType.NVarChar, 300, SqlDbType.Int);

        IfAdmin.Visible      = AuthenticationManager.IfAdmin && (AuthenticationManager.UserID != userid);
        IfAdminLabel.Visible = AuthenticationManager.IfAdmin && (AuthenticationManager.UserID != userid);

        MainAdapter.SelectCommand.Parameters["@UserID"].Value = userid;
        //lock (CommonFunctions.Connection)
        if (MainAdapter.Fill(MainDataSet, "Users") == 0)
        {
            Response.Redirect(CommonFunctions.PrepareURL("InternalError.aspx"), true);
        }

        //CountryRequired.Enabled = (MainDataSet.Tables["Users"].Rows[0]["IfAgent"] is bool) &&
        //    (bool)MainDataSet.Tables["Users"].Rows[0]["IfAgent"];
        DBConnection obj = new DBConnection();

        try
        {
            if (!IsPostBack)
            {
                DataTable dt = VADBCommander.CountyDistinctSimpleList();
                ddlCountries.DataSource = dt;
                //ddlCountries.DataTextField = "country";
                //ddlCountries.DataValueField = "country";

                if (ddlCountries.Items.Contains(new ListItem(MainDataSet.Tables["Users"].Rows[0]["country"].ToString(),
                                                             MainDataSet.Tables["Users"].Rows[0]["country"].ToString())))
                {
                    ddlCountries.SelectedValue = MainDataSet.Tables["Users"].Rows[0]["country"].ToString();
                }
                //ddlCountries.DataBind();
            }
        }
        catch (Exception ex) { Response.Write(ex.Message); }
        finally { obj.CloseConnection(); }


        if (!IsPostBack)
        {
            EmailAddress.Text = MainDataSet.Tables["Users"].Rows[0]["Email"].ToString();
            FirstName.Text    = MainDataSet.Tables["Users"].Rows[0]["FirstName"].ToString();
            LastName.Text     = MainDataSet.Tables["Users"].Rows[0]["LastName"].ToString();
            CompanyName.Text  = MainDataSet.Tables["Users"].Rows[0]["CompanyName"].ToString();
            Address.Text      = MainDataSet.Tables["Users"].Rows[0]["Address"].ToString();
            City.Text         = MainDataSet.Tables["Users"].Rows[0]["City"].ToString();
            State.Text        = MainDataSet.Tables["Users"].Rows[0]["State"].ToString();
            Zip.Text          = MainDataSet.Tables["Users"].Rows[0]["Zip"].ToString();

            //foreach (ListItem li in ddlCountries.Items)
            //{
            //    if (li.Value.ToLower() == MainDataSet.Tables["Users"].Rows[0]["Country"].ToString().ToLower())
            //    {
            //        ddlCountries.SelectedValue = MainDataSet.Tables["Users"].Rows[0]["Country"].ToString();
            //    }
            //}

            PrimaryTelephone.Text   = MainDataSet.Tables["Users"].Rows[0]["PrimaryTelephone"].ToString();
            EveningTelephone.Text   = MainDataSet.Tables["Users"].Rows[0]["EveningTelephone"].ToString();
            DaytimeTelephone.Text   = MainDataSet.Tables["Users"].Rows[0]["DaytimeTelephone"].ToString();
            MobileTelephone.Text    = MainDataSet.Tables["Users"].Rows[0]["MobileTelephone"].ToString();
            Website.Text            = MainDataSet.Tables["Users"].Rows[0]["Website"].ToString();
            Registered.Text         = MainDataSet.Tables["Users"].Rows[0]["Registered"].ToString();
            PayTravelAgents.Checked = MainDataSet.Tables["Users"].Rows[0]["IfPayTravelAgents"] is bool?
                                      (bool)MainDataSet.Tables["Users"].Rows[0]["IfPayTravelAgents"] : false;
            ReservationSame.Checked = MainDataSet.Tables["Users"].Rows[0]["IfReservationSame"] is bool?
                                      (bool)MainDataSet.Tables["Users"].Rows[0]["IfReservationSame"] : false;
            ReservationNotSame.Checked = !ReservationSame.Checked;
            ReservationEmail.Text      = MainDataSet.Tables["Users"].Rows[0]["ReservationEmail"].ToString();
            ReservationFirstName.Text  = MainDataSet.Tables["Users"].Rows[0]["ReservationFirstName"].ToString();
            ReservationLastName.Text   = MainDataSet.Tables["Users"].Rows[0]["ReservationLastName"].ToString();
            if (IfAdmin.Visible)
            {
                IfAdmin.SelectedIndex = (MainDataSet.Tables["Users"].Rows[0]["IfAdmin"] is bool) &&
                                        (bool)MainDataSet.Tables["Users"].Rows[0]["IfAdmin"] ? 0 : 1;
            }

            ReservationSame_CheckedChanged(sender, e);

            CountriesAdapter.SelectCommand.Parameters["@UserID"].Value = userid;

            //lock (CommonFunctions.Connection)
            CountriesAdapter.Fill(MainDataSet, "Countries");

            AgentCountries.DataSource = MainDataSet;

            if (!IsPostBack)
            {
                DataBind();
            }

            if (MainDataSet.Tables["Users"].Rows[0]["ReferredByID"] is int)
            {
                object country = null;
                using (SqlConnection connection = CommonFunctions.GetConnection()) {
                    connection.Open();
                    SqlCommand getcountry = new SqlCommand("SELECT Country FROM Users WHERE ID = @UserID", connection);
                    getcountry.Parameters.Add("@UserID", SqlDbType.Int, 4);
                    getcountry.Parameters["@UserID"].Value = (int)MainDataSet.Tables["Users"].Rows[0]["ReferredByID"];

                    country = getcountry.ExecuteScalar();
                    connection.Close();
                }
                if (country is string)
                {
                    try
                    {
                        AgentCountries.SelectedValue = (string)country;
                    }
                    catch (Exception)
                    {
                    }
                }

                AgentCountries_SelectedIndexChanged(sender, e);

                try
                {
                    Agents.SelectedValue = ((int)MainDataSet.Tables["Users"].Rows[0]["ReferredByID"]).ToString();
                }
                catch (Exception)
                {
                }
            }
            else
            {
                AgentCountries_SelectedIndexChanged(sender, e);
            }
        }
    }
Exemplo n.º 53
0
        private void iniciarSesionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int tries = 3;

            do
            {
                LogIn li = new LogIn();
                li.ShowDialog();
                if (li.Valid)
                {
                    string    user     = li.User;
                    string    password = Crypto.Encrypt(li.Password);
                    DataTable dt       = DBConnection.CheckLogIn(user, password);
                    if (dt.Rows.Count == 1)
                    {
                        switch ((int)dt.Rows[0][0])
                        {
                        case 10000:
                            currentRole = new Role("SuperAdmin", 10000);
                            break;

                        case 10001:
                            currentRole = new Role("Admin", 10001);
                            break;

                        case 10002:
                            currentRole = new Role("Manager", 10002);
                            break;

                        case 10003:
                            currentRole = new Role("Employee", 10003);
                            break;

                        case 10004:
                            currentRole = new Role("No role", 10004);
                            break;

                        default:
                            currentRole = null;
                            break;
                        }
                        updateRole();
                        tsslUser.Text = (string)dt.Rows[0][2];
                        tsslRole.Text = currentRole.ToString();
                        if (!this.Visible)
                        {
                            Show();
                        }
                        break;
                    }
                    else
                    {
                        MessageBox.Show(null, "Usuario o contraseña incorrectos\nIntentos restantes: " + --tries, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            } while (tries > 0);
            if (tries == 0)
            {
                MessageBox.Show("Usuario incorrecto muchas veces\nCerrando programa");
                Close();
            }
        }
Exemplo n.º 54
0
 private void mostrarArticulosToolStripMenuItem_Click(object sender, EventArgs e)
 {
     dgvResultados.DataSource = DBConnection.getItems();
 }
Exemplo n.º 55
0
 private void mostrarEstadosToolStripMenuItem_Click(object sender, EventArgs e)
 {
     dgvResultados.DataSource = DBConnection.GetStatuses();
 }
Exemplo n.º 56
0
        internal static void Generate(
            DBConnection cn, TextWriter writer, string namespaceDeclaration, Database database, IEnumerable <string> tableNames,
            Configuration.SystemDevelopment.Database configuration)
        {
            writer.WriteLine(namespaceDeclaration);
            foreach (var table in tableNames)
            {
                CodeGenerationStatics.AddSummaryDocComment(writer, "Contains logic that retrieves rows from the " + table + " table.");
                writer.WriteLine("public static partial class " + GetClassName(cn, table) + " {");

                var isRevisionHistoryTable = DataAccessStatics.IsRevisionHistoryTable(table, configuration);
                var columns = new TableColumns(cn, table, isRevisionHistoryTable);

                // Write nested classes.
                DataAccessStatics.WriteRowClasses(
                    writer,
                    columns.AllColumns,
                    localWriter => {
                    if (!isRevisionHistoryTable)
                    {
                        return;
                    }
                    writer.WriteLine(
                        "public UserTransaction Transaction { get { return RevisionHistoryStatics.UserTransactionsById[ RevisionHistoryStatics.RevisionsById[ System.Convert.ToInt32( " +
                        EwlStatics.GetCSharpIdentifier(columns.PrimaryKeyAndRevisionIdColumn.PascalCasedNameExceptForOracle) + " ) ].UserTransactionId ]; } }");
                },
                    localWriter => {
                    if (!columns.DataColumns.Any())
                    {
                        return;
                    }

                    var modClass = database.SecondaryDatabaseName + "Modification." +
                                   StandardModificationStatics.GetClassName(cn, table, isRevisionHistoryTable, isRevisionHistoryTable);
                    var revisionHistorySuffix = StandardModificationStatics.GetRevisionHistorySuffix(isRevisionHistoryTable);
                    writer.WriteLine("public " + modClass + " ToModification" + revisionHistorySuffix + "() {");
                    writer.WriteLine(
                        "return " + modClass + ".CreateForSingleRowUpdate" + revisionHistorySuffix + "( " +
                        StringTools.ConcatenateWithDelimiter(
                            ", ",
                            columns.AllColumnsExceptRowVersion.Select(i => EwlStatics.GetCSharpIdentifier(i.PascalCasedNameExceptForOracle)).ToArray()) + " );");
                    writer.WriteLine("}");
                });
                writeCacheClass(cn, writer, database, table, columns, isRevisionHistoryTable);

                var isSmallTable = configuration.SmallTables != null && configuration.SmallTables.Any(i => i.EqualsIgnoreCase(table));

                var tableUsesRowVersionedCaching = configuration.TablesUsingRowVersionedDataCaching != null &&
                                                   configuration.TablesUsingRowVersionedDataCaching.Any(i => i.EqualsIgnoreCase(table));
                if (tableUsesRowVersionedCaching && columns.RowVersionColumn == null && !(cn.DatabaseInfo is OracleInfo))
                {
                    throw new UserCorrectableException(
                              cn.DatabaseInfo is MySqlInfo
                                                        ? "Row-versioned data caching cannot currently be used with MySQL databases."
                                                        : "Row-versioned data caching can only be used with the {0} table if you add a rowversion column.".FormatWith(table));
                }

                if (isSmallTable)
                {
                    writeGetAllRowsMethod(writer, isRevisionHistoryTable, false);
                }
                writeGetRowsMethod(cn, writer, database, table, columns, isSmallTable, tableUsesRowVersionedCaching, isRevisionHistoryTable, false);
                if (isRevisionHistoryTable)
                {
                    if (isSmallTable)
                    {
                        writeGetAllRowsMethod(writer, true, true);
                    }
                    writeGetRowsMethod(cn, writer, database, table, columns, isSmallTable, tableUsesRowVersionedCaching, true, true);
                }

                writeGetRowMatchingPkMethod(cn, writer, database, table, columns, isSmallTable, tableUsesRowVersionedCaching, isRevisionHistoryTable);

                if (isRevisionHistoryTable)
                {
                    DataAccessStatics.WriteGetLatestRevisionsConditionMethod(writer, columns.PrimaryKeyAndRevisionIdColumn.Name);
                }

                if (tableUsesRowVersionedCaching)
                {
                    var keyTupleTypeArguments = getPkAndVersionTupleTypeArguments(cn, columns);

                    writer.WriteLine("private static " + "Cache<System.Tuple<" + keyTupleTypeArguments + ">, BasicRow>" + " getRowsByPkAndVersion() {");
                    writer.WriteLine(
                        "return AppMemoryCache.GetCacheValue<{0}>( \"{1}\", () => new {0}( i => System.Tuple.Create( {2} ) ) ).RowsByPkAndVersion;".FormatWith(
                            "VersionedRowDataCache<System.Tuple<{0}>, System.Tuple<{1}>, BasicRow>".FormatWith(getPkTupleTypeArguments(columns), keyTupleTypeArguments),
                            database.SecondaryDatabaseName + table.TableNameToPascal(cn) + "TableRetrievalRowsByPkAndVersion",
                            StringTools.ConcatenateWithDelimiter(", ", Enumerable.Range(1, columns.KeyColumns.Count()).Select(i => "i.Item{0}".FormatWith(i)).ToArray())));
                    writer.WriteLine("}");
                }

                // Initially we did not generate this method for small tables, but we found a need for it when the cache is disabled since that will cause
                // GetRowMatchingId to repeatedly query.
                if (columns.KeyColumns.Count() == 1 && columns.KeyColumns.Single().Name.ToLower().EndsWith("id"))
                {
                    writeToIdDictionaryMethod(writer, columns);
                }

                if (isRevisionHistoryTable)
                {
                    DataAccessStatics.WriteRevisionDeltaExtensionMethods(writer, GetClassName(cn, table), columns.DataColumns);
                }

                writer.WriteLine("}");           // class
            }
            writer.WriteLine("}");               // namespace
        }
Exemplo n.º 57
0
 private void mostrarPersonaToolStripMenuItem_Click(object sender, EventArgs e)
 {
     dgvResultados.DataSource = DBConnection.getStaff();
 }
Exemplo n.º 58
0
        private static void writeResultSetCreatorBody(
            DBConnection cn, TextWriter writer, Database database, string table, TableColumns tableColumns, bool tableUsesRowVersionedCaching,
            bool excludesPreviousRevisions, string cacheQueryInDbExpression)
        {
            if (tableUsesRowVersionedCaching)
            {
                writer.WriteLine("var results = new List<Row>();");
                writer.WriteLine(DataAccessStatics.GetConnectionExpression(database) + ".ExecuteInTransaction( delegate {");

                // Query for the cache keys of the results.
                writer.WriteLine(
                    "var keyCommand = {0};".FormatWith(
                        getInlineSelectExpression(
                            table,
                            tableColumns,
                            "{0}, \"{1}\"".FormatWith(
                                StringTools.ConcatenateWithDelimiter(", ", tableColumns.KeyColumns.Select(i => "\"{0}\"".FormatWith(i.Name)).ToArray()),
                                cn.DatabaseInfo is OracleInfo ? "ORA_ROWSCN" : tableColumns.RowVersionColumn.Name),
                            cacheQueryInDbExpression)));
                writer.WriteLine(getCommandConditionAddingStatement("keyCommand"));
                writer.WriteLine("var keys = new List<System.Tuple<{0}>>();".FormatWith(getPkAndVersionTupleTypeArguments(cn, tableColumns)));
                writer.WriteLine(
                    "keyCommand.Execute( " + DataAccessStatics.GetConnectionExpression(database) + ", r => { while( r.Read() ) keys.Add( " +
                    "System.Tuple.Create( {0}, {1} )".FormatWith(
                        StringTools.ConcatenateWithDelimiter(
                            ", ",
                            tableColumns.KeyColumns.Select((c, i) => c.GetDataReaderValueExpression("r", ordinalOverride: i)).ToArray()),
                        cn.DatabaseInfo is OracleInfo
                                                        ? "({0})r.GetValue( {1} )".FormatWith(oracleRowVersionDataType, tableColumns.KeyColumns.Count())
                                                        : tableColumns.RowVersionColumn.GetDataReaderValueExpression("r", ordinalOverride: tableColumns.KeyColumns.Count())) + " ); } );");

                writer.WriteLine("var rowsByPkAndVersion = getRowsByPkAndVersion();");
                writer.WriteLine("var cachedKeyCount = keys.Where( i => rowsByPkAndVersion.ContainsKey( i ) ).Count();");

                // If all but a few results are cached, execute a single-row query for each missing result.
                writer.WriteLine("if( cachedKeyCount >= keys.Count() - 1 || cachedKeyCount >= keys.Count() * .99 ) {");
                writer.WriteLine("foreach( var key in keys ) {");
                writer.WriteLine("results.Add( new Row( rowsByPkAndVersion.GetOrAdd( key, () => {");
                writer.WriteLine("var singleRowCommand = {0};".FormatWith(getInlineSelectExpression(table, tableColumns, "\"*\"", "false")));
                foreach (var i in tableColumns.KeyColumns.Select((c, i) => new { column = c, index = i }))
                {
                    writer.WriteLine(
                        "singleRowCommand.AddCondition( ( ({0})new {1}( key.Item{2} ) ).CommandCondition );".FormatWith(
                            DataAccessStatics.GetTableConditionInterfaceName(cn, database, table),
                            DataAccessStatics.GetEqualityConditionClassName(cn, database, table, i.column),
                            i.index + 1));
                }
                writer.WriteLine("var singleRowResults = new List<BasicRow>();");
                writer.WriteLine(
                    "singleRowCommand.Execute( " + DataAccessStatics.GetConnectionExpression(database) +
                    ", r => { while( r.Read() ) singleRowResults.Add( new BasicRow( r ) ); } );");
                writer.WriteLine("return singleRowResults.Single();");
                writer.WriteLine("} ) ) );");
                writer.WriteLine("}");
                writer.WriteLine("}");

                // Otherwise, execute the full query.
                writer.WriteLine("else {");
                writer.WriteLine(
                    "var command = {0};".FormatWith(
                        getInlineSelectExpression(
                            table,
                            tableColumns,
                            cn.DatabaseInfo is OracleInfo ? "\"{0}.*\", \"ORA_ROWSCN\"".FormatWith(table) : "\"*\"",
                            cacheQueryInDbExpression)));
                writer.WriteLine(getCommandConditionAddingStatement("command"));
                writer.WriteLine("command.Execute( " + DataAccessStatics.GetConnectionExpression(database) + ", r => {");
                writer.WriteLine(
                    "while( r.Read() ) results.Add( new Row( rowsByPkAndVersion.GetOrAdd( System.Tuple.Create( {0}, {1} ), () => new BasicRow( r ) ) ) );".FormatWith(
                        StringTools.ConcatenateWithDelimiter(", ", tableColumns.KeyColumns.Select(i => i.GetDataReaderValueExpression("r")).ToArray()),
                        cn.DatabaseInfo is OracleInfo
                                                        ? "({0})r.GetValue( {1} )".FormatWith(oracleRowVersionDataType, tableColumns.AllColumns.Count())
                                                        : tableColumns.RowVersionColumn.GetDataReaderValueExpression("r")));
                writer.WriteLine("} );");
                writer.WriteLine("}");

                writer.WriteLine("} );");
            }
            else
            {
                writer.WriteLine("var command = {0};".FormatWith(getInlineSelectExpression(table, tableColumns, "\"*\"", cacheQueryInDbExpression)));
                writer.WriteLine(getCommandConditionAddingStatement("command"));
                writer.WriteLine("var results = new List<Row>();");
                writer.WriteLine(
                    "command.Execute( " + DataAccessStatics.GetConnectionExpression(database) +
                    ", r => { while( r.Read() ) results.Add( new Row( new BasicRow( r ) ) ); } );");
            }

            // Add all results to RowsByPk.
            writer.WriteLine("foreach( var i in results ) {");
            var pkTupleCreationArgs = tableColumns.KeyColumns.Select(i => "i." + EwlStatics.GetCSharpIdentifier(i.PascalCasedNameExceptForOracle));
            var pkTuple             = "System.Tuple.Create( " + StringTools.ConcatenateWithDelimiter(", ", pkTupleCreationArgs.ToArray()) + " )";

            writer.WriteLine("cache.RowsByPk[ " + pkTuple + " ] = i;");
            if (excludesPreviousRevisions)
            {
                writer.WriteLine("cache.LatestRevisionRowsByPk[ " + pkTuple + " ] = i;");
            }
            writer.WriteLine("}");

            writer.WriteLine("return results;");
        }
Exemplo n.º 59
0
 public BillDao()
 {
     con = DBConnection.getConnection();
 }
Exemplo n.º 60
0
 private static string getPkAndVersionTupleTypeArguments(DBConnection cn, TableColumns tableColumns)
 {
     return("{0}, {1}".FormatWith(
                getPkTupleTypeArguments(tableColumns),
                cn.DatabaseInfo is OracleInfo ? oracleRowVersionDataType : tableColumns.RowVersionColumn.DataTypeName));
 }