A Developer Journey who codes for fun

Daily Dose Of Code

  • Home
  • Dot.Net Basics
    • .Net Basics
      • CTS
      • CLS
      • CLR
      • Strong Vs Weak Ref
      • .Net Framework
      • What is Manifest
    • Memory Management
      • Garbage Collection 1
      • Garbage Collection 2
      • Circular Reference
  • C Sharp
    • Abstract Class in C#
    • Interfaces in C#
    • Value type by Val and By Ref
    • Var keyword
    • Null Coalescing Operator
    • Buit-in code snippets
  • OOPS
    • Abstraction and Encapsulation
    • Polymorphism
    • Inheritence
    • Aggregation
  • Threading
    • Delegates
      • Calling Delegate using Invoke, BeginInvoke
      • Multicast Delegate
      • Exception Handling in Multicast Delegate
      • Action
      • Predicate
      • Func
    • Synchronization
    • Thread Pool
    • Exception Handling
    • TPL
  • Design Pattern
    • Creational Patterns
      • Singleton Pattern
      • Factory Pattern
      • Abstract Factory Pattern
      • Prototype Pattern
      • Builder Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Proxy Pattern
      • Facade Pattern
      • Decorator Pattern
      • Flyweight Pattern
    • Behavioral Patterns
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
      • Visitor Pattern
      • Chain Of Responsibility Pattern
      • Template Pattern
  • Data Structures
    • Generic List in C#
    • 2d array to 1d array
    • 3d arrayto 1d array
    • Linked List
      • Singly Linked List in C#
    • Queue
      • Dummy Data 1
    • Stack
      • Dummy Data 2
    • Tree
      • Dummy Data 3
    • Graph
      • Dummy Data 4
  • WCF
    • WCF Service using VS 2015
  • Scripts
    • Chrome Extensions
      • Create a Chrome Extension
      • Facebook autologout script
      • Gmail autologout script

How to set image resolution and paint it in C# ?

 Unknown     5:01 AM     No comments   

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Imaging;

public class Form1 : System.Windows.Forms.Form
{
Constructor.
public Form1()
{
InitializeComponent();
}
Initialize all the controls.
private void InitializeComponent()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Text = "";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);

}
Main method(Entry point).
public static void Main()
{
Application.Run(new Form1());
}
Handles the paint event.Create the grapics for the image,then set the resolution and then draw the image.
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
Bitmap bmp = new Bitmap("winter.jpg");

