.NET Diary

October 9, 2013

static vs. const vs. readOnly

Filed under: All, ASP.NET, C# — Tags: , , , , , , , — leoullas @ 10:06 pm

static vs. const vs. readOnly static Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
const • Can’t be static. As it is static by default.
• Value is evaluated at compile time.  So, value can’t be changed at runtime.
• Must be initialized as they are declared.
• Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can’t set a constant to a class or structure.
readonly • Can be either instance-level or static.
• Value is evaluated at run time.  So, value can be changed at runtime.
• Can be initialized in declaration or by code in the constructor.
N.B: readonly exists solely to prevent anyone from, either accidentally or intentionally, changing the value of a variable once it’s set. It is enforced at run-time.
const is similar, but enforced at compile-time. Thus, the value must be set at the time the variable is created.
Advertisements

March 19, 2013

C# .NET Split Function : Inputs – source word and spliter and return – string array

Filed under: All, ASP.NET, C# — leoullas @ 2:36 pm

internal string[] Split(string sourceWord, char[] splitter)
{
string[] retWords = sourceWord.Split(splitter);
return retWords;
}

Ping Server from .NET C# Application to check up/down status

Filed under: All, C# — Tags: — leoullas @ 2:33 pm

internal bool PingServer(string IpAddress)
{
string strDot = “.”;
string[] retWords = Split(IpAddress, strDot.ToCharArray());

bool netOK = false;

byte[] AddrBytes = new byte[] { Convert.ToByte(retWords[0]),
Convert.ToByte(retWords[1]),
Convert.ToByte(retWords[2]),
Convert.ToByte(retWords[3]) }; // byte array for server address.

using (System.Net.NetworkInformation.Ping png = new System.Net.NetworkInformation.Ping())
{
System.Net.IPAddress addr;

addr = new System.Net.IPAddress(AddrBytes);

try
{
netOK = (png.Send(addr, 1500, new byte[] { 0, 1, 2, 3 }).Status == IPStatus.Success);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
netOK = false;
}
return netOK;
}
}

 

internal string[] Split(string sourceWord, char[] splitter)
{
string[] retWords = sourceWord.Split(splitter);
return retWords;
}

BackgroundWorker : The basics

Filed under: All, C# — leoullas @ 2:29 pm

1. Add in your Windows form:

Tools -> backgroundWorker1

2. Event: Introduce the activities in the event “backgroundWorker1_DoWork”

In my Start Process GUI button click, I am calling the followings to start the back process.

blStopBackTrackProcess = false;
backgroundWorker1.RunWorkerAsync();

Then, I have written a non-stop continuous process which is breaking on a boolean value change on my Stop Process GUI button click event.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

while (1==1){

Thread.Sleep(DRLib.ClConstants.Check_Interval_Second * 1000);
MessageBox.Show(“abcd” );
CheckNormalServers();

if (blStopBackTrackProcess == true)
break;
}
}

November 3, 2009

Generics

Filed under: All, ASP.NET, C# — leoullas @ 8:55 am

Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

C#

// Declare the generic class
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}
  • Use generic types to maximize code reuse, type safety, and performance.
  • The most common use of generics is to create collection classes.
  • The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
  • You can create your own generic interfaces, classes, methods, events and delegates.
  • Generic classes may be constrained to enable access to methods on particular data types.
  • Information on the types used in a generic data type may be obtained at run-time by means of reflection.

//For Interfaces
interface IComparable <T>
//for structs
struct HashBucket <K,D>
//for methods
static void Reverse <T> (T[] arr)
//for delegates
delegate void Action <T> (T arg)

Strongly TYPED & Loosely TYPED

Filed under: All, ASP.NET, C# — leoullas @ 8:49 am

Definition: A strongly typed programming languages is one that requires the type of a variable to be explicitly stated. C is a strongly typed language. You must declare the type of data a variable will store for C to interpret it:

int myVariable;
myVariable = 25;

Perl is a loosely typed language. There is no need to declare the variable type before using it:

$myVariable = 25;
$myVariable = “A String.”;

Basic dode to fetch data from sql server using select statement and put it in dataset using dataadapter

Filed under: All, ASP.NET, C# — leoullas @ 8:42 am

System.Data.SqlClient.SqlConnection objConnection;

System.Data.DataSet objDataSet = new DataSet();

