Beispiel #1
1
        public string InsertUser(string Username,string Mailid)
        {
            string Result = "a";
            DBManager DbObj=new DBManager();

            DbParameter[] dbparms = new DbParameter[2];

            dbparms[0] = DbObj.CreateParameter("@Username", Username);
            dbparms[1] = DbObj.CreateParameter("@UserMail", Mailid);
            Result = DbObj.ExecuteScalar("InsertUser", dbparms, CommandType.StoredProcedure).ToString();

            return Result;
        }
Beispiel #2
0
 public void Save()
 {
     DBManager db = new DBManager();
     db.Connect();
     db.Insert(String.Format("insert into size VALUES (null,'{0}')", sizeLabel));
     db.Close();
 }
Beispiel #3
0
        public static int Execute(String query, String database)
        {
            DBManager dbManager = new DBManager();
            MySqlConnection con = null;

            try
            {
                String ip = DBConst.kDbIp;
                con = dbManager.CreateConnection(ip, database);
                con.Open();

                MySqlCommand cmd = new MySqlCommand(query, con);

                int ret = cmd.ExecuteNonQuery();
                return ret;
            }
            catch (System.Exception ex)
            {
                logger.Warn(ex.ToString());
            }
            finally
            {
                dbManager.Close(con);
            }
            return -1;
        }
        public EditParametersForm(DBManager aDBManager)
        {
            InitializeComponent();
            mDBManager = aDBManager;
            if (mDBManager.AlgorithmParameters == null)
            {
                mDBManager.AlgorithmParameters = new AlgorithmParameters();
            }

            ControlGroups.Add(new Control[] { firstLow, firstMedium, firstHigh});
            ControlGroups.Add(new Control[] { secondLow, secondMedium, secondHigh });
            ControlGroups.Add(new Control[] { thirdLow, thirdMedium, thirdHigh });
            ControlGroups.Add(new Control[] { fourthLow, fourthMedium, fourthHigh });
            ControlGroups.Add(new Control[] { fifthLow, fifthMedium, fifthHigh });
            ControlGroups.Add(new Control[] { sixthLow, sixthMedium, sixthHigh });
            ControlGroups.Add(new Control[] { seventhLow, seventhMedium, seventhHigh });

            for (int i = 0; i < 7; i++)
            {
                foreach (var item in ControlGroups[i])
                {
                    item.Enabled = false;
                }
            }
        }
        public AddOrEditClassForm(DBManager dbManag)
        {
            InitializeComponent();
            mDBManager = dbManag;

            this.Text = FormTitles.ClassForm.Add;
            mFormState = FormState.AddingNew;

            RadListDataItem dropDownItem = new RadListDataItem("1");
            dropDownItem.Value = 1;
            dropDownItem.Selected = true;
            gradeDropdownlist.Items.Add(dropDownItem);
            for (int i = 2; i <= 12; ++i)
            {
                dropDownItem = new RadListDataItem(i.ToString());
                dropDownItem.Value = i;
                gradeDropdownlist.Items.Add(dropDownItem);
            }

            importTeachersFromTheDatabase();

            changingHeadteacherReadyButton.Visible = false;
            teachersDropdownlist.Visible = false;

            changeHeadTeacherButton.Visible = false;
            changingHeadteacherReadyButton.Visible = true;
            teachersDropdownlist.Visible = true;

            colorPanel.BackColor = RandomColor.GetRandomColor();

            gradeDropdownlist.DropDownStyle = RadDropDownStyle.DropDownList;
            teachersDropdownlist.DropDownStyle = RadDropDownStyle.DropDownList;
        }
Beispiel #6
0
        public EditGroupsForm(DBManager aDBManager, int classID)
        {
            InitializeComponent();

            mDBManager = aDBManager;
            mClass = mDBManager.Classes[0];
            foreach(var c in mDBManager.Classes){
                if(c.ID == classID){
                    mClass = c;
                    break;
                }
            }

            gridviewGroups.Columns.Add("Име");
            gridviewGroups.AllowAutoSizeColumns = true;
            gridviewGroups.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill;
            gridviewGroups.AllowDrop = false;
            gridviewGroups.AllowMultiColumnSorting = false;
            gridviewGroups.AllowDragToGroup = false;
            gridviewGroups.ShowGroupPanel = false;

            try
            {
                foreach (var group in mClass.Groups)
                {
                    gridviewGroups.Rows.Add(group);
                }
            }
            catch {
                mClass.Groups = new List<string>();
            }
        }
Beispiel #7
0
        public static DataRowCollection SelectFromDB(String query, String database)
        {
            DBManager dbManager = new DBManager();
            MySqlConnection con = null;

            try
            {
                String ip = DBConst.kDbIp;
                con = dbManager.CreateConnection(ip, database);
                con.Open();

                MySqlCommand cmd = new MySqlCommand(query, con);
                MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd);

                DataSet ds = new DataSet("data");

                dataAdapter.Fill(ds, "data");
                DataRowCollection drc = ds.Tables["data"].Rows;

                return drc;
            }
            catch (System.Exception ex)
            {
                logger.Warn(ex.ToString());
            }
            finally
            {
                dbManager.Close(con);
            }
            return null;
        }
    public bool checkForErrors(DBManager dbManager)
    {
        //this should wipe error messages first
        removeNotificationsByType(typeof(NotifyError));

        foreach (Supervillain s in dbManager.SupervillainDB.listOfSupervillains()){
            //check for undecided students
            if (s.Age.GetType() == typeof(Student)){
                if (((Student) s.Age).School.GetType() == typeof (Undecided)) {
                    addNotification(new Notification(new NotifyError(),
                        "Assign " + s.SuperhumanName + " a school!"));
                }
            }
            //check for unemployed adults
            else if (s.Age.GetType() == typeof(Adult)) {
                if (((Adult)s.Age).Occupation.GetType() == typeof(Unemployed)) {
                    addNotification(new Notification(new NotifyError(),
                        "Assign " + s.SuperhumanName + " an occupation!"));
                }
            }
        }

        //more than 4 classes in a cirrculum
        //...
        return findErrorNotifications();
    }
Beispiel #9
0
 public void Save()
 {
     DBManager db = new DBManager();
     db.Connect();
     db.Insert(String.Format("insert into size_map VALUES (null,'{0}','{1}')", productID, sizeID));
     db.Close();
 }
        private void AssemblyDetailsForm_Load(object sender, EventArgs e)
        {
            manager = new DBManager(RevitDocument);

            //if (this.IsAdd)
            //{
            //    lblTitle.Text = "";
            //}
            //else
            //{
                toSwap = CurrentAssembly;
            //    lblToSwap.Text = toSwap.AssemblyName;
                loadInformation(toSwap);
            //}
            List<Assembly> fromModel = manager.RetrieveWallInfo();
            //List<Assembly> options = null;
            //if (this.IsAdd)
            //options = manager.getAllAssemblies();
            //options.AddRange(fromModel);

            //else
            //    options = manager.getAssembliesByCode(toSwap.AssemblyCode);
            //if (options != null)
            //{
            //    foreach (Assembly a in options)
            //        cboAlternatives.Items.Add(a);
            //}
        }
 static public DataTable   GetAllDataListCategory()
 {
     String SQL = "select Category, Category from Sch.DesignformDatalist group by category";
     DBManager db = new DBManager();
     return  db.GetDataTableFromSQL(SQL);
     
 }
Beispiel #12
0
 public void Save()
 {
     DBManager db = new DBManager();
     db.Connect();
     db.Insert(String.Format("insert into product_detail VALUES (null,'{0}')", description));
     db.Close();
 }
Beispiel #13
0
 public void Save()
 {
     DBManager db = new DBManager();
     db.Connect();
     db.Insert(String.Format("insert into product_image VALUES (null,'{0}','{1}','{2}')", productID, url, orderOfDisplay));
     db.Close();
 }
Beispiel #14
0
 public EnableFeatureInfoRec GetFeatureInfo(DBManager dbManager, FeatureType type, string subType)
 {
     using (IDBProvider dbInstance = SP.DB.GetInstance(dbManager))
     {
         return dbInstance._<EnableFeatureAccessor>().SelectInfoByType(GetFeatureTypeKey(type, subType));
     }
 }
        private void InitConfiguration(DBManager dbManager)
        {
            //init vars
            List<APITimeoutConfigRec> tmpConfigList;
            Dictionary<APIG, APITimeoutConfigRec> tmpMapByGroup = new Dictionary<APIG, APITimeoutConfigRec>();

            //get list
            using (IDBProvider dbInstance = SP.DB.GetInstance(dbManager))
            {
                tmpConfigList = dbInstance._<APITimeoutConfigAccessor>().SelectList();
                foreach (var record in tmpConfigList)
                {
                    tmpMapByGroup.Add(record.Type, record);
                }
            }

            //first init (if no data in the database)
            Util.Enum.GetValues<APIG>().ForEach(item =>
                {
                    if (!tmpMapByGroup.ContainsKey(item))
                    {
                        var record = new APITimeoutConfigRec
                            {
                                Type = item,
                                TimeoutMs = DEFAULT_TIMEOUT_MS
                            };
                        tmpConfigList.Add(record);
                        tmpMapByGroup.Add(item, record);
                    }
                });

            //result
            Interlocked.Exchange(ref _configList, tmpConfigList);
            Interlocked.Exchange(ref _mapByGroup, tmpMapByGroup);
        }
Beispiel #16
0
 public void Save()
 {
     DBManager db = new DBManager();
     db.Connect();
     db.Insert(String.Format("insert into product VALUES (null,'{0}','{1}','{2}','{3}')", name, collectionID, price, description));
     db.Close();
 }
        private void InitConfiguration(DBManager dbManager)
        {
            var tmpAccountTypeList = new Dictionary<long, List<VendorAccountTypeInfoRec>>();
            var tmpAccessList = new Dictionary<long, List<VendorAccountTypeAccessRec>>();

            using (IDBProvider dbInstance = SP.DB.GetInstance(dbManager))
            {
                var domainList = SP.DomainProvider.Domains;
                foreach (var domainRec in domainList)
                {
                    var domainID = domainRec.DomainID;

                    SP.SessionContext.ExecuteInSystemSessionContext(domainID, () =>
                    {
                        //start tx
                        dbInstance.BeginTransaction();

                        //translock
                        var dummy = Entity<DomainRec>.SelectForUpdate(dbInstance.Get, domainRec.ID);

                        //read config
                        tmpAccountTypeList.Add(domainID, dbInstance._<VendorAccountTypeAccessor>().AccountTypeList());
                        tmpAccessList.Add(domainID, dbInstance._<VendorAccountTypeAccessor>().AccessList());

                        //commit tx
                        dbInstance.CommitTransaction();
                    });
                }
            }

            //result
            Interlocked.Exchange(ref _accountTypeList, tmpAccountTypeList);
            Interlocked.Exchange(ref _accessList, tmpAccessList);
        }
 public static DBManager sharedManager()
 {
     if (_sharedDBManager == null) {
         GameObject obj = new GameObject();
         _sharedDBManager = obj.AddComponent<DBManager>();
     }
     return _sharedDBManager;
 }
 public void Update(DBManager dbManager, List<VendorAccountTypeRec> accountTypeList, List<VendorAccountTypeAccessRec> accessList, string note)
 {
     //lock to avoid concurrent actions
     lock (_locker)
     {
         UpdateConfiguration(dbManager, accountTypeList, accessList, note);
     }
 }
 public void Reload(DBManager dbManager, object parameter)
 {
     //lock to avoid concurrent actions
     lock (_locker)
     {
         InitConfiguration(dbManager);
     }
 }
		protected override async Task OpenMayOverrideAsync(object args = null)
		{
			_dbManager = new DBManager(_directory, false);
			await _dbManager.OpenAsync().ConfigureAwait(false);

			await LoadNonDbPropertiesAsync().ConfigureAwait(false);
			await LoadFoldersWithoutContentAsync().ConfigureAwait(false);
		}
 public void Update(DBManager dbManager,List<APITimeoutConfigRec> data)
 {
     //lock to avoid concurrent actions
     lock (_locker)
     {
         UpdateConfiguration(dbManager, data);
     }
 }
        public PrintTheScheduleForm(DBManager aDBManager)
        {
            InitializeComponent();

            mDBManager = aDBManager;

            #region Layout setting
            gridviewSchedule.Columns.Add("Час");
            gridviewSchedule.Columns["Час"].Width = 10;
            gridviewSchedule.Columns["Час"].TextAlignment = ContentAlignment.MiddleCenter;
            gridviewSchedule.Columns["Час"].WrapText = true;
            gridviewSchedule.Columns.Add("Понеделник");
            gridviewSchedule.Columns["Понеделник"].TextAlignment = ContentAlignment.MiddleCenter;
            gridviewSchedule.Columns["Понеделник"].WrapText = true;
            gridviewSchedule.Columns.Add("Вторник");
            gridviewSchedule.Columns["Вторник"].TextAlignment = ContentAlignment.MiddleCenter;
            gridviewSchedule.Columns["Вторник"].WrapText = true;
            gridviewSchedule.Columns.Add("Сряда");
            gridviewSchedule.Columns["Сряда"].TextAlignment = ContentAlignment.MiddleCenter;
            gridviewSchedule.Columns["Сряда"].WrapText = true;
            gridviewSchedule.Columns.Add("Четвъртък");
            gridviewSchedule.Columns["Четвъртък"].TextAlignment = ContentAlignment.MiddleCenter;
            gridviewSchedule.Columns["Четвъртък"].WrapText = true;
            gridviewSchedule.Columns.Add("Петък");
            gridviewSchedule.Columns["Петък"].TextAlignment = ContentAlignment.MiddleCenter;
            gridviewSchedule.Columns["Петък"].WrapText = true;

            gridviewSchedule.GridViewElement.DrawBorder = true;
            gridviewSchedule.TableElement.DrawBorder = true;

            gridviewSchedule.AllowAddNewRow = false;
            gridviewSchedule.AllowEditRow = true;
            gridviewSchedule.AllowDeleteRow = false;
            gridviewSchedule.AllowDragToGroup = false;
            gridviewSchedule.AllowRowReorder = false;
            gridviewSchedule.AllowRowResize = true;
            gridviewSchedule.EnableSorting = false;
            gridviewSchedule.ShowGroupPanel = false;
            gridviewSchedule.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill;
            gridviewSchedule.ShowColumnHeaders = true;
            gridviewSchedule.AllowColumnHeaderContextMenu = true;
            gridviewSchedule.ShowRowHeaderColumn = false;
            gridviewSchedule.EnableFastScrolling = false;
            gridviewSchedule.SelectionMode = GridViewSelectionMode.FullRowSelect;
            #endregion

            try
            {
                int i = 0;
                foreach (var c in mDBManager.Timetable[0].Classes)
                {
                    dropdownListClasses.Items.Add(new RadListDataItem(c.Class.Name) { Tag = i });
                    i++;
                }
            }
            catch { }
        }
    public void checkForWarnings(DBManager dbManager)
    {
        removeNotificationsByType(typeof(NotifyWarning));

        //check if gradeschool has 4 classes in a cirrculum
        if (dbManager.BuildingDB.GradeSchool.Curriculum.listOfSchoolClasses().Count < 4) {
            addNotification(new Notification(new NotifyWarning(), "Add more classes to the Gradeschool"));
        }
    }
 public Superhuman(int id, int weeksOld, Stats stats, SuperPower superPower, string superhumanName, DBManager dbManager)
 {
     this.id = id;
     this.stats = stats;
     this.superPower = superPower;
     this.superhumanName = superhumanName;
     this.weeksOld = weeksOld;
     this.dbManager = dbManager;
     setAge();
 }
        public AddOrEditLessonForm(DBManager aDBManager)
        {
            InitializeComponent();

            mFormState = FormState.AddingNew;
            mDBManager = aDBManager;
            this.Text = FormTitles.LessonForm.Add;

            addDefaultControlsInformationWhenAddingNew();
        }
        public AddOrEditTeacherForm(DBManager aDBManager)
        {
            InitializeComponent();

            mDBManager = aDBManager;
            mFormState = FormState.AddingNew;
            this.Text = FormTitles.TacherForm.Add;

            radioButtonFemale.IsChecked = true;

            groupboxColorPanelColor.BackColor = RandomColor.GetRandomColor();
        }
