IT Community - Software Programming, Web Development and Technical Support

C# .Net Tips & Tricks

This is a discussion on C# .Net Tips & Tricks within the C# Programming forums, part of the Software Development category; Getting IP address given the host name using System.Net; public string GetIPAddress(string sHostName) { IPHostEntry ipEntry = Dns.GetHostByName(sHostName); ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > C# Programming

Register FAQ Members List Calendar Mark Forums Read
  #41 (permalink)  
Old 11-27-2007, 09:27 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: C# .Net Tips & Tricks

Getting IP address given the host name
using System.Net;
public string GetIPAddress(string sHostName)
{
IPHostEntry ipEntry = Dns.GetHostByName(sHostName);
IPAddress [] addr = ipEntry.AddressList;
string sIPAddress = addr[0].ToString();
return sIPAddress;
}
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #42 (permalink)  
Old 11-28-2007, 03:33 AM
sathian sathian is offline
D-Web Analyst
 
Join Date: Aug 2007
Posts: 252
sathian is on a distinguished road
Default Re: C# .Net Tips & Tricks

Get environment conscious

If you are not yet environment conscious, it's time to be. First, thank God. This is something we always need to look up. Now with .NET, we have a single class which lets us access all this wealth of information. What are you looking for? The OS version, CLR version, user name, values of system variables such as the temp folder, physical memory mapped to your app?

All this valuable information can be extracted with the Environment class as illustrated below:
Collapse

using System;
public static void GetEnvironmentInfo()
{
// Fully qualified path of the current directory
Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
// Gets the NetBIOS name of this local computer
Console.WriteLine("MachineName: {0}", Environment.MachineName);
// Version number of the OS
Console.WriteLine("OSVersion: {0}", Environment.OSVersion.ToString());
// Fully qualified path of the system directory
Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
// Network domain name associated with the current user
Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
// Whether the current process is running in user interactive mode
Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
// User name of the person who started the current thread
Console.WriteLine("UserName: {0}", Environment.UserName);
// Major, minor, build, and revision numbers of the CLR
Console.WriteLine("CLRVersion: {0}", Environment.Version.ToString());
// Amount of physical memory mapped to the process context
Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet);
// Returns values of Environment variables enclosed in %%
Console.WriteLine("ExpandEnvironmentVariables: {0}",
Environment.ExpandEnvironmentVariables("System drive: " +
"%SystemDrive% System root: %SystemRoot%"));
// Array of string containing the names of the logical drives
Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ",
Environment.GetLogicalDrives()));
}

The above function will work with console applications only (as it has Console.Writelines). For your use, modify it the way you need.

Thanks
Sathian.K
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #43 (permalink)  
Old 11-28-2007, 03:36 AM
sathian sathian is offline
D-Web Analyst
 
Join Date: Aug 2007
Posts: 252
sathian is on a distinguished road
Default Re: C# .Net Tips & Tricks

Use the StringBuilder class.

Strings are immutable in the .NET framework. This means that methods and operators which appear to change the string are actually returning a modified copy of the string. This has significant performance implications. When doing a lot of string manipulation, it is much better to use the StringBuilder class.

