Search This Blog

Wednesday, 26 December 2012

split a string with multiple separators in javascript?


multibox text area values
var urlsArr = textarea.value.replace(/\r\n/g, "\n").split(/[\n,]+/);

Thursday, 20 December 2012

Memory Cleaner that forces GC to collect objects in asp.net or Wcf or Window service

The following example demonstrates how to use the Collect method to perform a collection on all generations of memory. The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

[DllImportAttribute("Kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
    private static extern int ProcessWorkingSetSize(IntPtr Process, int minimumWorkingSetSize, int maximumWorkingSetSize);
    public void Flushmemory()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
        {
            ProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
        }
    }

Monday, 17 December 2012

RowDataBound Event of GridView and take footer sum value in asp.net with C#

We are using RowDataBound event to perform summation in footer row.
we will show you how to display a summary or the sum of values in a particular column, in the GridView footer row. Also known as running total of a column, these accumulated figures needs to be displayed below all the pages, if GridView Paging is set as “True”.

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TotalsCnt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotaloCnt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotalcCnt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotalSaCnt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotalAmt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotalCAmt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotalPAmt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
                TotalAfAmt += Convert.ToInt32((DataBinder.Eval(e.Row.DataItem, "DataBaseValue")));
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[2].Text = string.Format("{0:N0}", TotalsentCnt);
                e.Row.Cells[3].Text = string.Format("{0:N0}", TotalopenCnt);
                e.Row.Cells[4].Text = string.Format("{0:N0}", TotalclickCnt);
                e.Row.Cells[5].Text = string.Format("{0:N0}", TotalSalesCnt);
                e.Row.Cells[6].Text = string.Format("{0:C2}", TotalAmt);
                e.Row.Cells[7].Text = string.Format("{0:C2}", TotalCustomerAmt);
                e.Row.Cells[8].Text = string.Format("{0:C2}", TotalPublisherAmt);
                e.Row.Cells[9].Text = string.Format("{0:C2}", TotalAffiliateAmt);
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

Friday, 14 December 2012

Remove QueryString value using Asp.net

To clear all query strings, you can invoke the Request.QueryString.Clear();
which will remove all the querystrings at the url
To remove a specific querystring invoke Request.QueryString.Remove("name of the querystring").

Please follow below Example


PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
            // make collection editable
            isreadonly.SetValue(this.Request.QueryString, false, null);
            // remove
            this.Request.QueryString.Remove("op");

Monday, 10 December 2012

How to check a checkbox on gridview using javascript


 <script type="text/javascript">
        function Delete(id) {    
            var frm = document.forms[0];
            for (i = 0; i < frm.elements.length; i++) {
                if (frm.elements[i].type == "checkbox") {
                    if (frm.elements[i].checked) {
                        if (confirm('Are you sure you want to delete the records?')) {
                            return true;
                        } else {
                            for (i = 0; i < frm.elements.length; i++) {
                                frm.elements[i].checked = false;
                            }
                            return false;
                        }
                    }
                }
            }
            alert("Please select a records to delete");
            return false;
        }
    </script>

 <asp:ImageButton ID="ImgBtnDelete" runat="server" ToolTip="Delete"
OnClientClick="javascript:return Delete(this);"/>

Reading Files in Asp.net or C# and Search for a particular text in files in a specific directory


using (StreamReader sr = new StreamReader("FilePath" + "Config.dat"))
{
    sConfigText = sr.ReadToEnd();
}
try
{
objEditvmta = new StringBuilder();
string Pickfile = "identifystring";
if (sConfigText.Contains(Pickfile))
{
   StartPoint = sConfigText.Substring(0, sConfigText.IndexOf(Pickfile)) + Environment.NewLine;
   RemainingText = sConfigText.Substring(StartPoint.Length - 1);
   EntairText = RemainingText.Substring(RemainingText.IndexOf("EndingstringValue") + "EndingstringValue Length");
   objVmta.Append(StartPoint.TrimEnd());
   objVmta.Append(EntairText.TrimEnd());
   sConfigEditData = objVmta.ToString();
   FinalDeletePattern = sConfigEditData;
   FileStream fsPattern = File.OpenWrite("FilePath" + "FileName");
   Encoding encPattern = Encoding.ASCII;
   byte[] restPattern = encPattern.GetBytes(sConfigEditData.ToString());
   fsPattern.Write(restPattern, 0, sConfigEditData.Length);
   fsPattern.Flush();
   fsPattern.Close();
   fsPattern.Dispose();
}
sConfigEditData = string.Empty;
objEditvmta = null;
StartPoint = string.Empty;
RemainingText = string.Empty;
EntairText = string.Empty;
}
catch (Exception ex)
{

thow;

}

Thursday, 15 November 2012

Import Data from Excel to DataGridView in C# or Asp.net

protected void Submit_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = ss();
            gvOne.DataSource = dt;
            gvOne.DataBind();
        }
        catch (Exception ex)
        {
            throw new Exception("Upload Failed: " + ex.Message);
        }

    }