Beispiel #28
0
        public int Getuserbymail(string Mailid)
        {
            int Result;
            DBManager DbObj = new DBManager();

            DbParameter[] dbparms = new DbParameter[1];

            dbparms[0] = DbObj.CreateParameter("@Mail", Mailid);
            Result = Convert.ToInt32(DbObj.ExecuteScalar("GetUserbyMail", dbparms, CommandType.StoredProcedure));

            return Result;
        }
Beispiel #29
0
        /// <summary>
        /// Bu metot kendi kompleks sorgunuzu oluşturabilmenizi sağlar.
        /// This method can be used to perform complex queries.
        /// </summary>
        /// <param name="query">Query statement.</param>
        /// <param name="parameters">Query parameters. This is not a required.</param>
        /// <returns>This method will return DbDataReader object.</returns>
        public DbDataReader ExecuteCustomQuery(string query, object parameters = null)
        {
            var dbManager = new DBManager(OrmConfiguration);

            dbManager.CreateCommand(query);

            if (parameters != null)
                dbManager.AddParameter(parameters);

            var reader = dbManager.ExecuteReader();

            return reader;
        }
 public static int Insert(TotalOutcomesModel totalOutcomes)
 {
     return(DBManager.InsertTotalOutcomes(totalOutcomes));
 }
Beispiel #31
0
        /// <summary>
        ///  Delete individual product type from product type master.
        /// For delete an entry, first set the particular id u want to delete
        /// </summary>
        /// <returns>return success alert when the details deleted successfully otherwise return error alert</returns>>
        public OutputMessage Delete()
        {
            using (DBManager db = new DBManager())
            {
                try
                {
                    if (!Entities.Security.Permissions.AuthorizeUser(this.Modifiedby, Security.BusinessModules.Type, Security.PermissionTypes.Delete))
                    {
                        return(new OutputMessage("Limited Access. Contact Administrator", false, Entities.Type.InsufficientPrivilege, "Type | Delete", System.Net.HttpStatusCode.InternalServerError));
                    }
                    else if (this.ID != 0)
                    {
                        db.Open();
                        string query = @"delete from TBL_TYPE_MST where Type_Id=@ID";
                        db.CreateParameters(1);
                        db.AddParameters(0, "@ID", this.ID);
                        if (Convert.ToInt32(db.ExecuteNonQuery(System.Data.CommandType.Text, query)) >= 1 ? true : false)
                        {
                            return(new OutputMessage("Product Type deleted successfully", true, Entities.Type.Others, "Type | Delete", System.Net.HttpStatusCode.OK));
                        }
                        else
                        {
                            return(new OutputMessage("Something went wrong. Product Type could not be deleted", false, Entities.Type.Others, "Type | Delete", System.Net.HttpStatusCode.InternalServerError));
                        }
                    }
                    else
                    {
                        return(new OutputMessage("ID must not be zero for deletion", false, Entities.Type.Others, "Type | Delete", System.Net.HttpStatusCode.InternalServerError));
                    }
                }
                catch (Exception ex)
                {
                    dynamic Exception = ex;
                    if (ex.GetType().GetProperty("Number") != null)
                    {
                        if (Exception.Number == 547)
                        {
                            db.RollBackTransaction();

                            return(new OutputMessage("You cannot delete this product type because it is referenced in other transactions", false, Entities.Type.ForeignKeyViolation, "producttype | Delete", System.Net.HttpStatusCode.InternalServerError, ex));
                        }
                        else
                        {
                            db.RollBackTransaction();

                            return(new OutputMessage("Something went wrong. Try again later", false, Type.RequiredFields, "producttype | Delete", System.Net.HttpStatusCode.InternalServerError, ex));
                        }
                    }
                    else
                    {
                        db.RollBackTransaction();

                        return(new OutputMessage("Something went wrong. Product Type could not be deleted", false, Type.Others, "producttype | Delete", System.Net.HttpStatusCode.InternalServerError, ex));
                    }
                }
                finally
                {
                    db.Close();
                }
            }
        }
Beispiel #32
0
    public string InsertSeatingForm(EntranceDM.EntranceSeat objESM, Admin.AdministratorData.AuditDM audit)
    {
        NewDAL.DBManager objDB = new DBManager();
        objDB.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["FeesManagementConn"].ConnectionString;
        objDB.DBManager(DataAccessLayer.DataProvider.SqlServer, objDB.ConnectionString);
        objDB.Open();
        objDB.BeginTransaction();
        string retv = "";
        string f    = "";

        try
        {
            objDB.CreateParameters(14);
            objDB.AddParameters(0, "ID", objESM.ID, DbType.Int32);
            objDB.AddParameters(1, "Examname", objESM.Examname, DbType.Int32);
            objDB.AddParameters(2, "Examvenue", objESM.Examvenue, DbType.String);
            objDB.AddParameters(3, "Venuestr", objESM.Venuestr, DbType.String);
            objDB.AddParameters(4, "Roomno", objESM.Roomno, DbType.String);
            objDB.AddParameters(5, "Roomstr", objESM.Roomstr, DbType.String);
            objDB.AddParameters(6, "Rowsno", objESM.Rowsno, DbType.String);
            objDB.AddParameters(7, "ColumnNo", objESM.ColumnNo, DbType.String);
            objDB.AddParameters(8, "Date", objESM.Date, DbType.DateTime);
            objDB.AddParameters(9, "Timefrom", objESM.Timefrom, DbType.String);
            objDB.AddParameters(10, "Timeto", objESM.Timeto, DbType.String);
            objDB.AddParameters(11, "seatcode", objESM.seatcode, DbType.String);
            objDB.AddParameters(12, "ExamYear", objESM.ExamYear, DbType.String);
            objDB.AddParameters(13, "Flag", objESM.Flag, DbType.String);
            objDB.ExecuteNonQuery(CommandType.StoredProcedure, "EntranceSeat_insert");
            objDB.CreateParameters(9);
            objDB.AddParameters(0, "ID", 0, DbType.Int32);
            objDB.AddParameters(1, "Form_Name", audit.Form_Name, DbType.String);
            objDB.AddParameters(2, "Action", audit.Action, DbType.String);
            objDB.AddParameters(3, "User_ID", audit.User_ID, DbType.String);
            objDB.AddParameters(4, "Entry_Date", audit.Entry_Date, DbType.String);
            objDB.AddParameters(5, "Record_ID", audit.Record_ID, DbType.String);
            objDB.AddParameters(6, "Entry_Time", audit.Entry_Time, DbType.String);
            objDB.AddParameters(7, "InstituteID", audit.InstituteID, DbType.Int32);
            objDB.AddParameters(8, "SessionID", audit.SessionID, DbType.String);
            objDB.ExecuteNonQuery(CommandType.StoredProcedure, "Audit_Insert");
            objDB.Transaction.Commit();
            if (objESM.Flag == "N")
            {
                retv = "Record saved.";
            }
            else if (objESM.Flag == "U")
            {
                retv = "Record Updated Successfully.";
            }
            else
            {
                retv = "Record deleted Successfully.";
            }
        }
        catch (Exception ex)
        {
            objDB.Transaction.Rollback();
            retv = "Unable to save record :-" + ex.Message.ToString();
        }
        finally
        {
            objDB.Connection.Close();
            objDB.Dispose();
        }
        return(retv);
    }