System.Data.SqlClient.SqlDataAdapter objDataAdapter;

objConnection = new SqlConnection("data source=192.168.93.60; uid= tallyman; pwd= tallyman; database=Tallyman");

#region Either of these 2 works

//objDataAdapter = new SqlDataAdapter("Select top 5 id from accounts", "data source=192.168.93.60; uid= tallyman; pwd= tallyman; database=Tallyman");

objDataAdapter = new SqlDataAdapter("Select top 5 id from accounts", objConnection);

#endregion Either of these 2 works

objDataAdapter.Fill(objDataSet, "accountsData");

Console.Write(objDataSet.Tables["accountsData"].Rows.Count);

Console.Read();

October 28, 2009

DropDown List With HardCoded Values with Default Selected a value

Filed under: All, ASP.NET, C# — leoullas @ 10:41 am

There are two ways:

 

Way 1:

In aspx file:

     <td style=”width: 90px; height: 56px;” valign=”middle”>

        <asp:DropDownList ID=”ddlTime” runat=”server” Width=”131px” onchange=”clickClient();”  Height=”19px”>

</asp:DropDownList>

     </td>

In aspx.CS file:

    public static void PopulateDdlTime(DropDownList ddlTime)

    {

        ddlTime.Items.Add(new ListItem(“12:00AM–08:00AM”, “1200AM0800AM”));

        ddlTime.Items.Add(new ListItem(“08:00AM–04:00PM”, “0800AM0400PM”));

        ddlTime.Items.Add(new ListItem(DRISInternatiolization.DRISInternatiolization.GetLabelText(“464”), “Customize”));

        ddlTime.SelectedValue = “0800AM0400PM”;

    }

protected void Page_Load(object sender, EventArgs e)

       {

PopulateDdlTime(ddlTime);

……

……

}

Way 2:

In aspx file:

<td style=”width: 90px; height: 56px;” valign=”middle”>

    <asp:DropDownList ID=”ddlTime” runat=”server” Width=”131px” onchange=”clickClient();” Height=”19px”>

                  <asp:ListItem Value=”1200AM0800AM”>12:00AM–08:00AM</asp:ListItem>

                  <asp:ListItem Value=”0800AM0400PM” Selected=”True”>08:00AM–04:00PM</asp:ListItem>

                  <asp:ListItem Value=”Customize”>Customize…</asp:ListItem>

    </asp:DropDownList>

</td>

Problem: Cant delete after copying FileInfo “The process cannot access the file because it is being used by another process.”

Filed under: All, ASP.NET, C# — leoullas @ 10:34 am

Solution:

You might have not disposed while reading/writing.
Use either of these two:

1.

StreamWriter objStreamWriterUp = null;

TextReader objTextReaderUp = null;

try

{

using (objTextReaderUp = new StreamReader(sourceFilePath)) 

{

using (objStreamWriterUp

= new StreamWriter(destiFilePath, !blIsFirstTimeCl))

{

//your code

}

}

}

catch (Exception ex)

{

throw;

}

finally

{

 

if (objStreamWriterUp != null)

{

                    objStreamWriterUp.Dispose();

}

       }

2.

StreamWriter objStreamWriterUp = null;

TextReader objTextReaderUp = null;

try

{

objTextReaderUp = new StreamReader(sourceFilePath);

objStreamWriterUp = new StreamWriter(destiFilePath, !blIsFirstTimeCl);

//your code

}

catch (Exception ex)

{

throw;

}

finally

{

 

if (objTextReaderUp != null)

{

objTextReaderUp.Dispose();

}

 

if (objStreamWriterUp != null)

{

objStreamWriterUp.Dispose();

}

       }

  

 

January 21, 2009

Textbox getting emptied (Passwords etc) while button clicking: Solution

Filed under: All, ASP.NET, C# — leoullas @ 10:10 am

 Put the following piece of code in your aspx.cs file where the pwd-text is getting emptied.

        if (txtPassword.Text != string.Empty)

        {

            txtPassword.Attributes.Add(“value”, txtPassword.Text);

        }

        if (txtConfirmPwd.Text != string.Empty)

        {

            txtConfirmPwd.Attributes.Add(“value”, txtConfirmPwd.Text);

        }

Older Posts »

Blog at WordPress.com.

%d bloggers like this: