Sunday, 24 May 2015

datatable.select (LINQ funda)

private void PopulateGrid(GridView gv, Int32 pageindex, DataSet dsGV)
    {
        try
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataRow[] dr = null;

            string exp = "rowno = " + pageindex;
            if (dsGV.Tables[0].Rows.Count > 0)
                dr = dsGV.Tables[0].Select(exp);

            ds = dsGV.Clone();
            foreach (DataRow drr in dr)
                ds.Tables[0].ImportRow(drr);

            gv.DataSource = ds;
            gv.DataBind();

            //following code is written to get current level description from id_member_levels table
            //this is written to avoid join in the main query
            //if we give join in main query in Populate proceure, it affects on the performance of the query.
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (cn.State == ConnectionState.Closed)
                {
                    cn.Open();
                    cm = new OleDbCommand("", cn);
                }
            }

            //for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //{

            //    if (ds.Tables[0].Rows[i]["MM_CURR_LEVEL"].ToString().Equals("0") == false)
            //    {
            //        strSQL = "select ML_DESC from id_member_levels where ml_level = " + ds.Tables[0].Rows[i]["MM_CURR_LEVEL"].ToString();
            //        cm.CommandText = strSQL;
            //        reader = cm.ExecuteReader();
            //        if (reader.Read())
            //            gv.Rows[i].Cells[c_Level].Text = reader["ML_DESC"].ToString();
            //        reader.Close();
            //    }
            //    else
            //        gv.Rows[i].Cells[c_Level].Text = "NA";
            //}

            if (cn.State == ConnectionState.Open)
            {
                cm.Dispose();
                cn.Close();
            }
        }
        catch (Exception ex) { lblError.Text = ex.Message; }
        finally { }
    }

Friday, 8 May 2015

Update textbox data on click of button on another page with telerik rad window



dark is parent window

 modal is individual page which is opened with telerik rad window

on click of save on modal page, we need to update parent page's benefeciary name also


On parent aspx
---------------------------------------------------
<%@ MasterType VirtualPath="~/Site.master" %>


function OnSubItemClose(oWnd, args) {
       if (args._argument != null) {
           console.log(args);
       }
   }



<telerik:RadWindowManager runat="server" ID="radmanager">
        <Windows>
            <telerik:RadWindow ID="ListDialog" runat="server" ReloadOnShow="true" ShowContentDuringLoad="false" Width="500px" Height="400px"
                Modal="true" VisibleStatusbar="false" ShowOnTopWhenMaximized="true" AutoSize="false"
                EnableViewState="false" KeepInScreenBounds="false" Behaviors="Close"
                VisibleTitlebar="true" VisibleOnPageLoad="false">
            </telerik:RadWindow>
        </Windows>
    </telerik:RadWindowManager>


<asp:TextBox ID="txt_beneficiary" runat="server"  ClientIDMode="Static" />

<asp:Button ID="btnbeneficiary" Text="..." runat="server"
                                onclick="btnbeneficiary_Click" />


On parent page code
----------------------------
private void SetWindow(string navurl, string onclientclose)
    {
        radmanager.Windows.Clear();
        ListDialog.NavigateUrl = navurl;
        ListDialog.VisibleOnPageLoad = true;
        ListDialog.OnClientClose = onclientclose;

        radmanager.Windows.Add(ListDialog);
    }
    protected void btnbeneficiary_Click(object sender, EventArgs e)
    {
        if (!ddl_CenterList.Enabled)
        {
            SetWindow("~/cp_beneficiary.aspx?Memid=" + ViewState["MemberID"].ToString(), "OnSubItemClose");
        }
        else
        {
            lblError.Text = "Please take appointment first.";
        }
    }


on modal page aspx
---------------------------------
<%@ MasterType VirtualPath="~/Site.master" %>


 <script type="text/javascript">

        function GetRadWindow() {
            var oWindow = null;
            if (window.radWindow)
                oWindow = window.radWindow;
            else if (window.frameElement.radWindow)
                oWindow = window.frameElement.radWindow;
            return oWindow;
        }

        function UpdateName() {
            GetRadWindow().BrowserWindow.document.getElementById("txt_beneficiary").value = <%= txtBenName.ClientID%>.value;
        }
    </script>

<asp:Button Text="Save" runat="server" ID="btnSave" onclick="btnSave_Click" OnClientClick="UpdateName(); return true;" />

Monday, 29 December 2014