Beispiel #33
0
 public ServiceController()
 {
     dbm = new DBManager();
 }
        public void GetTodaysTotalInvestmentCost()
        {
            try
            {
                DateTime      date = DateTime.Now;
                string        a, b, c, d, x;
                double        total;
                DBManager     manager    = new DBManager();
                SqlConnection connection = manager.Connection();

                string     selectQuery = "SELECT Sum(Book) ,sum(Paper),sum(Ink),sum(Equipment),sum(Others) From InvestmentCost ";
                SqlCommand cmd         = new SqlCommand(selectQuery, connection);
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    a = reader[0].ToString();

                    b = reader[1].ToString();
                    c = reader[2].ToString();
                    d = reader[3].ToString();
                    x = reader[4].ToString();

                    if (a.Equals(""))
                    {
                        total = 0.0;
                        showtotalInvestMentTextBox.Text = total.ToString();
                    }
                    else if (b.Equals(""))
                    {
                        total = 0.0;
                        showtotalInvestMentTextBox.Text = total.ToString();
                    }
                    else if (c.Equals(""))
                    {
                        total = 0.0;
                        showtotalInvestMentTextBox.Text = total.ToString();
                    }
                    else if (d.Equals(""))
                    {
                        total = 0.0;
                        showtotalInvestMentTextBox.Text = total.ToString();
                    }

                    else if (x.Equals(""))
                    {
                        total = 0.0;
                        showtotalInvestMentTextBox.Text = total.ToString();
                    }

                    else
                    {
                        total = (Convert.ToDouble(reader[0]) + Convert.ToDouble(reader[1]) + Convert.ToDouble(reader[2]) + Convert.ToDouble(reader[3]) + Convert.ToDouble(reader[4]));
                        showtotalInvestMentTextBox.Text = total.ToString();
                    }
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #35
0
 /// <summary>
 /// Checks whether any vehicles exist
 /// </summary>
 /// <returns>True if vehicles exist, otherwise false</returns>
 private Boolean HasVehicles()
 {
     return !DBManager.IsTableEmpty("vehicles");
 }
Beispiel #36
0
/*
 */
        public void LoadAnswers()
        {
            string strSQL;

            IDBManager dbManager = new DBManager(DataProvider.SqlServer);

            dbManager.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;;

            //build query
            if (hndUserId.Value == "-1")//not logged in
            {
                strSQL = @"SELECT a.dCreateDate, a.Answer, a.iUser, a.VoteY, a.VoteN, a.iD, a.QuestId, a.AbuseFlg, u.txtEmail, u.txtUserName, u.userDir, u.profilePic, -1 as ResponseId  
                           FROM Answers a
                           INNER JOIN tblUser u ON a.iUser = u.iD
                           WHERE QuestId = '" + hdnQId.Value + "'";
            }
            else //logged in
            {
                strSQL  = @"SELECT a.dCreateDate, a.iD, a.Answer, a.iUser, a.VoteY, a.VoteN, a.QuestId, u.txtEmail, a.AbuseFlg, u.txtEmail, u.txtUserName, u.userDir, u.profilePic
                             , r.iD as ResponseId 
                                       FROM Answers a
                                       LEFT JOIN tblUserResponse r ON a.iD = r.AnswerId AND r.userId ='" + hndUserId.Value + "'";
                strSQL += @"JOIN tblUser u ON a.iUser = u.iD
                                       WHERE a.QuestId='" + hdnQId.Value + "'";
            }

            //Declare Dataset
            DataSet dsItems = new DataSet();

            try
            {
                dbManager.Open();
                dsItems = dbManager.ExecuteDataSet(CommandType.Text, strSQL);

                int listCount = dsItems.Tables[0].Rows.Count;

                if (listCount > 0)
                {
                    dlCommentList.DataBind();

                    lblCommentCount.Text = (listCount == 1) ? listCount.ToString() + " Answer" : listCount.ToString() + " Answers";
                }
                else
                {
                    lblCommentCount.Text     = "Be the first answer!";
                    lblCommentCount.CssClass = "ltgreen14b";
                }

                dlCommentList.DataSource = dsItems;
                dlCommentList.DataBind();
            }
            catch (Exception ex)
            {
                ErrorLog.ErrorRoutine(false, "Error in AnswerList: " + ex.Message);
            }

            finally
            {
                dbManager.Close();
                dbManager.Dispose();
                dsItems = null;
            }

            //Always show comment box. Disable if not logged in
            pnlCommentBox.Visible = true;
            if (Session["LoggedIn"].ToString() == "No")
            {
                pnlLoginMsg.Visible    = true;
                pnlLogin.Visible       = true;
                txtComment.Enabled     = false;
                btnPostComment.Enabled = false;
            }
            else
            {
                pnlLoginMsg.Visible    = false;
                pnlLogin.Visible       = false;
                txtComment.Enabled     = true;
                btnPostComment.Enabled = true;
            }
        }
        private void method_0(ObjectId[] objectId_0, ProgressMeter progressMeter_0, CoordinateSystem coordinateSystem_0)
        {
            Database       workingDatabase = HostApplicationServices.WorkingDatabase;
            Editor         editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            List <Solid3d> list            = new List <Solid3d>();
            double         epsilon         = Convert.ToDouble(CMD_FacesToSolid.string_2);
            bool           flag            = true;

            if (CMD_FacesToSolid.string_0 == "N")
            {
                flag = false;
            }
            DBManager.SetEpsilon();
            List <Triangle> list2 = Conversions.ToCeometricAcDbTriangleList(objectId_0);

            if (!Conversions.IsWCS(coordinateSystem_0))
            {
                Triangle.TransformCoordinates(list2, CoordinateSystem.Global(), coordinateSystem_0);
            }
            list2.Sort(new Triangle.CompareMinX());
            int    num  = 0;
            double num2 = -1.7976931348623157E+308;
            double num3 = -1.7976931348623157E+308;
            double num4 = 1.7976931348623157E+308;
            double num5 = 1.7976931348623157E+308;

            for (int i = list2.Count - 1; i >= 0; i--)
            {
                if (list2[i].NormalVector.IsOrthogonalTo(new ngeometry.VectorGeometry.Vector3d(0.0, 0.0, 1.0)))
                {
                    list2.RemoveAt(i);
                    num++;
                }
                else
                {
                    double minimumX = list2[i].MinimumX;
                    if (minimumX < num4)
                    {
                        num4 = minimumX;
                    }
                    double maximumX = list2[i].MaximumX;
                    if (maximumX > num2)
                    {
                        num2 = maximumX;
                    }
                    double minimumY = list2[i].MinimumY;
                    if (minimumY < num5)
                    {
                        num5 = minimumY;
                    }
                    double maximumY = list2[i].MaximumY;
                    if (maximumY > num3)
                    {
                        num3 = maximumY;
                    }
                }
            }
            ngeometry.VectorGeometry.Vector3d vector3d = new ngeometry.VectorGeometry.Vector3d(0.5 * (num4 + num2), 0.5 * (num5 + num3), 0.0);
            double num6 = 0.5 * Math.Max(Math.Abs(num2 - num4), Math.Abs(num3 - num5));
            double num7 = Math.Ceiling(100000.0 / num6);

            for (int j = 0; j < list2.Count; j++)
            {
                list2[j] = list2[j].Move(-1.0 * vector3d);
            }
            SubDMeshHandler subDMeshHandler = new SubDMeshHandler(list2);

            subDMeshHandler.BuildDataStructure(false);
            int k = 2147483647;

            while (k > 0)
            {
                this.messageFilter_0.CheckMessageFilter();
                k    = subDMeshHandler.HealXY(epsilon);
                num += k;
            }
            editor.WriteMessage("\nDegenerate projections healed: " + num);
            Autodesk.AutoCAD.Geometry.Matrix3d matrix3d  = Autodesk.AutoCAD.Geometry.Matrix3d.Scaling(num7, new Point3d(0.0, 0.0, 0.0));
            Autodesk.AutoCAD.Geometry.Matrix3d matrix3d2 = Autodesk.AutoCAD.Geometry.Matrix3d.Scaling(1.0 / num7, new Point3d(0.0, 0.0, 0.0));
            Autodesk.AutoCAD.Geometry.Matrix3d matrix3d3 = Autodesk.AutoCAD.Geometry.Matrix3d.Displacement(new Autodesk.AutoCAD.Geometry.Vector3d(vector3d.X, vector3d.Y, 0.0));
            progressMeter_0 = new ProgressMeter();
            progressMeter_0.SetLimit(objectId_0.Length);
            progressMeter_0.Start("Extruding objects");
            int num8 = 0;
            int num9 = 0;

            for (int l = 0; l < subDMeshHandler.FaceVertexIndex1.Count; l++)
            {
                try
                {
                    progressMeter_0.MeterProgress();
                    this.messageFilter_0.CheckMessageFilter((long)l, 1000);
                }
                catch (System.Exception ex)
                {
                    for (int m = 0; m < list.Count; m++)
                    {
                        list[m].Dispose();
                    }
                    progressMeter_0.Stop();
                    throw;
                }
                try
                {
                    Face   face = new Face(new Point3d(subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex1[l]].X, subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex1[l]].Y, subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex1[l]].Z), new Point3d(subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex2[l]].X, subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex2[l]].Y, subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex2[l]].Z), new Point3d(subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex3[l]].X, subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex3[l]].Y, subDMeshHandler.Vertices[subDMeshHandler.FaceVertexIndex3[l]].Z), false, false, false, false);
                    double z    = face.GetVertexAt(0).Z;
                    double z2   = face.GetVertexAt(1).Z;
                    double z3   = face.GetVertexAt(2).Z;
                    short  num10;
                    if (CMD_FacesToSolid.double_0 < 0.0)
                    {
                        if (z <= z2 && z <= z3)
                        {
                            num10 = 0;
                        }
                        else if (z2 <= z && z2 <= z3)
                        {
                            num10 = 1;
                        }
                        else
                        {
                            num10 = 2;
                        }
                    }
                    else if (z >= z2 && z >= z3)
                    {
                        num10 = 0;
                    }
                    else if (z2 >= z && z2 >= z3)
                    {
                        num10 = 1;
                    }
                    else
                    {
                        num10 = 2;
                    }
                    Point3d vertexAt = face.GetVertexAt(num10);
                    Point3d point3d  = new Point3d(vertexAt.X, vertexAt.Y, vertexAt.Z + CMD_FacesToSolid.double_0);
                    //point3d..ctor(vertexAt.X, vertexAt.Y, vertexAt.Z + CMD_FacesToSolid.double_0);
                    Autodesk.AutoCAD.DatabaseServices.Line line = new Autodesk.AutoCAD.DatabaseServices.Line(vertexAt, point3d);
                    Region region = this.method_2(subDMeshHandler, l);
                    if (region == null)
                    {
                        num8++;
                    }
                    else
                    {
                        region.TransformBy(matrix3d);
                        line.TransformBy(matrix3d);
                        try
                        {
                            Solid3d solid3d = new Solid3d();
                            solid3d.ExtrudeAlongPath(region, line, 0.0);
                            solid3d.SetPropertiesFrom(face);
                            list.Add(solid3d);
                        }
                        catch (System.Exception ex)
                        {
                            num9++;
                        }
                        line.Dispose();
                        region.Dispose();
                    }
                }
                catch (System.Exception ex)
                {
                }
            }
            editor.WriteMessage("\nNumber of failed projections: " + num8.ToString());
            editor.WriteMessage("\nNumber of failed extrusions : " + num8.ToString());
            progressMeter_0.Stop();
            if (flag && list.Count > 1)
            {
                progressMeter_0 = new ProgressMeter();
                int limit = (int)Math.Ceiling(Math.Log((double)list.Count) / Math.Log(2.0));
                progressMeter_0.SetLimit(limit);
                progressMeter_0.Start("Building solid");
                this.method_1(ref list, ref progressMeter_0);
            }
            using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
            {
                BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                for (int n = 0; n < list.Count; n++)
                {
                    list[n].TransformBy(matrix3d2);
                    list[n].TransformBy(matrix3d3);
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(coordinateSystem_0, CoordinateSystem.Global());
                    if (!coordinateTransformator.bool_0)
                    {
                        list[n].TransformBy(coordinateTransformator.ToAcadTransformation());
                    }
                    blockTableRecord.AppendEntity(list[n]);
                    transaction.AddNewlyCreatedDBObject(list[n], true);
                }
                transaction.Commit();
            }
            progressMeter_0.Stop();
        }
Beispiel #38
0
/*
 */
        private void BindData()
        {
            //load detailed data for entry item
            string strSQL;
            string strUserId;

            //Get query strings for sql query
            string[] arString;
            arString = Request.QueryString.GetValues("q");
            if (arString == null)
            {
                lblStatus.Text = "Sorry...Couldn't find that person.";
                return;
            }
            strUserId       = HttpUtility.UrlDecode(arString[0].ToString());
            hdnUserId.Value = strUserId;
            arString[0]     = string.Empty;

            IDBManager dbManager = new DBManager(DataProvider.SqlServer);

            dbManager.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;;

            //query item and user details for entry
            strSQL = "SELECT u.txtFullName, u.txtUserName, u.profilePic, u.txtUserDetails, u.txtWebSite, u.txtEmail, u.txtPhonenum, u.userDir, u.iShowPhoneNum, u.notify_comment_flg from tblUser u WHERE iD='" + strUserId + "'";

            try
            {
                dbManager.Open();
                dbManager.ExecuteReader(CommandType.Text, strSQL);

                if (dbManager.DataReader.Read())
                {
                    lblFullName.Text = dbManager.DataReader["txtFullName"].ToString();

                    //Details
                    lblDetailsData.Text = dbManager.DataReader["txtUserDetails"].ToString();

                    //Contact
                    Session["Email"]             = dbManager.DataReader["txtEmail"].ToString();
                    lnkEmailData.Text            = ParseEmail(dbManager.DataReader["txtEmail"].ToString());
                    lnkEmailData.CommandArgument = dbManager.DataReader["txtEmail"].ToString();

                    lnkEmailData.Attributes.Add("href", "mailto:" + dbManager.DataReader["txtEmail"].ToString() + "?subject=Contact from Boardhunt");
                    hdnNotifyEmail.Value = dbManager.DataReader["notify_comment_flg"].ToString();

                    lblPhoneData.Text    = dbManager.DataReader["txtPhoneNum"].ToString();
                    lblPhoneData.Visible = ShowPhone(dbManager.DataReader["iShowPhoneNum"]);

                    lblDetailsData.Text = dbManager.DataReader["txtUserDetails"].ToString();

                    Pic1.ImageUrl = FormatPicPath(dbManager.DataReader["userDir"].ToString(), dbManager.DataReader["profilePic"].ToString());

                    string ratCnt = dbManager.DataReader["numRating"].ToString();
                }
                else
                {
                    lblStatus.Text = "Sorry...Couldn't find that person.";
                    return;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.ErrorRoutine(false, "Profile:Page_Load:Msg: " + ex.Message);
            }
            finally
            {
                dbManager.Close();
                dbManager.Dispose();
            }
        }
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="paramModel">UIModel</param>
        /// <param name="paramDepositDetailList">充值明细列表</param>
        /// <returns></returns>
        public bool SaveDetailDS(WalletDepositMoneyUIModel paramModel, List <WalletDepositMoneyUIModel> paramDepositDetailList)
        {
            var funcName = "SaveDetailDS";

            LogHelper.WriteBussLogStart(BussID, LoginInfoDAX.UserName, funcName, "", "", null);

            //服务端检查
            if (!ServerCheck(paramModel))
            {
                LogHelper.WriteBussLogEndNG(BussID, LoginInfoDAX.UserName, funcName, ResultMsg, "", null);
                return(false);
            }

            #region 准备数据

            //将UIModel转为TBModel
            var argsWallet = CopyModel <MDLEWM_Wallet>(paramModel);
            //待保存的钱包异动日志
            MDLEWM_WalletTrans newWalletTrans = new MDLEWM_WalletTrans();

            #region 更新[电子钱包]
            //钱包可用余额
            argsWallet.Wal_AvailableBalance = argsWallet.Wal_AvailableBalance;
            argsWallet.Wal_UpdatedBy        = LoginInfoDAX.UserName;
            argsWallet.Wal_UpdatedTime      = BLLCom.GetCurStdDatetime();
            argsWallet.WHERE_Wal_ID         = argsWallet.Wal_ID;
            argsWallet.WHERE_Wal_VersionNo  = argsWallet.Wal_VersionNo;
            #endregion

            if (paramModel.ThisDepositAmount > 0)
            {
                #region 获取充值方式

                //充值方式名称
                string tempPaymentModeName = string.Empty;
                //充值方式编码
                string tempPaymentModeCode = string.Empty;
                foreach (var loopAmountTransDetail in paramDepositDetailList)
                {
                    if (loopAmountTransDetail.PayAmount == null ||
                        loopAmountTransDetail.PayAmount == 0)
                    {
                        continue;
                    }
                    tempPaymentModeName += (!string.IsNullOrEmpty(tempPaymentModeName) ? SysConst.Semicolon_DBC : string.Empty) + loopAmountTransDetail.PaymentModeName;
                    tempPaymentModeCode += (!string.IsNullOrEmpty(tempPaymentModeCode) ? SysConst.Semicolon_DBC : string.Empty) + loopAmountTransDetail.PaymentModeCode;
                }
                #endregion

                //生成钱包异动日志
                newWalletTrans = BLLCom.CreateWalletTrans(new MDLEWM_WalletTrans()
                {
                    WalT_Org_ID   = LoginInfoDAX.OrgID,
                    WalT_Org_Name = LoginInfoDAX.OrgShortName,
                    WalT_Wal_ID   = argsWallet.Wal_ID,
                    WalT_Wal_No   = argsWallet.Wal_No,
                    //异动类型为{充值}
                    WalT_TypeName = WalTransTypeEnum.Name.CZ,
                    WalT_TypeCode = WalTransTypeEnum.Code.CZ,
                    //充值方式
                    WalT_RechargeTypeName = tempPaymentModeName,
                    WalT_RechargeTypeCode = tempPaymentModeCode,
                    //异动金额
                    WalT_Amount      = paramModel.ThisDepositAmount,
                    WalT_ChannelName = LoginTerminalEnum.Name.PC,
                    WalT_ChannelCode = LoginTerminalEnum.Code.PC,
                    WalT_Remark      = argsWallet.Wal_Remark,
                });
            }
            #endregion

            #region 带事务的保存

            try
            {
                DBManager.BeginTransaction(DBCONFIG.Coeus);

                #region 保存[电子钱包]

                bool saveWalletResult = _bll.Save(argsWallet);
                if (!saveWalletResult)
                {
                    DBManager.RollBackTransaction(DBCONFIG.Coeus);
                    ResultMsg = MsgHelp.GetMsg(MsgCode.E_0010, new object[] { SystemActionEnum.Name.RECHARGE + SystemTableEnums.Name.EWM_Wallet });
                    LogHelper.WriteBussLogEndNG(BussID, LoginInfoDAX.UserName, funcName, ResultMsg, "", null);
                    return(false);
                }

                #endregion

                #region 保存[电子钱包异动]

                bool insertWalletTransResult = _bll.Insert(newWalletTrans);
                if (!insertWalletTransResult)
                {
                    DBManager.RollBackTransaction(DBCONFIG.Coeus);
                    ResultMsg = MsgHelp.GetMsg(MsgCode.E_0010, new object[] { SystemActionEnum.Name.NEW + SystemTableEnums.Name.EWM_WalletTrans });
                    LogHelper.WriteBussLogEndNG(BussID, LoginInfoDAX.UserName, funcName, ResultMsg, "", null);
                    return(false);
                }
                #endregion

                DBManager.CommitTransaction(DBCONFIG.Coeus);
            }
            catch (Exception ex)
            {
                DBManager.RollBackTransaction(DBCONFIG.Coeus);
                ResultMsg = MsgHelp.GetMsg(MsgCode.E_0018, new object[] { SystemActionEnum.Name.RECHARGE, ex.Message });
                LogHelper.WriteBussLogEndNG(BussID, LoginInfoDAX.UserName, funcName, ex.Message, "", null);
                return(false);
            }

            #endregion

            //将最新数据回写给DetailDS
            CopyModel(argsWallet, paramModel);

            return(true);
        }
        public void ComputePrincipalAxisBoundingBox(ObjectId[] idArray)
        {
            Editor   editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database workingDatabase = HostApplicationServices.WorkingDatabase;

            DBManager.SetEpsilon();
            this.progressMeter_0 = new ProgressMeter();
            this.messageFilter_0 = new MessageFilter();
            System.Windows.Forms.Application.AddMessageFilter(this.messageFilter_0);
            this.int_0 = 0;
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    this.progressMeter_0.SetLimit(3 * idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        this.progressMeter_0.Start("Computing bounding box...");
                    }
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        pointSet.Add(point);
                        this.vmethod_0(null, null);
                    }
                    ConvexHull3d convexHull3d = new ConvexHull3d();
                    convexHull3d.PointInsertionHandler += new HullPointInsertionEventHandler(this.vmethod_0);
                    convexHull3d.InitialPoints          = pointSet;
                    convexHull3d.ComputeHull();
                    BoundingBox     boundingBox = convexHull3d.PrincipalAxesBoundingBox();
                    List <Triangle> surface     = boundingBox.GetSurface();
                    for (int j = 0; j < surface.Count; j++)
                    {
                        Point   vertex   = surface[j].Vertex1;
                        Point   vertex2  = surface[j].Vertex2;
                        Point   vertex3  = surface[j].Vertex3;
                        Point3d point3d  = new Point3d(vertex.X, vertex.Y, vertex.Z);
                        Point3d point3d2 = new Point3d(vertex2.X, vertex2.Y, vertex2.Z);
                        Point3d point3d3 = new Point3d(vertex3.X, vertex3.Y, vertex3.Z);
                        Face    face     = new Face(point3d, point3d2, point3d3, true, true, true, true);
                        face.LayerId = (layerId);
                        blockTableRecord.AppendEntity(face);
                        transaction.AddNewlyCreatedDBObject(face, true);
                    }
                    editor.WriteMessage("\nPrincipal axes bounding box properties:");
                    editor.WriteMessage("\n---------------------------------------");
                    editor.WriteMessage("\nWidth              : " + boundingBox.Width.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nLength             : " + boundingBox.Length.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nHeight             : " + boundingBox.Height.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nVolume             : " + boundingBox.Volume().ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nCenter             : " + boundingBox.CoordinateSystem.Origin.ToString());
                    editor.WriteMessage("\nFirst basis vector : " + boundingBox.CoordinateSystem.BasisVector[0].ToString());
                    editor.WriteMessage("\nSecond basis vector: " + boundingBox.CoordinateSystem.BasisVector[1].ToString());
                    editor.WriteMessage("\nThird basis vector : " + boundingBox.CoordinateSystem.BasisVector[2].ToString());
                    transaction.Commit();
                }
                this.progressMeter_0.Stop();
            }
            catch (System.Exception ex)
            {
                this.progressMeter_0.Stop();
                throw;
            }
        }