Consider the code shown in the following code listing (in C#). It measures the time to create a string from 10,000 substrings in two different ways. The first time, a simple string concatenation is used; the second time the StringBuilder class is used. To see the resulting string, uncomment the two commented lines in the code.


<%@ Page Language="C#" %>

<script runat="server">
void Page_Load(Object Source, EventArgs E)
{
int intLimit = 10000;
DateTime startTime;
DateTime endTime;
TimeSpan elapsedTime;
string strSub;
string strWhole = "";

// Do string concat first
startTime = DateTime.Now;
for (int i=0; i < intLimit; i++)
{
strSub = i.ToString();
strWhole = strWhole + " " + strSub;
}
endTime = DateTime.Now;
elapsedTime = endTime - startTime;
lblConcat.Text = elapsedTime.ToString();
// lblConcatString.Text = strWhole;

// Do stringBuilder next
startTime = DateTime.Now;
StringBuilder sb = new StringBuilder();
for (int i=0; i < intLimit; i++)
{
strSub = i.ToString();
sb.Append(" ");
sb.Append(strSub);
}
endTime = DateTime.Now;
elapsedTime = endTime - startTime;
lblBuild.Text = elapsedTime.ToString();
// lblBuildString.Text = sb.ToString();
}

</script>

<html>
<body>
<form runat="server">

<h1>String Concatenation Benchmark</h1>

Concatenation:
<asp:Label
id="lblConcat"
runat="server"/>

<br/>

<asp:Label
id="lblConcatString"
runat="server"/>

<br/>
<br/>

StringBuilder:
<asp:Label
id="lblBuild"
runat="server"/>

<br/>

<asp:Label
id="lblBuildString"
runat="server"/>

</form>
</body>
</html>

The difference between the two techniques is fairly dramatic: the StringBuilder's Append method is nearly 200 times faster than string concatenation

Thanks
Sathian.K
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #44 (permalink)  
Old 11-28-2007, 03:40 AM
sathian sathian is offline
D-Web Analyst
 
Join Date: Aug 2007
Posts: 252
sathian is on a distinguished road
Default Re: C# .Net Tips & Tricks

Comment your code.

This tip is not specific to ASP.NET, but rather is just good programming practice. Remember Alzheimer's Law of Programming. If you don't remember it, look at the end of the first tip in this article.

Comments should not only clarify what is going on, but also why. For example, don't just say you are iterating through an array. Say you are iterating through an array to compute a value according to an algorithm, then include the algorithm in the comment unless it is crystal clear from the code. It is often helpful to include a comment block at the beginning of a method that provides an overview of what the method does.

The different languages you may run across in a typical .NET project each have their own commenting syntax.

HTML : <!-- the comment -->
JavaScript : // the comment
VBScript :' the comment
VB.NET :' the comment
C# :// the comment
/* a multiline comment
goes between the two ends */
SQL :-- the comment

There is no comment syntax inside the opening and closing tags of a server control. However, the server ignores any attributes it does not recognize, so you can insert comments by using an undefined attribute, as in:


<asp:TextBox
id="txtName"
comment="This is my comment"
runat="server" />

Visual Studio .NET makes it easy to comment your source code. Highlight the line(s) to be commented and press Ctrl+K+C to comment the lines. To uncomment, highlight the commented code and press Ctrl+K+U.

In C# projects, you can also enter XML comment sections in your Visual Studio .NET projects using three slashes (///) at the beginning of each line in the section. Within the commented section, you can use the following XML tags to organize your comments:

* <summary></summary>
* <remarks></remarks >
* <param></param>
* <returns></returns>
* <newpara></newpara>

To view a formatted report of these XML comments in Visual Studio .NET, go to the Tools menu item, then select Build Comment Web Pages.

Thanks
Sathian.K
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #45 (permalink)  
Old 11-28-2007, 03:43 AM
sathian sathian is offline
D-Web Analyst
 
Join Date: Aug 2007
Posts: 252
sathian is on a distinguished road
Default Re: C# .Net Tips & Tricks

Use stored procedures.

Microsoft SQL Server and other modern relational databases use SQL statements to define and process queries. When a SQL statement or set of SQL statements are submitted to the SQL Server, the statements are parsed, a query plan is created and optimized, and the query is executed. This takes time.

A stored procedure is a set of SQL statements that have been pre-parsed and pre-optimized by the query processor, and stored so they are ready for quick execution. Stored procedures, often called sprocs, can be written to accept input parameters, allowing a single sproc to handle a wide range of specific queries.

Because sprocs are parsed in advance, and, more important for complex queries, have their query plans pre-optimized, calling a sproc is much faster than executing the same SQL statements outside of a sproc.

Thanks
Sathian.K
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #46 (permalink)  
Old 11-28-2007, 03:44 AM
sathian sathian is offline
D-Web Analyst
 
Join Date: Aug 2007
Posts: 252
sathian is on a distinguished road
Default Re: C# .Net Tips & Tricks

Test for postback on page load.

Every time a Button, LinkButton, or ImageButton is clicked on a Web page, the form is posted back to the server. Many other controls, such as CheckBox and CheckBoxList, will also cause a form to post back to the server when a change is made to the state of the control, if the AutoPostBack property of the control is set to true.

Every time a form is posted back to the server, it is reloaded and the Page_Load event fires, causing any code in the Page_Load event handler to execute. This is an excellent place to put initialization code for the page. However, you often want some code to execute every time the page loads, other code to execute only the first time the page loads, and even other code to execute every time the page loads except the first time.

This can be accomplished using the IsPostBack property. This property is false the first time the page is loaded. If the page is reloaded due to a postback, the IsPostBack property is true. By testing, you can cause specific lines of code to execute only when desired. Consider the following code snippet (in C#):


protected void Page_Load(Object sender, EventArgs e)
{
// Do stuff here every time the page loads
if (!IsPostBack)
{
// Do stuff here the first time the page loads only
}
else
{
// Do stuff here on postback only
}

// Do more stuff here every time the page loads
}

You want to postback as seldom as possible (each postback requires a round trip to the server) and when you do postback you want to do as little work as possible. Large, time-consuming operations (such as database look-ups) should be especially avoided, because they drive down the responsiveness of your program.

Thanks
Sathian.K
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #47 (permalink)  
Old 12-14-2007, 05:15 AM
Balasubramanian.S Balasubramanian.S is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 182
Balasubramanian.S is on a distinguished road
Default Re: C# .Net Tips & Tricks

Hi,

This project is used to read the xml value using c#.

Create xml like:

<India>
<State>Tamil Nadu</State>
<State>Andhra Pradesh</State>
<State>Karnataka</State>
<State>Maharastira</State>
<State>Kerala</State>
<State>West Bengal</State>
<State>Misoram</State>
<State>Kashmir</State>
</India>


In the aspx.cs file copy the following code:


protected void Page_Load(object sender, EventArgs e)
{
Response.Write(ReadXML(Server.MapPath("reader.xml" )));
}
public string ReadXML(string xmlUrl)
{
System.Text.StringBuilder sbXML = new System.Text.StringBuilder();
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlUrl);

object oProvinceName = reader.NameTable.Add("State");

while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name.Equals(oProvinceName))
{
sbXML.Append(reader.ReadString()).Append("<br />");
}
}
}
return sbXML.ToString();
}
catch (Exception e)
{
Response.Write(e.Message);
return "";
}
finally
{

if (reader != null)
reader.Close();
}
}
__________________
S.Balasubramanian
Nothing is impossible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #48 (permalink)  
Old 12-14-2007, 05:16 AM
Balasubramanian.S Balasubramanian.S is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 182
Balasubramanian.S is on a distinguished road
Default Re: C# .Net Tips & Tricks

