Posts

Showing posts from 2012

You work in a company, and need to send an email to a user, and a copy of that email to your manager. Which code should you use?

A.  MailMessage msg = new MailMessage();
msg.From = "from@yourcompany.com";
msg.To = "to@to.com, manager@yourcompany.com";
msg.Subject = "...";
msg.Body = "...";
SmtpClient client = new SmtpClient();
client.Send(msg);
B.  MailMessage msg = new MailMessage("from@yourcompany.com", "to@to.com");
msg.CC.Add(new MailAddress("manager@yourcompany.com"));
msg.Subject = "...";
msg.Body = "...";
SmtpClient client = new SmtpClient();
client.Send(msg);
C.  MailMessage msg = new MailMessage("from@yourcompany.com", "to@to.com");
msg.CC.Add(new MailAddress("manager@yourcompany.com"));
msg.Subject = "...";
msg.Body = "...";
SmtpClient client = new SmtpClient();
msg.Send(client);
D.  MailMessage msg = new MailMessage();
msg.From = "from@yourcompany.com";
msg.To = "to@to.com, manager@yourcompany.com";
msg.Subject = "...";
msg.Body = ".…

You are developing a .NET assembly which will be used from both, .NET components and COM components. Which 3 utilities do you need to use to ensure that COM components can access your assembly as easily as possible?

·Signtool ·Gacutil ·Sn ·Tlbimp ·regasm

What are the restrictions imposed on the signature of a method that is called when a serialization event occurs?

A.  Must not have any parameters (void) B.  Must not return anything (void) C.  Must take a StreamingContext parameter D.  Must return a StreamingContext object

split a string with multiple separators in javascript?

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

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);
        }
    }

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…

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");

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"
OnClientClic…

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();
   fsPat…

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=&q…

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>

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>
                    …

SQL Bulk Copy with C#.Net

string strConnection = ConfigurationManager.ConnectionStrings["Connection"].ToString();
 SqlConnection con = new SqlConnection(strConnection);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from TableName", con);
        cmd.Connection = con;
        SqlDataReader dr = cmd.ExecuteReader();

        SqlConnection con2 = new SqlConnection(strConnection);
        con2.Open();
        SqlBulkCopy copy = new SqlBulkCopy(con2);

        copy.DestinationTableName = "DestinationTable";
        copy.WriteToServer(dr);
        dr.Close();
        con2.Close();
        con.Close();

Executing Stored Procedures in Parallel using ADO.NET

string Conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();