g.FillRectangle(Brushes.White, this.ClientRectangle);
bmp.SetResolution(600f, 600f);
g.DrawImage(bmp, 0, 0);
bmp.SetResolution(1200f, 1200f);
g.DrawImage(bmp, 180, 0);
}
Handles the resize event.
private void Form1_Resize(object sender, System.EventArgs e)
{
Invalidate();
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

More Regular Expressions

 Unknown     11:27 PM     No comments   

To validate a URL with a regular expression :-
(http://|ftp://)([\w-\.)(\.)([a-zA-Z]+)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

C# Tutorial (Chapter - 1) Introduction about C# and .Net framework(1 :- .Net Plateform)

 Unknown     3:28 AM     No comments   

I :-.Net Plateform :-

The Microsoft® .NET platform provides all of the tools and technologies that
you need to build distributed Web applications. It exposes a languageindependent,
consistent programming model across all tiers of an application
while providing seamless interoperability with, and easy migration from,
existing technologies. The .NET platform fully supports the Internet’s platformneutral, standards-based technologies, including HTTP, Extensible Markup
Language (XML), and Simple Object Access Protocol (SOAP).

II :-The .NET Building Block Services :-

The .Net building block services are distributed programmable services that are availaible in both offline and online.A service can be invoked on stand alone computer not connected to the internet,provided by the server which is running inside from the company oer accessed by internet, This service can be used from the plateform which supports SOAP.Services include identity, notification and messaging,
personalization, schematized storage, calendar, directory, search, and software
delivery.

III :-The .NET Enterprise Servers :-
1: Microft Sql server - 2000
2: Microsoft Biztalk sever - 2000
3: Microsoft Host integration server - 2000
4: Microsoft Exchange 2000 Enterprise server
5: Microst Application center - 2000
6: Microsoft Internet security server - 2000

Microsoft Sql server - 2000 :- Supports XML functionality, support for Worldwide Web Consortium (W3C) standards, manipulate XML data by using Transact SQL (T-SQL), flexible Web-based analysis, and secure access to your data over the Web by using HTTP.

Microsoft Internet security server - 2000 :- Provides secure, fast, and manageable Internet connectivity. Internet Security and multilayer enterprise firewall and a scalable high-performance Web cache. It builds on Windows 2000 security.

Microst Application center - 2000 :- Provides a deployment and management tool for high-availability Web applications.

Microsoft Exchange 2000 Enterprise server :- Builds on the powerful Exchange messaging and collaboration technology by ntroducing new features, and further increasing the reliability,scalability, and performance of its core architecture.

Microsoft Biztalk sever - 2000 :- Provides enterprise application integration (EAI), business-to-business integration and to build dynamic business processes,the span applications and plate forms.

Microsoft Host integration server - 2000 Provides the best way to embrace Internet, intranet, and client/server technologies.

IV :-The .NET Framework Components :-
1:-Common Language Runtime
2:- Base Class Library
3:- ADO.NET: Data and XML
4:- Web Forms and Services
5:- User Interface

CLR(Comman Language Runtime) :- Central to the .NET framework is its run-time execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed
managed code
.However, before it can be executed by the CLR, any sourcecode that we develop (in C# or some other language) needs to be compiled. Compilation occurs in two steps in .NET:
1. Compilation of source code to Microsoft Intermediate Language (MS-IL)
2. Compilation of IL to platform-specific code by the CLR

Components of CLR :-
1 :-Class loader : Manages metadata, as well as the loading and layout of classes.
ClassLoader classLoader = TestClass.getClassLoader();
URL url = cl.getResource("someFileName");

2 :-Garbage collector (GC) :-The garbage collector is .NET's answer to memory management,Having the application code responsible for de-allocating memory is the technique used by lower-level,high-performance languages such as C++. It is efficient, and it has the advantage that (in general)resources are never occupied for longer than unnecessary. The big disadvantage, however, is the frequency of bugs. Code that requests memory also should explicitly inform the system when it no longer requires that memory. However, it is easy to overlook this, resulting in memory leaks.Provides automatic lifetime management of all of your objects. This is a multiprocessor, scalable garbage collector.
3 :-Security engine :-It based on the origin of the code.
4 :-Debug engine :- Debug your program and trace the execution of code.
5:-Code manager :-Manages the code execution.
6 :-Exception manager :- It provides structured exception management,which is integrated with Windows Structured Exception Handling (SEH),provides all the system exception classes.
7 :-Thread support :-Supports multi threaded programming.
8 :-COM :-Provides Interoperability class and marshalling to and from COM.
9 :-Type checker :-This will not allow unsafe typecasting and uninitialized variables Il verifies guaranteed type safety.
10 :-Microsoft intermediate language :-Converts MSIL to native code.
11 :- Base Class Library :- Executes run time.

2:-Base Class library :- This library contains namespaces like header files in C,C++,It expose features at run time and provide some high services.
I am mentioning namespace and about their services :-

System.Collections :- You can see all the interfaces and classes included in this namespace from below link :-
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

C# Tutorials

 Unknown     3:19 AM     No comments   

Hello to all, My next thread is about C#,In my next thread i will divide the C# thread into chapters each chapter will contain all the details about C# and .Net framework its a step by step process so go through to all the thread and please post a comment or email me at saurabhjnumca@gmail.com about this thread please give critics about this thread.If you will study the coming thread then you will able to explain about .net and you can easily code in C# .

Regards,
Saurabh Singh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to create a session manager in .Net ?

 Unknown     7:51 AM     No comments   

To create a SessionManager to save User objects in memory. It would be HashMap of HaspMaps.
It can be used as:

SessionManager MySessionManager= New SessionManager()
Student S1 = New Student ("Saurabh");
Student S2 = New Student ("Sandeep");
Student S3 = New Student ("Deepak");

//To create session
MySessionManager.createSession(S1);
MySessionManager.createSession(S2);
//SAVING S1 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S1, "Physics", phyisicsMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S1, "Chemistry",chemistryMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S1, "Mathematics" ,mathsMarks);

//SAVING S2 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S2, "Physics", phyMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85)
MySessionManager.Save(S2, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S2, "Mathematics" ,mathsMarks);

//SAVING S3 MARKS. NOTE: SESSION OF S3 IS NOT AVAILABLE. SO FIRST SESSION OF
S3 SHOULD BE CREATED AND THEN DATA SHOULD BE SAVED

Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S3, "Physics", phyMarks); //”Physics” is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S3, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S3, "Mathematics" ,mathsMarks);

///How to retrieve data
Out.Print ("Phyiscis Marks of S1," & MySessionManager.get(S1, "Physics").marks);
Out.Print ("Phyiscis Marks of S3," & MySessionManager.get(S1, "chemistry").marks);

IN REAL WORLD SCENARIO, S1, S2, S3 SHOULD NOT BE PASSED TO
MYSESSIONMANAGER. THEY WOULD BE OBTAINED FROM CONTEXT.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Tech-Giant(Jargons.. for Professionals): How to take Screenshot of panel,control and save it in a JPG format ?

 Unknown     6:58 AM     No comments   

Tech-Giant(Jargons.. for Professionals): How to take Screenshot of panel,control and save it in a JPG format ?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to take Screenshot of panel,control and save it in a JPG format ?

 Unknown     6:17 AM     No comments   

You can create a bitmap of screen and then save it give the stream or fileName and then dispose the object of screenshot.

Bitmap theScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
theScreenShot.Save(stream_or_filename, ImageFormat.Jpeg);
theScreenShot.Dispose();

Another way to save the panel as a jpg format and you can take a print of your control using below method.
Use this event on your form :-
_document.PrintPage += new PrintPageEventHandler(document_PrintPage);

/// Prepare the page to be print for the area of the control to be printed.
private void document_PrintPage(object sender, PrintPageEventArgs e)
{
this.Dock = System.Windows.Forms.DockStyle.None;
this.Size = Temp_Image.Size;
//Takes away focus from any printed controls to make sure output is what we want.
this.Focus();
this.Refresh();
this.DrawToBitmap(Temp_Image, New System.Drawing.Rectangle(0, 0, Temp_Image.Width, Temp_Image.Height));
this.Dock = System.Windows.Forms.DockStyle.Fill;
e.Graphics.DrawImage(Temp_Image, e.MarginBounds);
e.Graphics.Clip = new Region(e.MarginBounds);
}
By this method you can print your control you just pass the object of your control (control will be panel,treeView,listView)and this will calculate the height ,width and then call the print method ,print preview or save as jpg file.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Order of Event firing in ASP.Net

 Unknown     3:13 AM     1 comment   

Event firing order becomes critically important when you add event handling code to master pages and the content forms based on them. The following events occur when ASP.NET renders a page. I’ve listed these events in the order in which they occur.

1 :-Content Page Pre Initializes
2 :-Master Page Child Controls Initialize
3 :-Content Page Child Controls Initialize
4 :-Master Page Initializes
5 :-Content Page Initializes
6 :-Content Page Initialize Complete
7 :-Content Page Pre Loads
8 :-Content Page Loads
9 :-Master Page Loads
10 :-Master Page Child Controls Load
11 :-Content Page Child Controls Load
12 :-Content Page Load Complete
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Lambda Expressions in C#

 Unknown     2:49 AM     No comments   

Lambda expressions makes the searching life much easier.Have a look on this example :-

public class TestLambdaProgram
{
public static void Main( string[] args )
{
List names = new List();

names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);

string stringResult = names.Find( name => name.Equals(“Garima”));
}

You can print the whole list using this method :-

new List(names ).foreach(name => Console.WriteLine(name));
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Basics of .Net (What is IL,CLR,CTS,CLS ?)

 Unknown     6:23 AM     3 comments   

1: IL(Intermediate Language) :-(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. This IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler. Microsoft Intermediate Language (MSIL) is a language used as the output of a number of compilers (C#, VB, .NET, and so forth). The ILDasm (Intermediate Language Disassembler) program that ships with the .NET Framework SDK (FrameworkSDK\Bin\ildasm.exe) allows the user to see MSIL code in human-readable format. By using this utility, we can open any .NET executable file (EXE or DLL) and see MSIL code.

MSIL commands are as follows:

ldstr string :—loads the string constant onto the stack.
call function(parameters) :—calls the static function. Parameters for the function should be loaded onto the stack before this call.
pop :—pops a value from the stack. Used when we don't need to store a value in the variable.
ret :—returns from a function.
I will discuss about MSIL in my next article.

2 :- CLR(Comman Language Runtime) Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.It is the implementation of CLI .The core runtime engine in the microsoft .net framework for executing assemblies. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Internet Exlorer is the example of hosting CLR. CLR have following qualities :-

Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.

Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.

Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.

IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL
code.

3 :- CTS(Comman Type System) :- In order that two language communicate smoothly CLR has CTS (Common Type System).Example
in VB you have “Integer” and in C++ you have “long” in c u have "int" these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can 1. Basic .NET Framework communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and
“int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.

4 :-CLS(Common Language Specification) :- This is a subset of the CTS which all .NET languages are expected to support. It was always a
dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What are different types of JIT ?

 Unknown     1:42 AM     No comments   

In .net there are three type of JIT.JIT compiler is a part of the runtime execution environment.
Three JIT are following :-

Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.

Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.

Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is
used for execution.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What is Manifest in .net ?

 Unknown     1:24 AM     No comments   

An assembly manifest contains all the metadata.It means Assembly metadata is stored in Manifest and it needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes.Some points are given please go through it :-
1:- The assembly manifest can be stored in either a Portable Executable file an .exe or dll file with Microsoft intermediate language (MSIL) code or in a standalone Portable Executable file that contains only assembly manifest information.

These four items
1 :- assembly name
2 :- version number
3 :- culture
4 :- strong name information
These four make up the assembly's identity.

Assembly name: A string which specifying the assembly's name.

Version number: A major and minor version number, and a revision and build number. The clr uses these numbers to enforce version policy. Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
their individual folders.

Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information.

Satellite Assembly :- An assembly with culture information is automatically assumed to be a satellite assembly.

Strong name information: The public key from the publisher if the assembly has been given a strong name.

List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.

Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to view a Assembly of your code (What is ILDASM ?)

 Unknown     1:36 AM     No comments   


When it comes to understanding of internals nothing can beat ILDASM. ILDASM basically converts the whole exe or dll in to IL code. To run ILDASM you have to go to "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin". Note that i had v2.0 you have to probably change it depending on the type of framework version you have.

If you run IDASM.EXE from the path you will be popped with the IDASM exe program as
shown in figure ILDASM. Click on file and browse to the respective directory for the DLL whose assembly you want to view. After you select the DLL you will be popped with a tree view details of the DLL as shown in figure ILDASM. On double clicking on manifest you will be able to view details of assembly, internal IL code etc as shown in Figure Manifest View.

Note : The version number are in the manifest itself which is defined with the DLL or
EXE thus making deployment much easier as compared to COM where the information
was stored in registry. Note the version information in Figure Manifest view.
You can expand the tree for detail information regarding the DLL like methods etc
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to copy the text from label in window form at run time ?

 Unknown     11:42 PM     No comments   

Designer view:
#region DesignerView
Create a context menu strip :
this.copyPathMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.labelContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyPathMenuItem});
this.labelContextMenuStrip.Name = "labelContextMenuStrip";
this.labelContextMenuStrip.Size = new System.Drawing.Size(100, 22);

this.copyPathMenuItem.Name = "copyPathMenuItem";
this.copyPathMenuItem.Size = new System.Drawing.Size(100, 22);

this.lblSelectedNodePath.ContextMenuStrip = this.labelContextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem copyPathMenuItem;
#endregion

Now handles the label events like :-

private void lblSelectedNodePath_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
copyPathMenuItem.Visible = true;
copyPathMenuItem.Enabled = true;
}
}

Add an click event :-
copyPathMenuItem.Click += new EventHandler(copyPathMenuItem_Click);

Handles the click event :-

private void copyPathMenuItem_Click(object sender, EventArgs e)
{
string labelPath = lblSelectedNodePath.Text.Trim();
if (!string.IsNullOrEmpty(labelPath))
{
Clipboard.SetDataObject(labelPath, false);
}
}
Now you can paste your copy text anywhere Enjoy d Code .....
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How can I change the Border color of my control ?

 Unknown     6:40 AM     No comments   

public class MyButton : Button
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int borderWidth = 1;
Color borderColor = Color.Blue;
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, borderColor,
borderWidth, ButtonBorderStyle.Solid, borderColor, borderWidth,
ButtonBorderStyle.Solid, borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to change the color of Tab Control in c#

 Unknown     1:49 AM     No comments   

Steps :-
1. Set the TabControl's DrawMode to OwnerDraw.
2. Handle the DrawItem event.

