Like it

Showing posts with label C# tips. Show all posts
Showing posts with label C# tips. Show all posts

Sunday, July 17, 2011

A Simple Splash screen in C#

I started my .net career in VB.Net. While developing a windows application in VB.Net it is pretty easy to put a Splash screen. There is Project property called Splash screen and you can put any form there, after that the specified form will act as a Splash screen. But when I started an windows application in C#, there is no project property called Splash screen. While doing some searching, I found lot of ways, like Putting a timer and closing the splash etc. But I feel like it is not the right way of doing a splash screen, then I started my own implementation and found one. I am not sure it is good one or not, but it is working for me.

Here is the steps:

1) Added one Form with an Image, as Splashscreen.cs, and my main UI is Welcome.cs
2) In the Program.cs I modified the code like the following

[STAThread]
static void Main()
{
    Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    SplashScreen s = new SplashScreen();
    s.Show();
    Welcome welcome = new Welcome(s);
    Application.Run(welcome);
}

3) And in the Welcome.cs, added one parameterized constructor, with SplashScreen as the Parameter

SplashScreen _s = null;
public Welcome(SplashScreen s)
{
    InitializeComponent();
    this._s = s;
}

4) And in the Form_Load() event I added code to close the splash screen if exists.

if (this._s != null) { this._s.Close(); }

5) Run the application, see the splash is coming and after that Main UI is coming

Sunday, July 10, 2011

Queue in C# / Add and Remove items from Queue in C# (.NET)

Queues are common in real world - Flight checkins to School. Here is the way you can use it in C#

private static void CustomerServiceQueue() 
{ 
Queue CSQ = new Queue(); 
CSQ.Enqueue("Sid"); 
CSQ.Enqueue("Nad"); 
CSQ.Enqueue("Am"); 
CSQ.Enqueue("Sam"); 
Console.WriteLine("Peeking Queue: {0}", CSQ.Peek()); 
Console.WriteLine("Check if CSQ Contains Sid: {0}", CSQ.Contains("Sid"));
while (CSQ.Count > 0) 
{ 
Console.WriteLine(CSQ.Dequeue()); 
} 
}
Contains checks for presence of the given object in the queue. Peek returns the first element from the queue

Dequeuue does the same as Peek, however, it also removes the object


System.Xml.Serialization.XmlSerializer.XmlSerializer() is inaccessible due to its protection level

One reason for this error is if you haven't mentioned the type when you initialize the XmlSerializer object

XmlSerializer Xser = new XmlSerializer()  

can be replaced with

XmlSerializer Xser = new XmlSerializer(this.GetType() );  


How to Write Padded (Formatted) Text File using VB.NET/C#

Writing Equi-Spaced Output using C# and VB.NET

Here is a small code to write a multiplication table.

For i1 As Integer = 1 To 20

Console.WriteLine(i1.ToString & " x 12 = " & (i1 * 12).ToString)

Next i1




Have you ever thought it would be better to have it properly aligned. Then use the Padding options (PadeLeft here) to format the output



Private Sub WritePaddedText() 
' Write a Padded Multiplication Table 
For i1 As Integer = 1 To 20 
Console.WriteLine(i1.ToString.PadLeft(2) & " x  12 = " & (i1 * 12).ToString.PadLeft(3))          Next i1      End Sub  




How to CreateFolder in C# (.NET) / How to Create a Directory in C# (VB.NET)

How to check if a directory exists in C# / How to check if a folder exists in C#

Many times backups are created in a new folder with name as date etc. The following snippet checks if directory exists in the particular path and creates it

private static void CreateFolder() 
//This example creates a new folder under MyDocuments 
string folderName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string userName = Environment.UserName; 
folderName = Path.Combine(folderName, userName); 
if (Directory.Exists(folderName) == false) 
Directory.CreateDirectory(folderName); 
}  

How to combine two paths in .NET

The example combines two paths using Path.Combine method.



How to Override ToString Method in C# (VB.NET)

Customize ToString Method in C# (VB.NET)

Overriding ToString Method has its own advantages.

For example, the following class has four fields