SqlConnection con = new SqlConnection(Conn);
        SqlCommand cmd1;
        SqlCommand cmd2;
        SqlDataReader reader1;
        SqlDataReader reader2;
        try
        {
            if (!IsPostBack)
            {

                cmd1 = new SqlCommand("Sp Name", con);
                cmd1.CommandType = CommandType.StoredProcedure;
                con.Open();
                reader1 = cmd1.ExecuteReader();
                if (reader1.Read())
                {
                    grd_View.DataSource = reader1;
                    grd_View.DataBind();
                }
               if (!reader1.IsClosed)
                {
                    reader1.Close();
                }

                cmd2 = new SqlCommand("Sp Name", con);
                cmd2.CommandType = CommandType.StoredProcedure;

                reader2 = cmd2.ExecuteReader();
                if (reader2.Re…

Copy a table into new table with/without data - SQL Server

Lets see how to copy an existing table to new table in SQL Server. There are two options. They are

Copy only the structure of an existing table into new table
Copy only the structure with data of an existing table into new tableCopy only the structure of an existing table into new table:

SELECT * INTO  NewTable  FROM OldTable WHERE 3=4
The above query will copy the structure of  an existing table(OldTable ) into the new table(NewTable).

Copy only the structure with data of an existing table into new table:

SELECT * INTO NewTable  FROM OldTable

This is also same like the previous query, but it copies the structure of existing table(OldTable) with data as well into the new table(NewTable)


When we write  SELECT 3 + NULL
The output is null

When we write SELECT * FROM TableName WHERE 1=1

It will display entire table data

phone number validation code in javascript

Example :(080) 235-4354

 function PhoneNumberValidation(e) {
            var keynum;
            var keychar;
            // For Internet Explorer
            if (window.event) {
                keynum = e.keyCode;
            }
            // For Netscape/Firefox/Opera
            else if (e.which) {
                keynum = e.which;
            }
            keychar = String.fromCharCode(keynum)
            var r = new RegExp("[0-9]", "g");
            if (keychar.match(r) == null) {
                return false;
            }
            else {
                var getValue = document.getElementById('ctl00_ContentPlaceHolder1_txtPhone').value;
                var s = getValue.length;
                if (s == 3) {
                    document.getElementById('ctl00_ContentPlaceHolder1_txtPhone').value = '(' + document.getElementById('ctl00_ContentPlaceHolder1_txtPhone').value + ') ';
                }
                if (s =…

Validate multiple email id's using javascript?

<script type="text/javascript">

        function isUrl(s) {

            var regexp = /\w+([-+.]\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*/
            return regexp.test(s);
        }


        function trim(text) {

            return text.replace(/^\s+|\s+$/g, "");
        }

        function checkUrls(sender, args) {

            var urls = document.getElementById('<%=txtMisspellvalue.ClientID %>').value;

            if (document.getElementById('<%=txtMisspellvalue.ClientID %>').value == null
                     || document.getElementById('<%=txtMisspellvalue.ClientID %>').value == "") {
                args.IsValid = false;
                return;
            }
            else {
                var textarea = document.getElementById('<%=txtMisspellvalue.ClientID %>');
                var isOk = true;

                var urlsArr = textarea.value.replace(/\r\n/g, "\n").split("\n");

 …

Clock on webpage using server and system time?

Default.aspx page
<table>
            <tr>
                <td>
                    Time: <span id="TimeDisplay"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </td>
            </tr>
   </table>

Default.aspx.cs file

 protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Convert.ToString(DateTime.Now.TimeOfDay);
        Response.Write("<script>var timeServer = new Date('" + DateTime.Now.ToString() + "');</script>");


         const string crlf = "\r\n";
        string jsscript = "<script type='text/javascript'>"
            + crlf + "window.onload=startclock;" + crlf + "var clock;" + crlf + "var time_di…

Create a Pivot Table from a DataTable using C# in Asp.net

Normal Table

CustomerName   Value
  Vinod                    25
  Sagar                     35
  Manu                     45

Pivot Table

Vinod    Sagar   Manu
   25           35        45


Public DataTable Pivot()
{
                DataTable dt = new DataTable();
                dt = "Fetch Data from Database"
                try
                {
                    DataTable dtData = new DataTable();
                    DataColumn col;
                    DataRow newRow;
                    for (int I = 0; I < dt.Columns.Count - 1; I++)
                    {
                        newRow = dtData.NewRow();
                        for (int J = 0; J < dt.Rows.Count; J++)
                        {
                         col = new DataColumn(dt.Rows[J][I].ToString(),Type.GetType("System.String"));
                            dtData.Columns.Add(col);
                        }
                    }

                    for (int I = 1; I <= dt.Columns.Count - 1; I++)
                  …

How to pivot a normal sql query with dynamic columns

Normal Table

id      Name    Marks   ddd
1    aaa    20    1
2    bbb    35    2
3    ccc    12    3
4    ddd    32    4
5    test    35    5

pivot Table

aaa     bbb     ccc     ddd     test
20    NULL    NULL    NULL    NULL
NULL    35    NULL    NULL    NULL
NULL    NULL    12    NULL    NULL
NULL    NULL    NULL    32    NULL
NULL    NULL    NULL    NULL    35


select * from dbo.[auto]
select aaa,bbb,ccc,ddd,test from dbo.[auto]
pivot(max(marks) for name in(aaa,bbb,ccc,ddd,test))as p

sorting and paging with gridview asp.net

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING);
        }
    }
    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private void SortGridView(string sortExpression, string sortDirection)
    {
        try
        {
            DataView dv = new DataView((DataTable)ViewState["gvDetails"])…

Union,Except and Intersect operator in Linq

char[] delimiters = new char[] { '\n', '\r', ',' };
                string[] strNewValue = txtvalue.Text.Trim().Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                string OldString = ViewState["OldMisspell"].ToString();
                string[] strOld = OldString.Trim().Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                DataTable dtMissingValue = new DataTable();
                dtMissingValue.Columns.Add("ColumnName", typeof(string));
                dtMissingValue.Columns.Add("ColumnName ", typeof(string));
                dtMissingValue.Columns.Add("ColumnName ", typeof(int));
                dtMissingValue.Columns.Add("ColumnName ", typeof(bool));

      var vDeleteingValues = OldString.Except(strNewValue).Select(s => new { ColumnName = s, ColumnName = 1 });
      var vNewValues = strNewValue.Except(strOld).Select(a => new { ColumnName = a, ColumnName = 0 });
      var…

Read And Write Text in text file in asp.net using C sharp

Post Data To Remote Server in asp.net

try
        {
            using (StreamReader reader = new StreamReader("Give file path" + "file name"))
            {
                filecontent = reader.ReadToEnd();
            }
            postData = @"file=" + HttpUtility.UrlEncode(filecontent) + "&submit=save";
            byte[] data = Encoding.ASCII.GetBytes(postData);
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("Remote Server path");
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = data.Length;
            Stream dataStream = webRequest.GetRequestStream();
            dataStream.Write(data, 0, data.Length);
            dataStream.Close();

            HttpWebResponse webResponse;
            webResponse = (HttpWebResponse)webRequest.GetResponse();
            Stream answer = webResponse.GetResponseStream();
            StreamReader _answ…

Download data using Web Browser in asp.net

private void runBrowserThread(string url)
        {
            try
            {
                var th = new Thread(() =>
                {
                    var br = new WebBrowser();
                    br.DocumentCompleted += browser_DocumentCompleted;
                    br.Navigate(url);
                    Application.Run();
                });
                th.SetApartmentState(ApartmentState.STA);
                th.Start();
            }
            catch (Exception ex)
            {

            }
        }
#region - Browser Event -
        void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {           
            try
            {
                string Downloaddata = string.Empty;
                HtmlDocument doc = ((WebBrowser)sender).Document;
                HtmlElementCollection textboxes = doc.GetElementsByTagName("textarea");
                foreach (HtmlElement textbox in textboxes)
                {
                    Downloadda…

Roll Back Deleted Data in sql

We shoule have Full permission of Database

 Select [RowLog Contents 0] FROM   sys.fn_dblog(NULL, NULL) WHERE  AllocUnitName = 'dbo.Employee'     
   AND Context IN ( 'LCX_MARK_AS_GHOST', 'LCX_HEAP' ) AND Operation in ( 'LOP_DELETE_ROWS' )

Check Duplicate And Delete Duplicate Rows in sql server

Image
We can remove duplicate values in sql server using table expression and row_number
SelectWebAddress,COUNT(*)fromdbo.CompanyInformation groupbyWebAddresshavingCOUNT(*)>1; WithCTSAs ( SelectROW_NUMBER()over(partitionbyCompanyorderbyCompany)asRowid,WebAddress fromdbo.CompanyInformation ) select*fromCTSwhereWebAddress='www.oracle.com' --delete from CTS where Rowid >1;