private DataTable ss()
    {
     
       
        string FilePath = @"E:\Excel_Sample\Excel\ActionSchedule1.xlsx";
        string excelConnectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 12.0;";
        OleDbConnection objConn = new OleDbConnection(excelConnectString);
        OleDbCommand objCmd = new OleDbCommand("Select * From [Sheet1$]", objConn);
        OleDbDataAdapter objDatAdap = new OleDbDataAdapter();
        objDatAdap.SelectCommand = objCmd;
        DataSet ds = new DataSet();
        objDatAdap.Fill(ds);
        //BulkInsertUpload(ds);
        return ds.Tables[0];



    }


<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td>
    <asp:GridView ID="gvOne" runat="server" >
   
    </asp:GridView>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Button ID="Submit" runat="server" onclick="Submit_Click" Text="Submit" />
    </td>
    </tr>
    </table>
    </div>
    </form>
</body>

Tuesday, 13 November 2012

Load Css file Dynamically on page load in asp.net


if (!IsPostBack)
        {
            HtmlGenericControl css;
            css = new HtmlGenericControl();
            css.TagName = "style";
            css.Attributes.Add("type", "text/css");
            css.InnerHtml = "@import \"../css/CentralReport.css\";";
            Page.Header.Controls.Add(css);
        }

When Select value in DropDownlist it will redirect to particular page in javascript


function RedirectToPage(targ, selObj, restore) {        
            var vIndexValue = selObj.options[selObj.selectedIndex].value;
            var vCurInd = selObj.selectedIndex;
            // Making all Drops selected Index 0.........
            document.getElementById("Value").selectedIndex = 0;
         
            //alert(vIndexValue);
            // Making the Curent Selected .....
            selObj.selectedIndex = vCurInd;
            //selObj.options[selObj.selectedIndex].value = vIndexValue;

            eval(targ + ".location='" + vIndexValue + "'");
        }

<select name="Value" class="Item_IB_Drop" id="Call" onchange="RedirectToPage('parent',this,0)">
   <option value="#" selected="selected">Select Option Below </option>
   <option value="../FolderName/PageName.aspx">DisplayName</option>  
         </select>

How to auto-increment serial number in gridview


<asp:TemplateField HeaderText="SI No">
                                <ItemTemplate>
                                    <%# Container.DataItemIndex +1 %>
                                </ItemTemplate>
                            </asp:TemplateField>

Tuesday, 6 November 2012

Validate radioButtonlist in asp.net using custom validator

<script type="text/javascript" language="javascript">
        function ClientValidate(source, args) {

            var MyRadioButton = document.getElementById("<%=rbl_Menu.ClientID %>");
            var options = MyRadioButton.getElementsByTagName("input");
            var Checkvalue = false;
            var check;
            for (i = 0; i < options.length; i++) {
                if (options[i].checked) {
                    Checkvalue = true;
                    check = options[i].value;
                }
            }
            if (!Checkvalue) {
                args.IsValid = false;
            }
            else {
                args.IsValid = true;
            }

        }
    </script>
<asp:RadioButtonList ID="rbl" runat="server" Width="30%"
RepeatDirection="Horizontal">
                                    <asp:ListItem Value="1">Data</asp:ListItem>
                                    <asp:ListItem Value="2">Data1</asp:ListItem>
                                </asp:RadioButtonList>
<asp:CustomValidator ID="cvType" ValidationGroup="imgsave" runat="server" ControlToValidate="rbl"
ClientValidationFunction="ClientValidate" Display="Dynamic" ValidateEmptyText="true" ErrorMessage="Please select Value">
</asp:CustomValidator>