How to select checkbox and display values in textboxes and when checkbox not selected dont show value

 <tr>
                                <td>
                                    Select Center:
                                </td>
                                <td>
                                    <asp:TextBox ID="txt_city" runat="server" BackColor="White" CssClass="textbox" placeholder="Select Centre"
                                        ReadOnly="true" Width="300px"></asp:TextBox>
                                    <cc1:PopupControlExtender ID="PopupContExtcity" runat="server" Enabled="True" ExtenderControlID=""
                                        OffsetY="18" PopupControlID="pnl_city" TargetControlID="txt_city">
                                    </cc1:PopupControlExtender>
                                    <asp:Panel ID="pnl_city" runat="server" BackColor="White" BorderColor="#B3B1AD" BorderWidth="1px"
                                        Direction="LeftToRight" Height="116px" ScrollBars="Auto" Style="display: none"
                                        Width="300px">
                                        <asp:CheckBox ID="chk_city_all" runat="server" AutoPostBack="false" Text="All" />
                                        <asp:CheckBoxList ID="chklistCity" runat="server" AutoPostBack="false">
                                        </asp:CheckBoxList>
                                    </asp:Panel>
                                </td>
                            </tr>

=======================================================
<script language="javascript" type="text/javascript">
        var ModalProgress = '<%= ModalProgress.ClientID %>';

        function EndRequestHandler(sender, args) {
            if (args.get_error() == undefined) {
                chklistCity();
                ChkListEnterBy();
            }
        }

        $(function () {
            chklistCity();
        });

        function chklistCity() {
            $("[id*=chk_city_all]").bind("click", function () {
                if ($(this).is(":checked")) {
                    $("[id*=chklistCity] input").attr("checked", "checked");

                } else {
                    $("[id*=chklistCity] input").removeAttr("checked");
                }
                updatecity();
            });
            $("[id*=chklistCity] input").bind("click", function () {
                if ($("[id*=chklistCity] input:checked").length == $("[id*=chklistCity] input").length) {
                    $("[id*=chk_city_all]").attr("checked", "checked");

                } else {
                    $("[id*=chk_city_all]").removeAttr("checked");

                }
                updatecity();
            });

            function updatecity() {
                var txt_city = "";
                $("[id*=chklistCity] input:checked").each(function () {
                    txt_city += $(this).siblings("label").html() + ",";
                });
                //console.log(txtSubCity);
                $("#<%= txt_city.ClientID %>").val(txt_city);
            }
        }

       
    </script>
==============================================================
private void Bind_Center_CheckBox()
    {
        if (con.State != ConnectionState.Open)
        {
            con.Open();
        }
        //chklistCity.DataSource = clsc.Get_DataReader("Select SC_CODE,SC_DESC from ID_citymst order by SC_DESC", con);
        //chklistCity.DataValueField = "SC_CODE";
        //chklistCity.DataTextField = "SC_DESC";
        chklistCity.DataSource = clsc.Get_DataReader("Select cc_centerno code,cc_name descr from id_check_up_centers where cc_active_yn='Y' order by CC_NAME", con);
        chklistCity.DataValueField = "code";
        chklistCity.DataTextField = "descr";
        chklistCity.DataBind();
        chk_city_all.Checked = true;
        string strname = "";
        foreach (ListItem item in chklistCity.Items)
        {
            item.Selected = true;
            strname = strname + item.Text + ",";
        }
        txt_city.Text = strname;

        ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), "jscript1", "chklistCity();", true);
    }

Friday, 5 December 2014

export gridview to excel in asp.net c#