public class ClassExec 
string _Name; 
public string Name 
get { return _Name; } 
set { _Name = value ;} 
public string Source 
get; 
set; 
public string Destination 
{ get; set; } 
public DateTime  DOT 
get; 
set; 
}  

If you try to use the ClassExec.ToString() method it will return the fully qualified Class name as default. This doesn't help us much.

Instead let us override the ToString method to return the four fields in a formatted way

public override string ToString() 
return (Name + ' ' + Source + ' ' + Destination + ' ' + DOT); 
}  

The following code will now produce the desired output:

ClassExec cls = new ClassExec(); 
cls.Name = "Nadir"; 
cls.Source = "Only-dotnet"; 
cls.Destination = "Sydney"; 
cls.DOT = DateTime.Parse("12-Jan-2012"); 
Console.WriteLine(cls.ToString());



ForEach Loop in Array (C# / VB.NET)

How to iterate elements of Array using ForEach in .NET (C#)

Here is a simple example of that:

string[] arString = null; 
arString = new string[2]; 
arString[0] = "First Element"; 
arString[1] = "Second Element"; 
foreach (string s1 in arString) 
Console.WriteLine(s1); 
}  

Select Case Statement in C# / C-sharp

Switch Case Statement in C# (.NET)

Here is an example of Select Case like construct using C#:

private string ShirtSizes(int ShirtSize) 
switch (ShirtSize) 
case 36: 
return "Small"; 
case 38: 
return "Medium"; 
case 40: 
return "Large"; 
case 42: 
return "Extra Large"; 
case 44: 
return "XXL"; 
default: 
return "Free Size"; 
}  

Fall-Thru in Switch Case Statement in C#(Csharp)

Fall through can be achieved as follows:

switch (ShirtSize) 
case 34: 
case 35: 
case 36: 
return "Small"; 
case 38: 
return "Medium";  ...   

The Switch construct requires jump statements like GoTo or Break to transfer control outside the loop. Else it will throw an Error Control cannot fall through from one case label ### to another

To avoid this use break / goto statements. On the other hand if you use more than one jump statement for a case - like the one shown below - you will get Unreachable code detected warning

case 38: 
return "Medium"; 
break;                 


How to get number of Sundays/Saturdays in a given month using (C#/VB.NET)

Retrieve No of Fridays for the Current Month.

If you come across a situation where you need to know the number of Fridays/Sundays etc for a given month you can use the following snippet.

private void NoOfSpecificDaysThisMonth() 
int iDayCnt = 4; 
// Defaults to four days 
DayOfWeek dw = DayOfWeek.Wednesday; 
DateTime firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); 
int iRemainder = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) % 7; 
if ((dw >= firstDay.DayOfWeek) & ((dw - firstDay.DayOfWeek) < iRemainder)) 
iDayCnt = iDayCnt+1; 
else 
if ((dw < firstDay.DayOfWeek) & ((7+ dw - firstDay.DayOfWeek) < iRemainder)) 
iDayCnt = iDayCnt + 1; 
MessageBox.Show(iDayCnt.ToString()); 
}    
The above gives the No Of Wednesdays for the Current month. If you want for any specific month / year you can tweak it a bit like:


DateTime firstDay = new DateTime(2012, DateTime.Now.Month, 1); 
int iRemainder = DateTime.DaysInMonth(2012, DateTime.Now.Month) % 7;  

Other links that might be relevant:



Mod Functon in C# (Csharp)

Mod Operator in C#

Here is the code for Mod function in C#. Have given two ways. The first one is the C % operator

private void ModFunctionCsharpExample() 
int iRemainder = 31 % 3; 
MessageBox.Show("Remainder is " + iRemainder.ToString()); 
int iQuotient = Math.DivRem(31, 3, out iRemainder); 
MessageBox.Show("Remainder is " + iRemainder.ToString() + 
" and the Quotient is " + iQuotient); 
}    

Friday, July 8, 2011

 Read XML from Url into Dataset:

 System.Net.WebRequest webReq = System.Net.WebRequest.Create(rssUrl);
 System.Net.WebResponse webRes = webReq.GetResponse();
 System.IO.Stream mystream = webRes.GetResponseStream();
 DataSet ds = new DataSet();
 ds.ReadXml(mystream);