Category: C#

Back to Basic: Passing Parameter to method

What could be output of below code block:-

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Int32 varInt = 0;
        String strTestString = String.Empty;
        strTestString = “Before Function Call String Object”;
        varInt = 987;
        test userObj = new test();
        userObj.n = 34;
        userObj.str = “Before Function call Test Object”;
        check(userObj, varInt,strTestString);
        Response.Write(“
“+userObj.n);
        Response.Write(“
” + userObj.str);
        Response.Write(“
” + varInt);
        Response.Write(“
” + strTestString);
    }
    public void check(test userObjRec,int varIntRec,String strTestStringRec)
    {
        userObjRec.n = 110;
        userObjRec.str = “After Function call Test Object”;
        varIntRec = 555;
        strTestStringRec = “After Function Call String Object”;
    }
}
public class test
{
   public int n;
   public String str;

}
.
.
Output
    V

.
.
.
.
.
.
.
.
.
.
.
.
.
Output:-

110
After Function call Test Object
987
Before Function Call String Object

C# Delegate to perform asynchronous method calls

Paste below code in  VS 2010 console application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectDelegateAsync
{
    class Program
    {
        public delegate void LongTimeTask_Delegate(string s);
        public delegate void LongTimeTask_Delegate1(string s);
        static void Main(string[] args)
        {
            LongTimeTask_Delegate d = null;
            d = new LongTimeTask_Delegate(LongTimeTask);

            IAsyncResult R = null;
            R = d.BeginInvoke(“TestString”, null, null); //invoking the method

             LongTimeTask_Delegate1 d1 = null;

             d1 = new LongTimeTask_Delegate1(LongTimeTask1);

             IAsyncResult R1 = null;

             R1 = d1.BeginInvoke(“TestString”, null, null); //invoking the method

             Console.WriteLine(“last line of program”);
             Console.ReadLine();
        }
        public static void LongTimeTask(strings)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write(” i:” + i);
            }
        }
        public static void LongTimeTask1(strings)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write(” jj:” + i);
            }
        }
    }
}

Output:-

last line of program
 jj:0 jj:1 i:0 jj:2 jj:3 jj:4 jj:5 jj:6 jj:7 jj:8 jj:9 jj:10 jj:11 jj:12 jj:13 j
j:14 jj:15 jj:16 jj:17 jj:18 jj:19 jj:20 jj:21 jj:22 jj:23 jj:24 jj:25 jj:26 jj:
27 jj:28 jj:29 jj:30 jj:31 jj:32 jj:33 jj:34 jj:35 jj:36 jj:37 i:1 i:2 i:3 i:4 i
:5 i:6 i:7 i:8 i:9 i:10 i:11 i:12 i:13 i:14 i:15 i:16 i:17 i:18 i:19 i:20 i:21 i
:22 i:23 i:24 i:25 i:26 i:27 i:28 i:29 i:30 i:31 i:32 i:33 i:34 i:35 i:36 i:37 i
:38 i:39 i:40 i:41 i:42 i:43 i:44 jj:38 jj:39 jj:40 jj:41 jj:42 jj:43 jj:44 jj:4
5 jj:46 jj:47 jj:48 jj:49 jj:50 jj:51 jj:52 jj:53 jj:54 jj:55 jj:56 jj:57 jj:58
jj:59 jj:60 jj:61 jj:62 jj:63 jj:64 jj:65 jj:66 jj:67 jj:68 jj:69 jj:70 jj:71 jj
:72 jj:73 jj:74 jj:75 jj:76 jj:77 jj:78 jj:79 jj:80 jj:81 jj:82 jj:83 jj:84 jj:8
5 jj:86 jj:87 jj:88 jj:89 jj:90 jj:91 jj:92 jj:93 jj:94 jj:95 jj:96 jj:97 jj:98
jj:99 i:45 i:46 i:47 i:48 i:49 i:50 i:51 i:52 i:53 i:54 i:55 i:56 i:57 i:58 i:59
 i:60 i:61 i:62 i:63 i:64 i:65 i:66 i:67 i:68 i:69 i:70 i:71 i:72 i:73 i:74 i:75
 i:76 i:77 i:78 i:79 i:80 i:81 i:82 i:83 i:84 i:85 i:86 i:87 i:88 i:89 i:90 i:91
 i:92 i:93 i:94 i:95 i:96 i:97 i:98 i:99

On Enter Button click redirect with querystring as textbox value

put your text box and button in panel with default button


   
   

OR