Beispiel #41
0
 public OrdersController()
 {
     dbMan = new DBManager();
 }
    protected void btnlogssave_click(object sender, EventArgs e)
    {
        DataTable dtattandance        = (DataTable)Session["adata"];
        double    Finalsalarydays     = 0;
        double    Numberofworkingdays = 0;
        double    Lop                 = 0;
        double    Extradays           = 0;
        double    ConfirmholidaysDays = 0;

        lblmsg.Text = "";
        DBManager SalesDB  = new DBManager();
        DateTime  fromdate = DateTime.Now;
        DateTime  todate   = DateTime.Now;
        string    clorwo   = txt_cl.Text;

        string[] datestrig = dtp_FromDate.Text.Split(' ');
        string[] dates1    = datestrig[0].Split('-');
        if (datestrig.Length > 1)
        {
            if (datestrig[0].Split('-').Length > 0)
            {
                string[] dates = datestrig[0].Split('-');
                string[] times = datestrig[1].Split(':');
                fromdate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
            }
        }
        datestrig = dtp_Todate.Text.Split(' ');
        if (datestrig.Length > 1)
        {
            if (datestrig[0].Split('-').Length > 0)
            {
                string[] dates = datestrig[0].Split('-');
                string[] times = datestrig[1].Split(':');
                todate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
            }
        }


        //Total Days
        TimeSpan dateSpan  = todate.Subtract(fromdate);
        double   monthdays = dateSpan.Days;
        double   NoOfdays  = dateSpan.Days;

        NoOfdays = NoOfdays + 2;
        double TempNoOfdays1 = NoOfdays - 1;
        //No of Holidays
        double holidaycount = 0;

        cmd = new SqlCommand("SELECT holidayyear, holidaydate, status FROM holiday WHERE (holidaydate BETWEEN @fromdate AND @todate)");
        cmd.Parameters.Add("@fromdate", GetLowDate(fromdate));
        cmd.Parameters.Add("@todate", GetHighDate(todate));
        DataTable holiday = vdm.SelectQuery(cmd).Tables[0];

        foreach (DataRow dholiday in holiday.Rows)
        {
            string   holidaydate   = dholiday["holidaydate"].ToString();
            DateTime dateofaffence = Convert.ToDateTime(holidaydate);
            string   strdate       = dateofaffence.ToString("dd/MM/yyyy");
            string[] str           = strdate.Split('/');
            string   holidayday    = str[0];
            holidaycount++;
        }
        double numbrofholidays = Convert.ToDouble(holidaycount);
        //No of CL Day
        double casualleave = 1;


        //No of Sundays in month sundays++;
        lblFromDate.Text = fromdate.ToString("dd/MMM/yyyy");
        lbltodate.Text   = todate.ToString("dd/MMM/yyyy");
        string[] datestrig1 = dtp_Todate.Text.Split(' ');
        string[] dates2     = datestrig1[0].Split('-');
        string   month      = dates2[1].ToString();
        string   year       = dates2[2].ToString();
        DateTime fdate      = fromdate;
        //DateTime sdate = DateTime.Now.AddDays(-1);
        DateTime sdate   = todate;
        TimeSpan ts      = sdate - fdate;
        var      sundays = ((ts.TotalDays / 7) + (sdate.DayOfWeek == DayOfWeek.Sunday || fdate.DayOfWeek == DayOfWeek.Sunday || fdate.DayOfWeek > sdate.DayOfWeek ? 1 : 0));

        sundays = Math.Round(sundays - .5, MidpointRounding.AwayFromZero);
        cmd     = new SqlCommand("SELECT employedetails.employee_num, employedetails.empid, pay_structure.gross FROM employedetails INNER JOIN  pay_structure ON  pay_structure.empid=employedetails.empid");
        DataTable EMPINFO = vdm.SelectQuery(cmd).Tables[0];
        double    clor    = sundays + numbrofholidays;

        if (dtattandance.Rows.Count > 0)
        {
            foreach (DataRow dr in dtattandance.Rows)
            {
                double tdays              = 0;
                double clorr              = 0;
                double noofworkingdays    = 0;
                double lop                = 0;
                double conformworkingdays = 0;
                Extradays = 0;
                string totaldays = dr["Total"].ToString();
                double gross     = 0;
                string empid     = dr["empid"].ToString();
                string empno     = "";
                double sunday    = 0;
                foreach (DataRow dra in EMPINFO.Select("empid='" + dr["empid"].ToString() + "'"))
                {
                    empno = dra["employee_num"].ToString();
                    gross = Convert.ToDouble(dra["gross"].ToString());
                }
                if (totaldays != "")
                {
                    tdays              = Convert.ToDouble(totaldays);
                    clorr              = clor + 1;
                    noofworkingdays    = tdays - clorr;
                    conformworkingdays = TempNoOfdays1 - clorr;
                    if (tdays >= conformworkingdays)
                    {
                        if (gross < 20000)
                        {
                            Extradays = tdays - conformworkingdays;
                        }
                        else
                        {
                            Extradays = 0;
                        }
                        lop = 0;
                    }
                    else
                    {
                        // sunday = tdays / 7;
                        sunday = Math.Round(sundays);
                        clorr  = sunday + 1;
                        double nd  = TempNoOfdays1 - clorr;
                        double ttt = tdays + clorr;
                        lop = TempNoOfdays1 - ttt;
                        conformworkingdays = nd;
                    }
                }
                string   sempid = Session["empid"].ToString();
                DateTime ServerDateCurrentdate = DBManager.GetTime(vdm.conn);
                cmd = new SqlCommand("UPDATE monthly_attendance SET employee_num=@empno, numberofworkingdays=@nworkingdays, month=@mnth, year=@yr, clorwo=@clor, lop=@lopy, extradays=@exdays, modify_by=@modify_by,modify_date=@modify_date WHERE empid=@empid AND month=@mnth AND year=@yr");
                cmd.Parameters.Add("@empno", empno);
                cmd.Parameters.Add("@empid", empid);
                cmd.Parameters.Add("@mnth", month);
                cmd.Parameters.Add("@yr", year);
                cmd.Parameters.Add("@nworkingdays", conformworkingdays);
                cmd.Parameters.Add("@clor", clorr);
                cmd.Parameters.Add("@lopy", lop);
                cmd.Parameters.Add("@exdays", Extradays);
                cmd.Parameters.Add("@modify_by", sempid);
                cmd.Parameters.Add("@modify_date", ServerDateCurrentdate);
                if (vdm.Update(cmd) == 0)
                {
                    cmd = new SqlCommand("insert into monthly_attendance (empid,employee_num,doe,numberofworkingdays,month,year,clorwo,lop,extradays,entry_by) values (@employee, @employeeno, @doe, @numberofworkingdays,@month,@year,@clorwo,@lop,@extradays,@entry_by)");
                    cmd.Parameters.Add("@employeeno", empno);
                    cmd.Parameters.Add("@employee", empid);
                    cmd.Parameters.Add("@doe", ServerDateCurrentdate);
                    cmd.Parameters.Add("@month", month);
                    cmd.Parameters.Add("@year", year);
                    cmd.Parameters.Add("@numberofworkingdays", conformworkingdays);
                    cmd.Parameters.Add("@clorwo", clorr);
                    cmd.Parameters.Add("@lop", lop);
                    cmd.Parameters.Add("@extradays", Extradays);
                    cmd.Parameters.Add("@entry_by", sempid);
                    vdm.insert(cmd);
                }
                lblmsg.Text = "Employe attandance saved successfully";
            }
        }
    }
    protected void btn_InOutTime_Click(object sender, EventArgs e)
    {
        try
        {
            Lbl_Error_InOutTime.Text = "";
            DBManager SalesDB   = new DBManager();
            DateTime  fromdate  = DateTime.Now;
            DateTime  todate    = DateTime.Now;
            string[]  datestrig = dtp_InoutTimeFrmDate.Text.Split(' ');
            if (datestrig.Length > 1)
            {
                if (datestrig[0].Split('-').Length > 0)
                {
                    string[] dates = datestrig[0].Split('-');
                    string[] times = datestrig[1].Split(':');
                    fromdate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                }
            }
            datestrig = dtp_InoutTimeToDate.Text.Split(' ');
            if (datestrig.Length > 1)
            {
                if (datestrig[0].Split('-').Length > 0)
                {
                    string[] dates = datestrig[0].Split('-');
                    string[] times = datestrig[1].Split(':');
                    todate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                }
            }
            TimeSpan dateSpan = todate.Subtract(fromdate);
            int      NoOfdays = dateSpan.Days;
            NoOfdays          = NoOfdays + 2;
            lblFromDate1.Text = fromdate.ToString("dd/MMM/yyyy");
            lbltodate1.Text   = todate.ToString("dd/MMM/yyyy");
            lblbname1.Text    = ddl_Branch_InOutTime.SelectedItem.Text + "  " + ddl_Emptype_InOutTime.SelectedItem.Text;
            DataTable dtbetweendates = new DataTable();

            dtbetweendates.Columns.Add("attendance_date").DataType = typeof(DateTime);
            for (var dt = fromdate; dt <= todate; dt = dt.AddDays(1))
            {
                DataRow newrow = dtbetweendates.NewRow();
                newrow["attendance_date"] = dt;
                dtbetweendates.Rows.Add(newrow);
            }

            if (ddl_Emptype_InOutTime.SelectedItem.Value == "0")
            {
                cmd = new SqlCommand("SELECT t3.empid, t3.fullname, t3.employee_num, t3.SDate, t3.FD, t4.EDate, t4.D2 FROM  (SELECT t1.empid, t1.fullname, t1.employee_num, t2.SDate, t2.FD FROM (SELECT  empid, fullname, employee_num FROM  employedetails WHERE   (status = 'NO') AND (branchid = @BranchId)) AS t1 LEFT OUTER JOIN (SELECT MIN(LogDate) AS SDate, CONVERT(varchar, LogDate, 103) AS FD, EmpId AS Eid  FROM  AttendanceLogs WHERE (BranchId = @BranchId) AND (LogDate BETWEEN @d1 AND @d2) GROUP BY EmpId, CONVERT(varchar, LogDate, 103)) AS t2 ON t1.empid = t2.Eid) AS t3 LEFT OUTER JOIN (SELECT MAX(LogDate) AS EDate, CONVERT(varchar, LogDate, 103) AS D2, EmpId AS Eid1 FROM AttendanceLogs AS AttendanceLogs_1 WHERE (BranchId = @BranchId) AND (LogDate BETWEEN @d1 AND @d2) GROUP BY EmpId, CONVERT(varchar, LogDate, 103)) AS t4 ON t3.empid = t4.Eid1 ORDER BY t3.empid, t3.FD");
                cmd.Parameters.Add("@branchid", ddl_Branch_InOutTime.SelectedItem.Value);
                cmd.Parameters.Add("@d1", GetLowDate(fromdate));
                cmd.Parameters.Add("@d2", GetHighDate(todate));
            }
            else
            {
                //cmd = new SqlCommand("SELECT Q1.empid, Q1.fullname, Q1.employee_num, Q2.sno, Q2.branchid, Q2.empid AS Expr1, ISNULL(Q2.status, 'A') AS status, Q2.doe, ISNULL(Q2.attendance_date, Q2.attendance_date) AS attendance_date FROM  (SELECT empid, fullname, employee_num FROM employedetails  WHERE  (branchid = @branchid) AND (employee_type = @employee_type) AND (status = 'No')) AS Q1 LEFT OUTER JOIN(SELECT  sno, branchid, empid, status, doe, attendance_date, remarks FROM   dailyattandancedetails  WHERE  (attendance_date BETWEEN @d1 AND @d2)) AS Q2 ON Q1.empid = Q2.empid ORDER BY Q1.empid");
                cmd = new SqlCommand("SELECT t3.empid, t3.fullname, t3.employee_num, t3.SDate, t3.FD, t4.EDate, t4.D2 FROM  (SELECT t1.empid, t1.fullname, t1.employee_num, t2.SDate, t2.FD FROM (SELECT  empid, fullname, employee_num FROM  employedetails WHERE   (status = 'NO') AND (employee_type = @employee_type) AND (branchid = @BranchId)) AS t1 LEFT OUTER JOIN (SELECT MIN(LogDate) AS SDate, CONVERT(varchar, LogDate, 103) AS FD, EmpId AS Eid  FROM  AttendanceLogs WHERE (BranchId = @BranchId) AND (LogDate BETWEEN @d1 AND @d2) GROUP BY EmpId, CONVERT(varchar, LogDate, 103)) AS t2 ON t1.empid = t2.Eid) AS t3 LEFT OUTER JOIN (SELECT MAX(LogDate) AS EDate, CONVERT(varchar, LogDate, 103) AS D2, EmpId AS Eid1 FROM AttendanceLogs AS AttendanceLogs_1 WHERE (BranchId = @BranchId) AND (LogDate BETWEEN @d1 AND @d2) GROUP BY EmpId, CONVERT(varchar, LogDate, 103)) AS t4 ON t3.empid = t4.Eid1 AND t3.FD=t4.D2 ORDER BY t3.empid, t3.FD");
                cmd.Parameters.Add("@branchid", ddl_Branch_InOutTime.SelectedItem.Value);
                cmd.Parameters.Add("@d1", GetLowDate(fromdate));
                cmd.Parameters.Add("@d2", GetHighDate(todate));
                cmd.Parameters.Add("@employee_type", ddl_Emptype_InOutTime.SelectedItem.Text);
            }
            DataTable dtPuff = vdm.SelectQuery(cmd).Tables[0];
            DataTable sum    = new DataTable();
            sum = dtPuff.Copy();
            int count = 0;
            Report = new DataTable();
            Report.Columns.Add("Sno");
            Report.Columns.Add("Empid");
            Report.Columns.Add("FullName");
            DateTime dtFrm = new DateTime();
            for (int j = 1; j < NoOfdays; j++)
            {
                if (j == 1)
                {
                    dtFrm = fromdate;
                }
                else
                {
                    dtFrm = dtFrm.AddDays(1);
                }
                string strdate = dtFrm.ToString("dd/MMM");
                Report.Columns.Add(strdate);
                count++;
            }
            // Report.Columns.Add("Total", typeof(Double)).SetOrdinal(count + 3);
            DataView  view      = new DataView(sum);
            DataTable DTEmpname = view.ToTable(true, "FullName");
            int       i         = 1;
            string    prvdate   = "";
            DateTime  PREVDATE  = DateTime.Now;
            foreach (DataRow branch in DTEmpname.Rows)
            {
                DataRow newrow = Report.NewRow();
                newrow["Sno"]      = i++.ToString();
                newrow["FullName"] = branch["FullName"].ToString();
                int total = 0;
                foreach (DataRow drEmpname in sum.Rows)
                {
                    if (branch["FullName"].ToString() == drEmpname["FullName"].ToString())
                    {
                        string empno = drEmpname["empid"].ToString();
                        newrow["Empid"] = empno.ToString();
                        string fullname              = drEmpname["FullName"].ToString();
                        string attendance_date       = drEmpname["SDate"].ToString();
                        string attendance_Todatedate = drEmpname["EDate"].ToString();
                        // string status = drEmpname["status"].ToString();
                        if (attendance_date != "")
                        {
                            prvdate = attendance_date;
                            DateTime dtDoe  = Convert.ToDateTime(attendance_date);
                            DateTime dtDoe1 = Convert.ToDateTime(attendance_Todatedate);
                            PREVDATE = dtDoe;
                            string strdateTime = dtDoe.ToString("h:mm tt");
                            string strdate     = dtDoe.ToString("dd/MMM");
                            string EnddateTime = dtDoe1.ToString("h:mm tt");
                            string Enddate     = dtDoe1.ToString("dd/MMM");
                            newrow[strdate] = strdateTime + "_" + EnddateTime;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }
                Report.Rows.Add(newrow);
            }
            //
            gd_PerdayInOutTime.DataSource = Report;
            gd_PerdayInOutTime.DataBind();
            Session["adata"] = Report;

            hidepanelInOutTime.Visible = true;
        }
        catch (Exception ex)
        {
            Lbl_Error_InOutTime.Text   = ex.Message;
            hidepanelInOutTime.Visible = false;
        }
    }
Beispiel #44
0
        public void ProcessRequest(HttpContext context)
        {
            var id = context.Request.QueryString["id"];

            if (string.IsNullOrEmpty(id))
            {
                return;
            }

            try
            {
                var sqlParams = new Dictionary <string, object>();
                sqlParams.Add("@КодСотрудника", id);

                var dt = DBManager.GetData(SQLQueries.SELECT_КодЛицаПоКодуСотрудника, Config.DS_person, CommandType.Text, sqlParams);

                var qs  = context.Request.QueryString;
                var qps = qs.AllKeys.ToDictionary(k => k.ToLower(), k => qs[k]);


                if (dt != null && dt.Rows.Count > 0 && !dt.Rows[0]["КодЛица"].Equals(DBNull.Value))
                {
                    qps["id"] = dt.Rows[0]["КодЛица"].ToString();
                    if (!qps.ContainsKey("hideoldver"))
                    {
                        qps.Add("hideoldver", "false");
                    }
                }
                else
                {
                    qps.Remove("id");
                    if (!qps.ContainsKey("employeeid"))
                    {
                        qps.Add("employeeid", id);
                    }
                }

                var url = Config.person_form;

                if (url.Contains("?"))
                {
                    url += "&";
                }
                else
                {
                    url += "?";
                }

                url += CreateQueryString(qps);

                context.Response.Redirect(url, false);
            }
            catch (SqlException ex)
            {
                Logger.WriteEx(new DetailedException(ex.Message, ex));
            }
            catch (Exception ex)
            {
                string sContext = "Context:\n";
                foreach (string key in context.Request.Headers.AllKeys)
                {
                    sContext += String.Format("[{0}]->[{1}]\n", key, context.Request.Headers[key]);
                }

                Logger.WriteEx(new DetailedException(ex.Message, ex, sContext));
            }
        }
Beispiel #45
0
 private void Awake()
 {
     gm = GetComponent <GameManager>();
     db = GetComponent <DBManager>();
 }
 public static List <TotalOutcomesModel> SelectAll()
 {
     return(DBManager.SelectAllTotalOutcomes());
 }
Beispiel #47
0
        //sell Button

        private void SellButton(object sender, EventArgs e)
        {
            try
            {
                double total, unitPrice, totalBookPrice;
                int    a, b, quantity;


                int toatalQuantity;
                a = Convert.ToInt16(quantityTextBox.Text);
                b = Convert.ToInt16(quantitySellTextBox.Text);

                if (a <= 0 || (a < Convert.ToInt16(quantitySellTextBox.Text)))
                {
                    MessageBox.Show("There are no available book for sell.", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    toatalQuantity = a;
                    //return;
                }


                {
                    toatalQuantity = Convert.ToInt16(a - b);
                }


                DBManager     manager3     = new DBManager();
                SqlConnection connection3  = manager3.Connection();
                string        selectQuery1 = "select Quantiy,B_Unit_Price,Total_Price from Books where [S.No]=@serialNo";

                connection3.Open();
                SqlCommand cmd3 = new SqlCommand(selectQuery1, connection3);
                cmd3.Parameters.Clear();

                cmd3.Parameters.AddWithValue("@serialNo", serialTextBox.Text);
                SqlDataReader reader1 = cmd3.ExecuteReader();

                Book abook = new Book();
                while (reader1.Read())
                {
                    quantity  = Convert.ToInt16(reader1[0]);
                    unitPrice = Convert.ToDouble(reader1[1]);
                    total     = Convert.ToDouble(reader1[2]);

                    abook.Quantity  = quantity;
                    abook.UnitPrice = unitPrice;

                    totalBookPrice = total - (unitPrice * Convert.ToInt16(quantitySellTextBox.Text));
                    totalBookBuyAmount(totalBookPrice);
                }



                DBManager     manager     = new DBManager();
                SqlConnection connection  = manager.Connection();
                double        total_Price = ((abook.UnitPrice * abook.Quantity) - (b * abook.UnitPrice));
                String        updateQuery = "update Books set Name=@name,Writer=@writer,Edition=@edition,Type=@type,Book_Print=@print,Quantiy=@quantity,B_Unit_Price=@bunitprice,Total_Price=@total,Purchase_Date=@date where [S.No]=@serial";

                SqlCommand cmd = new SqlCommand(updateQuery, connection);
                connection.Open();
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@name", nameTextBox.Text);
                cmd.Parameters.AddWithValue("@writer", writernameTextBox.Text);
                cmd.Parameters.AddWithValue("@edition", editionTextBox.Text);
                cmd.Parameters.AddWithValue("@type", b_type);
                cmd.Parameters.AddWithValue("@print", book_Print);
                cmd.Parameters.AddWithValue("@quantity", toatalQuantity);
                cmd.Parameters.AddWithValue("@bunitprice", uintPriceTextBox.Text);
                cmd.Parameters.AddWithValue("@total", total_Price);
                cmd.Parameters.AddWithValue("@date", dateTimePiker.Text);
                cmd.Parameters.AddWithValue("@serial", newBook.SerialNo);
                cmd.ExecuteNonQuery();
                connection.Close();

                double unitprice, pay, due;

                double benifit, loss;
                double buy_total = Convert.ToDouble(uintPriceTextBox.Text) * Convert.ToDouble(quantitySellTextBox.Text);


                quantity  = Convert.ToInt16(quantitySellTextBox.Text);
                unitprice = Convert.ToDouble(unitpriceSellTextBox.Text);

                pay = Convert.ToDouble(payTextBox.Text);
                due = sell_total - Convert.ToDouble(payTextBox.Text);


                if (pay < sell_total)
                {
                    loss    = buy_total - pay;
                    benifit = 0;
                }
                else
                {
                    benifit = pay - buy_total;
                    loss    = 0;
                }
                string insertQuery = "Insert into sell_Counter values(@serial,@name,@writer,@edition,@type,@print,@quantity,@unitpricesell,@totalpricesell,@unitpriceBuy,@buy_total,@paytotal,@dueTotal,@benifitTotal,@lossTotal,@pdate)";

                SqlCommand insCmd = new SqlCommand(insertQuery, connection);
                connection.Open();
                insCmd.Parameters.Clear();
                insCmd.Parameters.Add("@serial", serialTextBox.Text);
                insCmd.Parameters.Add("@name", nameTextBox.Text);
                insCmd.Parameters.Add("@writer", writernameTextBox.Text);
                insCmd.Parameters.Add("@edition", editionTextBox.Text);
                insCmd.Parameters.Add("@type", b_type);
                insCmd.Parameters.Add("@print", book_Print);
                insCmd.Parameters.Add("@quantity", quantitySellTextBox.Text);
                insCmd.Parameters.Add("@unitpricesell", unitpriceSellTextBox.Text);
                insCmd.Parameters.Add("@totalpricesell", totalTextBox.Text);
                insCmd.Parameters.Add("@unitpriceBuy", uintPriceTextBox.Text);
                insCmd.Parameters.Add("@buy_total", buy_total);
                insCmd.Parameters.Add("@paytotal", payTextBox.Text);
                insCmd.Parameters.Add("@dueTotal", due);
                insCmd.Parameters.Add("@benifitTotal", benifit);
                insCmd.Parameters.Add("@lossTotal", loss);
                insCmd.Parameters.Add("@pdate", DateTime.Now.ToShortDateString());
                double x, y;
                x = Convert.ToDouble(totalTextBox.Text);
                y = Convert.ToDouble(payTextBox.Text);

                if (y > x)
                {
                    MessageBox.Show("Please check the paying amount.", "Message", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                }

                else
                {
                    int i = insCmd.ExecuteNonQuery();

                    MessageBox.Show("Successful", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    if (i == 1)
                    {
                        string     query   = "Insert Into Temp_Sell_Counter values(@bookname,@writerName,@edition,@type,@print,@quantity,@unitprice,@total,@pay,@due,@memoNumber)";
                        SqlCommand command = new SqlCommand(query, connection);
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@bookname", nameTextBox.Text);
                        command.Parameters.AddWithValue("@writerName", writernameTextBox.Text);
                        command.Parameters.AddWithValue("@edition", editionTextBox.Text);
                        command.Parameters.AddWithValue("@type", b_type);
                        command.Parameters.AddWithValue("@print", book_Print);
                        command.Parameters.AddWithValue("@quantity", Convert.ToInt16(quantitySellTextBox.Text));
                        command.Parameters.AddWithValue("@unitprice", Convert.ToDouble(unitpriceSellTextBox.Text));
                        command.Parameters.AddWithValue("@total", Convert.ToDouble(totalTextBox.Text));
                        command.Parameters.AddWithValue("@pay", Convert.ToDouble(payTextBox.Text));
                        //if (dueTextBox.Text.Equals("")||dueTextBox.Text.Equals("0"))
                        //{
                        command.Parameters.AddWithValue("@due", due);
                        command.Parameters.AddWithValue("@memoNumber", memoNumver + 1);



                        command.ExecuteNonQuery();
                    }
                    GetAll();
                    dueTextBox.Text = due.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #48
0
/*
 */
        protected void btnPostComment_Click(object sender, EventArgs e)
        {
            //add this entry into the favorites table
            string strSQL;
            string strUserId;

            //check login status
            strUserId = "-1";
            if (Session["LoggedIn"].ToString() == "Yes")
            {
                strUserId = Session["userId"].ToString();
            }
            else
            {
                lblMessage.Text = "LOGIN FIRST!";
            }

            //check for an empty comment
            //TODO: move to js
            if (txtComment.Text.Length <= 0)
            {
                txtComment.BorderColor = Color.Red;
                return;
            }

            if (chkNotify.Checked == true)
            {
                AddUserToENotifyList();
            }

            IDBManager dbManager = new DBManager(DataProvider.SqlServer);

            dbManager.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;;

            if (txtComment.Text.Length > 1000)
            {
                txtComment.Text = txtComment.Text.Substring(0, 1000);
            }

            //Build SQL
            strSQL  = "INSERT INTO Answers (dCreateDate, PublishFlg, Answer, iUser, QuestId, AbuseFlg, VoteY, VoteN)";
            strSQL += "VALUES ('" + DateTime.Now + "','1','" + Global.CheckString(txtComment.Text) + "','";
            strSQL += Convert.ToInt32(strUserId) + "','" + hdnQId.Value + "','0','0','0')";

            try
            {
                dbManager.Open();
                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                //clear comment box
                txtComment.Text = string.Empty;
            }
            catch (Exception ex)
            {
                ErrorLog.ErrorRoutine(false, "Error:QDetails:PostAnswer:Msg: " + ex.Message);
                classes.Email.SendErrorEmail("Error:QDetails:PostAnswer:Msg: " + ex.Message);
                return;
            }
            finally
            {
                dbManager.Close();
                dbManager.Dispose();
            }


            if (hdnNotifyEmail.Value == "1")
            {
                //0: url; 1: response text; 2: username

                string[] eLinkArr = new string[3];
                eLinkArr[0] = Request.Url.ToString();
                eLinkArr[1] = Global.CheckString(txtComment.Text);
                eLinkArr[2] = Session["userName"].ToString();

                //get bcc list
                strSQL = @"SELECT n.iUserId, u.txtEmail FROM tblNotify n 
                    INNER JOIN tblUser u ON n.iUserId = u.iD
                    WHERE iQuestion ='" + hdnQId.Value + "'";

                try
                {
                    dbManager.Open();
                    dbManager.ExecuteReader(CommandType.Text, strSQL);

                    //loop reader into array then pass to email
                    ArrayList alBccEmails = new ArrayList();
                    while (dbManager.DataReader.Read())
                    {
                        alBccEmails.Add(dbManager.DataReader["txtEmail"]);
                    }
                    classes.Email.SendEmailBccArry("Your question was answered on Boardhunt", lnkEmailData.CommandArgument, classes.Email.MSG_QUESTION_ANSWERED, eLinkArr, alBccEmails);
                }
                catch (Exception ex)
                {
                    ErrorLog.ErrorRoutine(false, "QDetails:btnPostComment:Error: " + ex.Message);
                    classes.Email.SendErrorEmail("QDetails:btnPostComment:Error: " + ex.Message);
                }
                finally
                {
                    dbManager.Close();
                    dbManager.Dispose();
                }
            }

            //Reload the answers
            LoadAnswers();
        }
Beispiel #49
0
        private void CalculateButton_Click(object sender, EventArgs e)
        {
            try
            {
                double p, q;
                int    a, b = 0, t;
                quantity = Convert.ToInt16(quantitySellTextBox.Text);
                double unitprice = Convert.ToDouble(unitpriceSellTextBox.Text);
                p = Convert.ToDouble(uintPriceTextBox.Text);
                q = Convert.ToDouble(unitpriceSellTextBox.Text);
                a = Convert.ToInt16(quantityTextBox.Text);
                //b = Convert.ToInt16(quantitySellTextBox.Text);

                //select Quantity form Order

                string name    = nameTextBox.Text;
                string writer  = writernameTextBox.Text;
                string edition = editionTextBox.Text;
                if (name.Contains("'"))
                {
                    name = name.Replace("'", "''");
                }
                if (writer.Contains("'"))
                {
                    writer = writer.Replace("'", "''");
                }
                if (edition.Contains("'"))
                {
                    edition = edition.Replace("'", "''");
                }



                DBManager     manager3    = new DBManager();
                SqlConnection connection3 = manager3.Connection();
                string        selectQuery = string.Format("SELECT  sum(Quantity) from Orders where Book_Name='" + name + "' and Writer='" + writer + " ' and Edition='" + edition + "'");
                connection3.Open();
                SqlCommand    cmd3    = new SqlCommand(selectQuery, connection3);
                SqlDataReader reader1 = cmd3.ExecuteReader();
                while (reader1.Read())
                {
                    if (reader1[0].ToString().Equals("0") || reader1[0].ToString().Equals(""))
                    {
                        b = 0;
                    }
                    else
                    {
                        b = Convert.ToInt16(reader1[0]);
                    }
                }

                if (a <= 0 || (a < Convert.ToInt16(quantitySellTextBox.Text)))
                {
                    MessageBox.Show("There are no available book for sell..", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    //toatalQuantity = a;
                    //return;
                }
                else if (a > 0)
                {
                    if (b >= a)
                    {
                        t = b - a;
                        MessageBox.Show("There are " + t + " book less than order. So,Please do not sell.", "Sorry",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else if (a > b)
                    {
                        t = a - b;
                        if (t >= quantity)
                        {
                            sell_total        = quantity * unitprice;
                            totalTextBox.Text = sell_total.ToString();
                            MessageBox.Show("Your total cost is : " + sell_total + " Tk", "Message", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("There are " + t + "  pices  available book for sell.", "Sorry",
                                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }



                    else if (p > q)
                    {
                        MessageBox.Show("Please check the buying unit price.", "Message", MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                    }
                    else
                    {
                        sell_total        = quantity * unitprice;
                        totalTextBox.Text = sell_total.ToString();
                        MessageBox.Show("Your total cost is : " + sell_total + " Tk", "Message", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }
            }
            catch (FormatException formatException)
            {
                MessageBox.Show(formatException.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 public static void LoadPremNamesFromDB(DBManager dbMgr)
 {
     DBQuery.QueryPreNames(dbMgr, PreNamesManager._PreNamesDict, PreNamesManager._MalePreNamesList, PreNamesManager._FemalePreNamesList);
 }
Beispiel #51
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                DBManager     manager    = new DBManager();
                SqlConnection connection = manager.Connection();
                String        query      = "select * from Temp_Sell_Counter";
                SqlCommand    command    = new SqlCommand(query, connection);
                connection.Open();
                List <TempSell> tempSells = new List <TempSell>();
                SqlDataReader   reader    = command.ExecuteReader();
                while (reader.Read())
                {
                    int      id         = Convert.ToInt16(reader[0]);
                    string   bookname   = reader[1].ToString();
                    string   writer     = reader[2].ToString();
                    string   edition    = reader[3].ToString();
                    string   type       = reader[4].ToString();
                    string   print      = reader[5].ToString();
                    int      quantity   = Convert.ToInt16(reader[6]);
                    double   unitpirce  = Convert.ToDouble(reader[7]);
                    double   total      = Convert.ToDouble(reader[8]);
                    double   pay        = Convert.ToDouble(reader[9]);
                    double   due        = Convert.ToDouble(reader[10]);
                    int      memoNumber = Convert.ToInt16(reader[11]);
                    TempSell aSell      = new TempSell();
                    aSell.Id         = id;
                    aSell.BookName   = bookname;
                    aSell.WriterName = writer;
                    aSell.Edition    = edition;
                    aSell.Type       = type;
                    aSell.Print      = print;
                    aSell.Quantity   = quantity;
                    aSell.Unitprice  = unitpirce;
                    aSell.Total      = total;
                    aSell.Pay        = pay;
                    aSell.Due        = due;
                    aSell.Memonumber = memoNumber;
                    tempSells.Add(aSell);
                }

                connection.Close();
                SellReprotUI sellReprot = new SellReprotUI(tempSells);
                sellReprot.ShowDialog();
                System.Windows.Forms.DialogResult dialog = MessageBox.Show("Did you print the document?", "Print Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                SqlCommand command1;
                String     deletequery = "delete from Temp_Sell_Counter";
                if (dialog == DialogResult.Yes)
                {
                    command1 = new SqlCommand(deletequery, connection);
                    connection.Open();
                    command1.ExecuteNonQuery();

                    string que = "DBCC CHECKIDENT (Temp_Sell_Counter,Reseed,0)";
                    command1 = new SqlCommand(que, connection);
                    command1.ExecuteNonQuery();
                    string que1 = "set identity_insert Temp_Sell_Counter on";
                    command1 = new SqlCommand(que1, connection);
                    command1.ExecuteNonQuery();

                    string insQuery = "insert into Memo_Counter values(@date)";
                    command1 = new SqlCommand(insQuery, connection);
                    command1.Parameters.Clear();
                    command1.Parameters.AddWithValue("@date", DateTime.Now.Date);
                    command1.ExecuteNonQuery();
                    memoNumver = GetLastMemoNumber();
                }
                else if (dialog == DialogResult.No)
                {
                    System.Windows.Forms.DialogResult dialog1 = MessageBox.Show("Are you want to print now?",
                                                                                "Print Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dialog1 == DialogResult.Yes)
                    {
                        sellReprot = new SellReprotUI(tempSells);
                        sellReprot.ShowDialog();
                        connection.Open();
                        command1 = new SqlCommand(deletequery, connection);
                        command1.ExecuteNonQuery();
                        string que = "DBCC CHECKIDENT (Temp_Sell_Counter,Reseed,0)";
                        command1 = new SqlCommand(que, connection);
                        command1.ExecuteNonQuery();
                        string que1 = "set identity_insert Temp_Sell_Counter on";
                        command1 = new SqlCommand(que1, connection);
                        command1.ExecuteNonQuery();

                        string insQuery = "insert into Memo_Counter values(@date)";
                        command1 = new SqlCommand(insQuery, connection);
                        command1.Parameters.Clear();
                        command1.Parameters.AddWithValue("@date", DateTime.Now.Date);
                        command1.ExecuteNonQuery();
                        memoNumver = GetLastMemoNumber();

                        DialogResult d2 = MessageBox.Show(" Print Sucessful! Are you want ot exit? ", "Print Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (d2 == DialogResult.Yes)
                        {
                            this.Close();
                        }
                        else if (d2 == DialogResult.No)
                        {
                        }
                    }
                    else if (dialog1 == DialogResult.No)
                    {
                        this.Close();
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #52
0
 static void InitDB()
 {
     DBManager.InitDB();
 }
Beispiel #53
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string strEventName = tbxEventName.Text.Trim();
        // string strImageUrl = tbxImageUrl.Text.Trim();

        string strLinkUrl  = tbxLinkUrl.Text.Trim();
        string strIsActive = ddlIsActive.Text;
        string strEventID  = hidEventID.Value;

        string sitePath   = HttpContext.Current.Request.PhysicalApplicationPath;
        string middlePath = @"\Images\Event\";
        string middleUrl  = @"/Images/Event/";
        string host       = "http://" + HttpContext.Current.Request.Url.Host;
        //Response.Write("host:" + host); Response.End();

        string fileName = "";

        // new event
        if (strEventID.Equals("0"))
        {
            //int nClass = int.Parse(인증회원.Tables[0].Rows[0]["Class"].ToString());
            if (CheckExistID(strEventName, strEventID))
            {
                cvResult.ErrorMessage = "이미 등록된 이벤트명 입니다.";
                cvResult.IsValid      = false;
                return;
            }

            if (tbxImageFile.HasFile)
            {
                fileName = tbxImageFile.FileName;
                string savePath = sitePath + middlePath + fileName;
                tbxImageFile.SaveAs(savePath);
            }

            DBManager dbManager = new DBManager();
            string    strQuery  = "INSERT INTO TBL_Event(EventName, ImageDir, ImagePhisicalDir, LinkUrl, IsActive) ";
            strQuery += "VALUES(@EventName, @ImageDir, @PhisicalDir, @LinkUrl, @IsActive)";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add(new SqlParameter("@EventName", strEventName));
            cmd.Parameters.Add(new SqlParameter("@ImageDir", host + middleUrl + fileName));
            cmd.Parameters.Add(new SqlParameter("@PhisicalDir", middlePath + fileName));
            cmd.Parameters.Add(new SqlParameter("@LinkUrl", strLinkUrl));
            cmd.Parameters.Add(new SqlParameter("@IsActive", strIsActive));
            try
            {
                dbManager.RunMQuery(cmd);
                cvResult.ErrorMessage = "게임이벤트정보가 등록되였습니다.";
            }
            catch (Exception ex)
            {
                cvResult.ErrorMessage = "게임이벤트 등록에서 오류가 발생하였습니다. " + ex.ToString();
            }
        }
        else
        {
            if (CheckExistID(strEventName, strEventID))
            {
                cvResult.ErrorMessage = "이미 등록된 이벤트명 입니다.";
                cvResult.IsValid      = false;
                return;
            }

            if (tbxImageFile.HasFile)
            {
                fileName = tbxImageFile.FileName;
                string savePath = sitePath + middlePath + fileName;
                tbxImageFile.SaveAs(savePath);
            }

            DBManager dbManager = new DBManager();
            string    strQuery;
            if (tbxImageFile.HasFile)
            {
                strQuery = "UPDATE TBL_Event SET EventName=@EventName, ImageDir=@ImageDir, ImagePhisicalDir=@PhisicalDir, LinkUrl=@LinkUrl, IsActive=@IsActive, RegTime=GetDate()";
            }
            else
            {
                strQuery = "UPDATE TBL_Event SET EventName=@EventName, LinkUrl=@LinkUrl, IsActive=@IsActive, RegTime=GetDate()";
            }
            strQuery += "WHERE EventID=" + strEventID;
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add(new SqlParameter("@EventName", strEventName));

            if (tbxImageFile.HasFile)
            {
                cmd.Parameters.Add(new SqlParameter("@ImageDir", host + middleUrl + fileName));
                cmd.Parameters.Add(new SqlParameter("@PhisicalDir", middlePath + fileName));
            }
            cmd.Parameters.Add(new SqlParameter("@LinkUrl", strLinkUrl));
            cmd.Parameters.Add(new SqlParameter("@IsActive", strIsActive));
            try
            {
                dbManager.RunMQuery(cmd);
                cvResult.ErrorMessage = "게임이벤트정보가 수정되였습니다.";
            }
            catch (Exception ex)
            {
                cvResult.ErrorMessage = "게임이벤트정보 수정에서 오류가 발생하였습니다. " + ex.ToString();
            }
        }
        cvResult.IsValid = false;
    }
Beispiel #54
0
 public AddTruckForm()
 {
     InitializeComponent();
     db = new DBManager();
 }
        Task StartConsumer(BlockingCollection <DBObject> input, BlockingCollection <GroupMembershipInfo> output, ConcurrentDictionary <string, DBObject> dnmap, TaskFactory factory, DBManager db)
        {
            return(factory.StartNew(() =>
            {
                foreach (DBObject obj in input.GetConsumingEnumerable())
                {
                    if (obj is DomainACL)
                    {
                        continue;
                    }
                    foreach (string dn in obj.MemberOf)
                    {
                        if (db.FindDistinguishedName(dn, out DBObject g))
                        {
                            output.Add(new GroupMembershipInfo
                            {
                                AccountName = obj.BloodHoundDisplayName,
                                GroupName = g.BloodHoundDisplayName,
                                ObjectType = obj.Type
                            });
                        }
                        else if (dnmap.TryGetValue(dn, out g))
                        {
                            output.Add(new GroupMembershipInfo
                            {
                                AccountName = obj.BloodHoundDisplayName,
                                GroupName = g.BloodHoundDisplayName,
                                ObjectType = obj.Type
                            });
                        }
                        else
                        {
                            try
                            {
                                DirectoryEntry entry = new DirectoryEntry($"LDAP://{dn}");
                                string ObjectSidString = new SecurityIdentifier(entry.GetPropBytes("objectsid"), 0).ToString();
                                List <string> memberof = entry.GetPropArray("memberOf");
                                string samaccountname = entry.GetProp("samaccountname");
                                string DomainName = Helpers.DomainFromDN(dn);
                                string BDisplay = string.Format("{0}@{1}", samaccountname.ToUpper(), DomainName);

                                g = new Group
                                {
                                    SID = ObjectSidString,
                                    DistinguishedName = dn,
                                    Domain = DomainName,
                                    MemberOf = memberof,
                                    SAMAccountName = samaccountname,
                                    PrimaryGroupID = entry.GetProp("primarygroupid"),
                                    BloodHoundDisplayName = BDisplay,
                                    Type = "group",
                                    NTSecurityDescriptor = entry.GetPropBytes("ntsecuritydescriptor")
                                };

                                db.InsertRecord(g);
                            }
                            catch (DirectoryServicesCOMException)
                            {
                                //We couldn't get the real object, so fallback stuff
                                string DomainName = Helpers.DomainFromDN(dn);
                                string GroupName = ConvertADName(dn, ADSTypes.ADS_NAME_TYPE_DN, ADSTypes.ADS_NAME_TYPE_NT4);
                                if (GroupName != null)
                                {
                                    GroupName = GroupName.Split('\\').Last();
                                }
                                else
                                {
                                    GroupName = dn.Substring(0, dn.IndexOf(",", StringComparison.Ordinal)).Split('=').Last();
                                }

                                g = new Group
                                {
                                    BloodHoundDisplayName = $"{GroupName}@{DomainName}",
                                    DistinguishedName = dn,
                                    Domain = DomainName,
                                    Type = "group"
                                };

                                dnmap.TryAdd(dn, g);
                            }

                            output.Add(new GroupMembershipInfo
                            {
                                AccountName = obj.BloodHoundDisplayName,
                                GroupName = g.BloodHoundDisplayName,
                                ObjectType = obj.Type
                            });
                        }
                    }

                    if (obj.PrimaryGroupID != null)
                    {
                        string domainsid = obj.SID.Substring(0, obj.SID.LastIndexOf("-", StringComparison.Ordinal));
                        string pgsid = $"{domainsid}-{obj.PrimaryGroupID}";

                        if (db.FindGroupBySID(pgsid, out DBObject g, CurrentDomain))
                        {
                            output.Add(new GroupMembershipInfo
                            {
                                AccountName = obj.BloodHoundDisplayName,
                                GroupName = g.BloodHoundDisplayName,
                                ObjectType = obj.Type
                            });
                        }
                        else if (dnmap.TryGetValue(pgsid, out g))
                        {
                            output.Add(new GroupMembershipInfo
                            {
                                AccountName = obj.BloodHoundDisplayName,
                                GroupName = g.BloodHoundDisplayName,
                                ObjectType = obj.Type
                            });
                        }
                        else
                        {
                            try
                            {
                                DirectoryEntry entry = new DirectoryEntry($"LDAP://<SID={pgsid}>");
                                g = (Group)entry.ConvertToDB();
                                manager.InsertRecord(g);
                                output.Add(new GroupMembershipInfo
                                {
                                    AccountName = obj.BloodHoundDisplayName,
                                    GroupName = g.BloodHoundDisplayName,
                                    ObjectType = obj.Type
                                });
                            }
                            catch
                            {
                                string group = Helpers.ConvertSIDToName(pgsid).Split('\\').Last();
                                g = new Group
                                {
                                    BloodHoundDisplayName = $"{group.ToUpper()}@{obj.Domain}"
                                };

                                dnmap.TryAdd(pgsid, g);
                                output.Add(new GroupMembershipInfo
                                {
                                    AccountName = obj.BloodHoundDisplayName,
                                    GroupName = g.BloodHoundDisplayName,
                                    ObjectType = obj.Type
                                });
                            }
                        }
                    }
                    Interlocked.Increment(ref progress);
                }
            }));
Beispiel #56
0
    public string InsertSaleForm(EntranceDM.SaleForm objSFM, Admin.AdministratorData.AuditDM audit)
    {
        NewDAL.DBManager objDB = new DBManager();
        objDB.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["FeesManagementConn"].ConnectionString;
        objDB.DBManager(DataAccessLayer.DataProvider.SqlServer, objDB.ConnectionString);
        objDB.Open();
        objDB.BeginTransaction();
        string retv = "";
        string f    = "";

        try
        {
            objDB.CreateParameters(12);
            objDB.AddParameters(0, "saleID", objSFM.saleID, DbType.Int32);
            objDB.AddParameters(1, "formsrno", objSFM.formsrno, DbType.Int32);
            objDB.AddParameters(2, "issuedate", objSFM.issuedate, DbType.DateTime);
            objDB.AddParameters(3, "fname", objSFM.fname, DbType.String);
            objDB.AddParameters(4, "mname", objSFM.mname, DbType.String);
            objDB.AddParameters(5, "lname", objSFM.lname, DbType.String);
            objDB.AddParameters(6, "contactno", objSFM.contactno, DbType.String);
            objDB.AddParameters(7, "amount", objSFM.amount, DbType.String);
            objDB.AddParameters(8, "paymentmode", objSFM.paymentmode, DbType.Int32);
            objDB.AddParameters(9, "issueto", objSFM.issueto, DbType.String);
            objDB.AddParameters(10, "formsquantity", objSFM.formsquantity, DbType.Int32);
            objDB.AddParameters(11, "flag", objSFM.Flag, DbType.String);
            objDB.ExecuteNonQuery(CommandType.StoredProcedure, "Saleform_insert");
            objDB.CreateParameters(9);
            objDB.AddParameters(0, "ID", 0, DbType.Int32);
            objDB.AddParameters(1, "Form_Name", audit.Form_Name, DbType.String);
            objDB.AddParameters(2, "Action", audit.Action, DbType.String);
            objDB.AddParameters(3, "User_ID", audit.User_ID, DbType.String);
            objDB.AddParameters(4, "Entry_Date", audit.Entry_Date, DbType.String);
            objDB.AddParameters(5, "Record_ID", audit.Record_ID, DbType.String);
            objDB.AddParameters(6, "Entry_Time", audit.Entry_Time, DbType.String);
            objDB.AddParameters(7, "InstituteID", audit.InstituteID, DbType.Int32);
            objDB.AddParameters(8, "SessionID", audit.SessionID, DbType.String);
            objDB.ExecuteNonQuery(CommandType.StoredProcedure, "Audit_Insert");
            objDB.Transaction.Commit();
            if (objSFM.Flag == "N")
            {
                retv = "Record saved.";
            }
            else if (objSFM.Flag == "U")
            {
                retv = "Record Updated Successfully.";
            }
            else
            {
                retv = "Record deleted Successfully.";
            }
        }
        catch (Exception ex)
        {
            objDB.Transaction.Rollback();
            retv = "Unable to save record :-" + ex.Message.ToString();
        }
        finally
        {
            objDB.Connection.Close();
            objDB.Dispose();
        }
        return(retv);
    }
 public DomainGroupEnumeration()
 {
     Helpers = Helpers.Instance;
     options = Helpers.Options;
     manager = DBManager.Instance;
 }
    protected void btn_Generate_Click(object sender, EventArgs e)
    {
        try
        {
            lblmsg.Text = "";
            DBManager SalesDB   = new DBManager();
            DateTime  fromdate  = DateTime.Now;
            DateTime  todate    = DateTime.Now;
            string[]  datestrig = dtp_FromDate.Text.Split(' ');
            if (datestrig.Length > 1)
            {
                if (datestrig[0].Split('-').Length > 0)
                {
                    string[] dates = datestrig[0].Split('-');
                    string[] times = datestrig[1].Split(':');
                    fromdate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                }
            }
            datestrig = dtp_Todate.Text.Split(' ');
            if (datestrig.Length > 1)
            {
                if (datestrig[0].Split('-').Length > 0)
                {
                    string[] dates = datestrig[0].Split('-');
                    string[] times = datestrig[1].Split(':');
                    todate = new DateTime(int.Parse(dates[2]), int.Parse(dates[1]), int.Parse(dates[0]), int.Parse(times[0]), int.Parse(times[1]), 0);
                }
            }
            TimeSpan dateSpan = todate.Subtract(fromdate);
            int      NoOfdays = dateSpan.Days;
            NoOfdays         = NoOfdays + 2;
            lblFromDate.Text = fromdate.ToString("dd/MMM/yyyy");
            lbltodate.Text   = todate.ToString("dd/MMM/yyyy");
            lblbname.Text    = ddlbranch.SelectedItem.Text + "  " + ddlemptype.SelectedItem.Text;
            DataTable dtbetweendates = new DataTable();
            //lblbname.Text = ddlemptype.SelectedItem.Text;
            dtbetweendates.Columns.Add("attendance_date").DataType = typeof(DateTime);
            for (var dt = fromdate; dt <= todate; dt = dt.AddDays(1))
            {
                DataRow newrow = dtbetweendates.NewRow();
                newrow["attendance_date"] = dt;
                dtbetweendates.Rows.Add(newrow);
            }

            //cmd = new SqlCommand("SELECT employedetails.employee_num, employedetails.empid, employedetails.fullname, dailyattandancedetails.status, dailyattandancedetails.attendance_date, dailyattandancedetails.doe FROM employedetails INNER JOIN dailyattandancedetails ON employedetails.empid = dailyattandancedetails.empid WHERE (dailyattandancedetails.attendance_date BETWEEN @d1 AND @d2) AND (dailyattandancedetails.branchid = @branchid)");
            if (ddlemptype.SelectedItem.Value == "0")
            {
                cmd = new SqlCommand("SELECT Q1.empid, Q1.fullname, Q1.employee_num, Q2.sno, Q2.branchid, Q2.empid AS Expr1, ISNULL(Q2.status, 'A') AS status, Q2.doe, ISNULL(Q2.attendance_date, Q2.attendance_date) AS attendance_date FROM  (SELECT empid, fullname, employee_num FROM employedetails  WHERE  (branchid = @branchid)  AND (status = 'No')) AS Q1 LEFT OUTER JOIN(SELECT  sno, branchid, empid, status, doe, attendance_date, remarks FROM   dailyattandancedetails  WHERE  (attendance_date BETWEEN @d1 AND @d2)) AS Q2 ON Q1.empid = Q2.empid ORDER BY Q1.empid");
                cmd.Parameters.Add("@branchid", ddlbranch.SelectedItem.Value);
                cmd.Parameters.Add("@d1", GetLowDate(fromdate));
                cmd.Parameters.Add("@d2", GetHighDate(todate));
            }
            else
            {
                cmd = new SqlCommand("SELECT Q1.empid, Q1.fullname, Q1.employee_num, Q2.sno, Q2.branchid, Q2.empid AS Expr1, ISNULL(Q2.status, 'A') AS status, Q2.doe, ISNULL(Q2.attendance_date, Q2.attendance_date) AS attendance_date FROM  (SELECT empid, fullname, employee_num FROM employedetails  WHERE  (branchid = @branchid) AND (employee_type = @employee_type) AND (status = 'No')) AS Q1 LEFT OUTER JOIN(SELECT  sno, branchid, empid, status, doe, attendance_date, remarks FROM   dailyattandancedetails  WHERE  (attendance_date BETWEEN @d1 AND @d2)) AS Q2 ON Q1.empid = Q2.empid ORDER BY Q1.empid");
                cmd.Parameters.Add("@branchid", ddlbranch.SelectedItem.Value);
                cmd.Parameters.Add("@d1", GetLowDate(fromdate));
                cmd.Parameters.Add("@d2", GetHighDate(todate));
                cmd.Parameters.Add("@employee_type", ddlemptype.SelectedItem.Text);
            }
            DataTable dtPuff = vdm.SelectQuery(cmd).Tables[0];
            DataTable sum    = new DataTable();
            sum = dtPuff.Copy();
            cmd = new SqlCommand("SELECT  la.leaveapplicationid, la.employee_no, la.remarks, la.leave_description, la.request_to, la.request_date, la.leave_from_dt, la.leave_to_dt, la.leave_satus, la.employee_no AS Expr1, la.aproved_by,la.operated_by, la.leave_type_id, la.mobile_number, la.leave_days, et.fullname AS approvedby, et.branchid FROM  leave_application AS la INNER JOIN employedetails AS et ON et.empid = la.request_to WHERE (et.status = 'No') AND (la.request_date BETWEEN @d1 AND @d2) AND (et.branchid = @branchid) ORDER BY la.leave_from_dt");
            cmd.Parameters.Add("@branchid", ddlbranch.SelectedItem.Value);
            cmd.Parameters.Add("@d1", GetLowDate(fromdate));
            cmd.Parameters.Add("@d2", GetHighDate(todate));
            DataTable dtleave = vdm.SelectQuery(cmd).Tables[0];

            Report = new DataTable();
            Report.Columns.Add("Sno");
            Report.Columns.Add("empid");
            Report.Columns.Add("fullname");
            int      count = 0;
            DateTime dtFrm = new DateTime();
            for (int j = 1; j < NoOfdays; j++)
            {
                if (j == 1)
                {
                    dtFrm = fromdate;
                }
                else
                {
                    dtFrm = dtFrm.AddDays(1);
                }
                string strdate = dtFrm.ToString("dd/MMM");
                Report.Columns.Add(strdate);
                count++;
            }
            Report.Columns.Add("Total", typeof(Double)).SetOrdinal(count + 3);
            DataView  view       = new DataView(sum);
            DataTable DriverData = view.ToTable(true, "fullname");
            int       i          = 1;
            string    prvdate    = "";
            DateTime  PREVDATE   = DateTime.Now;
            foreach (DataRow branch in DriverData.Rows)
            {
                DataRow newrow = Report.NewRow();
                newrow["Sno"]      = i++.ToString();
                newrow["fullname"] = branch["fullname"].ToString();
                int total = 0;
                foreach (DataRow drDriver in sum.Rows)
                {
                    if (branch["fullname"].ToString() == drDriver["fullname"].ToString())
                    {
                        string empno           = drDriver["empid"].ToString();
                        string fullname        = drDriver["fullname"].ToString();
                        string attendance_date = drDriver["attendance_date"].ToString();
                        string status          = drDriver["status"].ToString();
                        if (attendance_date != "")
                        {
                            prvdate = attendance_date;
                            DateTime dtDoe = Convert.ToDateTime(attendance_date);
                            PREVDATE = dtDoe;
                            string strdateTime = dtDoe.ToString("HH");
                            string strdate     = dtDoe.ToString("dd/MMM");
                            if (status == "P")
                            {
                                newrow[strdate] = "P";
                                total++;
                            }
                        }
                        else
                        {
                            //DateTime dtDoe = Convert.ToDateTime(prvdate);
                            //DateTime dtPRVDoe = dtDoe.AddDays(1);
                            //string strdateTime = dtPRVDoe.ToString("HH");
                            //string strdate = dtPRVDoe.ToString("dd/MMM");
                            //cmd = new SqlCommand("SELECT leave_satus, leave_from_dt, leave_days, leave_to_dt FROM leave_application WHERE @ldte between leave_from_dt and leave_to_dt AND employee_no = @empid AND (leave_satus='A')");
                            //cmd.Parameters.Add("@empid", empno);
                            //cmd.Parameters.Add("@ldte", dtPRVDoe);
                            //DataTable dtleaves = vdm.SelectQuery(cmd).Tables[0];
                            //if (dtleaves.Rows.Count > 0)
                            //{
                            //    newrow[strdate] = "L";
                            //}
                        }
                        string empid = drDriver["empid"].ToString();
                        newrow["empid"] = drDriver["empid"].ToString();
                    }
                    else
                    {
                    }
                }
                newrow["Total"] = total;
                Report.Rows.Add(newrow);
            }
            DateTime ServerDateCurrentdate = DBManager.GetTime(vdm.conn);
            if (Report.Rows.Count > 0)
            {
                for (int k = 0; k < Report.Rows.Count; k++)
                {
                    int od = 0;
                    for (int j = 0; j < Report.Columns.Count; j++)
                    {
                        if (Report.Rows[k][j] != null && string.IsNullOrEmpty(Report.Rows[k][j].ToString()))
                        {
                            string   COLNAME = Report.Columns[j].ToString();
                            string   empid   = Report.Rows[k][1].ToString();
                            DateTime dtDoe   = Convert.ToDateTime(ServerDateCurrentdate);
                            string   year    = dtDoe.Year.ToString();
                            string   date    = COLNAME + "/" + year;
                            DateTime dtpr    = Convert.ToDateTime(date);
                            date = dtpr.ToString("MM/dd/yyyy");
                            cmd  = new SqlCommand("SELECT sno, empid, fromdate, todate, reportingto, noofdays, reason, doe, status, mobileno, hrremarks, appremarks  FROM  oddetails WHERE @ldte between fromdate and todate AND empid = @empid");
                            // cmd = new SqlCommand("SELECT leave_satus, leave_from_dt, leave_days, leave_to_dt FROM leave_application WHERE @ldte between leave_from_dt and leave_to_dt AND employee_no = @empid AND (leave_satus='A')");
                            cmd.Parameters.Add("@empid", empid);
                            cmd.Parameters.Add("@ldte", date);
                            DataTable dtleaves = vdm.SelectQuery(cmd).Tables[0];
                            if (dtleaves.Rows.Count > 0)
                            {
                                Report.Rows[k][j] = "OD";
                                od++;
                            }
                            else
                            {
                                Report.Rows[k][j] = "L";
                            }
                        }
                        else
                        {
                            string coltotal = Report.Columns[j].ToString();
                            if (coltotal == "Total")
                            {
                                string total = Report.Rows[k][j].ToString();
                                int    tot   = Convert.ToInt32(total);
                                tot = tot + od;
                                Report.Rows[k][j] = tot;
                            }
                        }
                    }
                }
            }

            grdReports.DataSource = Report;
            grdReports.DataBind();
            Session["adata"]  = Report;
            hidepanel.Visible = true;
        }
        catch (Exception ex)
        {
            lblmsg.Text       = ex.Message;
            hidepanel.Visible = false;
        }
    }
        public static void SelectCMSLocations(int pageSize, int currentPageNumber, string sortExpression, Panel CMSLocationsPanel, Button buttonFirst,
                                              Button buttonNext, Button buttonPrevious, Button buttonLast, Label labelTotalPages, DropDownList dropDownListPage,
                                              GridView gridviewCMSLocations, Label labelTotalRecords, UserControl emptyDataTemplate, string country, int cms_pool_id)
        {
            //Initialise Connection
            SqlConnection con = DBManager.CreateConnection();
            SqlCommand    cmd = DBManager.CreateProcedure(StoredProcedures.Portal_CMSLocationGroupSelect, con);

            if (country == "-1" || country == null)
            {
                cmd.Parameters.AddWithValue("@country", System.DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@country", country);
            }


            if (cms_pool_id == 0)
            {
                cmd.Parameters.AddWithValue("@cms_pool_id", System.DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@cms_pool_id", cms_pool_id);
            }

            int startRowIndex = ((currentPageNumber - 1) * pageSize) + 1;
            int maximumRows   = (currentPageNumber * pageSize);


            cmd.Parameters.AddWithValue("@startRowIndex", startRowIndex);
            cmd.Parameters.AddWithValue("@maximumRows", maximumRows);

            if (sortExpression == null)
            {
                cmd.Parameters.AddWithValue("@sortExpression", System.DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@sortExpression", sortExpression);
            }

            //Execute Command
            List <MappingsCMSLocations.CMSLocations> results = new List <MappingsCMSLocations.CMSLocations>();
            int rowCount = 0;

            using (con)
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    results.Add(new MappingsCMSLocations.CMSLocations(reader));
                }

                reader.NextResult();

                while (reader.Read())
                {
                    rowCount = Convert.ToInt32(reader["totalCount"]);
                }
            }
            con.Close();



            if (rowCount >= 1)
            {
                //Show cms locations panel
                CMSLocationsPanel.Visible = true;
                //Hide Empty Data Template
                emptyDataTemplate.Visible = false;

                //Databind the gridview
                gridviewCMSLocations.DataSource = results;
                gridviewCMSLocations.DataBind();

                //Display results
                int totalPages = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(rowCount) / Convert.ToDouble(pageSize)));
                labelTotalPages.Text = totalPages.ToString();

                //Show totals label
                labelTotalRecords.Text = rowCount.ToString();

                //Clear items in page drop down list
                dropDownListPage.Items.Clear();
                //Add list of pages to drop down list
                for (int i = 1; i <= Convert.ToInt32(labelTotalPages.Text); i++)
                {
                    dropDownListPage.Items.Add(new ListItem(i.ToString()));
                }
                //Set the selected page
                dropDownListPage.SelectedValue = currentPageNumber.ToString();

                //Set pager buttons depending on page selected

                if (currentPageNumber == 1)
                {
                    buttonPrevious.Enabled  = false;
                    buttonPrevious.CssClass = "PagerPreviousInactive";
                    buttonFirst.Enabled     = false;
                    buttonFirst.CssClass    = "PagerFirstInactive";

                    if ((Convert.ToInt32(labelTotalPages.Text) > 1))
                    {
                        buttonNext.Enabled  = true;
                        buttonNext.CssClass = "PagerNextActive";
                        buttonLast.Enabled  = true;
                        buttonLast.CssClass = "PagerLastActive";
                    }
                    else
                    {
                        buttonNext.Enabled  = false;
                        buttonNext.CssClass = "PagerNextInactive";
                        buttonLast.Enabled  = false;
                        buttonLast.CssClass = "PagerLastInactive";
                    }
                }
                else
                {
                    buttonPrevious.Enabled  = true;
                    buttonPrevious.CssClass = "PagerPreviousActive";
                    buttonFirst.Enabled     = true;
                    buttonFirst.CssClass    = "PagerFirstActive";

                    if ((currentPageNumber == Convert.ToInt32(labelTotalPages.Text)))
                    {
                        buttonNext.Enabled  = false;
                        buttonNext.CssClass = "PagerNextInactive";
                        buttonLast.Enabled  = false;
                        buttonLast.CssClass = "PagerLastInactive";
                    }
                    else
                    {
                        buttonNext.Enabled  = true;
                        buttonNext.CssClass = "PagerNextActive";
                        buttonLast.Enabled  = true;
                        buttonLast.CssClass = "PagerLastActive";
                    }
                }
            }
            else
            {
                //Hide cms locations
                CMSLocationsPanel.Visible = false;
                //Show Empty Data Template
                emptyDataTemplate.Visible = true;
            }
        }
    protected void UploadButton_Click(object sender, EventArgs e)
    {
        if (FileUploadControl.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(FileUploadControl.FileName);
                string path = Server.MapPath("~/uploaded_images/");
                //if (File.Exists(path + filename))
                //{
                //    StatusLabel.Text = "File name already exists. Please choose another file name";
                //    return;
                //}

                FileUploadControl.SaveAs(path + filename);

                DBManager db = new DBManager();
                db.Connect();
                db.InsertNewPicture(filename, Constants.IMG_FOLDER, "");
                db.Close();

                StatusLabel.Text = "Upload status: File uploaded!";
                Application[Constants.FRONT_PAGE_IMG_API_CACHE] = null;
                Response.Redirect(Request.RawUrl);

            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }
    }