Hi,

This sample is used to extract a numbers from a string in C# using Regular Expression.

string value = "bku564dr43";
foreach (char c in value)
{
Match MyRegMatch = Regex.Match(c.ToString(), "^[0-9]$");
if (MyRegMatch.Success)
{
Response.Write(c.ToString());
}
}
__________________
S.Balasubramanian
Nothing is impossible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #49 (permalink)  
Old 12-18-2007, 11:42 PM
Balasubramanian.S Balasubramanian.S is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 182
Balasubramanian.S is on a distinguished road
Default Re: C# .Net Tips & Tricks

Hi,

This is a simple way to split a string for every UpperCase

string value = "balHHYHYggGG";
foreach (char c in value)
{
Match MyRegMatch = Regex.Match(c.ToString(), "^[A-Z]$");
if (MyRegMatch.Success)
{
Response.Write(c);
}
}
__________________
S.Balasubramanian
Nothing is impossible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #50 (permalink)  
Old 12-19-2007, 05:19 AM
santhakumar santhakumar is offline
D-Web Genius
 
Join Date: Mar 2007
Posts: 927
santhakumar is on a distinguished road
Default Re: C# .Net Tips & Tricks

checking querystring value in c#

if (Request.QueryString["id"] != null)
{
// if condition
}
else
{
// else part
}
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #51 (permalink)  
Old 12-24-2007, 04:43 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

Is there an equivalent of exit() for quitting a C# .NET application?

Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it's a Windows Forms app.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #52 (permalink)  
Old 12-24-2007, 04:44 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

Does C# support properties of array types?