private void ChangeColorOFTabControl(object sender, DrawItemEventArgs e)
{
Font TabFont;
Brush BackBrush = new SolidBrush(Color.Green); //Set background color
Brush ForeBrush = new SolidBrush(Color.Yellow);//Set foreground color
if (e.Index == this.tabControl1.SelectedIndex)
{
TabFont = new Font(e.Font, FontStyle.Italic | FontStyle.Bold);

}
else
{
TabFont = e.Font;
}
string TabName = this.tabControl1.TabPages[e.Index].Text;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
e.Graphics.FillRectangle(BackBrush, e.Bounds);
Rectangle r = e.Bounds;
r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
e.Graphics.DrawString(TabName, TabFont, ForeBrush, r, sf);
//Dispose objects
sf.Dispose();
if (e.Index == this.tabControl1.SelectedIndex)
{
TabFont.Dispose();
BackBrush.Dispose();
}
else
{
BackBrush.Dispose();
ForeBrush.Dispose();
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to set dropdown width according to longest string in C#

 Unknown     11:24 PM     No comments   

If you are using window control then use this method.
private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
?SystemInformation.VerticalScrollBarWidth:0;

int newWidth;
foreach (string s in ((ComboBox)sender).Items)
{
newWidth = (int) g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth )
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}

If you are a web developer then :-
Get the length of longest string and pass it in unit.pixel method like this :-
DropDownList1.Width = Unit.Pixel(LengthOfTheLongestString)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to get the file size like windows file property control ?

 Unknown     7:43 AM     No comments   

//Create an object of FileInfo like :-
FileInfo fileObject = new FileInfo(selectedFilename);
Int64 fileSize = 0;
float sizeOfFile = 0
fileSize = fileObject.Length;
sizeOfFile = fileObject.Length;
private const int FILESIZE_IN_KB = 1024;
public const int FILESIZE_IN_MB = 1048576;
public const int FILESIZE_IN_GB = 1073741824;
public const long FILESIZE_IN_TB = 1099511627776;
private const int START_INDEX = 0;
private const string STRING_VALUE_ZERO = "0";
private const string STRING_VALUE_ONE = "1";
private const string SYMBOL_BYTES = "bytes";
private const string STRING_FORMAT = "n";
public const string FILESIZE_KB = "KB";
private const int FILE_SIZE_LIMIT = 100;
private const string STRING_FORMAT_UPTO_TWO_DECIMAL = ".00";
private const int FILE_SIZE_IN_BYTES = 102400;
private const int FILE_SIZE_IN_MegaBytes = 104857600;
private const long FILE_SIZE_IN_GIGABYTES = 107374182400;
private const string SYMBOL_SPACE = " ";

string size = FormatSize(fileSize,sizeOFFile);

private string FormatSize(Int64 fileSize, float sizeOFFile)
{
//Format number to KB
string stringSize = string.Empty;
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();

Int64 fileSizeInKB = 0;
Int64 fileSizeInMB = 0;
long fileSizeInGB = 0;
float fileSizeInKBInFloat = 0;
float fileSizeInMBInFloat = 0;
float fileSizeInGBInFloat = 0;
string byteSize = string.Empty;

if (fileSize < FILESIZE_IN_KB)
{
if (fileSize == 0)
{
//zero byte
stringSize = STRING_VALUE_ZERO + SYMBOL_SPACE + SYMBOL_BYTES;
}
else
{
//less than 1K but not zero byte
stringSize = fileSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + fileSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
}
else if(fileSize < FILESIZE_IN_MB)
{
if (fileSize < FILE_SIZE_IN_BYTES)
{
fileSizeInKBInFloat = (sizeOFFile / (float)FILESIZE_IN_KB);
}
else
{
//convert to KB
fileSizeInKB = (fileSize / FILESIZE_IN_KB);
}
if (fileSizeInKBInFloat != 0)
{
stringSize = fileSizeInKBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInKB.ToString(STRING_FORMAT, numberFormatInfo);
///If file Size is morethan 100 than replace decimal string to emptyString.
if (fileSizeInKB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}
///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_DECIMAL, string.Empty);
stringSize = stringSize + "KB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
else if (fileSize < Constants.FILESIZE_IN_GB)
{
if (fileSize < FILE_SIZE_IN_MegaBytes)
{
fileSizeInMBInFloat = (sizeOFFile / (float)FILESIZE_IN_MB);
}
else
{
//convert to KB
fileSizeInMB = (fileSize / FILESIZE_IN_MB);
}
if (fileSizeInMBInFloat != 0)
{
stringSize = fileSizeInMBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInMB.ToString(STRING_FORMAT, numberFormatInfo);

if (fileSizeInMB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}

///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);

stringSize = stringSize + "MB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize +SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
else if(fileSize < FILESIZE_IN_TB)
{
if (fileSize < FILE_SIZE_IN_GIGABYTES)
{
fileSizeInGBInFloat = (sizeOFFile / (float)FILESIZE_IN_GB);
}
else
{
//convert to KB
fileSizeInGB = (fileSize / FILESIZE_IN_GB);
}
if (fileSizeInGBInFloat != 0)
{
stringSize = fileSizeInGBInFloat.ToString(STRING_FORMAT, numberFormatInfo);
}
else
{
//format number with default format
stringSize = fileSizeInGB.ToString(STRING_FORMAT, numberFormatInfo);

if (fileSizeInGB >= FILE_SIZE_LIMIT)
{
stringSize = stringSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
}
}

///Sets the byteSize like 12345 into 12,345.
byteSize = fileSize.ToString(STRING_FORMAT, numberFormatInfo);
byteSize = byteSize.Replace(STRING_FORMAT_UPTO_TWO_DECIMAL, string.Empty);
stringSize = stringSize + "GB" + SYMBOL_SPACE + SYMBOL_OPENING_BRACE + byteSize + SYMBOL_SPACE + SYMBOL_BYTES + SYMBOL_CLOSING_BRACE;
}
return stringSize;
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sort ListView on column click (like windows folder detail view in xp)

 Unknown     6:22 AM     No comments   





Step :1 Firstly Create the object of listviewcolumn sorter class.
private ListViewColumnSorter listviewColumnSorter=new ListViewColumnSorter();
Step :2 Set ListViewItemSorter property of listView
listView.ListViewItemSorter = listviewColumnSorter;
Handles columnclick event on your form like the above image.
I am pasting the images of listViewItemSorter class please go through it.This class sort the columns according to image,size,text,alphabet.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Get AssociatedFileTypes (.txt = TextDocument)

 Unknown     5:07 AM     No comments   

///
/// Get File Type for given file.
///

/// Pass the path of file
///

This method returns Associated file type like :-
.pdf = Adobe Acrobat Document
.txt = Text Document


private string GetAssociatedFileType(string filePath)
{
private const string STRING_SPACE = " ";
string extension = string.Empty;
if (!string.IsNullOrEmpty(filePath))
{
string extension = Path.GetExtension(filePath);
}
RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension);
while (key != null)
{
string name = (string)key.GetValue(null);
if (name == null)
{
return extension + STRING_SPACE + "File";
}
RegistryKey tempKey = Registry.ClassesRoot.OpenSubKey(name);
if (tempKey == null)
{
return name;
}
key = tempKey;
}
return extension + STRING_SPACE + "File";
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

File System Watcher in C#(Get notified after any modification)

 Unknown     7:26 AM     No comments   

Drag FileSystemWatcher control in your form from toolbox and add the events for created,deletion and renaming.
Ex:-
#region Designer view

this.fileSystemWatcher.EnableRaisingEvents = true;
this.fileSystemWatcher.IncludeSubdirectories = true;
this.fileSystemWatcher.SynchronizingObject = this;
this.fileSystemWatcher.Created += new System.IO.FileSystemEventHandler(this.fileSystemWatcher_Created);
this.fileSystemWatcher.Deleted += new System.IO.FileSystemEventHandler(this.fileSystemWatcher_Deleted);
this.fileSystemWatcher.Renamed += new System.IO.RenamedEventHandler(this.fileSystemWatcher_Renamed);
public System.IO.FileSystemWatcher fileSystemWatcher;

#endregion
Create three bool variables to set true or false :-
#region Properties
private bool _fileDeleted = false;
private bool _fileRenamed = false;
private bool _fileCreated = false;

public bool FileDeleted
{
set
{
_fileDeleted = value;
}
get
{
return _fileDeleted;
}
}
public bool FileRenamed
{
set
{
_fileRenamed = value;
}
get
{
return _fileRenamed;
}
}
pblic bool FileCreated
{
set
{
_fileCreated = value;
}
get
{
return _fileCreated;
}
}
#endregion

#region EventHandlers

private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
_fileRenamed = true;
MessageBox.Show(e.Name + " Renamed in " + e.FullPath);
}
private void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
_fileDeleted = true;
MessageBox.Show(e.Name + " Deleted in " + e.FullPath);
}
private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
_fileCreated = true;
MessageBox.Show(e.Name + " created in " + e.FullPath);
}

#endregion

By this property if you want to check file has been removed ,deleted from physical path then this will be true and you can check like if you have a tree view and you dont want to repopulate your tree view then use filesystemwatcher and repopulate the tree only when files have been changed,delete or rename. or you can throw a messagebox like above.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

String Functionality of C# (Play with strings)

 Unknown     7:01 AM     No comments   

1:- Convert string to LowerCase
public static String Lower(String constantString)
{
return constantString.ToLower();
}
2:-Convert String to UpperCase
public static String Upper(String constantString)
{
return constantString.ToUpper();
}
3:- Convert String to proper case
public static String PCase(String constantString)
{
String strProper=constantString.Substring(0,1).ToUpper();
constantString=constantString.Substring(1).ToLower();
String strPrev=string.Empty;

for(int iIndex=0;iIndex < constantString.Length;iIndex++)
{
if(iIndex > 1)
{
strPrev=constantString.Substring(iIndex-1,1);
}
if( strPrev.Equals(" ") ||
strPrev.Equals("\t") ||
strPrev.Equals("\n") ||
strPrev.Equals("."))
{
strProper+=constantString.Substring(iIndex,1).ToUpper();
}
else
{
strProper+=constantString.Substring(iIndex,1);
}
}
return strProper;
}
4- Function to Reverse the String
public static String Reverse(String constantString)
{
if(constantString.Length==1)
{
return constantString;
}
else
{
return Reverse(constantString.Substring(1)) + constantString.Substring(0,1);
}
}
5- Function to Test for Palindrome
public static bool IsPalindrome(String constantString)
{
int stringLength,halfLength;
stringLength=constantString.Length-1;
halfLength=stringLength/2;
for(int iIndex=0;iIndex<=halfLength;iIndex++)
{
if(constantString.Substring(iIndex,1)!=constantString.Substring(stringLength-iIndex,1))
{
return false;
}
}
return true;
}
6- Function to get string from beginning.
public static String Left(String constantString,int iLength)
{
if(iLength>0)
return constantString.Substring(0,iLength);
else
return constantString;
}
7- Function to get string from end
public static String Right(String constantString,int iLength)
{
if(iLength>0)
return constantString.Substring(constantString.Length-iLength,iLength);
else
return constantString;
}
8:-Function to count no.of occurences of Substring in Main string
public static int CharCount(String sourceString,String stringToCount)
{
int count=0;
int position=sourceString.IndexOf(stringToCount);
while(position!=-1)
{
count++;
strSource=sourceString.Substring(position+1);
position=strSource.IndexOf(stringToCount);
}
return count;
}
9:-Convert arrayList to string[]ArrayList subKeysColletion = new ArrayList();
string[] collectionOfSubkeys = new string[subKeysColletion.Count];
collectionOfSubkeys = subKeysColletion.ToArray(typeof(string)) as string[];
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Create customize OpenFileDialogBox and SaveFileDialogBox using shell

 Unknown     3:31 AM     No comments   




The Open dialog box lets the user specify the drive, directory, and the name of a file or set of files to open.

The Save As dialog box lets the user specify the drive, directory, and name of a file to save.

Explorer-style Open and Save As dialog boxes provide user-interface features that are similar to the Microsoft Windows Explorer. However, the system continues to support old-style Open and Save As dialog boxes for applications that must be consistent with the old-style user interface.

In addition to the difference in appearance, the Explorer-style and old-style dialog boxes differ in their use of custom templates and hook procedures for customizing the dialog boxes. However, the Explorer-style and old-style dialog boxes have the same behavior for most basic operations, such as specifying a file name filter, validating the user's input, and getting the file name specified by the user. For more information about the Explorer-style and old-style dialog boxes, Check out in the given images.

For more information check out MSDN link :---
http://msdn.microsoft.com/en-us/library/ms646960(VS.85).aspx
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Get CSIDL Code (System Index of Directories)

 Unknown     3:01 AM     No comments   

const int CSIDL_DESKTOP = 0x0000; //
const int CSIDL_INTERNET = 0x0001; // Internet Explorer (icon on desktop)
const int CSIDL_PROGRAMS = 0x0002; // Start Menu\Programs
const int CSIDL_CONTROLS = 0x0003; // My Computer\Control Panel
const int CSIDL_PRINTERS = 0x0004; // My Computer\Printers
const int CSIDL_PERSONAL = 0x0005; // My Documents
const int CSIDL_FAVORITES = 0x0006; // \Favorites
const int CSIDL_STARTUP = 0x0007; // Start Menu\Programs\Startup
const int CSIDL_RECENT = 0x0008; // \Recent
const int CSIDL_SENDTO = 0x0009; // \SendTo
const int CSIDL_BITBUCKET = 0x000a; // \Recycle Bin
const int CSIDL_STARTMENU = 0x000b; // \Start Menu
const int CSIDL_MYDOCUMENTS = CSIDL_PERSONAL; // Personal was just a silly name for My Documents
const int CSIDL_MYMUSIC = 0x000d; // "My Music" folder
const int CSIDL_MYVIDEO = 0x000e; // "My Videos" folder
const int CSIDL_DESKTOPDIRECTORY = 0x0010; // \Desktop
const int CSIDL_DRIVES = 0x0011; // My Computer
const int CSIDL_NETWORK = 0x0012; // Network Neighborhood (My Network Places)
const int CSIDL_NETHOOD = 0x0013; // \nethood
const int CSIDL_FONTS = 0x0014; // windows\fonts
const int CSIDL_TEMPLATES = 0x0015;
const int CSIDL_COMMON_STARTMENU = 0x0016; // All Users\Start Menu
const int CSIDL_COMMON_PROGRAMS = 0x0017; // All Users\Start Menu\Programs
const int CSIDL_COMMON_STARTUP = 0x0018; // All Users\Startup
const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019; // All Users\Desktop
const int CSIDL_APPDATA = 0x001a; // \Application Data
const int CSIDL_PRINTHOOD = 0x001b; // \PrintHood
const int CSIDL_LOCAL_APPDATA = 0x001c; // \Local Settings\Applicaiton Data (non roaming)
const int CSIDL_ALTSTARTUP = 0x001d; // non localized startup
const int CSIDL_COMMON_ALTSTARTUP = 0x001e; // non localized common startup
const int CSIDL_COMMON_FAVORITES = 0x001f;
const int CSIDL_INTERNET_CACHE = 0x0020;
const int CSIDL_COOKIES = 0x0021;
const int CSIDL_HISTORY = 0x0022;
const int CSIDL_COMMON_APPDATA = 0x0023; // All Users\Application Data
const int CSIDL_WINDOWS = 0x0024; // GetWindowsDirectory()
const int CSIDL_SYSTEM = 0x0025; // GetSystemDirectory()
const int CSIDL_PROGRAM_FILES = 0x0026; // C:\Program Files
const int CSIDL_MYPICTURES = 0x0027; // C:\Program Files\My Pictures
const int CSIDL_PROFILE = 0x0028; // USERPROFILE
const int CSIDL_SYSTEMX86 = 0x0029; // x86 system directory on RISC
const int CSIDL_PROGRAM_FILESX86 = 0x002a; // x86 C:\Program Files on RISC
const int CSIDL_PROGRAM_FILES_COMMON = 0x002b; // C:\Program Files\Common
const int CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c; // x86 Program Files\Common on RISC
const int CSIDL_COMMON_TEMPLATES = 0x002d; // All Users\Templates
const int CSIDL_COMMON_DOCUMENTS = 0x002e; // All Users\Documents
const int CSIDL_COMMON_ADMINTOOLS = 0x002f; // All Users\Start Menu\Programs\Administrative Tools
const int CSIDL_ADMINTOOLS = 0x0030; // \Start Menu\Programs\Administrative Tools
const int CSIDL_CONNECTIONS = 0x0031; // Network and Dial-up Connections
const int CSIDL_COMMON_MUSIC = 0x0035; // All Users\My Music
const int CSIDL_COMMON_PICTURES = 0x0036; // All Users\My Pictures
const int CSIDL_COMMON_VIDEO = 0x0037; // All Users\My Video
const int CSIDL_RESOURCES = 0x0038; // Resource Direcotry
const int CSIDL_RESOURCES_LOCALIZED = 0x0039; // Localized Resource Direcotry
const int CSIDL_COMMON_OEM_LINKS = 0x003a; // Links to All Users OEM specific apps
const int CSIDL_CDBURN_AREA = 0x003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
const int CSIDL_COMPUTERSNEARME = 0x003d; // Computers Near Me (computered from Workgroup membership)
const int CSIDL_FLAG_CREATE = 0x8000; // combine with CSIDL_ value to force folder creation in SHGetFolderPath()
const int CSIDL_FLAG_DONT_VERIFY = 0x4000; // combine with CSIDL_ value to return an unverified folder path
const int CSIDL_FLAG_DONT_UNEXPAND = 0x2000; // combine with CSIDL_ value to avoid unexpanding environment variables
const int CSIDL_FLAG_NO_ALIAS = 0x1000; // combine with CSIDL_ value to insure non-alias versions of the pidl
const int CSIDL_FLAG_PER_USER_INIT = 0x0800; // combine with CSIDL_ value to indicate per-user init (eg. upgrade)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Get Information about Operating-System(Like its an English operating system or German operating system)

 Unknown     2:50 AM     No comments   

///
/// Get the operating system language.
///

public static void GetOperatingSystemLanguage()
{
ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher("SELECT * FROM " + "Win32_OperatingSystem");
int languageCode = 0;
foreach (ManagementObject managementObject in objectSearcher.Get())
{
//Create the obect of propertydataCollection and get all the properties
PropertyDataCollection searcherProperties = managementObject.Properties;
foreach (PropertyData propertyData in searcherProperties)
{
string osLanguage = propertyData.Name;
if (osLanguage == STRING_OS_LANGUAGE)
{
if (int.TryParse(propertyData.Value.ToString(), out languageCode))
{
//This is English Laguage Code
if (languageCode == 1033)
{
_systemLanguage = OperatingSystemLanguage.English;
break;
}
//This is German Language Code
else if (languageCode == 1031)
{
_systemLanguage = OperatingSystemLanguage.German;
break;
}
}
}
}
break;
}
}



You can get all the hardware and software properties of OperatingSystem using this.like version number, Physicalmemory,Lastbootuptime.You can know even about processor for the whole project you can contact me at saurabhjnumca@gmail.com.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Flow Lay out panel in .net toolbar

 Unknown     4:16 AM     No comments   

There is a bug or some called microsoft functionality in the microsoft flowlayout panel .I have used flowlayout panel in my current project in that panel i have add controls like : Checklistbox control,radiolistbox,regitry flags and many more they all had labels in their top with some fixed size but when i added in the panel then they all are docked in the panel (Top) property but size of the labels was remain same.then i come to know it's a bug then i used panel instead of flowlayout panel.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Algorithms in C# (Anagram Method)

 Unknown     12:19 AM     No comments   

Input :-
1:- cba
2:- dsef
3:- sandy
Output :-
1:- abc
2:- defs
3:- adnsy
This is called alphabetized sorting using Anagram method.

To Use Anagram Method :-
Dictionary : 4556 ms
If we use generic list in dictionary then it will take longer time to compute
Dictionary : 5647 ms

Namespace :-
using System;
using System.Collections.Generic;
using System.IO;

Public class Anagrams
{
public static void Main()
{
Read and sort dictionary
var data = ReadText();

Read in user input and show anagrams
string lineToRead;
while ((lineToRead = Console.ReadLine()) != null)
{
ShowOutput(data, lineToRead);
}
}

Public Dictionary ReadText()
{
var data = new Dictionary();
Read each line
using (StreamReader readWholeText = new StreamReader("Some File .Text"))
{
string line;
while ((line = readWholeText.ReadLine()) != null)
{
Alphabetize the line for the key,Then add to the string
string alphabetize = Alphabetize(line);
string tempString = string.Empty;
if (data.TryGetValue(alphabetize, out tempString))
{
data[alphabetize] = tempString + "," + line;
}
else
{
data.Add(alphabetize, line);
}
}
}
return data;
}
Convert the text and sort it according to alphabet.
Public string Alphabetize(string text)
{
// Convert to char array, then sort and return
char[] arrayOfLine = text.ToCharArray();
Array.Sort(arrayOfLine);
return new string(arrayOfLine);
}
This method will show the output.
Public void ShowOutput(Dictionary objDictionary, string temp)
{
// Write value for alphabetized word
string tempText;
if (objDictionary.TryGetValue(Alphabetize(temp), out tempText))
{
Console.WriteLine(tempText);
}
else
{
Console.WriteLine("-");
}
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

MSIL code for Singleton and Static class

 Unknown     12:12 AM     No comments   

MSIL code for singleton

L_0000: ldsfld class Perls.Metadata Perls.Metadata::Instance
L_0005: ldarg.0
L_0006: ldloca.s data
L_0008: callvirt instance bool Perls.Metadata::TryGetFile(string, class Perls.FileData&)

MSIL code for static class

L_0000: ldarg.0
L_0001: ldloca.s data
L_0003: call bool Perls.Metadata::TryGetFile(string, class Perls.FileData&)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Comparison between NullCheckSingleton and OptimizedSingleton in C#

 Unknown     12:01 AM     No comments   

NullCheckSingleton
public sealed class SampleProgram
{
static readonly SampleProgram _instance;
public static readonly SampleProgram Instance
{
if (_instance == null)
{
_instance = new SampleProgram();
}
return _instance;
}
SampleProgram()
{
}
}

Optimized singleton
public sealed class SampleProgram
{
static readonly SampleProgram _instance = new SampleProgram();
public static readonly SampleProgram Instance
{
get
{
return _instance;
}
}
SampleProgram()
{
}
}
Optimized singleton is much faster than NullcheckSingleton Have a look on the above example and as i am discussed in my previous thread about the time comparison in both singleton pattern.
[Reference Jon Skeet's thorough singleton page.]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Singleton Class Uses and Drawbacks

 Unknown     11:42 PM     Happy to code     No comments   

Singleton :-
Singleton is controversial design pattern of OOPS. It allows you to restrict the number of instances of an object.It's an interface that allows a class to enforce that it is only allocated once.

Sample Code :-

Namespace :-
using system.text;
using System.collections;

class SampleProgram
{
public static void Main()
{
SingletonStructure singleton = SingletonStructure.Instance;
}
}

public sealed class SingletonStructure
{
static readonly SingletonStructure _instance = new SingletonStructure();
public static SingletonStructure Instance
{
get
{
return _instance;
}
}
Constructor which will be initialize and create the instance
SingletonStructure()
{
// Initialize.
}
}

Null check singleton: 435 ms
Optimized singleton : 42 ms (As Above)


This method is fast beacause instance member is created directly in its declaration
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to read XML Node using C#

 Unknown     1:53 PM     No comments   

Load an XML File

XmlDocument xdXml = new XmlDocument();
xdXml.Load("Index.xml");

Make a nodelist
XmlNodeList xnNodes = xdXml.SelectNodes("/Tools/Download");

Walk through the list
foreach (XmlNode node in xnNodes)
{
if (node.FirstChild.InnerText == ddlTools.Text)
{
//Get all the child nodes
XmlNodeList childNodes = node.ChildNodes;

//And walk through them
foreach (XmlNode child in childNodes)
{
//Check which node we have now
switch (child.Name)
{
case "Name":
txtName.Text = child.InnerText;
break;
case "Version":
txtVersion.Text = child.InnerText;
break;
case "Category":
txtCategory.Text = child.InnerText;
break;
case "Description":
txtDescription.Text = child.InnerText;
break;
}
}
childNodes = null;
break;
}
}

Clean up
xdXml = null;
xnNodes = null;
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Transparent images not displaying correctly

 Unknown     1:27 PM     No comments   

If images are not displaying correctly or showing a black spot at the back side of the image then play with the color depth property of imagelist or picture box.

Example :-

ImageList imageList = new ImageList();
imagelist.colorDepth = colorDepth.32Bit;
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to make Regular Expressions

 Unknown     12:26 PM     Enjoy..coding     No comments   

If you want to learn how to make regular expressions then visit this link this will be helpful for you...

http://www.zytrax.com/tech/web/regex.htm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Collection of Regular Expressions

 Unknown     11:35 AM     1 comment   

Regular expression to match email address

1 :- [\w-]+@([\w-]+\.)+[\w-]+
2 :- (?(?![ ])(\w|[.])*@(\w|[.])*)
3 :- ^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$
4 :- /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@
([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i

Regular Expression to validate US-Phone number.

Example :- (999) 999-9999 or (999)123-7869
1 :- /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/


Regular Expression which validate string which contains only valid numbers.


1 :- /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/


Regular Expression which validate string which contains only valid integer numbers.

1 :- /(^-?\d\d*$)/

Regular Expression to validate US-Zip Code
1:- /(^\d{5}$)|(^\d{5}-\d{4}$)/;

Regular Expression to check any social number :-
Replace 9 by any valid nuber you want to check

1 :-/^\d{9}$/

Expression to check amount example :- 100,100.00,$100,$100.00
1 :- /^((\$\d*)|(\$\d*\.\d{2})|(\d*)|(\d*\.\d{2}))$/

Regular Expression to check IP Address (0-255):-
/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/

Regular Expression to check Time :-

/^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/
Like :- HH:MM:SS, HH:MM, HH:MM:SS.mmm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to make Recycle - Bin in .net using C#

 Unknown     11:08 AM     No comments   

Visit this article and make your recycle bin

http://www.codeproject.com/KB/shell/recyclebin.aspx
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Detect the Encoding Type of given file

 Unknown     10:43 AM     No comments   

Encoding type : To add new Encoding we have to add new member in here,with the CodePage value as an value of the new encoding and have to modify FileHandler.DetectEncoding function.

public enum EncodingType
{
WindowsANSI = 1252,
Unicode = 1200,
UnixANSI = 28591
}

You can pass the path of the file and this method returns the encoding format
of type which has been defined in enum EncodingType.You just modify the enum with your encoding and code page value and get the encoding format of any file.

private Encoding DetectEncoding(string fileName)
{
byte[] data = new byte[4];
Encoding encoding = null;
StreamReader streamReader = new StreamReader(fileName);
streamReader.BaseStream.Read(data, 0, data.Length);

ApplicationNativeMethods.IsTextUnicodeFlags isTextUnicodeFlags = ApplicationNativeMethods.IsTextUnicodeFlags.UnicodeMask;
bool isTextUnicode = ApplicationNativeMethods.IsTextUnicode(data, 4, ref isTextUnicodeFlags);

if ((data[0] == 0xFF && data[1] == 0xFE) || (isTextUnicode == true))
{
encoding = Encoding.GetEncoding((int)EncodingType.Unicode);
}
else
{
streamReader.BaseStream.Position = 0;

char cr = char.MinValue;
char lf = char.MinValue;
char peekLf = char.MinValue;

while ((streamReader.EndOfStream != true))
{
peekLf = (char)streamReader.Peek();
if (peekLf == Constants.SYMBOL_LINEFEED)
{
cr = lf;
lf = (char)streamReader.Read();
break;
}
lf = (char)streamReader.Read();
}

if (cr != Constants.SYMBOL_CARRIAGERETURN)
{
encoding = Encoding.GetEncoding((int)EncodingType.UnixANSI);
}
else
{
encoding = Encoding.GetEncoding((int)EncodingType.WindowsANSI);
}
}
streamReader.Close();
return encoding;
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sorted List Implementation

 Unknown     10:35 AM     No comments   

In C# You can implement Sortedlist and sort the values according to the key.

using System;
using System.Collections;

Code:

static void Main(string[] args)
{
values in sorted list are sorted according to key

SortedList myList = new SortedList();

myList.Add(12, "December");
myList.Add(9, "September");
myList.Add(10, "October");
myList.Add(4, "April");
myList.Add(5, "May");
myList.Add(6, "June");
myList.Add(2, "February");
myList.Add(8, "August");
myList.Add(7, "July");
myList.Add(3, "March");
myList.Add(11, "November");
myList.Add(1, "January");

output values that are sorted according to key


foreach (DictionaryEntry item in myList)
{
Console.WriteLine(item.Value);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Hash Table Implementation

 Unknown     10:28 AM     No comments   

using System;
using System.Collections;

Code:

static void Main(string[] args)
{
Create an object of hash table
Hashtable myHash = new Hashtable();

Add key-pair values

myHash.Add("Saurabh", 1);
myHash.Add("Sandy", 2);
myHash.Add("Vivek", 3);

Move through hashtable data in cycle

foreach (DictionaryEntry item in myHash)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}

Get first item
Console.WriteLine("Get first item: " + myHash["Saurabh"]);

This will not work, name of item is not identical
Console.WriteLine("Get second item: " + myHash["Sandy"]);

}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Get System Boot Configuration using C#

 Unknown     10:22 AM     No comments   

using System;
using System.Management;

Code:

static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_BootConfiguration");

ManagementObjectSearcher find = new ManagementObjectSearcher(query);

foreach (ManagementObject mo in find.Get())
{

Console.WriteLine("Boot directory with files required for booting.." + mo["BootDirectory"]);

Console.WriteLine("Description.." + mo["Description"]);

Console.WriteLine("Directory with temporary files for booting.." + mo["ScratchDirectory"]);

Console.WriteLine("Directory with temporary files.." + mo["TempDirectory"]);

}

}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Get Environment variables..

 Unknown     10:17 AM     No comments   

Namespaces:

using System;
using System.Management;

Code:


static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("Select * from Win32_Environment");

ManagementObjectSearcher find = new ManagementObjectSearcher(query);

Console.WriteLine("Description - Name - User Name - Value");

foreach (ManagementObject mo in find.Get())
{

Console.WriteLine(mo["Description"] + " - " + mo["Name"] + " - " + mo["UserName"] + " - " + mo["VariableValue"]);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Obtain IP address and host

 Unknown     6:40 AM     No comments   

Namespaces:

using System;
using System.Net;

Code:

static void Main(string[] args)
{
Get Host Name
string host = Dns.GetHostName();

Console.WriteLine("Hostname is: {0}", host);

GetIP Entry
IPHostEntry entry = Dns.GetHostByName(host);

foreach (IPAddress ip in entry.AddressList)
{
Console.WriteLine("IP address: " + ip.ToString());
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Send mail message to .net Environment (Enjoy Mail System)

 Unknown     6:36 AM     No comments   

Namespaces:

using System;
using System.Web.Mail;

Code:

static void Main(string[] args)
{
MailMessage mailMsg = new MailMessage();

mailMsg.From = "saurabhsingh_jnu06@yahoo.co.in";

mailMsg.To = "saurabhjnumca@gmail.com";

mailMsg.Cc = string.Empty;

mailMsg.Bcc = string.Empty;

mailMsg.Subject = "Here goes a subject";

mailMsg.Body = "Here goes email body";

mailMsg.Priority = (MailPriority)1;

mailMsg.Attachments.Add(new MailAttachment("d:\\myText.txt"));

SmtpMail.SmtpServer = "smarthost";

SmtpMail.Send(mailMsg);
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Network Operations in C# (Play with system)

 Unknown     6:23 AM     No comments   

Retrieve DNS computer name

public static void Main(string[] args)
{
Console.WriteLine(“DNS: {0}”, System.Net.Dns.GetHostByName“LocalHost”).HostName);
}

Retrieve NetBIOS computer name

public static void Main(string[] args)
{
Console.WriteLine(“NetBIOS: {0}”, System.Environment.MachineName);}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

To get the system Icons(handle of system imagelist)

 Unknown     6:12 AM     No comments   

[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};


class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon

[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags);
}

//the handle to the system image list
IntPtr hImgSmall;

//the handle to the system image list
//IntPtr hImgLarge;

//Create an object of
SHFILEINFO shinfo = new SHFILEINFO();

try
{
//Use this to get the small Icon
hImgSmall = Win32.SHGetFileInfo( Path of file, 0, ref shinfo,
(uint)Marshal.SizeOf(shinfo),
Win32.SHGFI_ICON |
Win32.SHGFI_SMALLICON
);
Icon myIcon =Icon.FromHandle(shinfo.hIcon);

//This return the index on=f system image list
int iconIndex = shinfo.iIcon;

//Add the icon to imagelist or where ever you want to use you can
imageList.Images.Add(myIcon);
}
catch (Exception)
{

}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

To close the application from task manager.

 Unknown     6:08 AM     No comments   

If you have closed your appplication but still it runs in task manager then you can use this method to kill the thread.It happens only when some thread of your application is not closed.

Code:-

public const int SC_CLOSE = 0xF060;
public const int WM_SYSCOMMAND = 0x0112;

//Override method when You will close the window
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)

//close the application
MyClose();
// your method that cleans everything up and then runs
// System.Environment.Exit(0) which WILL close the threads forcefully if needed


base.WndProc(ref m);
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Play with Date-Time-Formats in C#

 Unknown     5:52 AM     No comments   

Code:

public static void Main(string[] args)
{
//Get the cureent date time
DateTime datetTime= DateTime.Now;

Formatting DateTime to full pattern (dddd, MMMM dd, yyyy hh:mm:ss)
Console.WriteLine(dt.ToString("F"));

Formatting DateTime to short date- time pattern (dddd, MMMM dd, yyyy, hh:mm)
Console.WriteLine(dt.ToString("f"));

Formatting DateTime to short date numerical pattern (M/d/yyyy)
Console.WriteLine(dt.ToString("d"));

Formatting DateTime to full date numeric pattern (dddd, MMMM dd, yyyy)
Console.WriteLine(dt.ToString("D"));

To the short date&time numerical pattern (M/d/yyyy hh:mm)
Console.WriteLine(dt.ToString("g"));

To the full date&time numerical pattern (M/d/yyyy hh:mm:ss)
Console.WriteLine(dt.ToString("G"));

DateTime to the month name pattern (MMMM dd)
Console.WriteLine(dt.ToString("m"));

DateTime to the short date pattern (MMMM, yyyy)
Console.WriteLine(dt.ToString("y"));

DateTime to the long time pattern (hh:mm:ss)
Console.WriteLine(dt.ToString("T"));

DateTime to the short time pattern (hh:mm)
Console.WriteLine(dt.ToString("t"));

DateTime to the RFC1123 pattern (ddd, dd MMM yyyy HH':'mm':'ss 'GMT')
Console.WriteLine(dt.ToString("r"));

DateTime to sortable pattern This format is based on ISO 8601 and uses local time.
Console.WriteLine(dt.ToString("s"));

DateTime to full date&time using universal time
Console.WriteLine(dt.ToString("U"));

DateTime to universal sortable pattern (yyyy'-'MM'-'dd HH':'mm':'ss'Z')
Console.WriteLine(dt.ToString("u"));
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to get Memory Info

 Unknown     5:45 AM     No comments   

Namespaces:

using System;

using System.Management;

Code:

static void Main(string[] args)
{

WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");

ManagementObjectSearcher find = new ManagementObjectSearcher(query);

//Traverse each management object.
foreach (ManagementObject mo in find.Get())
{

Console.WriteLine("Available bytes: " + mo["AvailableBytes"]);

Console.WriteLine("Available KBs: " + mo["AvailableKBytes"]);

Console.WriteLine("Available MBs: " + mo["AvailableMBytes"]);

Console.WriteLine("Cache bytes: " + mo["CacheBytes"]);

Console.WriteLine("Cache bytes peak: " + mo["CacheBytesPeak"]);

Console.WriteLine("Cache bytes: " + mo["CacheBytes"]);

Console.WriteLine("Commit limit: " + mo["CommitLimit"]);

Console.WriteLine("Committed bytes: " + mo["CommittedBytes"]);

Console.WriteLine("Free system page table entries: " + mo["FreeSystemPageTableEntries"]);

Console.WriteLine("Pool paged bytes: " + mo["PoolPagedBytes"]);

Console.WriteLine("System code total bytes: " + mo["SystemCodeTotalBytes"]);

Console.WriteLine("System driver total bytes: " + mo["SystemDriverTotalBytes"]);

}

}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Open Control Panel Items using Shell (COM)

 Unknown     5:39 AM     No comments   

Namespaces:

using System;
// this is COM component that can be found under the name "Microsoft Shell Controls And Automation"
// this must be added to project references

using Shell32;

Code:

static void Main()
{
//Creating an object of shell to access all the control panel items.
Shell shell = new Shell();

// accessibility options
shell.ControlPanelItem("access.cpl");

// add-remove programs
shell.ControlPanelItem("appwiz.cpl");

// bluetooth configuration
shell.ControlPanelItem("btcpl.cpl");

// desktop settings
shell.ControlPanelItem("desk.cpl");

// directX properties
shell.ControlPanelItem("directx.cpl");

// add hardware wizard
shell.ControlPanelItem("hdwwiz.cpl");

// internet properties
shell.ControlPanelItem("inetcpl.cpl");

// regional and language options
shell.ControlPanelItem("intl.cpl");

// Wireless link
shell.ControlPanelItem("irprops.cpl");

// Game controllers
shell.ControlPanelItem("joy.cpl");

// Mouse properties
shell.ControlPanelItem("main.cpl");

// Sounds and audio devices properties
shell.ControlPanelItem("mmsys.cpl");

// Network connections
shell.ControlPanelItem("ncpa.cpl");

// User accounts
shell.ControlPanelItem("nusrmgr.cpl");

// ODBC datasource administrator

shell.ControlPanelItem("odbccp32.cpl");

// Power options properties
shell.ControlPanelItem("powercfg.cpl");

// System properties
shell.ControlPanelItem("sysdm.cpl");

// Location information - telephone properties
shell.ControlPanelItem("telephon.cpl");

// Date and time properties
shell.ControlPanelItem("timedate.cpl");

// Automatic updates - WindowsUpdate settings

shell.ControlPanelItem("wuaucpl.cpl");
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Get folder items using Windows folder dialog

 Unknown     5:30 AM     No comments   

Namespaces:

using System;

using Shell32;

Code:

static void Main()
{

Shell shell = new Shell();

// open dialog for desktop folder

// use appropriate constant for folder type ShellSpecialFolderConstants

Folder folder = shell.BrowseForFolder(0, "folderPath/FilePath",0 ,ShellSpecialFolderConstants.ssfDESKTOP); if (folder != null)
{
foreach (FolderItem fi in folder.Items())
{
Console.WriteLine(fi.Name);
}

}

}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Window Controls in ASP.Net

 Unknown     3:12 AM     No comments   

Controls:-----------
Most controls in .NET derive from the System.Windows.Forms.Control class. This class defines the basic functionality of the controls, which is why many properties and events in the controls we'll see are identical. Many of these classes are themselves base classes for other controls, as is the case with the Label and TextBoxBase classes:--


Some controls, named custom or user controls, derive from another class: System.Windows.Forms.UserControl. This class is itself derived from the Control class and provides the functionality we need to create controls ourselves. We'll cover this class in Chapter 14. Incidentally, controls used for designing Web user interfaces derive from yet another class, System.Web.UI.Control.

Properties

All controls have a number of properties that are used to manipulate the behavior of the control. The base class of most controls, Control, has a number of properties that other controls either inherit directly or override to provide some kind of custom behavior.

The table below shows some of the most common properties of the Control class. These properties will be present in most of the controls we'll visit in this chapter, and they will therefore, not be explained in detail again, unless the behavior of the properties is changed for the control in question. Note that this table is not meant to be exhaustive; if you want to see all f the properties in the class, please refer to the MSDN library:

Name Availability Description

Anchor Read/Write Using this property, you can specify how the control

behaves when its container is resized. See below for a detailed explanation of this property.

BackColor Read/Write The background color of a control.

Bottom Read/Write By setting this property, you specify the distance

from the top of the window to the bottom of the control. This is not the same as specifying the height of the control.

Dock Read/Write Allows you to make a control dock to the edges of a

window. See below for a more detailed explanation of this property.

Enabled Read/Write Setting Enabled to true usually means that the control

can receive input from the user. Setting Enabled to false usually means that it cannot.

ForeColor Read/Write The foreground color of the control.

Height Read/Write The distance from the top to the bottom of the control.

Left Read/Write The left edge of the control relative to the left

edge of the window.

Name Read/Write The name of the control. This name can be used to reference the control in code.

Parent Read/Write The parent of the control.

Right Read/Write The right edge of the control relative to the left

edge of the window.

TabIndex Read/Write The number the control has in the tab order of its container.

TabStop Read/Write Specifies whether the control can be accessed by the Tab key.

Tag Read/Write This value is usually not used by the control itself,

and is there for you to store information about the control on the control itself. When this property is assigned a value through the Windows Form designer, you can only assign a string to it.

Top Read/Write The top edge of the control relative to the top of the window.

Visible Read/Write Specifies whether or not the control is visible
at runtime.

Width Read/Write The width of the control.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

An Example to create an UserControl to create a checklist box and how to set default check in ASP.Net Using C#

 Unknown     2:48 AM     No comments   

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace MatrixControl
{
public partial class M42CheckBoxControl : UserControl
{
private static int index = 0;

public M42CheckBoxControl()
{
InitializeComponent();
}
# region Properties
///
/// These are the properties value contains the text string seperated by the seperator
///

private string _value;
public string Value
{
set
{
_value = value;
}
}
///
/// Seperator is also a string by which we will parse the text string.
///

private string _seperator;
public string Seperator
{

set
{
_seperator = value;
}
}
///
/// This is default value means which checkbox will be checked by default.
///

private string _default;
public string Default
{
set
{
_default = value;
}
}

# endregion

#region private

///
/// This event will fire when checkBox will checked or unchecked.
///

///
///
private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
{
//Creates an array of strings upto the number of check boxes avaliable in check box list.

string[] checkedItems = new string[M42CheckedListBox.CheckedItems.Count];

foreach (object objchecked in M42CheckedListBox.CheckedItems)
{
checkedItems[M42CheckedListBox.CheckedItems.IndexOf(objchecked)] = objchecked.ToString();
}
//This join method string.Join(_seperator, collectionOfCheckedItems) will give the selected items.
this.Description.Text= string.Join(_seperator, checkedItems);
}

# endregion

#region public
///
/// This check box option is firstly parse all the values and defaults then store iot in check
/// list boxes and text.
///


public void CheckBoxOption()
{
index = 0;
//This is to split through seperator
string[] parseString = _value.Split(_seperator.ToCharArray());
//thisd is to split the defailt value through seperator
string[] defaultString = _default.Split(_seperator.ToCharArray());
//this default description string array is just to store all the default values.
string[] defaultDescription = new string[defaultString.Length];

//This for loop is just to find the index of default value and create the check boxes.
if (_value != string.Empty)
{
foreach (string value in parseString)
{
if (M42CheckedListBox.Items.Contains(value))
{
}
else
{
M42CheckedListBox.Items.Add(value);
}
}
foreach (string defaultValue in defaultString)
{
if (M42CheckedListBox.Items.Contains(defaultValue))
{
M42CheckedListBox.SetItemCheckState(M42CheckedListBox.Items.IndexOf(defaultValue), CheckState.Checked);
defaultDescription[index++] = (defaultValue);
}
this.Description.Text = string.Join(_seperator, defaultDescription);
}
}
}

# endregion

}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to Send data from a User Control to another user control on a single form using Events and Delegates:--

 Unknown     2:40 AM     No comments   

This is an example how to create Dynamic Check Boxes and how to communicate betwwen two user controls on a sigle form using Events and Delegates.
In this application I have to send some data from control2 to control1 on a single button click.So for this i have used event and Delegates.

Have A look.
//Control2:----
namespace ParserF
{
public partial class Control2 : UserControl
{
public ArrayList CheckBoxName = new ArrayList();
public char[] seperator = new char[5];
static int count = 0, indexing=0;
public delegate void PassSelectedValues(ArrayList CheckBoxName, int countDefault);
public event PassSelectedValues DataSelected;
public int Flag = 0;

public Control2()
{
InitializeComponent();
}

# region Properties
///
/// These are the properties value contains the text string seperated by the seperator
///

private string _Value;
public string Value
{
get
{
return _Value;
}
set
{
_Value = value;
}
}
///
/// Seperator is also a string by which we will parse the text string.
///

private string _Seperator;
public string Seperator
{
get
{
return _Seperator;
}
set
{
_Seperator = value;
}

}
///
/// This is default value means which checkbox will be checked by default.
///

private string _Default;
public string Default
{
get
{
return _Default;
}
set
{
_Default = value;
}
}

# endregion

# region private

///
/// This function is just when we will click on Ok button then all the data will be sent to control1
/// by delegate public delegate void PassSelectedValues(ArrayList CheckBoxName, int ind);
/// and event public event PassSelectedValues DataSelected; In this function i m taking a string Builder
/// Temporary String in that we will store the string after parsing through seperator and then store it in a arraylist.
///
///

///
///
private void OkButton_Click(object sender, EventArgs e)
{
StringBuilder TemporaryString = new StringBuilder();

InitializaValues();
//This if codition will check that value (Text String) contains default or not .If yes the continue otherwise will make a messagebox.
if (Value.Contains(Default))
{
for (int index = 0; index < Seperator.Length; index++)
{
seperator[index] = Seperator[index];
}
//This for loop is just to extract strings upto the length of the value
for (; (indexing < Value.Length); indexing++)
{
if (Value[indexing] != seperator[0])
{
TemporaryString.Append(Value[indexing]);
}
else
{
if (Flag == 0)
{
count++;
}
String str = TemporaryString.ToString();
//This if condition is just to comapare default one and store the index.
if (!System.Convert.ToBoolean((str.CompareTo(Default))))
{
Flag = count;
count = 0;
}

//This will add the string to the array list
CheckBoxName.Add(str);
//This will replace the string Builder Temporary String to Empty One.
TemporaryString.Replace(str, String.Empty);
}
}
if ((indexing == Value.Length)&&(Flag==0))
{
Flag = (count+1);
}
String str1 = TemporaryString.ToString();
CheckBoxName.Add(str1);
//DataSelected is the event which will fire by this we are sending the arraylist and the index for defaultCheck
DataSelected(CheckBoxName, Flag-1);
}
else
{
MessageBox.Show("No focus set due to No string matches from TextString");
}
}
///
/// This is just to Inotialize values to the text boxes.
///

private void InitializaValues()
{
Value = ValueTextBox.Text;
Seperator = SeperatorTextBox.Text;
Default = DefaultTextBox.Text;
}

# endregion
}
}

//Control1:---

namespace ParserF
{
public partial class Control1 : UserControl
{

public Control1()
{
InitializeComponent();
}
public int flag1;
ArrayList Array1 = new ArrayList();
static int index2 = 0;

public ArrayList SelectedCheckBox
{

set
{
Array1 = value;
}

}
public int indexing
{

set
{
flag1 = value;
}

}

public void AddCheckBox()
{
for (int index = 0; index < Array1.Count; index++)
{
CheckBox checkBox = new CheckBox();
checkBox.AutoSize = true;
checkBox.Location = new Point((28), (27 + index2));

checkBox.Size = new System.Drawing.Size(80, 17);
checkBox.Text = Array1[index].ToString();
if (index == flag1)
{
checkBox.Checked = true;
}
if (checkBox.Checked)
{
textBox1.Text = checkBox.Text;
}
checkBox.UseVisualStyleBackColor = true;
index2 += 20;
Controls.Add(checkBox);
checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);

}
}
///
/// This is an event which will fire when a user will check the check Box
///

///
///
private void checkBox_CheckedChanged(object sender, System.EventArgs e)
{
if (((CheckBox)sender).Checked == true)
{
if (textBox1.Text == string.Empty)
{
textBox1.Text = ((CheckBox)sender).Text;
}
else
{
textBox1.AppendText(",");
textBox1.AppendText(((CheckBox)sender).Text);
}
}
else if (textBox1.Text == ((CheckBox)sender).Text)
{
textBox1.Text = string.Empty;
}
else
{
int FirstIndex=textBox1.Text.IndexOf(((CheckBox)sender).Text);
int length=((CheckBox)sender).Text.Length;
string str1=textBox1.Text.Remove(FirstIndex, length);
textBox1.Text = str1;
}
}

private void Control1_Load(object sender, EventArgs e)
{

}

private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}
}
}

//Form1.cs

namespace ParserF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
control21.DataSelected += new Control2.PassSelectedValues(passValuesHandlerMethod);
}
protected void passValuesHandlerMethod(ArrayList CheckBoxName, int flag2)
{
control11.SelectedCheckBox = CheckBoxName;
control11.flag1 = flag2;
control11.AddCheckBox();
}
private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
{

}

private void control21_Load(object sender, EventArgs e)
{

}

private void control11_Load_1(object sender, EventArgs e)
{

}

}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

About The Author

Unknown
View my complete profile

Total Pageviews

Popular Posts

  • Clr - Common Language Runtime
    .Net framework provides a run time environment - CLR. Common language runtime takes the IL code from the compiler( language specific) and p...
  • Predicate delegate in C#
    Hello Everyone, In the article we will talk about Predicate delegate. Predicate is also a delegate which encapsulate a method that takes...
  • Auto logout chrome extension for Gmail
    Hello Friends, In the last article we learned to create a sample chrome extension. Here we are going to create auto logout Gmail script as...
  • .Net Framework overview
    Hello friends : Here i am writing my first article on .Net framework anyways....So the question is What is .Net Framework ? The .Net fram...
  • Nagarro Placement Papers..
    Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are...
  • C code to Check the string has valid identifier or not in.
    #include #include #include char keyword[][10]={"auto","break","case","char","const","...
  • What does it mean by disconnected data access architecture of ADO.Net?
    ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the databa...
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?
    Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss w...
  • Delegates in C Sharp
    A Delegate is a type variable that holds the reference to a method. Delegates are similar to Pointer to functions in C and C++ When we...
  • Garbage Collection - Automatic memory management
    While thinking of this question few things are coming in my mind ~ How .Net reclaims objects and memory used by an application ? So the ans...

Blog Archive

  • ▼  2016 (4)
    • ▼  September (2)
      • ▼  Sep 03 (2)
        • Auto logout chrome extension for Gmail
        • Auto logout chrome extension for facebook
    • ►  August (1)
      • ►  Aug 28 (1)
    • ►  April (1)
      • ►  Apr 24 (1)
  • ►  2015 (12)
    • ►  September (10)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 27 (2)
      • ►  Sep 26 (3)
      • ►  Sep 20 (1)
      • ►  Sep 19 (1)
    • ►  August (1)
      • ►  Aug 16 (1)
    • ►  March (1)
      • ►  Mar 31 (1)
  • ►  2013 (10)
    • ►  June (1)
      • ►  Jun 16 (1)
    • ►  April (1)
      • ►  Apr 21 (1)
    • ►  February (8)
      • ►  Feb 18 (3)
      • ►  Feb 17 (2)
      • ►  Feb 16 (2)
      • ►  Feb 15 (1)
  • ►  2012 (1)
    • ►  May (1)
      • ►  May 27 (1)
  • ►  2010 (22)
    • ►  October (14)
      • ►  Oct 21 (1)
      • ►  Oct 06 (12)
      • ►  Oct 04 (1)
    • ►  April (2)
      • ►  Apr 22 (1)
      • ►  Apr 16 (1)
    • ►  March (1)
      • ►  Mar 30 (1)
    • ►  January (5)
      • ►  Jan 08 (3)
      • ►  Jan 01 (2)
  • ►  2009 (110)
    • ►  December (8)
      • ►  Dec 18 (2)
      • ►  Dec 05 (1)
      • ►  Dec 04 (5)
    • ►  November (1)
      • ►  Nov 27 (1)
    • ►  October (14)
      • ►  Oct 09 (4)
      • ►  Oct 07 (1)
      • ►  Oct 06 (3)
      • ►  Oct 05 (3)
      • ►  Oct 01 (3)
    • ►  September (17)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 25 (1)
      • ►  Sep 24 (1)
      • ►  Sep 17 (2)
      • ►  Sep 15 (3)
      • ►  Sep 11 (2)
      • ►  Sep 09 (3)
      • ►  Sep 08 (2)
    • ►  August (31)
      • ►  Aug 31 (1)
      • ►  Aug 27 (3)
      • ►  Aug 26 (1)
      • ►  Aug 25 (2)
      • ►  Aug 24 (1)
      • ►  Aug 22 (2)
      • ►  Aug 21 (3)
      • ►  Aug 20 (2)
      • ►  Aug 19 (3)
      • ►  Aug 18 (1)
      • ►  Aug 16 (1)
      • ►  Aug 12 (2)
      • ►  Aug 11 (1)
      • ►  Aug 10 (3)
      • ►  Aug 07 (4)
      • ►  Aug 06 (1)
    • ►  July (24)
      • ►  Jul 25 (4)
      • ►  Jul 24 (20)
    • ►  April (15)
      • ►  Apr 10 (3)
      • ►  Apr 07 (9)
      • ►  Apr 06 (3)

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments
copyright @ TechGiant 2015. Powered by Blogger.

Disclaimer

This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Followers

Copyright © A Developer Journey who codes for fun | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com