Exemple #1
0
        /// <summary>
        /// This method is used for setting the Session variable for userId and
        /// after that filling the required dropdowns with database values
        /// and also check accessing priviledges for particular user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                uid = (Session["User_Name"].ToString());
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:Leave_Register.aspx,Method:pageload" + "EXCEPTION  " + ex.Message + uid);
                Response.Redirect("../../Sysitem/ErrorPage.aspx", false);
                return;
            }
            if (!Page.IsPostBack)
            {
                #region Check Privileges
                int    i;
                string View_flag = "0", Add_Flag = "0", Edit_Flag = "0", Del_Flag = "0";
                string Module    = "2";
                string SubModule = "3";
                string[,] Priv = (string[, ])Session["Privileges"];
                for (i = 0; i < Priv.GetLength(0); i++)
                {
                    if (Priv[i, 0] == Module && Priv[i, 1] == SubModule)
                    {
                        View_flag = Priv[i, 2];
                        Add_Flag  = Priv[i, 3];
                        Edit_Flag = Priv[i, 4];
                        Del_Flag  = Priv[i, 5];
                        break;
                    }
                }
                if (View_flag == "0")
                {
                    Response.Redirect("../../Sysitem/AccessDeny.aspx", false);
                    return;
                }
                //***********
                if (Add_Flag == "0")
                {
                    btnApply.Enabled = false;
                }
                //***********
                #endregion
                try
                {
                    // Sets todays date in from and to date text boxes.
                    txtDateFrom.Text = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();
                    txtDateTO.Text   = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();

                    #region Fetch Employee ID and Name of All Employee
                    EmployeeClass obj = new EmployeeClass();


                    List <string> Employee = new List <string>();
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(BaseUri);
                        client.DefaultRequestHeaders.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        var Res = client.GetAsync("api/LeaveRegister/GetEmployeeData").Result;
                        if (Res.IsSuccessStatusCode)
                        {
                            var id = Res.Content.ReadAsStringAsync().Result;
                            Employee = JsonConvert.DeserializeObject <List <string> >(id);
                        }
                        else
                        {
                            Res.EnsureSuccessStatusCode();
                        }
                    }
                    foreach (var item in Employee)
                    {
                        DropEmpName.Items.Add(item);
                    }
                    //               sql ="select Emp_ID,Emp_Name from Employee where status='1' order by Emp_Name";
                    //SqlDtr=obj.GetRecordSet(sql);
                    //while(SqlDtr.Read())
                    //{
                    //	DropEmpName.Items.Add(SqlDtr.GetValue(0).ToString ()+":"+SqlDtr.GetValue(1).ToString());
                    //}
                    //SqlDtr.Close();
                    #endregion
                }
                catch (Exception ex)
                {
                    CreateLogFiles.ErrorLog("Form:Leave_Register.aspx,Method:pageload" + "EXCEPTION  " + ex.Message + uid);
                }
            }
            txtDateFrom.Text = Request.Form["txtDateFrom"] == null?GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString()) : Request.Form["txtDateFrom"].ToString().Trim();

            txtDateTO.Text = Request.Form["txtDateTO"] == null?GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString()) : Request.Form["txtDateTO"].ToString().Trim();
        }