public void ExportGridviewToExcel(GridView gvnmae, string strFileName)
    {
        try
        {
            HttpContext context = HttpContext.Current;
            string strText = "";

            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".csv");
            context.Response.Charset = "";
            context.Response.ContentType = "application/text";

            StringBuilder sb = new StringBuilder();
            for (int k = 0; k <= gv.HeaderRow.Cells.Count - 1; k++)
            {
                if (gv.HeaderRow.Cells[k].Visible == true & gv.HeaderRow.Cells[k].CssClass != "hiddenColumn")
                {
                    //add separator
                    sb.Append(gv.HeaderRow.Cells[k].Text + ',');
                }
            }
            //append new line          
            sb.Append(System.Environment.NewLine);
            for (int i = 0; i <= gv.Rows.Count - 1; i++)
            {
                for (int k = 0; k <= gv.Rows[i].Cells.Count - 1; k++)
                {
                    if (gv.Rows[i].Cells[k].Visible == true & gv.Rows[i].Cells[k].CssClass != "hiddenColumn")
                    {
                        //add separator

                        strText = "";
                        strText = (gv.Rows[i].Cells[k].Text.Contains(",") ? "\"" + gv.Rows[i].Cells[k].Text + "\"" : gv.Rows[i].Cells[k].Text);
                        strText = strText.Replace("&nbsp;", "");

                        //sb.Append(gv.Rows(i).Cells(k).Text + ","c)
                        sb.Append(strText + ',');
                    }
                }
                //append new line
                sb.Append(System.Environment.NewLine);
            }
            context.Response.Output.Write(sb.ToString());
            context.Response.Flush();
            context.Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Getting database values into checkboxlist in templatefield in gridview

<asp:GridView ID="gvccedetails" runat="server" AutoGenerateColumns="false" CssClass="table">
                        <AlternatingRowStyle CssClass="success" />
                        <HeaderStyle CssClass="warning" />
                        <SelectedRowStyle CssClass="active" />
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
                                        OnCommand="btnSelect_Click" />
                                </ItemTemplate>
                            </asp:TemplateField>                          
                            <asp:BoundField DataField="cceid" HeaderText="CCE ID" />
                            <asp:BoundField DataField="ccename" HeaderText="CCE Name" />
                            <asp:BoundField DataField="ccecontact" HeaderText="CCE Contact" />
                            <asp:BoundField DataField="cceemail" HeaderText="CCE Email" />
                            <asp:BoundField DataField="ccesharedyn" HeaderText="Shared Resources Y/N" />
                            <asp:TemplateField HeaderText="Working Days">
                                <ItemTemplate>
                                    <asp:CheckBoxList ID="cbl_cceworkingDays" RepeatDirection="Horizontal" runat="server"
                                        EnableViewState="true">
                                        <asp:ListItem Text="Mon" Value="Mon"></asp:ListItem>
                                        <asp:ListItem Text="Tue" Value="Tue"></asp:ListItem>
                                        <asp:ListItem Text="Wed" Value="Wed"></asp:ListItem>
                                        <asp:ListItem Text="Thu" Value="Thu"></asp:ListItem>
                                        <asp:ListItem Text="Fri" Value="Fri"></asp:ListItem>
                                        <asp:ListItem Text="Sat" Value="Sat"></asp:ListItem>
                                        <asp:ListItem Text="Sun" Value="Sun"></asp:ListItem>
                                    </asp:CheckBoxList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="ccecentreid" HeaderText="" HeaderStyle-CssClass="hiddenColumn"
                                ItemStyle-CssClass="hiddenColumn" />
                        </Columns>
                    </asp:GridView>







private void fillGrid()
    {
        try
        {
            string[] items = null;

            strSql = " select distinct CCE_ID,CCE_WORKINGDAYS,cce_centreno, em_first_name ||' '|| em_middle_name ||' '|| em_last_name empname," +
                     " EM_EMAIL, to_char( EM_DS_CELL_NO) EM_DS_CELL_NO, EM_EMPCODE,DM_ID,dm_desc " +
                     " from id_cce_details,ID_EMPMST,id_deptmst " +
                     " where cce_centreno='" + hdnCenterID.Value + "' and EM_DEPT_ID = DM_ID and EM_EMPCODE=CCE_ID ";

            if (con.State != ConnectionState.Open) con.Open();
            DataSet ds = cls.Get_DataSet(strSql, con);

            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow[] drs = ds.Tables[0].Select("cce_centreno='" + hdnCenterID.Value + "' and CCE_ID='" + ds.Tables[0].Rows[i]["CCE_ID"].ToString() + "' ");

                    if (drs.Length > 0)
                    {
                        strWorkDays = "";
                        drGrid = dtGrid.NewRow();
                        drGrid["ccecentreid"] = drs[0]["CCE_CENTRENO"].ToString();
                        drGrid["cceid"] = drs[0]["CCE_ID"].ToString();
                        drGrid["ccename"] = drs[0]["empname"].ToString();
                        drGrid["ccecontact"] = drs[0]["EM_DS_CELL_NO"].ToString();
                        drGrid["cceemail"] = drs[0]["EM_EMAIL"].ToString();
                        drGrid["ccedepartment"] = drs[0]["dm_desc"].ToString();
                        for (int j = 0; j < drs.Length; j++)
                        {
                            strWorkDays += drs[j]["CCE_WORKINGDAYS"].ToString() + ",";
                            i++;
                        }
                        drGrid["cceworkingdays"] = strWorkDays;
                        dtGrid.Rows.Add(drGrid);
                    }
                }
                ViewState["dtGrid"] = dtGrid;
                dtGridmodified = dtGrid.DefaultView.ToTable(true);
                gvccedetails.DataSource = dtGridmodified;
                gvccedetails.DataBind();

                for (int j = 0; j < gvccedetails.Rows.Count; j++)
                {
                    CheckBoxList c = (CheckBoxList)gvccedetails.Rows[j].FindControl("cbl_cceworkingDays");
                    if (c != null)
                    {
                        items = null;
                        items = dtGrid.Rows[j]["cceworkingdays"].ToString().Split(',');
                        for (int i = 0; i < c.Items.Count; i++)
                        {
                            if (items.Contains(c.Items[i].Value))
                            {
                                c.Items[i].Selected = true;
                            }
                        }
                    }
                }
            }
            else lblError.Text = "No record found";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

Monday, 21 July 2014

Generate BarCode in ASP.NET

protected void btnGenerateBarCode_onclick(object sender, EventArgs e) 
 {

 string barcodeDetail =”12345”; 
 GenerateBarCode.CreateBarCode(barcodeDetail, "Free 3 of 9 Extended", 48, "D:\Projects\projectname\ImageFolder\" );
 imgBarcodeImage.ImageUrl = string.Format("ImageFolder/{0}.png", barcodeDetail);

 }


public static void CreateBarCode(string barCodedDetail,stringfontName,int fontSize, string physicalPath) 
 {

 //Find the Width for barcode
 int width = barCodedDetail.Length*35; 

 //create Bitmap object with Width and Height
 Bitmap barCode = new Bitmap(width, 120); 

 //path where you want to save the barcode Image
 string filePath = string.Format("{0}{1}.png", physicalPath, barCodedDetail);

 //create the barcoded font object
 Font barCodeFont = new Font(fontName, fontSize, FontStyle.Regular,GraphicsUnit.Point);

 //creating the graphics object for the Bitmap.
  Graphics graphics = Graphics.FromImage(barCode);

 SizeF sizeF = graphics.MeasureString(barCodedDetail, barCodeFont); 

 barCode = new Bitmap(barCode, sizeF.ToSize()); 

 graphics = Graphics.FromImage(barCode);

 SolidBrush brushBlack = new SolidBrush(Color.Black);

graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;

 //putting * before and after the barCodedDetail,
 //this is because scanner only read the data which is started and end with *
 graphics.DrawString("*" + barCodedDetail + "*", barCodeFont, brushBlack, 1,1); 

 graphics.Dispose(); 
 //Saving the Image file
 barCode.Save(filePath, ImageFormat.Png);
  barCode.Dispose();  
 HttpContext.Current.Response.Clear();

 }

Wednesday, 21 May 2014

how to call wcf service asynchronously from asp.net page

protected void btnSearch_Click(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(BeginGetrdgDetailsAsyncData, EndGetrdgDetailsAsyncData, null, null);
            Page.RegisterAsyncTask(task);
}



IAsyncResult BeginGetrdgDetailsAsyncData(object src, EventArgs args, AsyncCallback cb, object state)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<SalesAnalysis>");
        -----
-------
        sb.Append("</SalesAnalysis>");
        return pharma.BeginSales_Analysis(sb.ToString(), cb, state);
    }

    void EndGetrdgDetailsAsyncData(IAsyncResult ar)
    {
        try
        {
            String result = pharma.EndSales_Analysis(ar, out strerror);
            if (strerror == "")
            {
                DataSet dsresult = new DataSet();
                dsresult = JsonConvert.DeserializeObject<DataSet>(result);

                DataView dv = new DataView(dsresult.Tables[2]);
                DataTable distinctValues = dv.ToTable(true, "SCHEDULE_ID", "SCHEDULE_NAME");
                for (int i = 0; i < distinctValues.Rows.Count; i++)
                {
                    dsresult.Tables[1].Columns.Add(distinctValues.Rows[i]["SCHEDULE_NAME"].ToString());
                    DataRow[] drs = dsresult.Tables[1].Select("SCHEDULE_ID='" + distinctValues.Rows[i]["SCHEDULE_ID"].ToString() + "'");
                    if (drs.Length > 0)
                    {
                        //foreach (DataRow dr in drs)
                        //{
                        //    //assigning usage col values under dynamically created col "EQ_DESC"
                        //    dr[distinctValues.Rows[i]["SCHEDULE_NAME"].ToString()] = dr["Usage"].ToString();

                        //    //usage += Convert.ToDecimal(dr["Usage"].ToString());
                        //}
                    }
                }

                rdgDetails.DataSource = dsresult.Tables[1];
                rdgDetails.DataBind();
            }
            else
            {
                errormsg
            }
        }
        catch (Exception ex)
        {
         
        }
    }
--------------------------------------------------------------------------------
wcf

public String Sales_Analysis(String strParameter, out string error)
        {
            error = string.Empty;
            XmlDocument pdoc = new XmlDocument();
            pdoc.LoadXml(strParameter);
            DataSet ds = new DataSet();
            methodParameters = strParameter;
            try
            {
                if (dbclass.Connectdb(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
                {
                    dbclass.cmd = new OracleCommand();
                    dbclass.cmd.CommandText = "Proc Name";
                    dbclass.cmd.CommandType = CommandType.StoredProcedure;
                    #region add parameters
 //IN parameter..

                    //Out parameter..
                   
                    #endregion

                    ds = dbclass.ExecuteCommandDataSet(dbclass.con, dbclass.cmd);

                    if (ds.Tables[1].Rows.Count > 0)
                    {
                        return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
                    }
                    else
                    {
                        return "[]";
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
        }