<script>

     functionbutton_click(objTextBox, objBtnID) {
         if (window.event.keyCode == 13) {
             if (objTextBox.value != “”) {
                 document.getElementById(objBtnID).focus();
                 document.getElementById(objBtnID).click();
             }
            
         }
      }
    </script>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
    <asp:Button ID=”Button1″ runat=”server” Text=”Button” onclick=”Button1_Click” />
Page load:-
this.TextBox1.Attributes.Add(“onkeypress”, “button_click(this,'” + this.Button1.ClientID + “‘)”);
protected void Button1_Click(object sender, EventArgse)
    {
        if (!string.IsNullOrEmpty(TextBox1.Text))
        {
            Response.Redirect(“Default2.aspx?text=”+ TextBox1.Text);
        }
    }

Logging error to text file c#.Net

1. Add new static “ErrorLoging” class to solution and paste the below code in cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Diagnostics;

///

/// class contain methode for logging WriteToErrorLogFile_Trace(string)
///

public  static class ErrorLoging
{
    ///

    /// log error to path metion in web.config file for key “ErrorFolderPath”.
    /// new file will be created for each day
    ///

    /// error msg to log.
    /// exception object, Pass null to just log some msg.
    public static void WriteToErrorLogFile_Trace(string msg,Exception ex)
    {
        try
        {
            if (!System.IO.Directory.Exists(System.Configuration.ConfigurationManager.AppSettings[“ErrorFolderPath”] + “\\Errors\\”))
            {
                System.IO.Directory.CreateDirectory(System.Configuration.ConfigurationManager.AppSettings[“ErrorFolderPath”] + “\\Errors\\”);
            }
            //if (!System.IO.File.Exists(Application.StartupPath + “\\Errors\\” + DateTime.Today.Date.ToString().Replace(‘/’, ‘ ‘).Replace(‘:’, ‘ ‘)+”.txt”))
            //{
            //    System.IO.File.Create(Application.StartupPath + “\\Errors\\” + DateTime.Today.Date.ToString().Replace(‘/’, ‘ ‘).Replace(‘:’, ‘ ‘) + “.txt”);
            //}

            FileStream fs1 = new FileStream(System.Configuration.ConfigurationManager.AppSettings[“ErrorFolderPath”] + “\\Errors\\” + DateTime.Today.Year.ToString() + DateTime.Now.ToString(“MM”) + DateTime.Now.ToString(“dd”) + “.txt”, FileMode.Append, FileAccess.Write);
            StreamWriter s1 = new StreamWriter(fs1);

            s1.WriteLine(“==================” + DateTime.Now.ToString() + “===========================” + System.Environment.NewLine);
            s1.WriteLine(msg + System.Environment.NewLine);

            if (ex != null)
            {
                // Get stack trace for the exception with source file information
                var st = new StackTrace(ex, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);

                s1.WriteLine(“Line Number:” + System.Environment.NewLine + frame.GetFileLineNumber() + System.Environment.NewLine);
                s1.WriteLine(“File Name:” + System.Environment.NewLine + frame.GetFileName() + System.Environment.NewLine);
                s1.WriteLine(“Message:” + System.Environment.NewLine + ex.Message + System.Environment.NewLine);
                s1.WriteLine(“Methode:” + System.Environment.NewLine + ex.TargetSite + System.Environment.NewLine);
                s1.WriteLine(“Source:” + System.Environment.NewLine + ex.Source + System.Environment.NewLine);
                s1.WriteLine(“InnerException:” + System.Environment.NewLine + ex.InnerException + System.Environment.NewLine);
                s1.WriteLine(“StackTrace:” + System.Environment.NewLine + ex.StackTrace + System.Environment.NewLine);
            }
            s1.WriteLine(“================================================================” + System.Environment.NewLine);

            s1.Close();
            fs1.Close();
        }
        catch (Exception e)
        {

            throw e;
        }

    }
}

2. add follwing key in web.config <appSettings>
<appSettings>
    <add key=ErrorFolderPath value=d:\ErrorLogFolder/>
  </appSettings>

3. Add below code on your page/user control cs file

///

    /// calls static error log method
    ///

    /// specific developer msg for logging
    /// Exception object
    /// true if want to throw exception to user
    public voidLogError(string msg, Exceptionex,bool showUser)
    {
        ErrorLoging.WriteToErrorLogFile_Trace(msg + System.Environment.NewLine+“Show User:”+showUser, ex);
        if(showUser)
        {
            throwex;
        }
    }

4. Write below in all your catch
try
{
}
catch(Exception ex)
{
 LogError(“error on my code”,ex,false);
}