Exemple #2
0
    /// <summary>
    /// grows a room to wanted size
    /// </summary>
    /// <param name="gx">global starting positon</param>
    /// <param name="gy">global starting position</param>
    /// <param name="tWidth">target Width</param>
    /// <param name="tHeight">target Height</param>
    /// <param name="rect">the resulting Rect/best match</param>
    /// <param name="connectToWall">When hitting a wall should it be used?</param>
    /// <param name="startDir">the direction the rect should start growing in</param>
    /// <returns>if the procedure was successful</returns>
    public bool TryGrowRect(
        int gx,
        int gy,
        int tWidth,
        int tHeight,
        out GenRect rect,
        bool connectToWall          = false,
        GenUtil.Direction4 startDir = GenUtil.Direction4.Right,
        GrowSettings extra          = new GrowSettings()) // merge to wall
    {
        // create base rect
        rect = new GenRect(gx, gx, gy, gy);
        GenRect helper = new GenRect(rect);
        // this is used to confirm what is inside the rect and already allowed
        List <GenTile> Confirmed = new List <GenTile>();
        // add the current tile to it
        var s = GetTiles(rect).ToList();

        Confirmed.AddRange(s);
        // used to get easier access to

        // if we reached max growth in this direction
        // -1 is not reached
        // 0 is reached
        // 1 reached but grow 1 in the end
        int top   = extra.Top - 1;
        int right = extra.Right - 1;
        int bot   = extra.Bot - 1;
        int left  = extra.Left - 1;

        GenUtil.Direction4 direction = startDir;

        int width  = rect.WidthT;
        int height = rect.HeightT;
        int ohNo   = 100;

        while (width < tWidth || height < tHeight)
        {
            Confirmed.Clear();
            s = GetTiles(rect).ToList();
            Confirmed.AddRange(s);

            ohNo--;
            helper = rect;
            switch (direction)
            {
            case GenUtil.Direction4.Right:
                if (width == tWidth || right >= 0)
                {
                    break;
                }
                helper = helper.Transform(0, 0, 1, 0);
                List <GenTile> addR = GetTiles(helper).ToList();
                addR = addR.Except(Confirmed).ToList();
                if (addR.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                {
                    // we hit a wall next to us
                    // they are automatically allowed

                    Confirmed.AddRange(addR);
                    rect  = helper.Transform(0, 0, -1, 0);
                    right = 1;
                }
                else
                {
                    // we check the next one for safety

                    helper = helper.Transform(0, 0, 1, 0);
                    List <GenTile> query = GetTiles(helper).ToList();
                    query = query.Except(Confirmed).ToList();

                    if (query.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                    {
                        if (connectToWall)
                        {
                            // try and pull the other way
                            if (left < 1)
                            {
                                helper = helper.Transform(-1, 0, 0, 0);
                                left   = -1;
                            }

                            // we connect without problem
                            Confirmed.AddRange(query);
                            rect  = helper.Transform(0, 0, -1, 0);
                            right = 1;
                        }
                        else
                        {
                            // we prevent connection and transform 2 back
                            helper = helper.Transform(0, 0, -2, 0);
                            right  = 0;

                            rect = helper;
                        }
                    }
                    else
                    {
                        helper.Transform(0, 0, -1, 0);
                        rect = helper;
                    }
                }
                break;

            case GenUtil.Direction4.Bottom:
                if (height == tHeight || bot >= 0)
                {
                    break;
                }
                helper = helper.Transform(0, 0, 0, 1);
                List <GenTile> addB = GetTiles(helper).ToList();
                addB = addB.Except(Confirmed).ToList();
                if (addB.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                {
                    // we hit a wall next to us
                    // they are automatically allowed

                    Confirmed.AddRange(addB);
                    rect = helper.Transform(0, 0, 0, -1);
                    bot  = 1;
                }
                else
                {
                    // we check the next one for safety

                    helper = helper.Transform(0, 0, 0, 1);
                    List <GenTile> query = GetTiles(helper).ToList();
                    query = query.Except(Confirmed).ToList();

                    if (query.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                    {
                        if (connectToWall)
                        {
                            if (top < 1)
                            {
                                helper = helper.Transform(0, -1, 0, 0);
                                top    = -1;
                            }

                            // we connect without problem
                            Confirmed.AddRange(query);
                            rect = helper.Transform(0, 0, 0, -1);
                            bot  = 1;
                        }
                        else
                        {
                            // we prevent connection and transform 2 back
                            helper = helper.Transform(0, 0, -0, -2);
                            bot    = 0;

                            rect = helper;
                        }
                    }
                    else
                    {
                        helper.Transform(0, 0, 0, -1);
                        rect = helper;
                    }
                }

                break;

            case GenUtil.Direction4.Left:
                if (width == tWidth || left >= 0)
                {
                    break;
                }
                helper = helper.Transform(1, 0, 0, 0);
                List <GenTile> addL = GetTiles(helper).ToList();
                addL = addL.Except(Confirmed).ToList();
                if (addL.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                {
                    // we hit a wall next to us
                    // they are automatically allowed

                    Confirmed.AddRange(addL);
                    rect = helper.Transform(-1, 0, 0, 0);
                    left = 1;
                }
                else
                {
                    // we check the next one for safety

                    helper = helper.Transform(1, 0, 0, 0);
                    List <GenTile> query = GetTiles(helper).ToList();
                    query = query.Except(Confirmed).ToList();

                    if (query.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                    {
                        if (connectToWall)
                        {
                            // try and pull the other way
                            if (right < 1)
                            {
                                helper = helper.Transform(0, 0, -1, 0);
                                right  = -1;
                            }
                            // we connect without problem
                            Confirmed.AddRange(query);
                            rect = helper.Transform(-1, 0, 0, 0);
                            left = 1;
                        }
                        else
                        {
                            // we prevent connection and transform 2 back
                            helper = helper.Transform(-2, 0, 0, 0);
                            left   = 0;

                            rect = helper;
                        }
                    }
                    else
                    {
                        helper.Transform(-1, 0, 0, 0);
                        rect = helper;
                    }
                }

                break;

            case GenUtil.Direction4.Top:
                if (height == tHeight || top >= 0)
                {
                    break;
                }
                helper = helper.Transform(0, 1, 0, 0);
                List <GenTile> addT = GetTiles(helper).ToList();
                addT = addT.Except(Confirmed).ToList();
                if (addT.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                {
                    // we hit a wall next to us
                    // they are automatically allowed

                    Confirmed.AddRange(addT);
                    rect = helper.Transform(0, -1, 0, 0);
                    top  = 1;
                }
                else
                {
                    // we check the next one for safety

                    helper = helper.Transform(0, 1, 0, 0);
                    List <GenTile> query = GetTiles(helper).ToList();
                    query = query.Except(Confirmed).ToList();

                    if (query.Any(t => t.AnyTypes(GenDetail.DetailType.Wall)))
                    {
                        if (connectToWall)
                        {
                            // try and pull the other way
                            if (bot < 1)
                            {
                                helper = helper.Transform(0, 0, 0, -1);
                                bot    = -1;
                            }
                            // we connect without problem
                            Confirmed.AddRange(query);
                            rect = helper.Transform(0, -1, 0, 0);
                            top  = 1;
                        }
                        else
                        {
                            // we prevent connection and transform 2 back
                            helper = helper.Transform(0, -2, 0, 0);
                            top    = 0;

                            rect = helper;
                        }
                    }
                    else
                    {
                        helper.Transform(0, -1, 0, 0);
                        rect = helper;
                    }
                }

                break;

            default:
                break;
            }

            width = rect.WidthT;
            if (left > 0)
            {
                width++;
            }
            if (right > 0)
            {
                width++;
            }
            height = rect.HeightT;
            if (top > 0)
            {
                height++;
            }
            if (bot > 0)
            {
                height++;
            }

            if (top >= 0 && right >= 0 && bot >= 0 && left >= 0)
            {
                break;
            }
            if (ohNo <= 0)
            {
                break;
            }
            direction = GenUtil.Rotate(direction, 1);
        }

        rect = rect.Transform(Mathf.Max(0, left), Mathf.Max(0, top), Mathf.Max(0, right), Mathf.Max(0, bot));

        if (rect.WidthT == tWidth && rect.HeightT == tHeight)
        {
            return(true);
        }
        return(false);
    }
		/// <summary>
		/// This method is used to make the report for printing.
		/// </summary>
		public void makingReport()
		{
			
			System.Data.SqlClient.SqlDataReader rdr=null;
			string home_drive = Environment.SystemDirectory;
			home_drive = home_drive.Substring(0,2); 
			string path = home_drive+@"\Inetpub\wwwroot\Servosms\Sysitem\ServosmsPrintServices\ReportView\MarketPotentialReport.txt";
			StreamWriter sw = new StreamWriter(path);

			string sql="";
			string info = "";
			//string strDate = "";

			sql="select firmname m1,place m2,contactper m3,teleno m4,type m5,regcustomer m6,potential m7,servo m8,castrol m9,shell m10,bpcl m11,veedol m12,elf m13,hpcl m14,pennzoil m15,spurious m16 from marketcustomerentry1";
			sql=sql+" order by "+""+Cache["strorderby"]+"";
			dbobj.SelectQuery(sql,ref rdr);
			// Condensed
			sw.Write((char)27);//added by vishnu
			sw.Write((char)67);//added by vishnu
			sw.Write((char)0);//added by vishnu
			sw.Write((char)12);//added by vishnu
			
			sw.Write((char)27);//added by vishnu
			sw.Write((char)78);//added by vishnu
			sw.Write((char)5);//added by vishnu
							
			sw.Write((char)27);//added by vishnu
			sw.Write((char)15);
			//**********
			string des="-----------------------------------------------------------------------------------------------------------------------------------------";
			string Address=GenUtil.GetAddress();
			string[] addr=Address.Split(new char[] {':'},Address.Length);
			sw.WriteLine(GenUtil.GetCenterAddr(addr[0],des.Length).ToUpper());
			sw.WriteLine(GenUtil.GetCenterAddr(addr[1]+addr[2],des.Length));
			sw.WriteLine(GenUtil.GetCenterAddr("Tin No : "+addr[3],des.Length));
			sw.WriteLine(des);
			//**********
			sw.WriteLine(GenUtil.GetCenterAddr("=========================",des.Length));
			sw.WriteLine(GenUtil.GetCenterAddr("Market Potential REPORT",des.Length));
			sw.WriteLine(GenUtil.GetCenterAddr("=========================",des.Length));
			sw.WriteLine("Note --> Reg :- Reguler Customer, Potl :- Potential, pnzoil :- Pennzoil, Spurs :- Spurious");
			//sw.WriteLine("+---------------+---------------+---------------+-----------+-------------+-------+---------+-----+-------+-----+-----+------+-----+-----+--------+--------+");
			//			sw.WriteLine("|   Firm Name   |     Place     |Contact Person |  Tele No  |     Type    |Regular|Potential|Servo|Castrol|Shell|BPCL |Veedol| ELF |HPCL |Pennzoil|Spurious");
			//			sw.WriteLine("+---------------+---------------+---------------+-----------+-------------+-------+---------+-----+-------+-----+-----+------+-----+-----+--------+--------+");
			
			sw.WriteLine("+---------------+---------------+---------------+----------+-------------+---+----+-----+-------+-----+----+------+---+----+------+-----+");
			sw.WriteLine("|   Firm Name   |     Place     |Contact Person |  Tele No |     Type    |Reg|Potl|Servo|Castrol|Shell|BPCL|Veedol|ELF|HPCL|Pnzoil|Spurs");
			sw.WriteLine("+---------------+---------------+---------------+----------+-------------+---+----+-----+-------+-----+----+------+---+----+------+-----+");
        
			if(rdr.HasRows)
			{
				// info : to set the format the displaying string.
				info = " {0,-15:S} {1,-15:S} {2,-15:S} {3,10:S} {4,-13:S} {5,-3:S} {6,4:S} {7,5:S} {8,7:S} {9,5:S} {10,4:S} {11,6:S} {12,3:S} {13,4:S} {14,6:S} {15,5:S}"; 
				while(rdr.Read())
				{
										                                         
					/*sw.WriteLine(info,rdr["Prod_ID"].ToString().Trim(),
						rdr["Prod_Name"].ToString().Trim(),
						rdr["Pack_Type"].ToString(),
						GenUtil.strNumericFormat(rdr["Pur_Rate"].ToString().Trim()),
						GenUtil.strNumericFormat(rdr["sal_Rate"].ToString().Trim()),
						GenUtil.str2DDMMYYYY(strDate));*/
					sw.WriteLine(info,GenUtil.TrimLength(rdr["m1"].ToString(),15),
						GenUtil.TrimLength(rdr["m2"].ToString(),15),
						GenUtil.TrimLength(rdr["m3"].ToString(),15),
						rdr["m4"].ToString(),
						GenUtil.TrimLength(rdr["m5"].ToString(),13),
						rdr["m6"].ToString(),
						rdr["m7"].ToString(),
						rdr["m8"].ToString(),
						rdr["m9"].ToString(),
						rdr["m10"].ToString(),
						rdr["m11"].ToString(),
						rdr["m12"].ToString(),
						rdr["m13"].ToString(),
						rdr["m14"].ToString(),
						rdr["m15"].ToString(),
						rdr["m16"].ToString());
				}
			}
			//sw.WriteLine("+---------------+---------------+---------------+-----------+-------------+-------+---------+-----+-------+-----+-----+------+-----+-----+--------+--------+");
			sw.WriteLine("+---------------+---------------+---------------+----------+-------------+---+----+-----+-------+-----+----+------+---+----+------+-----+");
			dbobj.Dispose();
			sw.Close();
		}
Exemple #4
0
        /// <summary>
        /// this is used to view the report.
        /// </summary>
        protected void btnview1_Click(object sender, System.EventArgs e)
        {
            try
            {
                string s1        = "";
                string s2        = "";
                string cust_name = "";
                s1 = txtDateTo.Text;
                s2 = txtDateFrom.Text;
                string[] ds1 = s2.IndexOf("/") > 0? s2.Split(new char[] { '/' }, s2.Length) : s2.Split(new char[] { '-' }, s2.Length);
                string[] ds2 = s1.IndexOf("/") > 0? s1.Split(new char[] { '/' }, s1.Length) : s1.Split(new char[] { '/' }, s1.Length);
                ds10 = System.Convert.ToInt32(ds1[0]);
                ds20 = System.Convert.ToInt32(ds2[0]);
                ds11 = System.Convert.ToInt32(ds1[1]);
                ds12 = System.Convert.ToInt32(ds1[2]);
                ds21 = System.Convert.ToInt32(ds2[1]);
                ds22 = System.Convert.ToInt32(ds2[2]);
                if (ds12 == ds22 && ds11 > ds21)
                {
                    MessageBox.Show("Please Select Greater Month in DateTo");
                    View = 0;
                    return;
                }
                if (ds10 > ds20 && ds12 == ds22 && ds11 == ds21)
                {
                    MessageBox.Show("Please Select Greater Date");
                    View = 0;
                    return;
                }
                if ((ds22 - ds12) > 1)
                {
                    MessageBox.Show("Please Select date between one year");
                    View = 0;
                    return;
                }
                if ((ds22 - ds12) == -1 || ((ds22 - ds12) >= 1 && ds21 >= ds11))
                {
                    MessageBox.Show("Please Select date between one year");
                    View = 0;
                    return;
                }
                getDate(ds10, ds11, ds12, ds20, ds21, ds22);

                if (DropSearchBy.SelectedIndex == 0 && DropValue.Value == "All")
                {
                    sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                }
                else if (DropSearchBy.SelectedIndex == 1)
                {
                    if (DropValue.Value == "All")
                    {
                        //sql="select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and cast(floor(cast(invoice_date as float)) as datetime)>= '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and  cast(floor(cast(invoice_date as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                    else
                    {
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where cust_type like '" + DropValue.Value + "%' and c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                }
                else if (DropSearchBy.SelectedIndex == 2)
                {
                    if (DropValue.Value == "All")
                    {
                        //sql="select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and cast(floor(cast(invoice_date as float)) as datetime)>= '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and  cast(floor(cast(invoice_date as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                    else
                    {
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where state='" + DropValue.Value + "'and c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                }
                else if (DropSearchBy.SelectedIndex == 3)
                {
                    if (DropValue.Value == "All")
                    {
                        //sql="select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and cast(floor(cast(invoice_date as float)) as datetime)>= '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and  cast(floor(cast(invoice_date as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                    else
                    {
                        //Coment by vikas 25.05.09 sql="select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where cust_name='"+DropValue.Value+"' and c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and  cast(floor(cast(invoice_date as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                        cust_name = DropValue.Value.Substring(0, DropValue.Value.IndexOf(":"));
                        sql       = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where cust_name='" + cust_name.ToString() + "' and c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                }
                else if (DropSearchBy.SelectedIndex == 4)
                {
                    if (DropValue.Value == "All")
                    {
                        //sql="select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and cast(floor(cast(invoice_date as float)) as datetime)>= '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and  cast(floor(cast(invoice_date as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                    else
                    {
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where city='" + DropValue.Value + "' and c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                }
                else if (DropSearchBy.SelectedIndex == 5)
                {
                    if (DropValue.Value == "All")
                    {
                        //sql="select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and cast(floor(cast(invoice_date as float)) as datetime)>= '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and  cast(floor(cast(invoice_date as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                    else
                    {
                        sql = "select c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd from Customer c,sales_master sm,vw_salesoil v where SSR=(select Emp_ID from Employee where Emp_Name='" + DropValue.Value + "') and c.cust_id=sm.cust_id and sm.invoice_no=v.invoice_no and (cust_type not like('oe%') and cust_type not like('fleet%')) and cast(floor(cast(invoice_date as float)) as datetime)>= '" + GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) + "' and  cast(floor(cast(invoice_date as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) + "' group by c.Cust_ID,Cust_Name,state,city,cust_type,sadbhavnacd order by cust_name,state,sadbhavnacd,cust_type,city";
                    }
                }
                View = 1;
                CreateLogFiles.ErrorLog("Form:Salesreport1.aspx,Method:btnView, userid  " + UID);
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:Salesreport1.aspx,Method:btnView,   EXCEPTION " + ex.Message + "  userid  " + UID);
            }
        }
Exemple #5
0
        /// <summary>
        /// This method is used to update the particular employee record with the help of ProEmployeeUpdate Procedure
        /// before check the Employee name must be unique in Employee as well as Ledger Master table.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, System.EventArgs e)
        {
            EmployeeClass obj    = new EmployeeClass();
            SqlDataReader SqlDtr = null;

            try
            {
                if (!TempEmpName.Text.ToLower().Trim().Equals(lblName.Text.ToLower().Trim()))
                {
                    string ename = lblName.Text.Trim();
                    string sql1  = "select * from employee where Emp_Name='" + ename.Trim() + "'";
                    SqlDtr = obj.GetRecordSet(sql1);
                    if (SqlDtr.HasRows)
                    {
                        MessageBox.Show("Employee Name  " + ename + " Already Exist");
                        return;
                    }
                    SqlDtr.Close();
                    sql1   = "select * from Ledger_Master where Ledger_Name='" + ename.Trim() + "'";
                    SqlDtr = obj.GetRecordSet(sql1);
                    if (SqlDtr.HasRows)
                    {
                        MessageBox.Show("Ledger Name  " + ename + " Already Exist");
                        return;
                    }
                    SqlDtr.Close();
                }
                obj.Emp_ID      = LblEmployeeID.Text.ToString();
                obj.Emp_Name    = lblName.Text;
                obj.TempEmpName = TempEmpName.Text;
                obj.Address     = txtAddress.Text.ToString();
                obj.EMail       = txtEMail.Text.ToString();
                obj.City        = DropCity.SelectedItem.Value.ToString();
                obj.State       = DropState.SelectedItem.Value.ToString();
                obj.Country     = DropCountry.SelectedItem.Value.ToString();
                if (txtContactNo.Text.ToString() == "")
                {
                    obj.Phone = "0";
                }
                else
                {
                    obj.Phone = txtContactNo.Text.ToString();
                }
                if (txtMobile.Text.ToString() == "")
                {
                    obj.Mobile = "0";
                }
                else
                {
                    obj.Mobile = txtMobile.Text.ToString();
                }
                obj.Designation         = DropDesig.SelectedItem.Value.ToString();
                obj.Salary              = txtSalary.Text.ToString();
                obj.OT_Compensation     = txtOT_Comp.Text.ToString();
                obj.Dr_License_No       = txtLicenseNo.Text.ToString().Trim();
                obj.Dr_License_validity = GenUtil.str2MMDDYYYY(txtLicenseValidity.Text.Trim());
                obj.Dr_LIC_No           = txtLICNo.Text.Trim();
                obj.Dr_LIC_validity     = GenUtil.str2MMDDYYYY(txtLicenseValidity.Text.Trim());
                obj.OpBalance           = txtopbal.Text.Trim().ToString();
                obj.BalType             = DropType.SelectedItem.Text;
                string vehicle_no = DropVehicleNo.SelectedItem.Text.Trim();
                if (vehicle_no.Equals(""))
                {
                    vehicle_no = "0";
                }

                obj.Vehicle_NO = vehicle_no;
                // calls the update employee procedures through the UpdateEmployee() method.
                /************Add by vikas 27.10.2012*****************/
                if (RbtnActive.Checked == true)
                {
                    obj.Status = "1";
                }
                else if (RbtnNone.Checked == true)
                {
                    obj.Status = "0";
                }
                /************End*****************/
                obj.UpdateEmployee();
                string Ledger_ID = "";
                dbobj.SelectQuery("select Ledger_ID from Ledger_Master where Ledger_Name=(select Emp_Name from Employee where Emp_ID='" + LblEmployeeID.Text.Trim() + "')", ref SqlDtr);
                if (SqlDtr.Read())
                {
                    Ledger_ID = SqlDtr.GetValue(0).ToString();
                }
                UpdateCustomerBalance(Ledger_ID);
                MessageBox.Show("Employee Updated");
                CreateLogFiles.ErrorLog("Form:Employee_Update.aspx,Method:btnUpdate_Click" + "EmployeeID   " + LblEmployeeID.Text.ToString() + " IS UPDATED  " + " userid " + uid);
                Response.Redirect("Employee_List.aspx", false);
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:Employee_Update.aspx,Method:btnUpdate_Click" + "EmployeeID  " + LblEmployeeID.Text.ToString() + "  IS UPDATED " + "  EXCEPTION" + ex.Message + " userid  " + uid);
            }
        }
Exemple #6
0
		/// <summary>
		/// this is used to save the scheme .
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void btnSubmit_Click(object sender, System.EventArgs e)
		{
			try
			{
				InventoryClass obj =new InventoryClass();
				//string sql;
				SqlDataReader SqlDtr=null;
				if(ListEmpAssigned.Items.Count!=0)
				{
					for(int i=0;i<ListEmpAssigned.Items.Count;++i)
					{
						ListEmpAssigned.SelectedIndex =i;
						string pname = ListEmpAssigned.SelectedItem.Value; 
						string[] arr1=pname.Split(new char[]{':'},pname.Length);
						InventoryClass obj1 = new InventoryClass();
						SqlDataReader rdr;
						//string sname=DropSchType.SelectedItem.Text;
						string schname="";
						string sql1="select Prod_ID from Products where Prod_Name='"+arr1[0]+"' and Pack_Type='"+arr1[1]+"'";
						rdr = obj1.GetRecordSet (sql1);
						if(rdr.Read ())
						{
							/*if(sname.IndexOf("Free")>0)
								schname="Free Scheme";
							else if(sname.IndexOf("LTR&%")>0)
								schname="LTR&% Scheme";
							else if(sname.IndexOf("LTRSP")>0)
								schname="LTRSP Scheme";
							else
								schname="LTR Scheme";*/
							schname="Secondry Claim";
							//coment by vikas 02.06.09 sql1="select * from StktSchDiscount where Prodid='"+rdr["Prod_ID"].ToString()+"' and schtype like '%"+schname+"%' and (cast(floor(cast(datefrom as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and cast(floor(cast(dateto as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(datefrom as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(dateto as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"')";
							sql1="select * from Prod_Promo_Grade_Entry where Prodid='"+rdr["Prod_ID"].ToString()+"' and schtype like '%"+schname+"%' and (cast(floor(cast(datefrom as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and cast(floor(cast(dateto as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(datefrom as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(dateto as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"')";
							dbobj.SelectQuery(sql1,ref SqlDtr);
							if(SqlDtr.Read())
							{
								MessageBox.Show("'"+pname+"'"+" Allready Exist");
								return;
							}
						}
						rdr.Close();
					}
				}
				else
				{
					MessageBox.Show("Please Select At Least One Product");
					return;
				}
				
				//obj.schtype=DropSchType.SelectedItem.Text.ToString();
				obj.schtype="Secondry Claim";
				obj.schid=lblschid.Text;
				if(txtschname.Text.Equals(""))
					obj.schname="";
				else
					obj.schname=txtschname.Text.ToString();

				if(txtSchDiscount.Text.Equals(""))
					obj.discount="";
				else
					obj.discount=txtSchDiscount.Text.ToString();
				
				obj.discounttype=DropSchDiscount.SelectedItem.Text;                
                obj.dateto = System.Convert.ToDateTime(GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()));
                obj.datefrom = System.Convert.ToDateTime(GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()));

                for (int i=0;i<ListEmpAssigned.Items.Count;++i)
				{
					ListEmpAssigned.SelectedIndex =i;
					string pname = ListEmpAssigned.SelectedItem.Value; 
					string[] arr1=pname.Split(new char[]{':'},pname.Length);  
					string sql1="select Prod_ID from Products where Prod_Name='"+arr1[0]+"' and Pack_Type='"+arr1[1]+"'";
					dbobj.SelectQuery(sql1,ref SqlDtr);
					while(SqlDtr.Read ())
					{
						obj.prodid=SqlDtr.GetValue(0).ToString();
						//obj.InsertStockiestSchemediscount();
						obj.InsertPPGE(); //add by vikas 02.06.09 
					}
				}
				SqlDtr.Close();
				MessageBox.Show("Product Promotion Grade Saved");
				Clear();
				FillList();
				GetNextschemeID();
				CreateLogFiles.ErrorLog("Form:Prod_Promo_Dis_Entry.aspx,Method:btnSubmit_Click  Stockiest Discount Entry Saved, User : "******"Form:Prod_Promo_Dis_Entry.aspx,Method:btnSubmit_Click EXCEPTION "+ex.Message );	
			}
		}
Exemple #7
0
		/// <summary>
		/// This method is used for setting the Session variable for userId and 
		/// after that filling the required dropdowns with database values 
		/// and also check accessing priviledges for particular user
		/// and generate the next ID also.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			try
			{
				uid=(Session["User_Name"].ToString());
			}
			catch(Exception ex)
			{
				CreateLogFiles.ErrorLog("Form:Prod_Promo_Dis_Entry.aspx,Method:pageload"+ ex.Message+"  EXCEPTION  "+uid);
				Response.Redirect("../../Sysitem/ErrorPage.aspx",false);
				return;
			}
			if (!Page.IsPostBack )
			{
				txtDateFrom.Text=GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString());
				txtDateTo.Text=GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString());
/*
				#region Check Privileges
				int i;
				string View_Flag="0", Add_Flag="0", Edit_Flag="0", Del_Flag="0";
				string Module="3";
				string SubModule="11";
				string[,] Priv=(string[,]) Session["Privileges"];
				for(i=0;i<Priv.GetLength(0);i++)
				{
					if(Priv[i,0]== Module &&  Priv[i,1]==SubModule)
					{						
						View_Flag=Priv[i,2];
						Add_Flag=Priv[i,3];
						Edit_Flag=Priv[i,4];
						Del_Flag=Priv[i,5];
						break;
					}
				}	
				if(View_Flag=="0")
				{
					Response.Redirect("../../Sysitem/AccessDeny.aspx",false);
					return;
				}
				if(Add_Flag=="0")
					btnSubmit.Enabled=false;
				if(Edit_Flag=="0")
					btschid.Enabled=false;
				#endregion
*/
				try
				{
					dropschid.Visible=false;
					btnupdate.Visible=false;
					GetNextschemeID();
					InventoryClass obj= new InventoryClass();
					
					FillList();
				}
				catch(Exception ex)
				{
					CreateLogFiles.ErrorLog("Form:Prod_Promo_Dis_Entry.aspx,Method:pageload"+ ex.Message+"  EXCEPTION  "+uid); 
				}
			}
            txtDateFrom.Text = Request.Form["txtDateFrom"] == null ? GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString()) : Request.Form["txtDateFrom"].ToString().Trim();
            txtDateTo.Text = Request.Form["txtDateTo"] == null ? GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString()) : Request.Form["txtDateTo"].ToString().Trim();
        }
        /// <summary>
        /// </summary>
        private void Worker()
        {
            selWebId    = Guid.NewGuid();
            selWebTitle = string.Empty;
            var       lst    = new List <CustXMLList>();
            Exception retErr = null;

            try
            {
                SPWSLists.Lists proxy = new SPCAMLQueryHelperOnline.SPWSLists.Lists();

                if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                {
                    proxy.UseDefaultCredentials = true;
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                {
                    proxy.UseDefaultCredentials = false;
                    proxy.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                {
                    proxy.CookieContainer = SharedStuff.GetAuthCookies(new Uri(url), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                }

                proxy.Url = GenUtil.CombineUrls(url, XMLConsts.AsmxSuffix_Lists);

                XElement xLists = proxy.GetListCollection().GetXElement();

                foreach (XElement xList in xLists.Elements(XMLConsts.s + "List"))
                {
                    CustXMLList cXmlList = new CustXMLList()
                    {
                        DefaultViewUrl = GenUtil.GetXElemAttrAsString(xList, "DefaultViewUrl"),
                        ID             = GenUtil.GetXElemAttrAsString(xList, "ID"),
                        Hidden         = GenUtil.SafeToBool(GenUtil.GetXElemAttrAsString(xList, "Hidden")),
                        Name           = GenUtil.GetXElemAttrAsString(xList, "Name"),
                        Title          = GenUtil.GetXElemAttrAsString(xList, "Title"),
                        WebFullUrl     = GenUtil.GetXElemAttrAsString(xList, "WebFullUrl"),
                        WebId          = GenUtil.GetXElemAttrAsString(xList, "WebId")
                    };

                    if (!cXmlList.Hidden)
                    {
                        lst.Add(cXmlList);
                    }
                }
            }
            catch (Exception ex)
            {
                retErr = ex;
            }


            // update gui
            parentForm.Invoke(new MethodInvoker(() =>
            {
                tvLists.Nodes.Clear();

                if (retErr != null)
                {
                    GenUtil.LogIt(txtStatus, retErr.ToString());
                }
                else
                {
                    GenUtil.LogIt(txtStatus, "OK");

                    foreach (CustXMLList l in lst)
                    {
                        tvLists.Nodes.Add(l.ID, (l.Hidden ? l.Title + " [HIDDEN]" : l.Title));
                    }
                }

                // finish action
                btnLoad.Enabled = true;

                toolStripStatusLabel1.Text = "";
                statusStrip1.Refresh();

                picLogoWait.Visible = false;
                picLogoWait.Refresh();
            }));
        }
        /// <summary>
        /// </summary>
        private void Worker()
        {
            Exception retErr = null;
            DataTable dt     = null;

            try
            {
                SPWSLists.Lists proxy = new SPCAMLQueryHelperOnline.SPWSLists.Lists();

                if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                {
                    proxy.UseDefaultCredentials = true;
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                {
                    proxy.UseDefaultCredentials = false;
                    proxy.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                {
                    proxy.CookieContainer = SharedStuff.GetAuthCookies(new Uri(siteUrl), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                }

                proxy.Url = GenUtil.CombineUrls(siteUrl, XMLConsts.AsmxSuffix_Lists);

                var strQuery = GenUtil.RemoveWhiteSpace(txtQuery.Text);
                strQuery = GenUtil.WrapWSQuery(strQuery);

                //
                StringReader rdrQuery = new StringReader(strQuery);
                XElement     xQuery   = XElement.Load(rdrQuery);

                //
                string rowLimit = (GenUtil.SafeToNum(txtRowLimit.Text) == 0 ? "" : GenUtil.SafeToNum(txtRowLimit.Text).ToString());

                //
                string webID = "";

                //
                StringReader rdrQueryOptions = null;
                if (GenUtil.IsNull(txtViewAttributes.Text))
                {
                    rdrQueryOptions = new StringReader("<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns></QueryOptions>");
                }
                else
                {
                    rdrQueryOptions = new StringReader(string.Format("<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><ViewAttributes {0} /></QueryOptions>",
                                                                     GenUtil.RemoveWhiteSpace(txtViewAttributes.Text.Trim())));
                }
                XElement xQueryOptions = XElement.Load(rdrQueryOptions);

                //
                XElement xViewFields = null;
                if (GenUtil.IsNull(txtViewFields.Text))
                {
                    xViewFields = new XElement("ViewFields");
                }
                else
                {
                    StringReader rdrViewFields = new StringReader(string.Format("<ViewFields>{0}</ViewFields>",
                                                                                GenUtil.RemoveWhiteSpace(txtViewFields.Text.Trim())));
                    xViewFields = XElement.Load(rdrViewFields);
                }

                //
                string viewName = "";

                //
                XElement results = proxy.GetListItems(
                    listName,
                    viewName,
                    xQuery.GetXmlNode(),
                    xViewFields.GetXmlNode(),
                    rowLimit,
                    xQueryOptions.GetXmlNode(),
                    webID).GetXElement();


                //
                dt = new DataTable();

                foreach (XElement xRow in results.Descendants(XMLConsts.z + "row"))
                {
                    foreach (XAttribute xAttr in xRow.Attributes())
                    {
                        string colName = xAttr.Name.ToString();

                        if (!dt.Columns.Contains(xAttr.Name.ToString()))
                        {
                            dt.Columns.Add(xAttr.Name.ToString(), typeof(string));
                        }
                    }
                }

                foreach (XElement xRow in results.Descendants(XMLConsts.z + "row"))
                {
                    DataRow dr = dt.NewRow();

                    foreach (XAttribute xAttr in xRow.Attributes())
                    {
                        string colName = xAttr.Name.ToString();
                        string colVal  = xAttr.Value;

                        dr[colName] = colVal;
                    }

                    dt.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
                retErr = ex;
            }



            // update gui
            parentForm.Invoke(new MethodInvoker(() =>
            {
                if (retErr != null)
                {
                    GenUtil.LogIt(txtStatus, retErr.ToString());
                }
                else
                {
                    GenUtil.LogIt(txtStatus, string.Format("Found {0} Record(s).", dt.Rows.Count));

                    gvResults.DataSource = dt;

                    if (dt.Rows.Count > 0)
                    {
                        tabControl1.SelectTab(2);
                    }
                }


                // finish action
                btnSearch.Enabled          = true;
                toolStripStatusLabel1.Text = "";
                statusStrip1.Refresh();
                picLogoWait.Visible = false;
                picLogoWait.Refresh();
            }));
        }
 void WriteToTb(string s1, object o1)
 {
     tbFieldInfo.Text += string.Format("{0}: {1}{2}", GenUtil.SafeTrim(s1), GenUtil.SafeTrim(o1), Environment.NewLine);
 }
        /// <summary>
        /// </summary>
        private void Worker()
        {
            // configure view web service
            List <CustXMLView>  lstViews  = new List <CustXMLView>();
            List <CustXMLField> lstFields = new List <CustXMLField>();

            Exception retErr = null;

            try
            {
                SPWSViews.Views proxyViews = new SPCAMLQueryHelperOnline.SPWSViews.Views();

                if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                {
                    proxyViews.UseDefaultCredentials = true;
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                {
                    proxyViews.UseDefaultCredentials = false;
                    proxyViews.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                {
                    proxyViews.CookieContainer = SharedStuff.GetAuthCookies(new Uri(url), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                }

                proxyViews.Url = GenUtil.CombineUrls(url, XMLConsts.AsmxSuffix_Views);

                // configure list web service
                SPWSLists.Lists proxyLists = new SPCAMLQueryHelperOnline.SPWSLists.Lists();

                if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                {
                    proxyLists.UseDefaultCredentials = true;
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                {
                    proxyLists.UseDefaultCredentials = false;
                    proxyLists.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                {
                    proxyLists.CookieContainer = SharedStuff.GetAuthCookies(new Uri(url), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                }

                proxyLists.Url = GenUtil.CombineUrls(url, XMLConsts.AsmxSuffix_Lists);

                // get list views
                XElement xViews = proxyViews.GetViewCollection(listName).GetXElement();

                foreach (XElement xView in xViews.Elements(XMLConsts.s + "View"))
                {
                    lstViews.Add(new CustXMLView()
                    {
                        DefaultView = GenUtil.SafeToBool(GenUtil.GetXElemAttrAsString(xView, "DefaultView")),
                        DisplayName = GenUtil.GetXElemAttrAsString(xView, "DisplayName"),
                        Name        = GenUtil.GetXElemAttrAsString(xView, "Name"),
                        Url         = GenUtil.GetXElemAttrAsString(xView, "Url")
                    });
                }

                // get list fields
                XElement xList = proxyLists.GetList(listName).GetXElement();

                foreach (XElement xField in xList.Descendants(XMLConsts.s + "Field"))
                {
                    CustXMLField cXmlField = new CustXMLField();

                    cXmlField.DisplayName = GenUtil.GetXElemAttrAsString(xField, "DisplayName");
                    cXmlField.ID          = GenUtil.GetXElemAttrAsString(xField, "ID");
                    cXmlField.Name        = GenUtil.GetXElemAttrAsString(xField, "Name");
                    cXmlField.Required    = GenUtil.SafeToBool(GenUtil.GetXElemAttrAsString(xField, "Required"));
                    cXmlField.Type        = GenUtil.GetXElemAttrAsString(xField, "Type");

                    if (!GenUtil.IsNull(cXmlField.ID))
                    {
                        lstFields.Add(cXmlField);
                    }
                }
            }
            catch (Exception ex)
            {
                retErr = ex;
            }



            // update gui
            parentForm.Invoke(new MethodInvoker(() =>
            {
                ddlListViews.Items.Clear();
                tvFields.Nodes.Clear();
                btnOpenListDetails.Visible = false;


                if (retErr != null)
                {
                    GenUtil.LogIt(txtStatus, retErr.ToString());
                }
                else
                {
                    GenUtil.LogIt(txtStatus, "OK");


                    // render list views
                    ddlListViews.Items.Insert(0, "None");
                    ddlListViews.SelectedIndex = 0;

                    foreach (CustXMLView v in lstViews)
                    {
                        ddlListViews.Items.Add(v.DisplayName);
                    }


                    // render list fields
                    DataTable dt = new DataTable();

                    dt.Columns.Add("Id", typeof(string));
                    dt.Columns.Add("InternalName", typeof(string));
                    dt.Columns.Add("Required", typeof(string));
                    dt.Columns.Add("Title", typeof(string));
                    dt.Columns.Add("TypeAsString", typeof(string));

                    foreach (CustXMLField cXmlField in lstFields)
                    {
                        DataRow dr = dt.NewRow();

                        dr["Id"]           = cXmlField.ID;
                        dr["InternalName"] = cXmlField.Name;
                        dr["Required"]     = cXmlField.Required.ToString();
                        dr["Title"]        = cXmlField.DisplayName;
                        dr["TypeAsString"] = cXmlField.Type;

                        dt.Rows.Add(dr);


                        TreeNode tn = new TreeNode();

                        if (lnkToggleFieldsName.Text == text_show_internalnames)
                        {
                            tn.Text = string.Format("{0} [{1}]", cXmlField.DisplayName, cXmlField.Name);
                        }
                        else
                        {
                            tn.Text = string.Format("{0} [{1}]", cXmlField.Name, cXmlField.DisplayName);
                        }

                        tn.Name = cXmlField.Name;

                        tvFields.Nodes.Add(tn);
                    }


                    DataView dv         = new DataView(dt);
                    dv.Sort             = "Title";
                    gvFields.DataSource = dv;


                    if (tvFields.Nodes.Count > 0)
                    {
                        tvFields.Sort();
                        tvFields.SelectedNode = tvFields.Nodes[0];
                    }
                }

                btnOpenListDetails.Visible = true;

                // finish action
                toolStripStatusLabel1.Text = "";
                statusStrip1.Refresh();

                picLogoWait.Visible = false;
                picLogoWait.Refresh();
            }));
        }
        /// <summary>
        /// </summary>
        private void Worker()
        {
            // configure list web service

            // update gui
            parentForm.Invoke(new MethodInvoker(() =>
            {
                try
                {
                    SPWSLists.Lists proxy = new SPCAMLQueryHelperOnline.SPWSLists.Lists();

                    if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                    {
                        proxy.UseDefaultCredentials = true;
                    }
                    else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                    {
                        proxy.UseDefaultCredentials = false;
                        proxy.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                    }
                    else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                    {
                        proxy.CookieContainer = SharedStuff.GetAuthCookies(new Uri(siteUrl), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                    }

                    proxy.Url = GenUtil.CombineUrls(siteUrl, XMLConsts.AsmxSuffix_Lists);

                    XElement xList = proxy.GetList(listName).GetXElement();

                    var lst = new List <string>();

                    foreach (XElement xField in xList.Descendants(XMLConsts.s + "Field"))
                    {
                        var attr = xField.Attribute("ID");

                        if (attr != null)
                        {
                            var tmp  = Regex.Replace(GenUtil.SafeTrim(attr.Value), "[^a-zA-Z0-9]", "");
                            var tmp2 = Regex.Replace(fieldId.ToString().Trim().ToLower(), "[^a-zA-Z0-9]", "");

                            if (tmp == tmp2)
                            {
                                foreach (var attr2 in xField.Attributes())
                                {
                                    lst.Add(attr2.Name.LocalName + ": " + GenUtil.SafeTrim(attr2.Value));
                                }

                                break;
                            }
                        }
                    }

                    foreach (string s in lst.OrderBy(x => x))
                    {
                        WriteToTb(s);
                    }
                }
                catch (Exception ex)
                {
                    WriteToTb("ERROR", ex.ToString());
                }
            }));
        }
        /// <summary>
        /// </summary>
        private void Worker()
        {
            // configure list web service
            Exception retErr = null;

            var dictAttrs       = new Dictionary <string, string>();
            var lstContentTypes = new List <string>();

            try
            {
                var proxy = new SPCAMLQueryHelperOnline.SPWSLists.Lists();

                if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                {
                    proxy.UseDefaultCredentials = true;
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                {
                    proxy.UseDefaultCredentials = false;
                    proxy.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                {
                    proxy.CookieContainer = SharedStuff.GetAuthCookies(new Uri(siteUrl), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                }

                proxy.Url = GenUtil.CombineUrls(siteUrl, XMLConsts.AsmxSuffix_Lists);

                XElement xList = proxy.GetList(listName).GetXElement();

                foreach (XAttribute att in xList.Attributes())
                {
                    if (!dictAttrs.ContainsKey(att.Name.LocalName))
                    {
                        dictAttrs.Add(att.Name.LocalName, GenUtil.SafeTrim(att.Value));
                    }
                }

                XElement xContType = proxy.GetListContentTypes(listName, "0x").GetXElement();

                foreach (var el in xContType.Elements(XMLConsts.s + "ContentType"))
                {
                    var lstAttrs = new List <string>();

                    foreach (var attr in el.Attributes())
                    {
                        lstAttrs.Add(string.Concat(attr.Name, "=", attr.Value));
                    }

                    lstContentTypes.Add(string.Join("; ", lstAttrs.ToArray()));
                }
            }
            catch (Exception ex)
            {
                retErr = ex;
            }

            // update gui
            parentForm.Invoke(new MethodInvoker(() =>
            {
                if (retErr != null)
                {
                    WriteToTb("ERROR", retErr.ToString());
                }
                else
                {
                    var keys = dictAttrs.Keys.OrderBy(x => x.Trim().ToLower());
                    foreach (string key in keys)
                    {
                        WriteToTb(key, dictAttrs[key]);
                    }

                    WriteToTb();
                    WriteToTb("CONTENTTYPES", "");
                    foreach (string contentType in lstContentTypes)
                    {
                        WriteToTb("-ContentType", contentType);
                    }
                }
            }));
        }
        /// <summary>
        /// </summary>
        private void Worker()
        {
            // configure view web service
            List <CustXMLView> lstCustXmlViews = new List <CustXMLView>();
            Exception          retErr          = null;

            try
            {
                SPWSViews.Views proxy = new SPCAMLQueryHelperOnline.SPWSViews.Views();

                if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSDef)
                {
                    proxy.UseDefaultCredentials = true;
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSCreds)
                {
                    proxy.UseDefaultCredentials = false;
                    proxy.Credentials           = new System.Net.NetworkCredential(parentForm.formChooser.credUsername, parentForm.formChooser.credPassword, parentForm.formChooser.credDomain);
                }
                else if (parentForm.formChooser.appMode == Chooser.AppMode.UseWSOffice365)
                {
                    proxy.CookieContainer = SharedStuff.GetAuthCookies(new Uri(siteUrl), parentForm.formChooser.credUsername, parentForm.formChooser.credPassword);
                }

                proxy.Url = GenUtil.CombineUrls(siteUrl, XMLConsts.AsmxSuffix_Views);

                XElement xViews = proxy.GetViewCollection(listName).GetXElement();

                foreach (XElement xView in xViews.Elements(XMLConsts.s + "View"))
                {
                    lstCustXmlViews.Add(new CustXMLView()
                    {
                        DefaultView = GenUtil.SafeToBool(GenUtil.GetXElemAttrAsString(xView, "DefaultView")),
                        DisplayName = GenUtil.GetXElemAttrAsString(xView, "DisplayName"),
                        Name        = GenUtil.GetXElemAttrAsString(xView, "Name"),
                        Url         = GenUtil.GetXElemAttrAsString(xView, "Url")
                    });
                }
            }
            catch (Exception ex)
            {
                retErr = ex;
            }



            // update gui
            parentForm.Invoke(new MethodInvoker(() =>
            {
                lstViews.Items.Clear();
                htViews.Clear();

                if (retErr != null)
                {
                }
                else
                {
                    foreach (CustXMLView cXmlView in lstCustXmlViews)
                    {
                        htViews.Add(cXmlView.DisplayName, cXmlView);
                        lstViews.Items.Add(cXmlView.DisplayName);
                    }
                }
            }));
        }
Exemple #15
0
        /// <summary>
        /// Method to write into the report file to print.
        /// </summary>
        public void makingReport()
        {
            string home_drive = Environment.SystemDirectory;

            home_drive = home_drive.Substring(0, 2);
            string        path     = home_drive + @"\Inetpub\wwwroot\Servosms\Sysitem\ServosmsPrintServices\ReportView\DistrictWiseChannelSalesReport.txt";
            StreamWriter  sw       = new StreamWriter(path);
            DBUtil        dbobj2   = new DBUtil(System.Configuration.ConfigurationSettings.AppSettings["Servosms"], true);
            SqlDataReader rdr1     = null;
            ArrayList     arrType  = new ArrayList();
            ArrayList     arrState = new ArrayList();

            double[] arrTotal = null, arrTotal1 = null;
            string   Header = "", desdes = "", des = "";
            string   Header1 = "", desdes1 = "", des1 = "";

            //dbobj2.SelectQuery("select distinct state from customer order by state",ref rdr1);
            if (radDetails.Checked)
            {
                dbobj2.SelectQuery("(select distinct case when substring(cust_type,1,2)='Ro' then 'RO' when substring(cust_type,1,2)='Oe' then 'OE' else substring(cust_type,1,2) end from customer where (substring(cust_type,1,2)='Ro' or substring(cust_type,1,2)='oe') group by substring(cust_type,1,2)) union (select customertypename from customertype where (substring(customertypename,1,2)!='Ro' and substring(customertypename,1,2)!='oe') group by customertypename)", ref rdr1);
            }
            else
            {
                dbobj2.SelectQuery("(select distinct case when substring(cust_type,1,2)='Ro' then 'RO' when substring(cust_type,1,2)='Oe' then 'OE' when substring(cust_type,1,2)='Ks' then 'KSK' when substring(cust_type,1,2)='N-' then 'N-KSK' else substring(cust_type,1,2) end from customer where (substring(cust_type,1,2)='Ro' or substring(cust_type,1,2)='oe' or substring(cust_type,1,2)='Ks' or substring(cust_type,1,2)='n-') group by substring(cust_type,1,2)) union (select customertypename from customertype where (substring(customertypename,1,2)!='Ro' and substring(customertypename,1,2)!='oe' and substring(customertypename,1,2)!='ks' and substring(customertypename,1,2)!='N-') group by customertypename)", ref rdr1);
            }
            if (rdr1.HasRows)
            {
                int cc = 0;
                Header  = "| Distict/Type ";
                desdes  = "+--------------";
                des     = "---------------";
                Header1 = "| Distict/Type ";
                desdes1 = "+--------------";
                des1    = "---------------";
                while (rdr1.Read())
                {
                    if (cc > 10)
                    {
                        Header1 += "| " + rdr1.GetValue(0).ToString();
                        for (int i = rdr1.GetValue(0).ToString().Length + 1; i < 10; i++)
                        {
                            Header1 += " ";
                        }
                        desdes1 += "+----------";
                        des1    += "-----------";
                    }
                    else
                    {
                        Header += "| " + rdr1.GetValue(0).ToString();
                        for (int i = rdr1.GetValue(0).ToString().Length + 1; i < 10; i++)
                        {
                            Header += " ";
                        }
                        desdes += "+----------";
                        des    += "-----------";
                    }
                    arrType.Add(rdr1.GetValue(0).ToString());
                    cc++;
                }
                if (cc < 9)
                {
                    Header += "| Total Sales | Monthly Avr. |";
                    desdes += "+-------------+--------------+";
                    des    += "------------------------------";
                }
                else
                {
                    Header1 += "| Total Sales | Monthly Avr. |";
                    desdes1 += "+-------------+--------------+";
                    des1    += "------------------------------";
                }
            }
            rdr1.Close();
            //*********************************
            // Condensed
            sw.Write((char)27);           //added by vishnu
            sw.Write((char)67);           //added by vishnu
            sw.Write((char)0);            //added by vishnu
            sw.Write((char)12);           //added by vishnu

            sw.Write((char)27);           //added by vishnu
            sw.Write((char)78);           //added by vishnu
            sw.Write((char)5);            //added by vishnu

            sw.Write((char)27);           //added by vishnu
            sw.Write((char)15);
            //**********
            string Address = GenUtil.GetAddress();

            string[] addr = Address.Split(new char[] { ':' }, Address.Length);
            sw.WriteLine(GenUtil.GetCenterAddr(addr[0], des.Length).ToUpper());
            sw.WriteLine(GenUtil.GetCenterAddr(addr[1] + addr[2], des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("Tin No : " + addr[3], des.Length));
            sw.WriteLine(des);
            //******S***
            sw.WriteLine(GenUtil.GetCenterAddr("-------------------------------------------------------------------------------------------", des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("District / Channel Wise Summerized Sales Report Form Date : " + txtDateFrom.Text + " To Date : " + txtDateTo.Text, des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("-------------------------------------------------------------------------------------------", des.Length));
            //sw.WriteLine(" From Date : "+txtDateFrom.Text+" , To Date : "+txtDateTo.Text);
            //*********************************

            sw.WriteLine(desdes);
            sw.WriteLine(Header);
            sw.WriteLine(desdes);

            arrTotal = new double[arrType.Count];
            double Total = 0, GTotal = 0, GAvrTotal = 0;

            //dbobj2.SelectQuery("(select distinct case when substring(cust_type,1,2)='Ro' then 'RO' when substring(cust_type,1,2)='Oe' then 'OE' else substring(cust_type,1,2) end from customer where (substring(cust_type,1,2)='Ro' or substring(cust_type,1,2)='oe') group by substring(cust_type,1,2)) union (select cust_type from customer where (substring(cust_type,1,2)!='Ro' and substring(cust_type,1,2)!='oe') group by cust_type)",ref rdr1);
            dbobj2.SelectQuery("select distinct state from customer order by state", ref rdr1);
            while (rdr1.Read())
            {
                arrState.Add(rdr1.GetValue(0).ToString());
            }
            rdr1.Close();
            arrTotal1 = new double[arrState.Count];
            int Flag = 0;

            for (int i = 0; i < arrState.Count; i++)
            {
                Total = 0;
                sw.Write(" " + arrState[i].ToString());
                //for(int k=arrState[i].ToString().Length;k<=16;k++)
                for (int k = arrState[i].ToString().Length; k <= 14; k++)
                {
                    sw.Write(" ");
                }
                for (int j = 0; j < arrType.Count; j++)
                {
                    //dbobj2.SelectQuery("select case when sum(net_amount) is null then '0' else sum(net_amount) end from sales_master sm,customer c where sm.cust_id=c.cust_id and c.state='"+arrState[i].ToString()+"' and cust_type like'"+arrType[j].ToString()+"%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
                    //dbobj2.SelectQuery("select case when sum(qty) is null then '0' else sum(qty) end from sales_master sm,customer c,sales_details sd where sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='"+arrState[i].ToString()+"' and cust_type like'"+arrType[j].ToString()+"%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
                    if (j == 8)
                    {
                        Flag = 1;
                    }
                    if (j == 11)
                    {
                        break;
                    }
                    if (radDetails.Checked)
                    {
                        if (arrType[j].ToString().ToLower() == "ksk")
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type ='" + arrType[j].ToString() + "' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                        else
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                    }
                    else
                    {
                        if (arrType[j].ToString().ToLower() == "ksk")
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                        else if (arrType[j].ToString().ToLower() == "n-ksk")
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                        else
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                    }
                    if (rdr1.Read())
                    {
                        arrTotal[j] += double.Parse(rdr1.GetValue(0).ToString());
                        sw.Write(rdr1.GetValue(0).ToString());
                        for (int k = rdr1.GetValue(0).ToString().Length; k <= 10; k++)
                        {
                            sw.Write(" ");
                        }
                        Total += double.Parse(rdr1.GetValue(0).ToString());
                    }
                }
                arrTotal1[i] = Total;
                if (Flag == 0)
                {
                    sw.Write(Total.ToString());
                    for (int k = Total.ToString().Length; k <= 13; k++)
                    {
                        sw.Write(" ");
                    }
                    string GAvr = System.Convert.ToString(Total / double.Parse(Count.ToString()));
                    sw.Write(GenUtil.strNumericFormat(GAvr));
                    for (int k = GAvr.Length; k <= 14; k++)
                    {
                        sw.Write(" ");
                    }
                    GTotal    += Total;
                    GAvrTotal += double.Parse(GAvr);
                }
                sw.WriteLine();
            }

            sw.WriteLine(desdes);
            string str = " Total";

            sw.Write(str);
            for (int k = str.ToString().Length; k <= 15; k++)
            {
                sw.Write(" ");
            }
            for (int n = 0; n < arrTotal.Length; n++)
            {
                if (n > 10)
                {
                    break;
                }
                sw.Write(arrTotal[n].ToString());
                for (int k = arrTotal[n].ToString().Length; k <= 10; k++)
                {
                    sw.Write(" ");
                }
            }
            if (Flag == 0)
            {
                sw.Write(GTotal.ToString());
                for (int k = GTotal.ToString().Length; k <= 13; k++)
                {
                    sw.Write(" ");
                }
                sw.Write(GenUtil.strNumericFormat(GAvrTotal.ToString()));
                for (int k = GAvrTotal.ToString().Length; k <= 14; k++)
                {
                    sw.Write(" ");
                }
            }
            sw.WriteLine();
            sw.WriteLine(desdes);

            if (Flag == 1)
            {
                sw.WriteLine();
                sw.WriteLine();
                sw.WriteLine(desdes1);
                sw.WriteLine(Header1);
                sw.WriteLine(desdes1);

                for (int i = 0; i < arrState.Count; i++)
                {
                    //Total=0;
                    Total = arrTotal1[i];
                    sw.Write(" " + arrState[i].ToString());
                    //for(int k=arrState[i].ToString().Length;k<=16;k++)
                    for (int k = arrState[i].ToString().Length; k <= 14; k++)
                    {
                        sw.Write(" ");
                    }

                    for (int j = 11; j < arrType.Count; j++)
                    {
                        //dbobj2.SelectQuery("select case when sum(net_amount) is null then '0' else sum(net_amount) end from sales_master sm,customer c where sm.cust_id=c.cust_id and c.state='"+arrState[i].ToString()+"' and cust_type like'"+arrType[j].ToString()+"%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
                        //dbobj2.SelectQuery("select case when sum(qty) is null then '0' else sum(qty) end from sales_master sm,customer c,sales_details sd where sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='"+arrState[i].ToString()+"' and cust_type like'"+arrType[j].ToString()+"%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
//						if(arrType[j].ToString().ToLower()=="ksk")
//							dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='"+arrState[i].ToString()+"' and cust_type ='"+arrType[j].ToString()+"' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
//						else
                        dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        if (rdr1.Read())
                        {
                            arrTotal[j] += double.Parse(rdr1.GetValue(0).ToString());
                            sw.Write(rdr1.GetValue(0).ToString());
                            for (int k = rdr1.GetValue(0).ToString().Length; k <= 10; k++)
                            {
                                sw.Write(" ");
                            }
                            Total += double.Parse(rdr1.GetValue(0).ToString());
                        }
                    }
                    sw.Write(Total.ToString());
                    for (int k = Total.ToString().Length; k <= 13; k++)
                    {
                        sw.Write(" ");
                    }
                    string GAvr = System.Convert.ToString(Total / double.Parse(Count.ToString()));
                    sw.Write(GenUtil.strNumericFormat(GAvr));
                    for (int k = GAvr.Length; k <= 14; k++)
                    {
                        sw.Write(" ");
                    }
                    GTotal    += Total;
                    GAvrTotal += double.Parse(GAvr);
                    sw.WriteLine();
                }
                //				if(Flag!=2)
                //				{
                //					Flag=3;
                //					for(int i=0;i<arrState.Count;i++)
                //					{
                //						sw.Write(Total.ToString());
                //						for(int k=Total.ToString().Length;k<=13;k++)
                //						{
                //							sw.Write(" ");
                //						}
                //						string GAvr=System.Convert.ToString(Total/double.Parse(Count.ToString()));
                //						sw.Write(GenUtil.strNumericFormat(GAvr));
                //						for(int k=GAvr.Length;k<=14;k++)
                //						{
                //							sw.Write(" ");
                //						}
                //						GTotal+=Total;
                //						GAvrTotal+=double.Parse(GAvr);
                //						sw.WriteLine();
                //					}
                //				}
                //***********
                sw.WriteLine(desdes1);
                str = " Total";
                sw.Write(str);
                for (int k = str.ToString().Length; k <= 15; k++)
                {
                    sw.Write(" ");
                }
                for (int n = 11; n < arrTotal.Length; n++)
                {
                    sw.Write(arrTotal[n].ToString());
                    for (int k = arrTotal[n].ToString().Length; k <= 10; k++)
                    {
                        sw.Write(" ");
                    }
                }
                sw.Write(GTotal.ToString());
                for (int k = GTotal.ToString().Length; k <= 13; k++)
                {
                    sw.Write(" ");
                }
                sw.Write(GenUtil.strNumericFormat(GAvrTotal.ToString()));
                for (int k = GAvrTotal.ToString().Length; k <= 14; k++)
                {
                    sw.Write(" ");
                }
                sw.WriteLine();
                sw.WriteLine(desdes1);
            }
            sw.Close();
        }
Exemple #16
0
        /// <summary>
        /// This is used to save the employee information with the help of ProEmployeeEntry Procedure
        /// before check the given employee name must be unique.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, System.EventArgs e)
        {
            EmployeeClass obj  = new EmployeeClass();
            string        str2 = "";

            try
            {
                SqlDataReader SqlDr;

                if (DropDesig.SelectedItem.Text == "Driver")
                {
                    if (txtLicenseNo.Text.Trim().Equals(""))
                    {
                        MessageBox.Show("Please enter License No");
                        return;
                    }
                }
                string sql1;
                string ename = "";
                if (txtFName.Text.Trim() != "")
                {
                    ename += txtFName.Text.Trim();
                }
                if (txtMName.Text.Trim() != "")
                {
                    ename += " " + txtMName.Text.Trim();
                }
                if (txtLName.Text.Trim() != "")
                {
                    ename += " " + txtLName.Text.Trim();
                }
                //((txtFName.Text.ToString().Trim() )) +" "+ StringUtil.FirstCharUpper((txtMName.Text.ToString().Trim() ))+" "+ StringUtil.FirstCharUpper((txtLName.Text.ToString().Trim() ));
                sql1  = "select Emp_Id from employee where Emp_Name='" + ename.Trim() + "'";
                SqlDr = obj.GetRecordSet(sql1);
                if (SqlDr.HasRows)
                {
                    MessageBox.Show("Employee Name  " + ename + " Already Exist");
                    return;
                }
                SqlDr.Close();
                sql1  = "select * from Ledger_Master where Ledger_Name='" + ename.Trim() + "'";
                SqlDr = obj.GetRecordSet(sql1);
                if (SqlDr.HasRows)
                {
                    MessageBox.Show("Employee Name  " + ename + " Already Exist");
                    return;
                }
                SqlDr.Close();
                obj.Emp_ID = LblEmployeeID.Text.ToString();
                //obj.Emp_Name =StringUtil.FirstCharUpper((txtFName.Text.ToString().Trim() )) +" "+ StringUtil.FirstCharUpper((txtMName.Text.ToString().Trim() ))+" "+ StringUtil.FirstCharUpper((txtLName.Text.ToString().Trim() ));
                obj.Emp_Name = ename.Trim();
                obj.Address  = StringUtil.FirstCharUpper(txtAddress.Text.ToString());

                obj.EMail   = txtEMail.Text;
                obj.City    = DropCity.SelectedItem.Value.ToString();
                obj.State   = DropState.SelectedItem.Value.ToString();
                obj.Country = DropCountry.SelectedItem.Value.ToString();
                if (txtContactNo.Text.ToString() == "")
                {
                    obj.Phone = "0";
                }
                else
                {
                    obj.Phone = txtContactNo.Text.ToString();
                }
                if (txtMobile.Text.ToString() == "")
                {
                    obj.Mobile = "0";
                }
                else
                {
                    obj.Mobile = txtMobile.Text.ToString();
                }
                obj.Designation         = DropDesig.SelectedItem.Value.ToString();
                obj.Salary              = txtSalary.Text.ToString();
                obj.OT_Compensation     = txtOT_Comp.Text.ToString();
                obj.Dr_License_No       = txtLicenseNo.Text.ToString().Trim();
                obj.Dr_License_validity = GenUtil.str2MMDDYYYY(txtLicenseValidity.Text.Trim());
                obj.Dr_LIC_No           = txtLICNo.Text.Trim();
                obj.Dr_LIC_validity     = GenUtil.str2MMDDYYYY(txtLicenseValidity.Text.Trim());
                obj.OpBalance           = txtopbal.Text.Trim().ToString();
                obj.BalType             = DropType.SelectedItem.Text;
                string vehicle_no = DropVehicleNo.SelectedItem.Text.Trim();
                if (vehicle_no.Equals(""))
                {
                    vehicle_no = "0";
                }
                obj.Vehicle_NO = vehicle_no;
                // Call the function from employee class to execute the procedure to insert the record.

                /************Add by vikas 27.10.2012*****************/
                if (RbtnActive.Checked == true)
                {
                    obj.Status = "1";
                }
                else if (RbtnNone.Checked == true)
                {
                    obj.Status = "0";
                }
                /************End*****************/

                obj.InsertEmployee();
                MessageBox.Show("Employee Saved");
                CreateLogFiles.ErrorLog("Form:Employee_Entry.aspx,Class:Employeee.cs,Methd: btnUpdate_Click   " + "Employee ID " + LblEmployeeID.Text.ToString() + "   Employee Name  " + obj.Emp_Name + " city   " + obj.City + " Salary  " + obj.Salary + " Designation " + obj.Designation + " IS SAVED  " + " userid " + Session["User_Name"].ToString() + "    " + uid);
                Clear();
                GetNextEmpID();
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:Employee_Entry.aspx,Class:Employeee.cs,Methd: btnUpdate_Click   Exception: " + ex.Message + "   userid  " + str2 + "  " + uid);
                Response.Redirect("../../Sysitem/ErrorPage.aspx", false);
            }
        }
Exemple #17
0
        /// <summary>
        /// Method to write into the excel report file to print.
        /// </summary>
        public void ConvertToExcel()
        {
            string home_drive = Environment.SystemDirectory;

            home_drive = home_drive.Substring(0, 2);
            string strExcelPath = home_drive + "\\Servosms_ExcelFile\\Export\\";

            Directory.CreateDirectory(strExcelPath);
            string        path     = home_drive + @"\Servosms_ExcelFile\Export\DistrictWiseChannelSalesReport.xls";
            StreamWriter  sw       = new StreamWriter(path);
            DBUtil        dbobj2   = new DBUtil(System.Configuration.ConfigurationSettings.AppSettings["Servosms"], true);
            SqlDataReader rdr1     = null;
            ArrayList     arrType  = new ArrayList();
            ArrayList     arrState = new ArrayList();

            double[] arrTotal = null;
            string   Header   = "";

            //dbobj2.SelectQuery("select distinct state from customer order by state",ref rdr1);
            if (radDetails.Checked)
            {
                dbobj2.SelectQuery("(select distinct case when substring(cust_type,1,2)='Ro' then 'RO' when substring(cust_type,1,2)='Oe' then 'OE' else substring(cust_type,1,2) end from customer where (substring(cust_type,1,2)='Ro' or substring(cust_type,1,2)='oe') group by substring(cust_type,1,2)) union (select customertypename from customertype where (substring(customertypename,1,2)!='Ro' and substring(customertypename,1,2)!='oe') group by customertypename)", ref rdr1);
            }
            else
            {
                dbobj2.SelectQuery("(select distinct case when substring(cust_type,1,2)='Ro' then 'RO' when substring(cust_type,1,2)='Oe' then 'OE' when substring(cust_type,1,2)='Ks' then 'KSK' when substring(cust_type,1,2)='N-' then 'N-KSK' else substring(cust_type,1,2) end from customer where (substring(cust_type,1,2)='Ro' or substring(cust_type,1,2)='oe' or substring(cust_type,1,2)='Ks' or substring(cust_type,1,2)='n-') group by substring(cust_type,1,2)) union (select customertypename from customertype where (substring(customertypename,1,2)!='Ro' and substring(customertypename,1,2)!='oe' and substring(customertypename,1,2)!='ks' and substring(customertypename,1,2)!='N-') group by customertypename)", ref rdr1);
            }
            if (rdr1.HasRows)
            {
                Header = "Distict / Type";
                while (rdr1.Read())
                {
                    arrType.Add(rdr1.GetValue(0).ToString());
                    Header += "\t" + rdr1.GetValue(0).ToString();
                }
                Header += "\tTotal Sales\tMonthly Avr.";
            }
            rdr1.Close();
            sw.WriteLine("From Date\t" + txtDateFrom.Text + "\tTo Date\t" + txtDateTo.Text);
            //*********************************
            sw.WriteLine(Header);
            arrTotal = new double[arrType.Count];
            double Total = 0, GTotal = 0, GAvrTotal = 0;

            //dbobj2.SelectQuery("(select distinct case when substring(cust_type,1,2)='Ro' then 'RO' when substring(cust_type,1,2)='Oe' then 'OE' else substring(cust_type,1,2) end from customer where (substring(cust_type,1,2)='Ro' or substring(cust_type,1,2)='oe') group by substring(cust_type,1,2)) union (select cust_type from customer where (substring(cust_type,1,2)!='Ro' and substring(cust_type,1,2)!='oe') group by cust_type)",ref rdr1);
            dbobj2.SelectQuery("select distinct state from customer order by state", ref rdr1);
            while (rdr1.Read())
            {
                arrState.Add(rdr1.GetValue(0).ToString());
            }
            rdr1.Close();
            for (int i = 0; i < arrState.Count; i++)
            {
                Total = 0;
                sw.Write(arrState[i].ToString());
                for (int j = 0; j < arrType.Count; j++)
                {
                    //dbobj2.SelectQuery("select case when sum(net_amount) is null then '0' else sum(net_amount) end from sales_master sm,customer c where sm.cust_id=c.cust_id and c.state='"+arrState[i].ToString()+"' and cust_type like'"+arrType[j].ToString()+"%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
                    //dbobj2.SelectQuery("select case when sum(qty) is null then '0' else sum(qty) end from sales_master sm,customer c,sales_details sd where sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='"+arrState[i].ToString()+"' and cust_type like'"+arrType[j].ToString()+"%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)",ref rdr1);
                    if (radDetails.Checked)
                    {
                        if (arrType[j].ToString().ToLower() == "ksk")
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type ='" + arrType[j].ToString() + "' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                        else
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                    }
                    else
                    {
                        if (arrType[j].ToString().ToLower() == "ksk")
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                        else if (arrType[j].ToString().ToLower() == "n-ksk")
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                        else
                        {
                            dbobj2.SelectQuery("select case when sum(Total_Qty*Qty) is null then '0' else sum(Total_Qty*Qty) end from sales_master sm,customer c,sales_details sd,Products p where p.Prod_ID=sd.Prod_ID and sm.cust_id=c.cust_id and sd.invoice_no=sm.invoice_no and c.state='" + arrState[i].ToString() + "' and cust_type like'" + arrType[j].ToString() + "%' and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(cast(invoice_date as datetime) as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()) + "',103)", ref rdr1);
                        }
                    }
                    if (rdr1.Read())
                    {
                        arrTotal[j] += double.Parse(rdr1.GetValue(0).ToString());
                        sw.Write("\t" + rdr1.GetValue(0).ToString());
                        Total += double.Parse(rdr1.GetValue(0).ToString());
                    }
                }
                sw.Write("\t" + Total.ToString());
                string GAvr = System.Convert.ToString(Total / double.Parse(Count.ToString()));
                sw.Write("\t" + GenUtil.strNumericFormat(GAvr.ToString()));
                GTotal    += Total;
                GAvrTotal += double.Parse(GAvr);
                sw.WriteLine();
            }
            string str = "Total";

            sw.Write(str);
            for (int n = 0; n < arrTotal.Length; n++)
            {
                sw.Write("\t" + arrTotal[n].ToString());
            }
            sw.Write("\t" + GTotal.ToString());
            sw.Write("\t" + GenUtil.strNumericFormat(GAvrTotal.ToString()));
            sw.Close();
        }
        public IHttpActionResult CustomerInsertUpdate(VoucherModel Voucher)
        {
            SqlDataReader  rdr  = null;
            InventoryClass obj  = new InventoryClass();
            SqlConnection  Con  = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Servosms"]);
            object         obj1 = null;

            dbobj.ExecProc(DbOperations_LATEST.OprType.Insert, "UpdateAccountsLedgerForCustomer", ref obj1, "@Ledger_ID", Voucher.LedgerID, "@Invoice_Date", System.Convert.ToDateTime(GenUtil.str2DDMMYYYY(Voucher.InvoiceDate)));
            dbobj.SelectQuery("select cust_id from customer,ledger_master where ledger_name=cust_name and ledger_id='" + Voucher.LedgerID + "'", ref rdr);
            if (rdr.Read())
            {
                dbobj.ExecProc(DbOperations_LATEST.OprType.Insert, "UpdateCustomerLedgerForCustomer", ref obj1, "@Cust_ID", rdr["Cust_ID"].ToString(), "@Invoice_Date", System.Convert.ToDateTime(GenUtil.str2DDMMYYYY(Voucher.InvoiceDate)));
            }
            rdr.Close();
            return(Created(new Uri(Request.RequestUri + ""), "CustomerInsertUpdate"));
        }
Exemple #19
0
		/// <summary>
		/// this is used to Update the scheme on behalf of the selected scheme in dropdown.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void btnupdate_Click(object sender, System.EventArgs e)
		{
			try
			{
				InventoryClass obj =new InventoryClass();
				SqlDataReader SqlDtr=null;
				//obj.schtype=DropSchType.SelectedItem.Text.ToString();
				obj.schtype="Secondry Claim";
				string scheme=dropschid.SelectedItem.Text.Trim().ToString();
				string[] schid=scheme.Split(new char[]{':'},scheme.Length);  
				obj.schid=schid[0];
				if(txtschname.Text.Equals(""))
					obj.schname="";
				else
					obj.schname=txtschname.Text.ToString();
				if(txtSchDiscount.Text.Equals(""))
					obj.discount="";
				else
					obj.discount=txtSchDiscount.Text.ToString();
				obj.discounttype=DropSchDiscount.SelectedItem.Text;
                obj.dateto = System.Convert.ToDateTime(GenUtil.str2DDMMYYYY(Request.Form["txtDateTo"].ToString()));
                obj.datefrom = System.Convert.ToDateTime(GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()));
                if (ListEmpAssigned.Items.Count!=0)
				{
					for(int i=0;i<ListEmpAssigned.Items.Count;++i)
					{
						ListEmpAssigned.SelectedIndex =i;
						string pname = ListEmpAssigned.SelectedItem.Value; 
						string[] arr1=pname.Split(new char[]{':'},pname.Length);
						InventoryClass obj1 = new InventoryClass();
						SqlDataReader rdr,rdr1=null;
						//string sname=DropSchType.SelectedItem.Text;
						string schname="";
						string sql1="select Prod_ID from Products where Prod_Name='"+arr1[0]+"' and Pack_Type='"+arr1[1]+"'";
						rdr = obj1.GetRecordSet (sql1);
						if(rdr.Read ())
						{
							//sql1="select * from StktSchDiscount where Prodid='"+rdr["Prod_ID"].ToString()+"' and sch_id='"+schid[0]+"'";
							sql1="select * from Prod_Promo_Grade_Entry where Prodid='"+rdr["Prod_ID"].ToString()+"' and PPGE_id='"+schid[0]+"'";
							dbobj.SelectQuery(sql1,ref rdr1);
							if(rdr1.Read())
							{
							}
							else
							{
								/*if(sname.IndexOf("Free")>0)
									schname="Free Scheme";
								else if(sname.IndexOf("LTR&%")>0)
									schname="LTR&% Scheme";
								else if(sname.IndexOf("LTRSP")>0)
									schname="LTRSP Scheme";
								else
									schname="LTR Scheme";*/
									schname="Secondry Claim";
								//sql1="select * from StktSchDiscount where Prodid='"+rdr["Prod_ID"].ToString()+"'and SchType like '%"+schname+"%' and (cast(floor(cast(datefrom as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and cast(floor(cast(dateto as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(datefrom as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(dateto as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"')";
								sql1="select * from Prod_Promo_Grade_Entry where Prodid='"+rdr["Prod_ID"].ToString()+"'and SchType like '%"+schname+"%' and (cast(floor(cast(datefrom as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and cast(floor(cast(dateto as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(datefrom as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"' or cast(floor(cast(dateto as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateFrom"].ToString()) +"' and '"+GenUtil.str2MMDDYYYY(Request.Form["txtDateTo"].ToString()) +"')";
								dbobj.SelectQuery(sql1,ref SqlDtr);
								if(SqlDtr.Read())
								{
									MessageBox.Show("'"+pname+"'"+" Allready Exist");
									return;
								}
							}
						}
						rdr.Close();
					}
				}
				else
				{
					MessageBox.Show("Please Select At Least One Product");
					return;
				}
				SqlConnection SqlCon =new SqlConnection(System .Configuration.ConfigurationSettings.AppSettings["Servosms"]);
				SqlCon.Open();
				SqlCommand cmd;
				//cmd=new SqlCommand("delete from StktschDiscount where sch_id='"+schid[0]+"'",SqlCon);
				cmd=new SqlCommand("delete from Prod_Promo_Grade_Entry where PPGE_id='"+schid[0]+"'",SqlCon);
				cmd.ExecuteNonQuery();
				SqlCon.Close();
				cmd.Dispose();
				for(int i=0;i<ListEmpAssigned.Items.Count;++i)
				{
					ListEmpAssigned.SelectedIndex =i;
					string pname = ListEmpAssigned.SelectedItem.Value; 
					string[] arr1=pname.Split(new char[]{':'},pname.Length);  
					string sql1="select Prod_ID from Products where Prod_Name='"+arr1[0]+"' and Pack_Type='"+arr1[1]+"'";
					dbobj.SelectQuery(sql1,ref SqlDtr);
					while(SqlDtr.Read ())
					{
						obj.prodid=SqlDtr.GetValue(0).ToString();
						//obj.InsertStockiestSchemediscount();
						obj.InsertPPGE();
					}
				}
				MessageBox.Show("Stockiest Discount Updated"); 
				Clear();
				FillList();
				GetNextschemeID();
				dropschid.Visible=false;
				btnupdate.Visible=false;
				lblschid.Visible=true;
				btnSubmit.Visible=true;
				btnSubmit.Enabled=true;
				btschid.Visible=true;
				CreateLogFiles.ErrorLog("Form:Prod_Promo_Dis_Entry.aspx,Method:btnupdate_Click  Stockiest Discount Entry Updated, User "+uid);
			}
			catch(Exception ex)
			{
				CreateLogFiles.ErrorLog("Form:Schemediscount.aspx,Method:btnupdate_Click   EXCEPTION "+ ex.Message  + "  User  "+uid);	
			}
		}
        /// <summary>
        /// This method is used to bind the datagrid and display the information by given order and display
        /// the data grid.
        /// </summary>
        public void BindTheData()
        {
            SqlConnection  SqlCon = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Servosms"]);
            string         sqlstr = "select lr.Emp_ID,e.Emp_Name,lr.Date_From,lr.Date_To,lr.Reason,lr.isSanction from Employee e,Leave_Register lr where e.Emp_ID=lr.Emp_ID and cast(floor(cast(lr.Date_From as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(lr.Date_To as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["Textbox1"].ToString()) + "',103)";
            DataSet        ds     = new DataSet();
            SqlDataAdapter da     = new SqlDataAdapter(sqlstr, SqlCon);

            da.Fill(ds, "Leave_Register");
            DataTable dtCustomers = ds.Tables["Leave_Register"];
            DataView  dv          = new DataView(dtCustomers);

            dv.Sort             = strOrderBy;
            Cache["strOrderBy"] = strOrderBy;
            if (dv.Count == 0)
            {
                MessageBox.Show("Data not available");
                GridReport.Visible = false;
            }
            else
            {
                GridReport.DataSource = dv;
                GridReport.DataBind();
                GridReport.Visible = true;
            }
        }
Exemple #21
0
		/// <summary>
		/// this is used to fill all the data on the behalf of selected Id in the dropdown.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void dropschid_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			SqlConnection con;
			SqlCommand cmd;
			InventoryClass obj=new InventoryClass ();
			SqlDataReader rdr1=null;
			try
			{
				if(dropschid.SelectedIndex!=0)
				{
					con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Servosms"]);
					con.Open ();
					SqlDataReader SqlDtr; 
					string scheme=dropschid.SelectedItem.Text.Trim().ToString();
					string[] schid=scheme.Split(new char[]{':'},scheme.Length);  
					//cmd=new SqlCommand("select * from StktSchDiscount WHERE sch_id='"+schid[0]+"'",con);
					cmd=new SqlCommand("select * from Prod_promo_grade_entry WHERE PPGE_id='"+schid[0]+"'",con);
					SqlDtr=cmd.ExecuteReader();
					ListEmpAssigned.Items.Clear();
					if(SqlDtr.HasRows )
					{
						while(SqlDtr.Read ())
						{
							//DropSchType.SelectedIndex=(DropSchType.Items.IndexOf((DropSchType.Items.FindByValue(SqlDtr.GetValue(1).ToString()))));
							if(SqlDtr.GetValue(3).Equals("")||SqlDtr.GetValue(1).Equals("NULL"))
								txtschname.Text="";
							else
								txtschname.Text=SqlDtr.GetValue(3).ToString();
							txtSchDiscount.Text=SqlDtr.GetValue(4).ToString();
							DropSchDiscount.SelectedIndex=(DropSchDiscount.Items.IndexOf((DropSchDiscount.Items.FindByValue(SqlDtr.GetValue(5).ToString()))));
							txtDateFrom.Text=GenUtil.str2DDMMYYYY(GenUtil.trimDate(SqlDtr.GetValue(6).ToString()));
							txtDateTo.Text=GenUtil.str2DDMMYYYY(GenUtil.trimDate(SqlDtr.GetValue(7).ToString()));
							dbobj.SelectQuery("select prod_name+':'+pack_type from products where prod_ID="+SqlDtr.GetValue(2).ToString()+" ", ref rdr1);
							if(rdr1.Read())
							{
								ListEmpAssigned.Items.Add(rdr1.GetValue(0).ToString());
							}
						}
					}
					dropschid.Visible=true;
					btschid.Visible=false;
					SqlDtr.Close (); 
					con.Close();
				}
				else
				{
					//DropSchType.SelectedIndex=0;
					txtschname.Text="";
					txtSchDiscount.Text="";
					DropSchDiscount.SelectedIndex=0;
					txtDateFrom.Text=GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString());
					txtDateTo.Text=GenUtil.str2DDMMYYYY(System.DateTime.Now.ToShortDateString());
					ListEmpAssigned.Items.Clear();
				}
				CreateLogFiles.ErrorLog("Form:Prod_Promo_Dis_Entry.aspx,Method:dropschid_SelectedIndexChange, Userid= "+uid);
			}
			catch(Exception ex)
			{
				CreateLogFiles.ErrorLog("Form:Prod_Promo_Dis_Entry.aspx,Method:dropschid_SelectedIndexChange"+"  EXCEPTION "+ ex.Message+"Userid= "+uid);
			}
		}
        /// <summary>
        /// This method is used to write into the report file to print.
        /// </summary>
        public void makingReport()
        {
            System.Data.SqlClient.SqlDataReader rdr = null;
            string home_drive = Environment.SystemDirectory;

            home_drive = home_drive.Substring(0, 2);
            string       path = home_drive + @"\Inetpub\wwwroot\Servosms\Sysitem\ServosmsPrintServices\ReportView\LeaveReport.txt";
            StreamWriter sw   = new StreamWriter(path);
            string       sql  = "";
            string       info = "";

            //string strDate = "";
            //sql="select lr.Emp_ID r1,e.Emp_Name r2,lr.Date_From r3,lr.Date_To r4,lr.Reason r5,lr.isSanction r6 from Employee e,Leave_Register lr where e.Emp_ID=lr.Emp_ID and cast(floor(cast(lr.Date_From as float)) as datetime)>='"+ ToMMddYYYY(txtDateFrom.Text)  +"' and cast(floor(cast(lr.Date_To as float)) as datetime)<='"+ ToMMddYYYY(Textbox1.Text) +"'";
            sql = "select lr.Emp_ID,e.Emp_Name,lr.Date_From,lr.Date_To,lr.Reason,lr.isSanction from Employee e,Leave_Register lr where e.Emp_ID=lr.Emp_ID and cast(floor(cast(lr.Date_From as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(lr.Date_To as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["Textbox1"].ToString()) + "',103)";
            sql = sql + " order by " + Cache["strOrderBy"];
            dbobj.SelectQuery(sql, ref rdr);
            // Condensed
            sw.Write((char)27);           //added by vishnu
            sw.Write((char)67);           //added by vishnu
            sw.Write((char)0);            //added by vishnu
            sw.Write((char)12);           //added by vishnu

            sw.Write((char)27);           //added by vishnu
            sw.Write((char)78);           //added by vishnu
            sw.Write((char)5);            //added by vishnu

            sw.Write((char)27);           //added by vishnu
            sw.Write((char)15);
            //**********
            string des     = "--------------------------------------------------------------------------------------";
            string Address = GenUtil.GetAddress();

            string[] addr = Address.Split(new char[] { ':' }, Address.Length);
            sw.WriteLine(GenUtil.GetCenterAddr(addr[0], des.Length).ToUpper());
            sw.WriteLine(GenUtil.GetCenterAddr(addr[1] + addr[2], des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("Tin No : " + addr[3], des.Length));
            sw.WriteLine(des);
            //******S***
            sw.WriteLine(GenUtil.GetCenterAddr("================", des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("LEAVE REPORT", des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("================", des.Length));
            sw.WriteLine("+-----------+--------------------+----------+----------+--------------------+--------+");
            sw.WriteLine("|Employee ID|    Employee Name   |From Date | To Date  |       Reason       |Approved|");
            sw.WriteLine("+-----------+--------------------+----------+----------+--------------------+--------+");
            //             12345678901 12345678901234567890 1234567890 1234567890 12345678901234567890 12345678
            if (rdr.HasRows)
            {
                info = " {0,-11:S} {1,-20:F} {2,-10:S} {3,-10:S} {4,-20:S}   {5,-6:S}";
                while (rdr.Read())
                {
                    sw.WriteLine(info, GenUtil.TrimLength(rdr["Emp_ID"].ToString(), 10),
                                 GenUtil.TrimLength(rdr["Emp_Name"].ToString(), 20),
                                 GenUtil.str2DDMMYYYY(GenUtil.trimDate(rdr["Date_From"].ToString())),
                                 GenUtil.str2DDMMYYYY(GenUtil.trimDate(rdr["Date_To"].ToString())),
                                 GenUtil.TrimLength(rdr["Reason"].ToString(), 20),
                                 Approved(rdr["isSanction"].ToString())
                                 );
                }
            }
            sw.WriteLine("+-----------+--------------------+----------+----------+--------------------+--------+");
            dbobj.Dispose();
            sw.Close();
        }
Exemple #23
0
 public void Resize()
 {
     GenUtil.Resize(map, leftReserve, upReserve, Parent, CurrentLevel.W, CurrentLevel.H, Gap, StoneDeltaTime);
 }
        /// <summary>
        /// This method is used to write into the excel report file to print.
        /// </summary>
        public void ConvertToExcel()
        {
            InventoryClass obj = new InventoryClass();
            SqlDataReader  rdr;
            string         home_drive = Environment.SystemDirectory;

            home_drive = home_drive.Substring(0, 2);
            string strExcelPath = home_drive + "\\Servosms_ExcelFile\\Export\\";

            Directory.CreateDirectory(strExcelPath);
            string       path = home_drive + @"\Servosms_ExcelFile\Export\LeaveReport.xls";
            StreamWriter sw   = new StreamWriter(path);
            string       sql  = "";

            sql = "select lr.Emp_ID,e.Emp_Name,lr.Date_From,lr.Date_To,lr.Reason,lr.isSanction from Employee e,Leave_Register lr where e.Emp_ID=lr.Emp_ID and cast(floor(cast(lr.Date_From as float)) as datetime)>=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["txtDateFrom"].ToString()) + "',103) and cast(floor(cast(lr.Date_To as float)) as datetime)<=Convert(datetime,'" + GenUtil.str2DDMMYYYY(Request.Form["Textbox1"].ToString()) + "',103)";
            sql = sql + " order by " + Cache["strOrderBy"];

            rdr = obj.GetRecordSet(sql);
            sw.WriteLine("Employee ID\tEmployee Name\tFrom Date\tTo Date\tReason\tApproved");
            while (rdr.Read())
            {
                sw.WriteLine(rdr["Emp_ID"].ToString() + "\t" +
                             rdr["Emp_Name"].ToString() + "\t" +
                             GenUtil.str2DDMMYYYY(GenUtil.trimDate(rdr["Date_From"].ToString())) + "\t" +
                             GenUtil.str2DDMMYYYY(GenUtil.trimDate(rdr["Date_To"].ToString())) + "\t" +
                             rdr["Reason"].ToString() + "\t" +
                             Approved(rdr["isSanction"].ToString())
                             );
            }
            sw.Close();
        }
Exemple #25
0
        /// <summary>
        /// This method is used for setting the Session variable for userId and
        /// after that filling the required dropdowns with database values
        /// and also check accessing priviledges for particular user
        /// and generate the next ID also.
        /// and also fatch the employee information according to select employee ID in comes from url.
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                uid = (Session["User_Name"].ToString());
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:Employee_Update.aspx,Method:page_load" + " EXCEPTION  " + ex.Message + uid);
                Response.Redirect("../../Sysitem/ErrorPage.aspx", false);
                return;
            }
            if (!Page.IsPostBack)
            {
                #region Check Privileges
                int    i;
                string View_flag = "0", Add_Flag = "0", Edit_Flag = "0", Del_Flag = "0";
                string Module    = "2";
                string SubModule = "2";
                string[,] Priv = (string[, ])Session["Privileges"];
                for (i = 0; i < Priv.GetLength(0); i++)
                {
                    if (Priv[i, 0] == Module && Priv[i, 1] == SubModule)
                    {
                        View_flag = Priv[i, 2];
                        Add_Flag  = Priv[i, 3];
                        Edit_Flag = Priv[i, 4];
                        Del_Flag  = Priv[i, 5];
                        break;
                    }
                }
                if (View_flag == "0")
                {
                    //	string msg="UnAthourized Visit to Enployee Entry Page";
                    //dbobj.LogActivity(msg,Session["User_Name"].ToString());
                    Response.Redirect("../../Sysitem/AccessDeny.aspx", false);
                    return;
                }
                //************
                if (Edit_Flag == "0")
                {
                    btnUpdate.Enabled = false;
                }
                //************
                #endregion
                try
                {
                    LblEmployeeID.Text = Request.QueryString.Get("ID");
                    MasterClass   obj1 = new MasterClass();
                    EmployeeClass obj  = new EmployeeClass();
                    SqlDataReader SqlDtr;
                    string        sql;
                    getbeat();
                    #region Fetch Extra Cities,Designation,country and State from Database and add to the ComboBox
                    sql    = "select distinct Country from Beat_Master";
                    SqlDtr = obj.GetRecordSet(sql);
                    while (SqlDtr.Read())
                    {
                        DropCountry.Items.Add(SqlDtr.GetValue(0).ToString());
                    }
                    SqlDtr.Close();
                    sql    = "select distinct City from Beat_Master order by city";
                    SqlDtr = obj.GetRecordSet(sql);
                    while (SqlDtr.Read())
                    {
                        DropCity.Items.Add(SqlDtr.GetValue(0).ToString());
                    }
                    SqlDtr.Close();


                    string sql1;
                    sql1   = "select  distinct State from Beat_Master";
                    SqlDtr = obj.GetRecordSet(sql1);
                    while (SqlDtr.Read())
                    {
                        DropState.Items.Add(SqlDtr.GetValue(0).ToString());
                    }
                    SqlDtr.Close();

                    DropVehicleNo.Items.Clear();
                    DropVehicleNo.Items.Add("Select");
                    SqlDtr = obj.GetRecordSet("Select vehicle_no from vehicleentry");
                    while (SqlDtr.Read())
                    {
                        DropVehicleNo.Items.Add(SqlDtr.GetValue(0).ToString());
                    }
                    SqlDtr.Close();

                    txtLicenseNo.Text           = "";
                    txtLicenseValidity.Text     = "";
                    txtLICNo.Text               = "";
                    txtLICvalidity.Text         = "";
                    DropVehicleNo.SelectedIndex = 0;

                    #endregion

                    SqlDtr = obj.EmployeeList(LblEmployeeID.Text.ToString(), "", "");
                    while (SqlDtr.Read())
                    {
                        lblName.Text            = SqlDtr.GetValue(1).ToString();
                        TempEmpName.Text        = SqlDtr.GetValue(1).ToString();
                        DropDesig.SelectedIndex = DropDesig.Items.IndexOf(DropDesig.Items.FindByValue(SqlDtr.GetValue(2).ToString()));
                        txtAddress.Text         = SqlDtr.GetValue(3).ToString();
                        DropCity.SelectedIndex  = DropCity.Items.IndexOf(DropCity.Items.FindByValue(SqlDtr.GetValue(4).ToString()));
                        DropState.SelectedIndex = DropState.Items.IndexOf(DropState.Items.FindByValue(SqlDtr.GetValue(5).ToString()));
                        // If the designation is driver then it shows the extra fields related to driver , else hide that fields.
                        if (SqlDtr.GetValue(2).ToString().Trim().Equals("Driver"))
                        {
                            lblDrLicense.Visible       = true;
                            lblLicenseVali.Visible     = true;
                            lblLICPolicy.Visible       = true;
                            lblLICValid.Visible        = true;
                            lblVehicleNo.Visible       = true;
                            txtLicenseNo.Visible       = true;
                            txtLicenseValidity.Visible = true;
                            txtLICNo.Visible           = true;
                            txtLICvalidity.Visible     = true;
                            DropVehicleNo.Visible      = true;
                        }
                        else
                        {
                            lblDrLicense.Visible       = false;
                            lblLicenseVali.Visible     = false;
                            lblLICPolicy.Visible       = false;
                            lblLICValid.Visible        = false;
                            lblVehicleNo.Visible       = false;
                            txtLicenseNo.Visible       = false;
                            txtLicenseValidity.Visible = false;
                            txtLICNo.Visible           = false;
                            txtLICvalidity.Visible     = false;
                            DropVehicleNo.Visible      = false;
                        }
                        DropCountry.SelectedIndex = DropCountry.Items.IndexOf(DropCountry.Items.FindByValue(SqlDtr.GetValue(6).ToString()));
                        txtContactNo.Text         = SqlDtr.GetValue(7).ToString();
                        if (txtContactNo.Text == "0")
                        {
                            txtContactNo.Text = "";
                        }
                        txtMobile.Text = SqlDtr.GetValue(8).ToString();
                        if (txtMobile.Text == "0")
                        {
                            txtMobile.Text = "";
                        }
                        txtEMail.Text           = SqlDtr.GetValue(9).ToString();
                        txtSalary.Text          = SqlDtr.GetValue(10).ToString();
                        txtOT_Comp.Text         = SqlDtr.GetValue(11).ToString();
                        txtLicenseNo.Text       = SqlDtr.GetValue(12).ToString();
                        txtLicenseValidity.Text = GenUtil.str2DDMMYYYY(trimDate(SqlDtr.GetValue(13).ToString()));
                        txtLICNo.Text           = SqlDtr.GetValue(14).ToString();
                        txtLICvalidity.Text     = GenUtil.str2DDMMYYYY(trimDate(SqlDtr.GetValue(15).ToString()));
                        //Response.Write(SqlDtr.GetValue(16).ToString());
                        SqlDataReader rdr = null;
                        dbobj.SelectQuery("Select vehicle_no from vehicleentry where vehicledetail_id = " + SqlDtr.GetValue(16).ToString(), ref rdr);
                        if (rdr.Read())
                        {
                            //Response.Write(rdr.GetValue(0).ToString ());
                            DropVehicleNo.SelectedIndex = DropVehicleNo.Items.IndexOf(DropVehicleNo.Items.FindByValue(rdr.GetValue(0).ToString().Trim()));
                        }
                        rdr.Close();
                        rdr = null;
                        dbobj.SelectQuery("Select Op_Balance,Bal_Type from Ledger_Master where Ledger_Name = '" + SqlDtr.GetValue(1).ToString() + "'", ref rdr);
                        if (rdr.Read())
                        {
                            txtopbal.Text          = rdr.GetValue(0).ToString();
                            DropType.SelectedIndex = DropVehicleNo.Items.IndexOf(DropVehicleNo.Items.FindByValue(rdr.GetValue(1).ToString().Trim()));
                        }
                        rdr.Close();

                        /********Add by vikas 27.10.2012*********************/
                        if (SqlDtr["Status"].ToString().Trim() != null && SqlDtr["Status"].ToString().Trim() != "")
                        {
                            if (SqlDtr["Status"].ToString().Trim() == "1")
                            {
                                RbtnActive.Checked = true;
                            }
                            else
                            {
                                RbtnNone.Checked = true;
                            }
                        }
                        else
                        {
                            RbtnActive.Checked = false;
                            RbtnNone.Checked   = false;
                        }
                        /********End*********************/
                    }
                    SqlDtr.Close();
                }
                catch (Exception ex)
                {
                    CreateLogFiles.ErrorLog("Form:Employee_Update.aspx,Method:Page_Load() " + "EmployeeID.   EXCEPTION" + ex.Message + " userid  " + uid);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// This method is used to write into the report file to print.
        /// </summary>
        public void makingReport()
        {
            System.Data.SqlClient.SqlDataReader rdr = null;
            string home_drive = Environment.SystemDirectory;

            home_drive = home_drive.Substring(0, 2);
            string       path = home_drive + @"\Inetpub\wwwroot\Servosms\Sysitem\ServosmsPrintServices\ReportView\LY_PS_SalesReport.txt";
            StreamWriter sw   = new StreamWriter(path);
            string       sql  = "";
            string       info = "";

            //string strDate = "";
            //sql="select lr.Emp_ID r1,e.Emp_Name r2,lr.Date_From r3,lr.Date_To r4,lr.Reason r5,lr.isSanction r6 from Employee e,Leave_Register lr where e.Emp_ID=lr.Emp_ID and cast(floor(cast(lr.Date_From as float)) as datetime)>='"+ ToMMddYYYY(txtDateFrom.Text)  +"' and cast(floor(cast(lr.Date_To as float)) as datetime)<='"+ ToMMddYYYY(Textbox1.Text) +"'";
            sql = "select * from LY_PS_SALES";
            //sql=sql+" order by "+Cache["strOrderBy"];
            dbobj.SelectQuery(sql, ref rdr);
            // Condensed
            sw.Write((char)27);           //added by vishnu
            sw.Write((char)67);           //added by vishnu
            sw.Write((char)0);            //added by vishnu
            sw.Write((char)12);           //added by vishnu

            sw.Write((char)27);           //added by vishnu
            sw.Write((char)78);           //added by vishnu
            sw.Write((char)5);            //added by vishnu

            sw.Write((char)27);           //added by vishnu
            sw.Write((char)15);
            //**********
            string des     = "----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------";
            string Address = GenUtil.GetAddress();

            string[] addr = Address.Split(new char[] { ':' }, Address.Length);
            sw.WriteLine(GenUtil.GetCenterAddr(addr[0], des.Length).ToUpper());
            sw.WriteLine(GenUtil.GetCenterAddr(addr[1] + addr[2], des.Length));
            sw.WriteLine(GenUtil.GetCenterAddr("Tin No : " + addr[3], des.Length));
            sw.WriteLine(des);
            //**********

            /*
             * sw.WriteLine(GenUtil.GetCenterAddr("====================",des.Length));
             * sw.WriteLine(GenUtil.GetCenterAddr("LY_PS_Sales REPORT",des.Length));
             * sw.WriteLine(GenUtil.GetCenterAddr("====================",des.Length));
             *
             * sw.WriteLine("+------+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+");
             * sw.WriteLine("|Month |         Primary Sales         |                                                          Secondary Sales                                                                      |");
             * sw.WriteLine("+------+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+");
             * sw.WriteLine("|      | Total |  Pur  |  Gen  |Greases|      RO1      |      RO2      |      RO3      |      RO4      |      RO5      |  IBP  |Bazzar |  OE   | Fleet |Maruti |Eicher |Hyundai| Total |");
             * sw.WriteLine("|      |  Pur  |  FOC  |  Oils |       | Lube  | 2T/4T | Lube  | 2T/4T | Lube  | 2T/4T | Lube  | 2T/4T | Lube  | 2T/4T |       |       |       |       |       |       |       | Sales |");
             * sw.WriteLine("+------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+");
             * //             123456 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567
             */
            if (rdr.HasRows)
            {
                sw.WriteLine(GenUtil.GetCenterAddr("====================", des.Length));
                sw.WriteLine(GenUtil.GetCenterAddr("LY_PS_Sales REPORT", des.Length));
                sw.WriteLine(GenUtil.GetCenterAddr("====================", des.Length));

                sw.WriteLine("+------+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+");
                sw.WriteLine("|Month |         Primary Sales         |                                                          Secondary Sales                                                                      |");
                sw.WriteLine("+------+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+");
                sw.WriteLine("|      | Total |  Pur  |  Gen  |Greases|      RO1      |      RO2      |      RO3      |      RO4      |      RO5      |  IBP  |Bazzar |  OE   | Fleet |Maruti |Eicher |Hyundai| Total |");
                sw.WriteLine("|      |  Pur  |  FOC  |  Oils |       | Lube  | 2T/4T | Lube  | 2T/4T | Lube  | 2T/4T | Lube  | 2T/4T | Lube  | 2T/4T |       |       |       |       |       |       |       | Sales |");
                sw.WriteLine("+------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+");
                //             123456 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567 1234567
                int i = 0;
                info = " {0,-6:S} {1,7:F} {2,7:S} {3,7:S} {4,7:S} {5,7:S} {6,7:S} {7,7:S} {8,7:S} {9,7:S} {10,7:S} {11,7:S} {12,7:S} {13,7:S} {14,7:S} {15,7:S} {16,7:S} {17,7:S} {18,7:S} {19,7:S} {20,7:S} {21,7:S} {22,7:S}";
                while (rdr.Read())
                {
                    if (i < 12)
                    {
                        sw.WriteLine(info, rdr.GetValue(1).ToString(),
                                     rdr.GetValue(2).ToString(),
                                     rdr.GetValue(3).ToString(),
                                     rdr.GetValue(4).ToString(),
                                     rdr.GetValue(5).ToString(),
                                     rdr.GetValue(6).ToString(),
                                     rdr.GetValue(7).ToString(),
                                     rdr.GetValue(8).ToString(),
                                     rdr.GetValue(9).ToString(),
                                     rdr.GetValue(10).ToString(),
                                     rdr.GetValue(11).ToString(),
                                     rdr.GetValue(12).ToString(),
                                     rdr.GetValue(13).ToString(),
                                     rdr.GetValue(14).ToString(),
                                     rdr.GetValue(15).ToString(),
                                     rdr.GetValue(16).ToString(),
                                     rdr.GetValue(17).ToString(),
                                     rdr.GetValue(18).ToString(),
                                     rdr.GetValue(19).ToString(),
                                     rdr.GetValue(20).ToString(),
                                     rdr.GetValue(21).ToString(),
                                     rdr.GetValue(22).ToString(),
                                     rdr.GetValue(23).ToString()
                                     );
                    }
                    else
                    {
                        sw.WriteLine("+------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+");

                        sw.WriteLine(info, rdr.GetValue(1).ToString(),
                                     rdr.GetValue(2).ToString(),
                                     rdr.GetValue(3).ToString(),
                                     rdr.GetValue(4).ToString(),
                                     rdr.GetValue(5).ToString(),
                                     rdr.GetValue(6).ToString(),
                                     rdr.GetValue(7).ToString(),
                                     rdr.GetValue(8).ToString(),
                                     rdr.GetValue(9).ToString(),
                                     rdr.GetValue(10).ToString(),
                                     rdr.GetValue(11).ToString(),
                                     rdr.GetValue(12).ToString(),
                                     rdr.GetValue(13).ToString(),
                                     rdr.GetValue(14).ToString(),
                                     rdr.GetValue(15).ToString(),
                                     rdr.GetValue(16).ToString(),
                                     rdr.GetValue(17).ToString(),
                                     rdr.GetValue(18).ToString(),
                                     rdr.GetValue(19).ToString(),
                                     rdr.GetValue(20).ToString(),
                                     rdr.GetValue(21).ToString(),
                                     rdr.GetValue(22).ToString(),
                                     rdr.GetValue(23).ToString()
                                     );
                        sw.WriteLine("+------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+");
                    }
                    i++;
                }
            }
            else
            {
                MessageBox.Show("Data Not Available");
                return;
            }
            //sw.WriteLine("+------+-------+-------+-------+-------+----------+----------+----------+----------+----------+-----+-----+-----+-----+-----+-----+-----+");
            dbobj.Dispose();
            sw.Close();
        }
        public ActionResult Register(RegisterViewModel model)
        {
            SessionManager.RegisterSessionActivity();

            // Get all states again
            var roles = GetAllRoles();

            // Set these states on the model. We need to do this because
            // only the selected value from the DropDownList is posted back, not the whole
            // list of states.
            model.Roles = GenUtil.GetSelectListItems(roles);

            // In case everything is fine - i.e. both "Name" and "State" are entered/selected,
            // redirect user to the "Done" page, and pass the user object along via Session
            if (ModelState.IsValid)
            {
                SHA1HashProvider sHA1HashProvider = new SHA1HashProvider();
                if (!ceUserManager.IsRegistered(model.Email))
                {
                    string sha1HashText = sHA1HashProvider.SecureSHA1(model.Password.Trim());
                    int?   newUserID    = ceUserManager.RegisterNew(model.Email, sha1HashText, model.Role);
                    if (newUserID.HasValue)
                    {
                        UserDTO userDTO = new UserDTO()
                        {
                            Id         = DataSecurityTripleDES.GetEncryptedText(newUserID),
                            FirstName  = model.FirstName,
                            Surname    = model.Surname,
                            UserStatus = (int?)UserStatusEnum.Active
                        };

                        ceUserManager.SaveUserDetail(userDTO);

                        StringBuilder sbSubject   = new StringBuilder("Craveats new registrant notification"),
                                      sbEmailBody = new StringBuilder("<p>A new user with the following detail has been registered in the system. " +
                                                                      $"<br/><em>FirstName            </em>: {model.FirstName}" +
                                                                      $"<br/><em>Surname              </em>: {model.Surname}" +
                                                                      $"<br/><em>Email                </em>: {model.Email}" +
                                                                      $"<br/><em>Registration Type    </em>: {model.Role}" +
                                                                      "</p><p>Thank you.</p><p>Craveats</p>");

                        CommunicationServiceProvider.SendOutgoingNotification(
                            new MailAddress(
                                model.Email,
                                string.Format("{0}{1}{2}", model.FirstName, " ", model?.Surname).Trim()),
                            sbSubject.ToString(),
                            sbEmailBody.ToString());

                        User result = ceUserManager.FindByCriteria(email: model.Email, userStatusEnums: new List <int> {
                            (int)UserStatusEnum.Active, (int)UserStatusEnum.Blocked
                        });
                        if (result != null)
                        {
                            userDTO = EntityDTOHelper.GetEntityDTO <User, UserDTO>(result);

                            AuthenticatedUserInfo authenticatedUserInfo = new AuthenticatedUserInfo(userDTO);
                            Session["loggeduser"] = authenticatedUserInfo;

                            SessionManager.RegisterSessionActivity(userID: result.Id, loggedInAt: DateTime.Now);

                            ceUserManager.SignInUser(HttpContext, string.Format("{0}", authenticatedUserInfo.FullName), false);

                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "An error occurred in reading user data. Please review input and re-try.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "An error occurred in registering new user. Please review input and re-try.");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Email is registered and cannot be used to create another account.");
                }
            }

            // Something is not right - so render the registration page again,
            // keeping the data user has entered by supplying the model.
            return(View("Register", model));
        }
Exemple #28
0
    public static IEnumerator GetSimpleTemple()
    {
        GenData temple = new GenData(Random.Range(TempleWidth.start, TempleWidth.end), Random.Range(TempleHeight.start, TempleHeight.end));

        List <GenRoom> AutoFillRoom = new List <GenRoom>();

        // list of all rooms that are not allowed to be used for door placement
        List <GenRoom> NoAutoDoor  = new List <GenRoom>();
        List <GenRoom> SecretRooms = new List <GenRoom>();

        GenTile Chest = GenTile.GetEmpty();

        Chest.Details.Add(new GenDetail()
        {
            Char = '=', Type = GenDetail.DetailType.Entity, Entity = GenDetail.EntityType.Chest
        });

        GenTile pillar = GenTile.GetEmpty();

        //pillar.Details.Add(new GenDetail() { Char = '\u01C1', Type = GenDetail.DetailType.Decoration });
        pillar.Details.Add(new GenDetail()
        {
            Char = 'O', Type = GenDetail.DetailType.Decoration
        });

        GenTile[,] pillars = new GenTile[, ]
        {
            { GenTile.Copy(pillar), GenTile.Copy(pillar) },
            { GenTile.Copy(pillar), GenTile.Copy(pillar) }
        };

        GenTile Door = GenTile.GetEmpty();

        Door.Details.Add(new GenDetail()
        {
            Char = '+', Type = GenDetail.DetailType.Door, Entity = GenDetail.EntityType.Door
        });


        GenRoom outer = GenRoom.Sized(temple.Width, temple.Height);

        outer.FillFloor('+');
        outer.SpacePriority = -2;
        temple.PlaceRoom(0, 0, outer);
        temple.EdgeWalls('#', outer);


        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------


        int w = Random.Range(9, 12);
        int h = Random.Range(10, 16);

        // EntryHall
        temple.TryGrowRect(1, outer.Outer.GetCenter().y, w, h, out GenRect EntrySize, false);
        GenRoom EntryHall = GenRoom.At(EntrySize.MinX, EntrySize.MinY, EntrySize.WidthT, EntrySize.HeightT);

        EntryHall.FillFloor('.');
        temple.PlaceRoom(EntrySize.MinX, EntrySize.MinY, EntryHall);
        temple.EdgeWalls('#');
        EntryHall.GetAtWorldspaceG(
            EntrySize.MinX + 1, EntrySize.GetCenter().y)
        .Details
        .Add(new GenDetail()
        {
            Char = '>', Type = GenDetail.DetailType.Entity, Entity = GenDetail.EntityType.StairsDown
        });


        int posX = EntrySize.MinX + 2;
        int posy = EntrySize.MinY + 2;

        GenTile[,] sym = GenUtil.GetSymetry(pillars.GetCopy(), ref posX, ref posy, EntryHall, GenUtil.Axis.Horizontal | GenUtil.Axis.Vertical);

        EntryHall.PlaceDetailsAt(posX, posy, sym);
        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // hall to big thing
        int whall = Random.Range(10, 25);
        int hhall = Random.Range(5, 7);
        int space = Random.Range(2, 4);

        temple.TryGrowRect(EntrySize.MaxX + 1, EntrySize.GetCenter().y, whall, hhall, out GenRect HallSize);
        GenRoom PillarHall = GenRoom.Sized(HallSize.WidthT, HallSize.HeightT);

        PillarHall.FillFloor('.');
        PillarHall.SpacePriority = 3;
        temple.PlaceRoom(HallSize.MinX, HallSize.MinY, PillarHall);
        temple.EdgeWalls('#', PillarHall);

        NoAutoDoor.Add(PillarHall);

        // place doors to the entry
        if (hhall == 5)
        {
            // a single door in the middle
            PillarHall.AddDetails(HallSize.MinX, HallSize.MinY + 2, GenTile.Copy(Door));
            PillarHall.AddDetails(HallSize.MaxX, HallSize.MinY + 2, GenTile.Copy(Door));
        }
        else
        {
            // place symetric doors
            PillarHall.AddDetails(HallSize.MinX, HallSize.MinY + 2, GenTile.Copy(Door));
            PillarHall.AddDetails(HallSize.MinX, HallSize.MinY + 3, GenTile.Copy(Door));

            PillarHall.AddDetails(HallSize.MaxX, HallSize.MinY + 2, GenTile.Copy(Door));
            PillarHall.AddDetails(HallSize.MaxX, HallSize.MinY + 3, GenTile.Copy(Door));
        }

        int currBar = HallSize.MinX + space;

        GenTile[,] singlePillar = new GenTile[, ] {
            { GenTile.Copy(pillar) }
        };
        while (temple.IsInsideRoom(currBar, HallSize.MinY + 1, PillarHall))
        {
            int fx = currBar;
            int fy = HallSize.MinY + 1;
            GenTile[,] feature = GenUtil.GetSymetry(singlePillar, ref fx, ref fy, PillarHall, GenUtil.Axis.Vertical);
            PillarHall.PlaceDetailsAt(fx, fy, feature);
            currBar += space;
        }
        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // holy water or something

        int waterHeight      = Random.Range(2, 4);
        int waterWidth       = Random.Range(2, 4);
        int waterPillarWidth = Random.Range(2, 3);

        int waterRoomHeight = waterHeight + 4 + waterPillarWidth * 2;
        int waterRoomWidth  = waterWidth + 6 + waterPillarWidth * 2;

        temple.TryGrowRect(HallSize.MaxX + 1, HallSize.GetCenter().y, waterRoomWidth, waterRoomHeight, out GenRect WaterSize, false, GenUtil.Direction4.Top);

        GenRoom waterRoom = GenRoom.Sized(WaterSize.WidthT, WaterSize.HeightT);

        waterRoom.FillFloor();
        waterRoom.SpacePriority = 2;
        temple.PlaceRoom(WaterSize.MinX, WaterSize.MinY, waterRoom);
        temple.EdgeWalls('#', waterRoom);


        int BackDoorWater = Random.Range(1, waterRoom.Height / 2);

        waterRoom.AddDetails(WaterSize.MaxX, WaterSize.MinY + BackDoorWater, GenTile.Copy(Door));
        waterRoom.AddDetails(WaterSize.MaxX, WaterSize.MaxY - BackDoorWater, GenTile.Copy(Door));


        GenTile waterSingle = GenTile.GetEmpty();

        waterSingle.Details.Add(new GenDetail()
        {
            Char = '~', Type = GenDetail.DetailType.Background
        });
        GenTile[,] water = GenUtil.Fill(waterWidth, waterHeight, waterSingle);

        waterRoom.PlaceDetailsAt(WaterSize.MinX + 3 + waterPillarWidth, WaterSize.MinY + 2 + waterPillarWidth, water);

        int waterPX = WaterSize.MinX + 3;
        int waterPY = WaterSize.MinY + 2;

        GenTile[,] waterPillarPlace = GenUtil.GetSymetry(pillars.GetCopy(), ref waterPX, ref waterPY, waterRoom, GenUtil.Axis.Horizontal | GenUtil.Axis.Vertical);
        waterRoom.PlaceDetailsAt(waterPX, waterPY, waterPillarPlace);


        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // pillar spam
        int spamWidth  = Random.Range(10, 20);
        int spamHeight = WaterSize.HeightT + Random.Range(8, 15);

        temple.TryGrowRect(WaterSize.MaxX + 1, WaterSize.GetCenter().y, spamWidth, spamHeight, out GenRect SpamSize, true, GenUtil.Direction4.Top);
        GenRoom Spam = GenRoom.Sized(SpamSize.WidthT, SpamSize.HeightT);

        Spam.FillFloor();
        Spam.SpacePriority = 1;
        temple.PlaceRoom(SpamSize.MinX, SpamSize.MinY, Spam);
        temple.EdgeWalls('#', Spam);

        int spamPX = SpamSize.MinX + 2;
        int spamPY = SpamSize.MinY + 2;

        for (int x = spamPX; temple.IsInsideRoom(x, spamPY, Spam); x += 2)
        {
            for (int y = spamPY; temple.IsInsideRoom(x, y, Spam); y += 2)
            {
                GenTile p = GenTile.Copy(pillar);
                Spam.AddDetails(x, y, p);
            }
        }
        Spam.AddDetail(
            SpamSize.MaxX - 1,
            SpamSize.GetCenter().y,
            new GenDetail()
        {
            Char = '<', Type = GenDetail.DetailType.Entity, Entity = GenDetail.EntityType.StairsUp
        });

        temple.FixOverlap();

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        //temple.Rooms.Remove(outer); // we dont have boundries
        for (int x = outer.Inner.MinX; x < outer.Outer.MaxX; x++)
        {
            for (int y = outer.Inner.MinY; y < outer.Outer.MaxY; y++)
            {
                outer.RemoveTileAtG(x, y);
            }
        }


        //GenRoom Mark = GenRoom.Sized(0, 0);
        //Mark.FillFloor('X');
        //Mark.SpacePriority = 100;


        // lets go ham with randomly sized rooms
        int spawnAttemptsRemaining = 1000;

        while (spawnAttemptsRemaining-- > 0)// lol the arrow
        {
            int rWidth  = Random.Range(RandomWidth.start, RandomWidth.end);
            int rHeight = Random.Range(RandomHeight.start, RandomHeight.end);

            int     rX        = Random.Range(2, temple.Width - 2);
            int     rY        = Random.Range(2, temple.Height - 2);
            GenRect rHopeSize = new GenRect(rX, rX + rWidth + 1, rY, rY + rWidth - 1);


            if (temple.IsInsideRoom(rX, rY) || temple.GetTile(rX, rY) != null)
            {
                continue;
            }

            temple.TryGrowRect(rX, rY, rWidth, rHeight, out GenRect rSize, true);

            GenRoom add = GenRoom.Sized(rSize.WidthT, rSize.HeightT);
            add.FillFloor();
            add.SpacePriority = 01;

            temple.PlaceRoom(rSize.MinX, rSize.MinY, add);

            AutoFillRoom.Add(add);

            temple.EdgeWalls('#', add);

            temple.FixOverlap();

            /*
             * if (rWidth * 2 < rHeight || rHeight * 2 < rWidth)
             * {
             *  if (Random.Range(0,10)>4)
             *  {
             *      // we are making a hallway
             *
             *      //TODO: hallway
             *
             *      temple.PlaceRoom(rX, rY, Mark);
             *      Log(temple);
             *      if (Logging!=null)
             *  {
             *      yield return new WaitForSeconds(0.25f);
             *  }
             *      temple.Rooms.Remove(Mark);
             *      continue;
             *  }
             * }
             */

            /*
             * int randomChance = Random.Range(0, 4);
             * switch (randomChance)
             * {
             *  case 0:
             *      // random pillars in the room
             *
             *      for (int i = 0; i < 7 + (rSize.WidthT + rSize.HeightT)/5; i++)
             *      {
             *          int px = Random.Range(rSize.MinX + 1, rSize.MaxX);
             *          int py = Random.Range(rSize.MinY + 1, rSize.MaxY);
             *          add.AddDetails(px, py, pillar);
             *      }
             *
             *      break;
             *  case 1:
             *      // random water
             *      for (int i = 0; i < 15 + (rSize.WidthT + rSize.HeightT)/3; i++)
             *      {
             *          int px = Random.Range(rSize.MinX + 1, rSize.MaxX);
             *          int py = Random.Range(rSize.MinY + 1, rSize.MaxY);
             *          GenDetail littleWater= new GenDetail() { Char = '~', Type = GenDetail.DetailType.Background};
             *          add.AddDetail(px, py, littleWater);
             *      }
             *      break;
             *  case 2:
             *      // random room inside if possible else empty
             *      if (rSize.WidthT>=7&& rSize.HeightT >= 7)
             *      {
             *          int insideX = rSize.GetCenter().x;
             *          int insideY = rSize.GetCenter().y;
             *
             *          temple.TryGrowRect(insideX, insideY, 100, 100, out GenRect insideSize, false);
             *          GenRoom inside = GenRoom.Sized(insideSize.WidthT, insideSize.HeightT);
             *          inside.FillFloor();
             *          inside.SpacePriority = 2;
             *          temple.PlaceRoom(insideSize.MinX, insideSize.MinY, inside);
             *          temple.EdgeWalls('#',inside);
             *          temple.FixOverlap();
             *
             *      }
             *      else
             *      {
             *          for (int i = 0; i < 7; i++)
             *          {
             *              int px = Random.Range(rSize.MinX + 1, rSize.MaxX);
             *              int py = Random.Range(rSize.MinY + 1, rSize.MaxY);
             *              add.AddDetails(px, py, pillar);
             *          }
             *      }
             *      break;
             *  default:
             *      break;
             * }
             *
             * Log(temple);
             * if (Logging!=null)
             *  {
             *      yield return new WaitForSeconds(0.25f);
             *  }
             */
        }

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // now fill the rooms with things

        var adjList = temple.GetAdjacentRoomMap();
        // remove any Room that is too small and have no connections

        List <GenRoom> tooSmall = new List <GenRoom>();

        foreach (var room in temple.Rooms)
        {
            if (room.Width >= 5 && room.Height == 3)
            {
                tooSmall.Add(room);
                continue;
            }
            if (room.Height >= 5 && room.Width == 3)
            {
                tooSmall.Add(room);
                continue;
            }
            if (room.Height <= 3 && room.Width <= 3)
            {
                tooSmall.Add(room);
                continue;
            }
            if (adjList[room].Count == 0)
            {
                tooSmall.Add(room);
                continue;
            }
        }
        foreach (var room in tooSmall)
        {
            temple.Rooms.Remove(room);
        }

        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        List <GenRoom> PotentialSecret = new List <GenRoom>();

        foreach (var room in temple.Rooms)
        {
            if (room.Width + room.Height <= 12)
            {
                PotentialSecret.Add(room);
            }
        }

        Debug.Log("potential " + PotentialSecret.Count + "Secret rooms");

        // 1 room --> 0,1,2,3
        // 2 room --> 4,5
        int SecretCount = Mathf.Min(Mathf.FloorToInt(Mathf.Sqrt(Random.Range(1, 6))), PotentialSecret.Count); // this goes to 5

        Debug.Log(SecretCount + " Secret rooms chosen");
        foreach (var secret in PotentialSecret.GetRandom(SecretCount))
        {
            // we get random door
            // add a chest
            // remove it from door spawn
            GenPositionTile entry = temple.GetDoorableTiles(secret.GetAllTiles()).GetRandom();
            secret.AddDetail(entry.PositionG.x, entry.PositionG.y,
                             new GenDetail()
            {
                Char = '*', Entity = GenDetail.EntityType.Door, Type = GenDetail.DetailType.Door
            });

            GenPositionTile myChest = secret
                                      .GetAllTiles()
                                      .Where(t => temple.IsInsideRoom(t.PositionG.x, t.PositionG.y, secret) && temple.IsCornerGR(t.PositionG.x, t.PositionG.y, secret))
                                      .ToList()
                                      .GetRandom();
            secret.AddDetails(myChest.PositionG.x, myChest.PositionG.y, GenTile.Copy(Chest));

            AutoFillRoom.Remove(secret);
            SecretRooms.Add(secret);
            NoAutoDoor.Add(secret);
        }
        // -----------
        Log(temple);
        if (Logging != null)
        {
            yield return(new WaitForSeconds(0.25f));
        }
        // -----------

        // go through all other rooms and determin what they are

        foreach (GenRoom room in AutoFillRoom)
        {
            // -----------
            Log(temple);
            if (Logging != null)
            {
                yield return(new WaitForSeconds(0.25f));
            }
            // -----------

            // pillar hallway
            if (room.Height <= 7 && room.Height >= 5 && room.Width > 6)
            {
                // potential horizontal hallway
                if (Random.value < 0.4f)
                {
                    // hallway confirmed
                    // left to right

                    GenTile[,] p = new GenTile[, ]
                    {
                        { GenTile.Copy(pillar) }
                    };
                    int spacing = Random.Range(2, 5);

                    int tmpX = room.Outer.MinX + spacing;
                    int tmpY = room.Outer.MinY + 1;


                    p = GenUtil.GetSymetry(p, ref tmpX, ref tmpY, room, GenUtil.Axis.Vertical);

                    while (temple.IsInsideRoom(tmpX, tmpY, room))
                    {
                        room.PlaceDetailsAt(tmpX, tmpY, p);

                        tmpX = tmpX + spacing;
                    }
                    int enemyCount = Random.Range(0, 4);
                    for (int i = 0; i < enemyCount; i++)
                    {
                        SpawnEnemy(temple, room);
                    }
                    int itemCount = Random.Range(-1, 3);
                    for (int i = 0; i < itemCount; i++)
                    {
                        SpawnItem(temple, room, true);
                    }
                    int chestCount = Random.Range(-2, 2);
                    for (int i = 0; i < chestCount; i++)
                    {
                        SpawnChest(temple, room, true);
                    }
                    continue;
                }
            }
            if (room.Width <= 7 && room.Width >= 5 && room.Height > 6)
            {
                // potential horizontal hallway
                if (Random.value < 0.4f)
                {
                    // hallway confirmed
                    // left to right

                    GenTile[,] p = new GenTile[, ]
                    {
                        { GenTile.Copy(pillar) }
                    };
                    int spacing = Random.Range(2, 5);

                    int tmpX = room.Outer.MinX + 1;
                    int tmpY = room.Outer.MinY + spacing;


                    p = GenUtil.GetSymetry(p, ref tmpX, ref tmpY, room, GenUtil.Axis.Horizontal);

                    while (temple.IsInsideRoom(tmpX, tmpY, room))
                    {
                        room.PlaceDetailsAt(tmpX, tmpY, p);

                        tmpY = tmpY + spacing;
                    }
                    int enemyCount = Random.Range(0, 4);
                    for (int i = 0; i < enemyCount; i++)
                    {
                        SpawnEnemy(temple, room);
                    }
                    int itemCount = Random.Range(-1, 3);
                    for (int i = 0; i < itemCount; i++)
                    {
                        SpawnItem(temple, room, true);
                    }
                    int chestCount = Random.Range(-2, 2);
                    for (int i = 0; i < chestCount; i++)
                    {
                        SpawnChest(temple, room, true);
                    }
                    continue;
                }
            }

            if (room.Height >= 8 && room.Width >= 8)
            {
                // can either be pillar spam or room in room

                if (Random.value < 0.6f)
                {
                    if (Random.value < 0.7f && room.Width % 2 == 1 && room.Height % 2 == 1)
                    {
                        // pillar spam

                        for (int x = 2; x < room.Width - 2; x += 2)
                        {
                            for (int y = 2; y < room.Height - 2; y += 2)
                            {
                                room.AddDetails(room.PosX + x, room.PosY + y, GenTile.Copy(pillar));
                            }
                        }
                        int enemyCount = Random.Range(0, 5);
                        for (int i = 0; i < enemyCount; i++)
                        {
                            SpawnEnemy(temple, room);
                        }
                        int itemCount = Random.Range(-1, 3);
                        for (int i = 0; i < itemCount; i++)
                        {
                            SpawnItem(temple, room, true);
                        }
                        int chestCount = Random.Range(-3, 3);
                        for (int i = 0; i < chestCount; i++)
                        {
                            SpawnChest(temple, room, true);
                        }
                    }
                    else
                    {
                        // room in room

                        // find where to put the inner room
                        temple.TryGrowRect(room.Inner.GetCenter().x, room.Inner.GetCenter().y, 100, 100, out GenRect InnerSize);


                        if (InnerSize.WidthT >= 4 && InnerSize.HeightT >= 4)
                        {
                            if (InnerSize.WidthT >= 10 || InnerSize.HeightT >= 10)
                            {
                                if (Mathf.Abs(InnerSize.WidthT - InnerSize.HeightT) > 3)
                                {
                                    // we want to divide
                                    if (InnerSize.WidthT > InnerSize.HeightT)
                                    {
                                        // divide left and right
                                        int singleWidth = InnerSize.WidthT / 2 - 2;
                                        // left
                                        GenRect LeftRoom = new GenRect(InnerSize.MinX, InnerSize.MinX + singleWidth, InnerSize.MinY, InnerSize.MaxY);
                                        // right
                                        GenRect RightRoom = new GenRect(InnerSize.MaxX - singleWidth, InnerSize.MaxX, InnerSize.MinY, InnerSize.MaxY);

                                        GenRoom left = GenRoom.Sized(LeftRoom.WidthT, LeftRoom.HeightT);
                                        left.FillFloor();
                                        left.SpacePriority = 4;
                                        GenRoom right = GenRoom.Sized(RightRoom.WidthT, RightRoom.HeightT);
                                        right.FillFloor();
                                        right.SpacePriority = 4;
                                        temple.PlaceRoom(LeftRoom.MinX, LeftRoom.MinY, left);
                                        temple.PlaceRoom(RightRoom.MinX, RightRoom.MinY, right);

                                        NoAutoDoor.Add(left);
                                        NoAutoDoor.Add(right);

                                        temple.EdgeWalls('#', left);
                                        temple.EdgeWalls('#', right);

                                        temple.FixOverlap();
                                        // -----------
                                        Log(temple);
                                        if (Logging != null)
                                        {
                                            yield return(new WaitForSeconds(0.25f));
                                        }
                                        // -----------

                                        var leftDoor  = temple.GetDoorableTiles(left.GetAllTiles()).GetRandom(1);
                                        var rightDoor = temple.GetDoorableTiles(right.GetAllTiles()).GetRandom(1);

                                        for (int i = 0; i < leftDoor.Count; i++)
                                        {
                                            left.AddDetails(leftDoor[i].PositionG.x, leftDoor[i].PositionG.y, GenTile.Copy(Door));
                                        }
                                        for (int i = 0; i < rightDoor.Count; i++)
                                        {
                                            right.AddDetails(rightDoor[i].PositionG.x, rightDoor[i].PositionG.y, GenTile.Copy(Door));
                                        }
                                        SpawnItem(temple, left);
                                        SpawnItem(temple, right);
                                        if (Random.value < 0.4f)
                                        {
                                            SpawnItem(temple, right);
                                        }
                                        if (Random.value < 0.4f)
                                        {
                                            SpawnItem(temple, left);
                                        }
                                        if (Random.value < 0.2f)
                                        {
                                            SpawnChest(temple, left, true);
                                        }
                                        if (Random.value < 0.2f)
                                        {
                                            SpawnChest(temple, left, true);
                                        }
                                    }
                                    else
                                    {
                                        // divide top bot
                                        Debug.Log("currently not implemented, sorry");
                                    }
                                }
                            }
                            else
                            {
                                // one single room
                                if (InnerSize.WidthT > 5)
                                {
                                    InnerSize = InnerSize.Transform(-1, 0, -1, 0);
                                }
                                if (InnerSize.HeightT > 5)
                                {
                                    InnerSize = InnerSize.Transform(0, -1, 0, -1);
                                }

                                Debug.Log("HERE");

                                GenRoom single = GenRoom.Sized(InnerSize.WidthT, InnerSize.HeightT);
                                single.SpacePriority = 4;
                                single.FillFloor();
                                NoAutoDoor.Add(single);

                                temple.PlaceRoom(InnerSize.MinX, InnerSize.MinY, single);
                                temple.EdgeWalls('#', single);
                                temple.FixOverlap();
                                // -----------
                                Log(temple);
                                if (Logging != null)
                                {
                                    yield return(new WaitForSeconds(0.25f));
                                }
                                // -----------



                                // double doors
                                var doorables = single.GetAllTiles();// single.GetEdge().ToList();
                                var theDoors  = temple.GetDoorableTiles(doorables).GetRandom(2);

                                for (int i = 0; i < theDoors.Count; i++)
                                {
                                    single.AddDetails(theDoors[i].PositionG.x, theDoors[i].PositionG.y, GenTile.Copy(Door));
                                }

                                SpawnItem(temple, single);

                                if (Random.value < 0.2f)
                                {
                                    SpawnChest(temple, single, true);
                                }
                                if (Random.value < 0.2f)
                                {
                                    SpawnChest(temple, single, true);
                                }
                            }
                        }

                        SpawnEnemy(temple, room);
                        if (Random.value < 0.5f)
                        {
                            SpawnEnemy(temple, room);
                        }
                        if (Random.value < 0.2f)
                        {
                            SpawnEnemy(temple, room);
                        }
                    }
                    continue;
                }
            }
            // something random
            //room.FillFloor('~');

            SpawnEnemy(temple, room);
            SpawnEnemy(temple, room);

            if (Random.value < 0.5f)
            {
                SpawnEnemy(temple, room);
            }
            if (Random.value < 0.2f)
            {
                SpawnEnemy(temple, room);
            }
            SpawnItem(temple, room);
            if (Random.value < 0.3f)
            {
                SpawnItem(temple, room);
            }
            if (Random.value < 0.3f)
            {
                SpawnItem(temple, room);
            }
            if (Random.value < 0.4f)
            {
                SpawnChest(temple, room);
            }
            if (Random.value < 0.1f)
            {
                SpawnChest(temple, room);
            }
        }


        List <GenRoom> RequireDoor = new List <GenRoom>(temple.Rooms);

        foreach (var doo in NoAutoDoor)
        {
            RequireDoor.Remove(doo);
        }
        List <GenRoom> DoorIteration = new List <GenRoom>(RequireDoor);
        GenRoom        start         = EntryHall;

        Dictionary <GenRoom, List <GenRoom> > adj = temple.GetAdjacentRoomMap();

        void RandomDoorTo(GenRoom a, GenRoom b)
        {
            var tiles    = temple.GetDoorableTiles(temple.GetConnectingTiles(a, b));
            var location = tiles.GetRandom();

            a.AddDetails(location.PositionG.x, location.PositionG.y, GenTile.Copy(Door));
        }

        while (RequireDoor.Count > 0)
        {
            DoorIteration.Clear();
            DoorIteration.AddRange(RequireDoor);
            foreach (var room in DoorIteration)
            {
                if (temple.IsReachable(start, room))
                {
                    // reachable so we dont have to do a thing
                    RequireDoor.Remove(room);
                }
                else
                {
                    // place random door
                    var available = adj[room];
                    RandomDoorTo(room, available.GetRandom());
                }
                // -----------
                Log(temple);
                if (Logging != null)
                {
                    yield return(new WaitForSeconds(0.1f));
                }

                // -----------
            }
        }


        foreach (var room in adj[Spam].GetRandom(2))
        {
            RandomDoorTo(Spam, room);
        }

        Log(temple);
        Debug.Log("Done");


        LastOutput = GenUtil.Print(temple, false);
        Done?.Invoke();
    }
Exemple #29
0
        /// <summary>
        /// Method to write into the excel report file to print.
        /// </summary>
        public void ConvertToExcel()
        {
            try
            {
                string home_drive = Environment.SystemDirectory;
                home_drive = home_drive.Substring(0, 2);
                string strExcelPath = home_drive + "\\Servosms_ExcelFile\\Export\\";
                Directory.CreateDirectory(strExcelPath);
                string         path    = home_drive + @"\Servosms_ExcelFile\Export\HSD_MS_Report.xls";
                StreamWriter   sw      = new StreamWriter(path);
                InventoryClass obj     = new InventoryClass();
                double         Tot_MS  = 0;
                double         Tot_HSD = 0;
                //coment by vikas 21.12.2012 sql="select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and (cast(floor(cast(datefrom as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and cast(floor(cast(dateto as float)) as datetime)<='"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' or cast(floor(cast(datefrom as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and '"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"' or cast(floor(cast(dateto as float)) as datetime) between '"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and '"+GenUtil.str2MMDDYYYY(txtDateTo.Text)+"')";

                if (DropSearchBy.SelectedIndex != 0)
                {
                    if (DropSearchBy.SelectedIndex == 1)
                    {
                        sql = "select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and c.cust_name='" + DropValue.Value.ToString() + "' and (cast(floor(cast(datefrom as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(dateto as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(datefrom as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(dateto as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "')";
                    }
                    else if (DropSearchBy.SelectedIndex == 2)
                    {
                        sql = "select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and Cust_type in (select customertypename from customertype where Sub_group_name='" + DropValue.Value.ToString() + "') and (cast(floor(cast(datefrom as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(dateto as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(datefrom as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(dateto as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "')";
                    }
                    else if (DropSearchBy.SelectedIndex == 3)
                    {
                        sql = "select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and City='" + DropValue.Value.ToString() + "' and (cast(floor(cast(datefrom as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(dateto as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(datefrom as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(dateto as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "')";
                    }
                    else if (DropSearchBy.SelectedIndex == 4)
                    {
                        sql = "select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and State='" + DropValue.Value.ToString() + "' and (cast(floor(cast(datefrom as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(dateto as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(datefrom as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(dateto as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "')";
                    }
                    else if (DropSearchBy.SelectedIndex == 5)
                    {
                        sql = "select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and SSR in (select emp_id from employee where Emp_Name='" + DropValue.Value.ToString() + "') and (cast(floor(cast(datefrom as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(dateto as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(datefrom as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(dateto as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "')";
                    }
                }
                else
                {
                    sql = "select c.Cust_id,Cust_Name,cust_type,city,ms,hsd,datefrom,dateto from Customer c,Cust_sale_ms_hsd CSMH where c.cust_id=csmh.cust_id and (cast(floor(cast(datefrom as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(dateto as float)) as datetime)<='" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(datefrom as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "' or cast(floor(cast(dateto as float)) as datetime) between '" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and '" + GenUtil.str2MMDDYYYY(txtDateTo.Text) + "')";
                }

                rdr = obj.GetRecordSet(sql);
                int i = 1;
                if (rdr.HasRows)
                {
                    sw.WriteLine("SNo\tCustomer Name\tCust Type\tPlace\tMS\tHSD\t");
                    while (rdr.Read())
                    {
                        sw.WriteLine(i.ToString() + "\t" +
                                     rdr["Cust_Type"].ToString() + "\t" +
                                     rdr["City"].ToString() + "\t" +
                                     rdr["MS"].ToString() + "\t" +
                                     rdr["HSD"].ToString());
                        i++;
                        Tot_MS  += double.Parse(rdr["MS"].ToString());
                        Tot_HSD += double.Parse(rdr["HSD"].ToString());
                    }
                    rdr.Close();
                }

                if (DropSearchBy.SelectedIndex == 0)
                {
                    sql = "select * from cust_sale_ms_hsd where cust_id=0";
                    rdr = obj.GetRecordSet(sql);
                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            sw.WriteLine(i.ToString() + "\t\t\t" +
                                         rdr["MS"].ToString() + "\t" +
                                         rdr["HSD"].ToString());
                            i++;
                            Tot_MS  += double.Parse(rdr["MS"].ToString());
                            Tot_HSD += double.Parse(rdr["HSD"].ToString());
                        }
                        rdr.Close();
                    }
                }
                sw.WriteLine("\tTotal\t\t\t" + Tot_MS.ToString() + "\t" + Tot_HSD.ToString() + "\t");
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
Exemple #30
0
        /// <summary>
        /// This method is used to save the employee leave with the help of ProLeaveEntry Procedure
        /// before check the date if Leave save already in this given date then first delete the record
        /// and save the record update otherwise save the record in Leave_Register table.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnApply_Click(object sender, System.EventArgs e)
        {
            EmployeeClass obj = new EmployeeClass();

            try
            {
                #region Check Validation
                if (DateTime.Compare(ToMMddYYYY(txtDateFrom.Text), ToMMddYYYY(txtDateTO.Text)) > 0)
                {
                    MessageBox.Show("Date From Should Be Less Than Date To");
                    return;
                }
                if (DateTime.Compare(ToMMddYYYY(GenUtil.str2DDMMYYYY(GenUtil.trimDate(DateTime.Now.ToString()))), ToMMddYYYY(txtDateFrom.Text)) > 0)
                {
                    MessageBox.Show("Date From Should Be Gratter Or Equal to Date To");
                    return;
                }
                int    Count = 0, Count1 = 0;
                string str1, str2, str3;
                str1 = DropEmpName.SelectedItem.Value.Substring(0, DropEmpName.SelectedItem.Value.LastIndexOf(":"));;
                str2 = GenUtil.str2MMDDYYYY(txtDateFrom.Text);
                str3 = GenUtil.str2MMDDYYYY(txtDateFrom.Text);

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(BaseUri);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var Res = client.GetAsync("api/LeaveRegister/CountLeaveRegister?str1=" + str1 + "&str2=" + str2 + "&str3=" + str3).Result;
                    if (Res.IsSuccessStatusCode)
                    {
                        var id = Res.Content.ReadAsStringAsync().Result;
                        Count1 = JsonConvert.DeserializeObject <int>(id);
                    }
                    else
                    {
                        Res.EnsureSuccessStatusCode();
                    }
                }
                Count = Count1;

                //            string str = "select count(*) from Leave_Register where Emp_ID='"+DropEmpName.SelectedItem.Value.Substring(0,DropEmpName.SelectedItem.Value.LastIndexOf(":"))+"' and cast(floor(cast(cast(date_from as datetime) as float)) as datetime) <='"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and cast(floor(cast(cast(date_to as datetime) as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and isSanction=1";
                //dbobj.ExecuteScalar(str,ref Count);
                if (Count > 0)
                {
                    MessageBox.Show("Employee already allow leave is given date");
                    return;
                }

                str1 = DropEmpName.SelectedItem.Value.Substring(0, DropEmpName.SelectedItem.Value.LastIndexOf(":"));
                str2 = GenUtil.str2MMDDYYYY(txtDateFrom.Text);
                str3 = GenUtil.str2MMDDYYYY(txtDateFrom.Text);

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(BaseUri);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var Res = client.GetAsync("api/LeaveRegister/GetLeaveRegister?str1=" + str1 + "&str2=" + str2 + "&str3=" + str3).Result;
                    if (Res.IsSuccessStatusCode)
                    {
                        var id = Res.Content.ReadAsStringAsync().Result;
                        Count1 = JsonConvert.DeserializeObject <int>(id);
                    }
                    else
                    {
                        Res.EnsureSuccessStatusCode();
                    }
                }
                Count = Count1;
                //            str = "select * from Leave_Register where Emp_ID='"+DropEmpName.SelectedItem.Value.Substring(0,DropEmpName.SelectedItem.Value.LastIndexOf(":"))+"' and cast(floor(cast(cast(date_from as datetime) as float)) as datetime) <='"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and cast(floor(cast(cast(date_to as datetime) as float)) as datetime)>='"+GenUtil.str2MMDDYYYY(txtDateFrom.Text)+"' and isSanction=0";
                //dbobj.ExecuteScalar(str,ref Count);
                if (Count > 0)
                {
                    int x = 0;
                    dbobj.Insert_or_Update("delete from Leave_Register where Emp_ID='" + DropEmpName.SelectedItem.Value.Substring(0, DropEmpName.SelectedItem.Value.LastIndexOf(":")) + "' and cast(floor(cast(cast(date_from as datetime) as float)) as datetime) <='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and cast(floor(cast(cast(date_to as datetime) as float)) as datetime)>='" + GenUtil.str2MMDDYYYY(txtDateFrom.Text) + "' and isSanction=0", ref x);
                }
                #endregion
                obj.Emp_Name  = DropEmpName.SelectedItem.Value.Substring(0, DropEmpName.SelectedItem.Value.LastIndexOf(":"));
                obj.Date_From = ToMMddYYYY(txtDateFrom.Text).ToShortDateString();
                obj.Date_To   = ToMMddYYYY(txtDateTO.Text).ToShortDateString();
                obj.Reason    = StringUtil.FirstCharUpper(txtReason.Text.ToString());
                obj.Days      = txtleaveday.Text.ToString().Trim();                      //add by vikas 17.11.2012
                // calls fuction to insert the leave
                obj.InsertLeave();
                MessageBox.Show("Leave Application Saved");
                Clear();
                CreateLogFiles.ErrorLog("Form:Leave_Register.aspx,Method:btnApply_Click" + "  empname  :" + obj.Emp_Name + " datefrom  " + obj.Date_From + "        uptodate   " + obj.Date_To + " for Reason " + obj.Reason + "  is saved  " + "  userid:   " + uid);
            }
            catch (Exception ex)
            {
                CreateLogFiles.ErrorLog("Form:Leave_Register.aspx,Method:btnApply_Click" + "  empname  :" + obj.Emp_Name + "  is saved  " + "  EXCEPTION  " + ex.Message + "  userid:   " + uid);
                Response.Redirect("../../Sysitem/ErrorPage.aspx", false);
            }
        }