Yes. Here's a simple example: using System;
class Class1
{
private string[] MyField;
public string[] MyProperty
{
get { return MyField; }
set { MyField = value; }
}
}
class MainClass
{
public static int Main(string[] args)
{
Class1 c = new Class1();
string[] arr = new string[] {"apple", "banana"};
c.MyProperty = arr;
Console.WriteLine(c.MyProperty[0]); // "apple"
return 0;
}
}
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #53 (permalink)  
Old 12-24-2007, 04:45 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #54 (permalink)  
Old 12-24-2007, 04:47 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

What is a satellite assembly?

When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #55 (permalink)  
Old 12-24-2007, 04:47 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

How do I register my code for use by classic COM clients?

Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #56 (permalink)  
Old 12-24-2007, 04:48 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?

When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #57 (permalink)  
Old 12-24-2007, 04:49 AM
sureshbb sureshbb is offline
D-Web Sr.Programmer
 
Join Date: Aug 2007
Posts: 149
sureshbb is on a distinguished road
Default Re: C# .Net Tips & Tricks

How do I do implement a trace and assert?

Use a conditional attribute on the method, as shown below:
class Debug
{
[conditional("TRACE")]
public void Trace(string s)
{
Console.WriteLine(s);
}
}
class MyClass
{
public static void Main()
{
Debug.Trace("hello");
}
}
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #58 (permalink)  
Old 12-25-2007, 09:38 PM
Balasubramanian.S Balasubramanian.S is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 182
Balasubramanian.S is on a distinguished road
Default Re: C# .Net Tips & Tricks

A class implement multiple interfaces containing methods with identical signatures.

you have two interfaces (I1 & I2) that both contain a Send method with the same signature (identical method name, same return type, same argument types in the same order:

public interface I1
{
int Send(int id);
}

public interface I2
{
int Send(int id);
}

If you don't care which interface was used to make the call to the Send method, just implement the method:

public class c1 : I1, I2
{
int Send(int id)
{
return 0;
}
}

If you do care about which interface was used to make the Send call, use Explicit Interface Implementation by specifying the interface name before the method name (I1.Send, I2,Send):

public class c1 : I1, I2
{
int I1.Send(int id)
{
return 1;
}

int I2.Send(int id)
{
return 2;
}
}
__________________
S.Balasubramanian
Nothing is impossible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #59 (permalink)  
Old 12-28-2007, 01:00 AM
Balasubramanian.S Balasubramanian.S is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 182
Balasubramanian.S is on a distinguished road
Default Re: C# .Net Tips & Tricks

Creating Event Log in Windows service.

if (!EventLog.SourceExists("eventLog1"))
{
EventLog.CreateEventSource("eventLog1", "eventLog1");
}
eventLog = new EventLog("eventLog1", Environment.MachineName, "eventLog1");

eventLog.WriteEntry("Service Started");
__________________
S.Balasubramanian
Nothing is impossible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #60 (permalink)  
Old 12-28-2007, 01:01 AM
Balasubramanian.S Balasubramanian.S is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Posts: 182
Balasubramanian.S is on a distinguished road
Default Re: C# .Net Tips & Tricks

Connecting MS-Access database in C#.

OleDbConnection conn;
OleDbCommand comm;
OleDbDataReader dr;
conn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = address.mdb");
comm = new OleDbCommand("Select * from Table1", conn);
conn.Open();
dr = comm.ExecuteReader();
DataGrid1.DataSource = dr;
DataGrid1.DataBind();
conn.Close();
__________________
S.Balasubramanian
Nothing is impossible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

LinkBacks (?)
LinkBack to this Thread: http://www.discussweb.com/c-programming/3129-c-net-tips-tricks.html
Posted By For Type Date
DiscussWeb IT Community - Technical Support and Technology Discussions This thread Refback 08-18-2007 04:01 AM

Similar Threads
Thread Thread Starter Forum Replies Last Post
SAP Tips & Tricks leoraja8 Operating Systems 0 03-29-2008 01:11 AM
BlueTooth tips and tricks devarajan.v Mobile Software Development 52 03-13-2008 10:46 PM
PHP Tips and Tricks Sabari PHP Programming 20 12-18-2007