RSS

Sql CASE With IN

The Bellow statements used to access the CASE With IN Condtions for Selecting the city Names


DECLARE @City AS Varchar(30)
SELECT buildingid,(
CASE
WHEN buildingid IN (1,2,3)
THEN 'Chennai'
WHEN buildingid=6
THEN 'Madurai'
WHEN buildingid=7
THEN 'Thiruchy'
ELSE ''
END) AS 'City Name'
FROM tHMSFloor

read comments Read User's Comments

Using SubString,Left Right and Reverse in SQL Server


DECLARE @IP Varchar(20)
SET @IP='10.161.105.148'
SELECT SUBSTRING(@IP,1,LEN(@IP)-4)
-- This is get the Sub String of the IP

-- Result
--100.1601.105

-- Using Left in Sql Server

SELECT LEFT(@IP,LEN(@IP)-4)
SELECT RIGHT(@IP,LEN(@IP)-4)

Result
-----
10.161.105
61.105.148

DECLARE @MachineIP NVARCHAR(20)
SET @MachineIP='10.2.15.132'
-- Bellow Query is used to Reverse the given String
SELECT Reverse(@MachineIP)
-- This used to get First Three Part of the IP Address
SELECT SUBSTRING(@MachineIP ,1 ,Len(@MachineIP)-(CHARINDEX('.',Reverse(@MachineIP),-1)))

/*------ Result ------
231.51.2.01
10.2.15
---------------------- */

A Simple Example For Group By Having

Create table #temp(name varchar(20))
insert into #temp values('Siva')
insert into #temp values('Raghu')
SELECT Name +' - ' + Cast(count(Name)As varchar) FROM #temp Group by Name
--Having Name='siva'
drop table #temp

Result:
Babu - 2
Raghu - 1
Siva - 2

read comments Read User's Comments

More about Sql_Variant

- Microsoft introduced the sql_variant in SQL Server 2000. We can use the sql_variant to store data of an unspecified or inconsistant type Or to store data of almost any SQL Server datatype.
- A sql_variant can hold any datatype except text, ntext, image, and timestamp without conversion.
For example, the following Query will explains how this acts

Declare @var1 sql_variant, @var2 sql_variant
Declare @var3 sql_variant, @var4 sql_variant,@var5 sql_variant
Declare @IntVar as integer, @DatetimeVar as Datetime
Declare @MoneyVar as Money, @BitVar as bit,@decimalVar as float
--To Assign Values to the correct data type variables
Set @IntVar = 37
Set @DatetimeVar = '2/18/02'
Set @MoneyVar = $37.23
Set @BitVar = 1
Set @decimalVar =0.5678
--To assign the values to the Sql_variant Data type variables
Select @var1 = @MyInt,
@var2 =@DatetimeVar,
@var3 = @MoneyVar,
@var4 = @BitVar,
@var5=@decimalVar
--To display the Result
Select @var1 as [Int Data Type],
@var2 as [Datetime Data Type],
@var3 as [Money Data Type],
@var4 as [Bit Data Type],
cast(@var5 as numeric(5,5)) as [Decimal Data Type]

- We can use the SQL_VARIANT_PROPERTY function to identify the Data Type.
Select sql_variant_property(@var1, 'BaseType')
SELECT sql_variant_property(@var5,'BaseType')

read comments Read User's Comments

SQL Interview Questions

Some of the Sql Server Questions
1.What is Log Shipping and its purpose


In Log Shipping the transactional log file from one server is automatically updated in backup database on the other server and in the case when one server fails the other server will have the same DB and we can use this as the DDR(disaster recovery) plan.


2.What is the advantage of SET NOCOUNT ON


When we use SELECT and DML statement in SQL .SQL server return a message which specify the number of rows effected by these statements. This information helps coder when they are debugging the code other wise this is not useful we can disable this by typing SET NOCOUNT ON. It is very helpful when we are doing on store procedure contains lots of statements,loops its also increase in performance and boost network traffic.


3.How to load .NET code in SQL SERVER 2005


First of all write managed code and compile it to DLL/Assembly.Now we can load the assembly in SQL SERVER.Here i have given a example of SQL SERVER. CREATE ASSEMBLY percode FROM 'c:/percode.dll'


4.What are the Global Temporary Tables


We can create global temporary tables but these are not using much in sql an the name of these table start with two pound signs. For example, ##interviewqsn is a global temporary table.As the name suggest these table is Global temporary tables and visible to all SQL Server connections. When we create any one of these all users can see it.

5.What are Checkpoint in SQL Server


When we done operation on SQL SERVER that is not commited directly to the database.All operation must be logged in to Transaction Log files after that they should be done on to the main database.CheckPoint are the point which alert Sql Server to save all the data to main database if no Check point is there then log files get full we can use Checkpoint command to commit all data in the SQL SERVER.When we stop the SQL Server it will take long time because Ch eckpoint is also fired.

read comments Read User's Comments

Generics and Nullables in C# 2.0

Generics in C# 2.0
1. The Generics was added to C# 2.0 to remove the need for casting, improve type safety, reduce the amount of boxing required, and to make it easier to create generalized classes and methods.
2. Generic classes and methods accept type parameters, which specify the type of objects that they operate on.
3. Version 2.0 of the .NET Framework Class Library includes generic versions of many of the collection classes and interfaces in the System.Collections.Generic namespace
EX:

using System.Collections.Generic;
...
Queue myQueue = new Queue();
Circle myCircle = new Circle();
myQueue.Enqueue(myCircle);
...
myCircle = myQueue.Dequeue();


NOTE:
• The use of the type parameter between the angle brackets, , when
declaring the myQueue variable.
• The lack of a cast when executing the Dequeue method.
* The compiler will check to ensure that types are not accidentally mixed,
generating an error at compile time rather than runtime if you try to
dequeue an item from circleQueue into a Some other object.
- The bellow class explains the Generic with Delegate of Type T

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public delegate void dele1(T x);

class Class1
{
public void fn1(int x)
{
Console.WriteLine(x);
}
public void fn2(string x)
{
Console.WriteLine(x);
}
}
class myclass
{
static void Main(string[] ar)
{
Class1 c = new Class1();
dele1 ob = new dele1(c.fn1);
dele1 ob1 = new dele1(c.fn2);
ob(10);
ob1("stg");
}
}
}

Nullable Types in C# 2.0
We can now assign the null value to value types by defining nullable types. We do this by adding a question mark to the immediate right of the type name when defining a variable. Nullable types derive from the generic type System.Nullable. Instead of defining types from this generic class, We can simply just use T? (where T is the type (class, struct, etc.).

Two properties make nullable types quite useful: HasValue and Value. HasValue evaluates to true if the type is not null, otherwise it's false. Value will return the underlying value, whether it's null or not.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Class3
{
static void Main(string[] a)
{
int? myInt1 = null;

if (myInt1 == null)
Console.WriteLine("myInt1 is null.");
else
Console.WriteLine("myInt1 is Not null.");
// Or, we can check for a value this way:
myInt1 = 1;
if (myInt1.HasValue)
Console.WriteLine("myInt1 has a value = {0}", myInt1.Value);
else
Console.WriteLine("myInt1 is null.");
}
}
}

read comments Read User's Comments

About Partial Classes in C#

The C# Partial Class
• C# 1.1 requires you to put all the code for a class in a single file
• C# 2.0 allows you to split the definition and implementation of a class or a
struct across multiple files. You can put one part of a class in one file and
another part of the class in a different file, noting the split by using the new
partial keyword
* Normally Partial Classes are classes that can be defined at more than one
location, but which contain different members.
* Partial Classes also allow you to store the same class, with different members, in
different physical locations.

using System;
using System.Collections.Generic;
using System.Text;
namespace PartialClassExample
{
public partial class class1
{
public void fn1()
{
Console.WriteLine("Hi");
}
}

public partial class class1
{
public void fn2()
{
Console.WriteLine("Hello");
}
}

public partial class class1
{
public void fn3()
{
Console.WriteLine("Bye");
}
}

public class myclass
{
static void Main(string[] ar)
{
class1 ob = new class1();
ob.fn1();
ob.fn2();
ob.fn3();
}
}
}

• Partial type support is available for classes, structures, and interfaces, but you
cannot have a partial enum definition.
• ASP.NET 2.0 uses partial classes for the code-beside class (the evolution of
codebehind), storing the machine-generated part of the page separately.
• Windows® Forms uses partial classes to store the visual designer output of the
InitializeComponent method as well as the member controls.
• Partial types also enable two or more developers to work on the same type while
both have their files checked out from source control without interfering with
each other.
• C# 2.0 supports partial types as follows: when the compiler builds the assembly,
it combines from the various files the parts of a type and compiles them into a
single type in Microsoft intermediate language (MSIL). The generated MSIL has no
recollection which part came from which file. Just like in C# 1.1 the MSIL has no
record of which file was used to define which type.
• Also worth noting is that partial types cannot span assemblies, and that a type
can refuse to have other parts by omitting the partial qualifier from its
definition.
Note: Classname should be the same in different files
changes made to the file will be lost if you regenerate the wrapper class. Using a partial class, you can factor those changes into a separate file.

read comments Read User's Comments

Some of the Basic Javascript user defind functions

To Identify of there is a any Item is available in a List box Using Javascript


function CheckSelected() {
var sMsg = "";
if (document.getElementById('<%=lstMinorErrors.ClientID %>') != null) {
//alert(document.getElementById('<%=lstMinorErrors.ClientID %>').options.length);
if (document.getElementById('<%=lstMinorErrors.ClientID %>').options.length < 0) {
sMsg = "No Items Found to Insert!"
}
}
if (sMsg != "") {
alert(sMsg);
return false;
}
else
return true;
}

To valid Gridview if any of the Checkbox item Selected or Not:

//To check whether the user checked any of the item in a Gridview for Delete Options
function ClientCheck(sMsg) {
var valid = false;
var gv = document.getElementById('<%=gvMinorErrorMaster.ClientID%>');//gvMinorErrorMaster- denotes gridview Name

for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Please select a checkbox to continue.");
}
else {
var sConform = confirm(sMsg);
if (sConform == true)
valid = true;
else
valid = false;
}
return valid;
}


//In code behind of the page_load Event:
btnDelete.Attributes.Add("OnClick", "return ClientCheck('Are you sure to Delete the Selected Rows.');");

To check if any of the Items user select in a DropDown List

function CheckSearchProCustSel() {
var ddlReport;
var sObj;
var sErrMsg = "";
ddlReport = document.getElementById("<%=ddlSProCust.ClientID%>");//ddlSProCust- denotes Dropdown list Id
sObj = ddlReport.options[ddlReport.selectedIndex].value;//Get the Selected index value
//check if the selectedindex
if (sObj == 0) {
sErrMsg = "Select Customer-Project to Serach! \n";
}
if (sErrMsg != "") {
alert(sErrMsg);
return false;
}
else
return true;
}

To Trim the Spaces in a String from the textbox or other controls:

// Removes leading whitespaces
function LTrim(value) {
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim(value) {
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim(value) {
return LTrim(RTrim(value));
}

read comments Read User's Comments

Move Items Between 2 ListBoxes Using Javascript

Just wrote this little JavaScript snippet to your asp.net page and make a moment of Items between two ListBox.

 
<script>

function MoveItem(ctrlSource, ctrlTarget) {
var Source = document.getElementById(ctrlSource);
var Target = document.getElementById(ctrlTarget);
if ((Source != null) && (Target != null)) {
while ( Source.options.selectedIndex >= 0 ) {
var newOption = new Option(); // Create a new instance of ListItem
newOption.text = Source.options[Source.options.selectedIndex].text;
newOption.value = Source.options[Source.options.selectedIndex].value;
Target.options[Target.length] = newOption;//Append the item in Target
Source.remove(Source.options.selectedIndex);//Remove the item from Source
}
}
}
</script>

And the HTML Code of the Page:

<table height="150" width="300">
<tr>
<td>
<asp:ListBox id="ListBox1" runat="server" Height="111px" SelectionMode="Multiple">
<asp:ListItem Value="1">One</asp:ListItem>
<asp:ListItem Value="2">Two</asp:ListItem>
<asp:ListItem Value="3">Three</asp:ListItem>
</asp:ListBox>
</td>
<td>
<p>
<input onclick="Javascript:MoveItem('ListBox1', 'ListBox2');" type="button" value="->" />
</p>
<p>
<input onclick="Javascript:MoveItem('ListBox2', 'ListBox1');" type="button" value="<-" />
</p>
</td>
<td>
<asp:ListBox id="ListBox2" runat="server" Height="111px" SelectionMode="Multiple">
<asp:ListItem Value="8">Eight</asp:ListItem>
<asp:ListItem Value="9">Nine</asp:ListItem>
<asp:ListItem Value="10">Ten</asp:ListItem></asp:ListBox>
</td>
</tr>
</table>

read comments Read User's Comments

How to Register and Call the Client Side Script

- We can register and call the Javascript while the page load event using the 'Page.ClientScript.RegisterStartupScript()' method.
-If you want intimate some inforamtion before user viewing the page we can use this kind of Ajax style javascript calling.

Setps
1. Create a Javascript eighter in design page or inline javascript string for calling the RegisterStartupScript method.
2. Write the Page Load event and use the page.ClientScript.RegisterStartupScript.
example:


function SetPanelHeight(gvCellMaster) {
if (document.getElementById(gvCellMaster) != null) {
if (document.getElementById(gvCellMaster).clientHeight > 410) {
document.getElementById('gvCellMaster').style.height = "410px";
}
}
}
//In Code behind Page( i.e .cs page) of the Page Load event
//This bellow function calls the Javascript of SetPanelHeight
//Change the Grid
protected void page_Load(object sender, EventArgs e) {
string jscript = "";
jscript = "";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", jscript);
}

read comments Read User's Comments

Creating Negative Identity Column

We can creating the Negative Identity Column in SQL server
- We can create a nagative Identity and the negative seed values for the the Identity column.


Create Table Emp
(
RecID int Not NULL IDENTITY (-100,-1),
Name Varchar(30)
)

-- To insert the value to Table:
Insert into EMP(Name)
SELECT 'Siva'
Union ALL
SELECT 'Kannan'
Union ALL
SELECT 'Krishna'
Union ALL
SELECT 'Devi'
Go
SELECT * FROM EMP


Result
------
-100 Siva
-101 Kannan
-102 Krishna
-103 Devi

read comments Read User's Comments

To Modify The Config File Using C#

We Can modify the configuration files app settings and the Connection Strings through Configuration Manager.

- Add the Reference of System.Configuration for accessing the ConfigurationManager Class.

The Bellow Method is used to Modify the Value of the AppSettings Key Values.


private void ModifyKeyValue(string strKey, string strValue)
{
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Check if the key available
if (!Array.Exists(config.AppSettings.Settings.AllKeys, delegate(string s) { return (s == strKey); }))
{
//Create the Key and assign value
config.AppSettings.Settings.Add(strKey, strValue);
}
else
{
// Add an Application Setting.
config.AppSettings.Settings[strKey].Value = strValue;
}
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}



We can also Remove the already available Keys and Values after that recreate the New Keys using the bellow method:


private void DropAndCreateKey()
{
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Remove("Name");
config.AppSettings.Settings.Add("Name", "Krishna");
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
String siteID = ConfigurationManager.AppSettings["Name"].ToString(); //GetValue("Name");
}

read comments Read User's Comments

To Listing the Files of the Directroy as a Data Table Using LINQ in C#

Introduction

The LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

The Bellow class Use the Advantage og the LINQ througth the from,Select and where keys.IEnumerable data type is mainly used to handle the collections of items with different types.


// This class is used to Get the Picture Files from given Path and
// set the list of files as Data Table Using LINQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace WindowsFormsApplication1
{
class Helper
{
public String DirPath { get; set; }
public String FileType { get; set; }
public Helper(String sPath, String sFileType)
{
DirPath = sPath;
FileType = sFileType;
}
// To Get the IEnumerable type of Files List
public IEnumerable GetFiles()
{
try
{
// Simple LINQ in Files Systems
IEnumerable ObjFilesList = from String sFile in Directory.GetFiles(DirPath, FileType, SearchOption.AllDirectories)
select sFile;
return ObjFilesList;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return null;
}
}
//To Get the Data Table
public DataTable GetDataTable()
{
IEnumerable ObjlstFiles = null;
DataTable Objdt = new DataTable();
try
{
ObjlstFiles = GetFiles(); //"D:\\Siva\\Icons", "*.ico");
Objdt.Columns.Add("ICON File Names");
foreach (String sFileName in ObjlstFiles)
{
DataRow Objdr = Objdt.NewRow();
Objdr["ICON File Names"] = sFileName;//sFileName.Replace(DirPath, String.Empty);
Objdt.Rows.Add(Objdr);
}
return Objdt;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return null;
}
}
}
}

// Now we can get the DataTable and display in the DataGrid.

ObjHelper = new Helper(@"D:\Siva\Images\", "*.jpg");
Objdt = ObjHelper.GetDataTable();
if (Objdt.Rows.Count > 0)
{
grdvFiles.DataSource = Objdt.DefaultView;
grdvFiles.AutoResizeColumns();
grdvFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
else
{
lblMsg.Text = "Sorry!, No Picture File Found";
lblMsg.ForeColor = Color.Red;
}

Download the sample Application for Image Viewer Click Here

read comments Read User's Comments

Some of the important SQL SERVER Functions


  1. @@CONNECTIONS - return the number of connections since sql server was started.

  2. @@CPU_BUSY
    - return the time in milliseconds that the CPU has been actively doing work since
    sql server was started.

  3. @@CURSOR_ROWS - the number of rows currently in the last cursor set opened on the current connection.

  4. @@DATEFIRST
    - returns the numeric value that corresponds to day of week.
    1 -> Monday to 7 -> Sunday

  5. @@DBTS - returns the last used timestamp for the current database.

  6. @@ERROR - Return the error code of the last sql statement

  7. @@IDENTITY - returns the identity value of the last sql insert statement.
  8. @@FETCH_STATUS - return the indicator of the of the last cursor fetch operation.

  9. Replication is the process of automatically doing what, in a very loose sense, amount of copying some or all the information in your database to some other database. The other database may be on the same physical machine as the original, or it may be located remotely.

  10. To View the total table in database    SELECT NAME FROM SYSOBJECTS WHERE TYPE='U'

  11. Stored Procedure with output parameter       Create Proc USP_GetEmpDetails

  12. Normalization: The process of organizing data to minimize redundancy is called normalization.

  13. De-Normalization:
    De-normalization is the process of attempting to optimize the performance of a database by adding redundant data.

  14.  Use SET NOCOUNT ON/OFF while using SELECT and Other DML Commands.

  15. E.g.
    CREATE PROC dbo.ProcName
    AS
    SET NOCOUNT ON;
    --Procedure code here
    SELECT column1 FROM dbo.TblTable1
    -- Reset SET NOCOUNT to OFF
    SET NOCOUNT OFF;
      GO 
  16.  Use Schema Name with Object Name while writing the Stored Procedures(Sql Server 2005)
    e.g.SELECT EMPNO, NAME FROM Dbo.EMPLOYEE

  17. Do not use the prefix “sp_Trans” in the stored procedure name. Use like
    "USP_Trans"

read comments Read User's Comments

Programmatically Setting meta Tag's Keywords and Description Tags in Asp.Net 4

Programmatically Setting <meta> Keywords and Description Tags

- The <head> element in an HTML document provides metadata about the web page, including the page's title (via the <title> element), and links to external CSS and JavaScript files, among other information.

- ASP.NET offers ways to have this metadata assigned automatically or programmatically. For example, you can programmatically set the page's title using the Page class's Title property. (See Dynamically Setting the Page's Title for more information.) Likewise, when using ASP.NET Themes any stylesheets defined in the theme are automatically included in the page's <head> section.

- When crawling through the pages in a website, a search engine spider will examine the <head> section to determine more information about the page. A page's keywords and a human-friendly description of the page may be included in the <head> section through the use of <meta> elements. For example, the following <head> element includes a hard-coded title and hard-coded keyword and description <meta> tags:


<head runat="server">
<title>The web page title...</title>
<meta name="keywords" Content="your,keywords,each
one delimited by a,comma" />
<meta name="description" content="A description of your web page
goes here." />
</head>


- ASP.NET 4 adds two new properties to the Page class that allow for these two <meta> tags to be specified programmatically:

* MetaKeywords, and
* MetaDescription


- You can set these properties from code just like you can the Page.Title property. For example, to generate the above></meta> tags programmatically we'd simply need to add the following lines of code to the ASP.NET page's code-behind class:
 
Page.MetaKeywords = "your,keywords,each one delimited by a,comma";
Page.MetaDescription = "A description of your web page goes here.";

read comments Read User's Comments

Bulk Copy Using ADO.Net Sql Client

Bulk Copy Using ADO.Net Sql Client

The Namespace System.Data.SqlClient's SqlBulkCopy class is used to copy the data from the one SQl Server table To another other table in the same or another database.

The Metod "WriteToServer" is used to write the source data to destination table.
The Bellow C# Class used for Bulk Copy


public class CopyData
{
string _sourceConnectionString;
string _destinationConnectionString;

public CopyData(string sourceConnectionString,string destinationConnectionString)
{
_sourceConnectionString = sourceConnectionString;
_destinationConnectionString = destinationConnectionString;
}

public void CopyTable(string table)
{
using (SqlConnection source = new SqlConnection(_sourceConnectionString))
{
string sql = string.Format("SELECT * FROM [{0}]",table);
SqlCommand command = new SqlCommand(sql, source);
source.Open();
IDataReader dr = command.ExecuteReader();
using (SqlBulkCopy copy = new SqlBulkCopy(_destinationConnectionString))
{
copy.DestinationTableName = table;
copy.WriteToServer(dr);
}
}
}
}
//To using the bellow code we can create object and call the buk copy method with the table name
CopyData c = new CopyData("Server=server;Database=Northwind;Integrated Security=SSPI", "Server=server;Database=master;Integrated Security=SSPI");
c.CopyTable("Orders");

read comments Read User's Comments

Encrypt and Decrypt your self some of the String

Encrypt and Decrypt your Self Using Base64

- To Encrypt the ASCIIEncoding and ToBase64String

Dim a() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("9894465945")
Dim ent As String = Convert.ToBase64String(a)
MsgBox(ent)


- To Decrypt the Encrypted String
Dim k() As Byte = Convert.FromBase64String("OTg5NDQ2NTk0NQ==")
Dim et As String = System.Text.ASCIIEncoding.ASCII.GetString(k)
MsgBox(et)

read comments Read User's Comments

To Set Custom Heading in the Winfrom's Tab Control

We can set using the bellow code :


private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
// TestTab.Properties.Resources.
TabPage CurrentTab = tabControl1.TabPages[e.Index];
Rectangle ItemRect = tabControl1.GetTabRect(e.Index);
SolidBrush FillBrush = new SolidBrush(Color.Indigo);
SolidBrush TextBrush = new SolidBrush(Color.Ivory);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;

//If we are currently painting the Selected TabItem we'll
//change the brush colors and inflate the rectangle.
if (System.Convert.ToBoolean(e.State & DrawItemState.Selected))
{
FillBrush.Color = Color.Khaki;
TextBrush.Color = Color.Purple;
ItemRect.Inflate(2, 2);
}

//Set up rotation for left and right aligned tabs
if (tabControl1.Alignment == TabAlignment.Left || tabControl1.Alignment == TabAlignment.Right)
{
float RotateAngle = 90;
if (tabControl1.Alignment == TabAlignment.Left)
RotateAngle = 270;
PointF cp = new PointF(ItemRect.Left + (ItemRect.Width / 2), ItemRect.Top + (ItemRect.Height / 2));
e.Graphics.TranslateTransform(cp.X, cp.Y);
e.Graphics.RotateTransform(RotateAngle);
ItemRect = new Rectangle(-(ItemRect.Height / 2), -(ItemRect.Width / 2), ItemRect.Height, ItemRect.Width);
}

//Next we'll paint the TabItem with our Fill Brush
e.Graphics.FillRectangle(FillBrush, ItemRect);

//Now draw the text.
e.Graphics.DrawString(CurrentTab.Text, e.Font, TextBrush, (RectangleF)ItemRect, sf);

//Reset any Graphics rotation
e.Graphics.ResetTransform();

//Finally, we should Dispose of our brushes.
FillBrush.Dispose();
TextBrush.Dispose();
}

read comments Read User's Comments

Working with Culture Info

How to create the Culture Info for Date Time Format Provider

CultureInfo represents information about a specific culture including the names of the culture, the writing system, and the calendar used, as well as access to culture-specific objects that provide information for common operations, such as formatting dates and sorting strings.


The CultureInfo class holds culture-specific information, such as the associated language, sublanguage, country/region, calendar, and cultural conventions. This class also provides access to culture-specific instances of DateTimeFormatInfo, NumberFormatInfo, CompareInfo, and TextInfo. These objects contain the information required for culture-specific operations, such as casing, formatting dates and numbers, and comparing strings.


Assembly: Mscorlib (in Mscorlib.dll)
Namespace: System.Globalization

using System.Globalization;

To Create Object for CultureInfo:
CultureInfo Culture = new CultureInfo("en-Us");
DateTime Dt=Convert.ToDateTime("01/01/1984",Culture);

-> Culture For Tamil India -> ta-IN , ta
- For More About CultureInfoVisit MSDN

read comments Read User's Comments

How to Use Background Worker to Update the UI or Win Form Controls

About BackgroundWorker Process

When we have a function that takes a long time and it freezes the screen, the user gets nervous. They simply don't like to lose the control. It would give a friendly impression when they can still click on the form while the application is busy with getting the information.



For example, when you start implementing asynchronous methods, you will wonder which technique is best suitable for your application. Would you use a Timer class or a Thread class or a Background Worker? This post uses a BackgroundWorker class to show how easy it is, and where we need to pay attention when using it.



- There are three event handler methods are available to call the method asynchronously.
1. DoWork Event Handler
The DoWork method is like any other event handler.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Very time-consuming process or method.
}

2.RunWorkerCompleted Method
This event handler is used to display the status of the worker process after completion. So we can use for to display “Success” or “Failed” of the Process.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Convert.ToBoolean(e.Result) == true)
MessageBox.Show("Process List Loaded Successfully!");
else
MessageBox.Show("Process List Load Failed!");

}

3.Progress Changed Method
This is used to display the status of the process. For example we will have a Progress bar and each and every step increase the Progress status.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){  }

Some of other important Keys are:

1.e.Argument – Used to get the parameter reference received by RunWorkerAsync.
2.e.Result - Check to see what the BackgroundWorker processing did
3.backgroundWorker1.RunWorkerAsync(object)
Called to start a process on the worker thread.
4.DoWorkEventArgs e :
Contains e.Argument and e.Result, so it is used to access those properties.

How to Accessing the Win Forms Controls form the Background worker:

- We can access through the anonymous methods of C#. The bellow example shows how to access the win forms combo box control through the background worker process.
- In this example retrieve the current process name list available of your system.



- So first add the namespace to Process, Thread class
using System.Diagnostics;
using System.Threading;

- To call background worker’s RunWorkerAsync() method
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}

- Next Background worker’s DoWorker Method
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// To call method directly
// bflg = LoadCombo();
// To call Using delegates
ToLoadCombo Tocall = new ToLoadCombo(LoadCombo);
e.Result = Tocall();
}

- Then Next Step we need to include LoadCombo()
//Public Method For Accessing Form Control (i.e CmbProcess)
public bool LoadCombo()
{
//Here is a simple way to update any UI controls from worker threads
// using anonymous methods and local variable capture.
try
{
new Thread(delegate() // anonymous methods
{
this.Invoke((ThreadStart)delegate() // anonymous methods Call
{
foreach (Process item in Process.GetProcesses())
{
cmbProcess.Items.Add(item.ProcessName.ToString());
}
cmbProcess.SelectedIndex = 0;
});
}).Start();
}
catch
{
return false;
}
return true;
}

- At Last we need to add RunWorkerCompleted Event Handler

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Convert.ToBoolean(e.Result) == true)
MessageBox.Show("Process List Loaded Successfully!");
else
MessageBox.Show("Process List Load Failed!");

}

Using the above code we will develop faster and freezes the screen Application.

read comments Read User's Comments

How to Generate Unique ID using GUID in C#

We can Generate the Unique ID or number for our Web User as Member ID. And also we can update the unique records of the Database using GUID of the C#.

>> The GUID is used to Generate the unique id's. It is pronounced as goo'id - Globally unique identifier.

>> It is a 128-bit integer that can be used to uniquely identify something. You may store users or products in your database and you want somehow uniquely identify each row in the database. A common approach is to create a autoincrementing integer, another way would be to create a GUID for your products.

>> How to Create ID

- System.GUID class is used to create a Rand Id for members.

-> Using this bellow code we can create

System.Guid mid = Guid.NewGuid();
MessageBox.Show(mid.ToString());

or
 MessageBox.Show(System.Guid.NewGuid().ToString("P"));

Some of Formats: P, N, D,B
Ex.
MessageBox.Show("This is Test ID:" + System.Guid.NewGuid().ToString("P"));
MessageBox.Show("This is Test ID:" + System.Guid.NewGuid().ToString("D"));
MessageBox.Show("This is Test ID:" + System.Guid.NewGuid().ToString("B"));

read comments Read User's Comments

Date Time conversion Formats in SQL Server

Date Time conversion Format

DATE FORMATS


Format # Query (current date: 12/30/2006) Sample
1 select convert(varchar, getdate(), 1) 12/30/06
2 select convert(varchar, getdate(), 2) 06.12.30
3 select convert(varchar, getdate(), 3) 30/12/06
4 select convert(varchar, getdate(), 4) 30.12.06
5 select convert(varchar, getdate(), 5) 30-12-06
6 select convert(varchar, getdate(), 6) 30 Dec 06
7 select convert(varchar, getdate(), 7) Dec 30, 06
10 select convert(varchar, getdate(), 10) 12-30-06
11 select convert(varchar, getdate(), 11) 06/12/30
101 select convert(varchar, getdate(), 101) 12/30/2006
102 select convert(varchar, getdate(), 102) 2006.12.30
103 select convert(varchar, getdate(), 103) 30/12/2006
104 select convert(varchar, getdate(), 104) 30.12.2006
105 select convert(varchar, getdate(), 105) 30-12-2006
106 select convert(varchar, getdate(), 106) 30 Dec 2006
107 select convert(varchar, getdate(), 107) Dec 30, 2006
110 select convert(varchar, getdate(), 110) 12-30-2006
111 select convert(varchar, getdate(), 111) 2006/12/30

read comments Read User's Comments

How to Use PropertyGrid

How to use PropertyGrid in our C# Application

- The Propertygrid is like our Property window available in the .Net IDE. We can also add the propertygrid in C# window application

-The property grid is a powerful control for allowing users to edit the internals of your published classes.Because of the ability for the property grid to reflect and bind to your class, there is not much work involved in getting the property grid up and working.You can add categories and descriptions to your property grid by using the special grid attributes in the System.Component model.

-It displays the Properties and attributes with it's Description and the Category wise details of Object.

- All properties should have get and set methods.(If you don't have a get method, the property won't show up in the PropertyGrid).




- The Bellow attributes are used to manipulate the Properties of the class

1.CategoryAttribute - This will Arrange the Properties as a Category wise.
2.DescriptionAttribute - This will used for description of the Property
3.BrowsableAttribute -
This is used to determine whether or not the property is shown or hidden in
the property grid.
4.ReadOnlyAttribute -
Use this attribute to make your property read only inside the property grid
5.DefaultValueAttribute -
Specifies the default value of the property shown in the property grid
6.DefaultPropertyAttribute -
If placed above a property, this property gets the focus when the property
grid is first launched. Unlike the other attributes, this attribute goes
above the class.
The Bellow cust class object is used to load in PropertyGrid

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace ExampleForTabControl
{
[DefaultPropertyAttribute("ID Settings")]
class Cust
{
private string _name;
private int _age;
private DateTime _dob;
private string _address;
private string _email;
private bool _freq;

[CategoryAttribute("ID Settings"), DescriptionAttribute("Name of the customer") ]
public string Name
{
get {return _name; }
set { _name = value; }
}
[CategoryAttribute("Age Details"), DescriptionAttribute("DOB Details")]
public DateTime DOB
{
get { return _dob; }
set { _dob = Convert.ToDateTime(value); }
}
[CategoryAttribute("Age Details"), DescriptionAttribute("Age in No of Years")]
public int Age
{
get { return _age; }
set { _age = Convert.ToInt32(value); }

}

[CategoryAttribute("Addressing Settings"), DescriptionAttribute("Customers Address")]
public string Address
{
get { return _address; }
set { _address = value; }
}
[CategoryAttribute("Marketting Settings"), DescriptionAttribute("Most current e-mail of the customer")]
public string Email
{
get { return _email; }
set { _email = value; }
}
[CategoryAttribute("Buying Status"), DescriptionAttribute("Frequently Buying Status")]
public bool FrequentBuyer
{
get { return _freq; }
set { _freq =Convert.ToBoolean(value); }
}
}
}


To Bind with PropertyGrid available in the Form1:
private void Form1_Load(object sender, EventArgs e)
{
tabEx1.Visible = false;
Cust Siva = new Cust();
Siva.Name = "Raja";
Siva.Age = 55;
Siva.DOB = Convert.ToDateTime("10-Feb-1985");
Siva.Email = "Siva@gmail.com";
Siva.FrequentBuyer = true;
Siva.Address = "Pallikkaranai,Chennai";
this.proGridCust.SelectedObject = Siva;
this.Text = "Customer";
}

* To download the Source code for the PropetyGrid Example, Please Click Here

read comments Read User's Comments

Generate a Random Password or Verification String

How to Generate a Random Password or Verification String

- In some cases we need to generate the random string using the some of the input from the user. This post simply explains about the generating the Random Verification string.

- To generate the random verification string we need to give the input for how many characters we need a output, input Letter (e.g., User Name) and the number for mixing to the string.

- Use the following Random generator code class library we can create the verification codes.

''' <summary>
''' GENERATES A RANDOM STRING OF LETTERS AND NUMBERS. LETTERS CAN BE RANDOMLY
'CAPITAL OR SMALL.
''' </summary>
''' <returns type="String">RETURNS THE RANDOMLY GENERATED KEY</returns>

Public Function Generate() As String
Dim i_key As Integer
Dim Random1 As Single
Dim arrIndex As Int16
Dim sb As New StringBuilder
Dim RandomLetter As String

' CONVERT LettersArray & NumbersArray TO CHARACTR ARRAYS
LettersArray = Key_Letters.ToCharArray
NumbersArray = Key_Numbers.ToCharArray

For i_key = 1 To Key_Chars
Randomize()
Random1 = Rnd()
arrIndex = -1
' IF THE VALUE IS AN EVEN NUMBER WE GENERATE A LETTER, OTHERWISE WE
' GENERATE A NUMBER
' THE NUMBER '111' WAS RANDOMLY CHOSEN. ANY NUMBER WILL DO, WE JUST NEED
' TO BRING THE VALUE ABOVE '0'

If (CType(Random1 * 111, Integer)) Mod 2 = 0 Then
' GENERATE A RANDOM LOCATION IN THE LETTERS CHARACTER ARRAY
Do While arrIndex < 0
arrIndex = Convert.ToInt16(LettersArray.GetUpperBound(0) * Random1)
Loop
RandomLetter = LettersArray(arrIndex)
' CREATE ANOTHER RANDOM NUMBER. IF IT IS ODD, WE CAPITALIZE THE
' LETTER
If (CType(arrIndex * Random1 * 99, Integer)) Mod 2 <> 0 Then
RandomLetter = LettersArray(arrIndex).ToString
RandomLetter = RandomLetter.ToUpper
End If
sb.Append(RandomLetter)
Else
' GENERATE A RANDOM LOCATION IN THE NUMBERS CHARACTER ARRAY
Do While arrIndex < 0
arrIndex = Convert.ToInt16(NumbersArray.GetUpperBound(0) * Random1)
Loop
sb.Append(NumbersArray(arrIndex))
End If
Next
Return sb.ToString
End Function


- To add the Reference of the dll to another project (Window or Web) and create teh object for the class RandomKeyGenerator and call the method Generate().
E.g.
protected void Button1_Click(object sender, EventArgs e)
{
RandomKeyGenerator Rnd = new RandomKeyGenerator();
Rnd.KeyChars = 5;
Rnd.KeyLetters = "Siva";
Rnd.KeyNumbers = "12345";
Response.Write(Rnd.Generate());
}

To use the namespace using RandomKey;

-> To download Random Verification String Generator Click Here

read comments Read User's Comments

Working With Session in Asp.Net (Vb.Net Code behind)

Working With Session

- How to Check the Session expires in the main page, the redirect to the default page or login page.
- In Default.aspx page To add a label with the text “Your Name” , Text Box and Button Control with text “Go”



- To set the Session for the Name which you gave, use the following code

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If (Trim(TextBox1.Text) <> "") Then
Session("UserName") = UCase(Trim(TextBox1.Text))
Response.Redirect("Mainpage.aspx")
Else
Response.Write("User Name Required!")
End If
End Sub

To check session expires and the other pages redirect to default page
- We can check using the Query String from the other pages to the Default Page in the Page load event.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If (Request.QueryString("session") = "expired") Then
Response.Write("Your Session has Expired")
End If
End If
End Sub

To Validate the Session in other page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As 
System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If (Session.Item("UserName") <> Nothing) Then
Label1.Text = "Welcome Dear " &
Session.Item("UserName").ToString()
ElseIf (Session.IsNewSession = True) Then
Response.Redirect("Default.aspx?Session=expired")
Else
Response.Redirect("Default.aspx?Session=Empty")
End If
End If
' Response.Write("Session Time out:-" &
' *Session.Timeout.ToString())
End Sub

- To Make the Session Expiry the Session.Abandon() Method is used. This Will act like Logout.

- To Set the Session Timeout duration using the web config file’s SessionState Tag.
E.g.
<sessionState mode="InProc" timeout="10">
</sessionState>

- To Use this we can set the State to Handling the Session. Normally in a small Web Application we can use the InProc mode. Other Session Modes are StateServer,SQLServer,Off,Custom.

- The Default Session Timeout Time span is 20 minutes. We can Set the Session time out maximum of 1 year i.e, 525,601 minutes.

To Set the Session Expiry in Local IIS

- If we are using the Local IIS as web server we can set the Session expiry time through the Application Pool of the IIS.

read comments Read User's Comments

How to Get the COM Port List

>> We can get the COM port list available in the local system using the Name space System.Management.

>> The Serial port class's GetPortNames() method is used to get the COM Ports alone.
Eg.

String[] COMS =System.IO.Ports.SerialPort.GetPortNames();

>> We need to list the all the Ports available in the Local System then the ManagementObjectSearcher Class used.
Eg.

ManagementObjectSearcher ObjUsbSearcher = new ManagementObjectSearcher("Select * from WIN32_SerialPort");

>> The bellow code is Navigate through the ObjUsbSearcher
foreach(ManagementObject Port1 in ObjUsbSearcher.Get())
{
listBox1.Items.Add((String)Port1.GetPropertyValue("Name"));

}

read comments Read User's Comments

Simple Example for event handling in C#

To place a singe button(Button1),textbox(txtViewer) in the Form and create teh new user defind method called OnClick() and wireup the event using the bellow code part

//The Default Form1() initializer Method
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(OnClick);// Onclick Based
this.Resize+=new EventHandler(this.ResizeForm); //While Form is Resized
}

// User defind method wireupped with Button1 Click
public void OnClick(object sender, EventArgs e)
{
this.txtViewer.Text = "This is test for Event";
}

//User defind method wired with form resize
private void ResizeForm(object sender, EventArgs e)
{
MessageBox.Show("Oops! Form Resized");
}

read comments Read User's Comments

To Retrieve the Sheet Names From the Excel Book

To Use the bellow Method we can get the Sheets Names in the List Box(i.e, lstSheetName) availble in the Form.

public string GetExcelSheetName(String xlsName)
{
OleDbConnection ObjCon = null;
DataTable ObjTable = null;
String ConStr = String.Empty;

try
{
ConStr = "Provider=Microsoft.Jet.Oledb.4.0;Data source=" + XlsFileName;
ConStr += ";Extended Properties=Excel 8.0;";
ObjCon = new OleDbConnection(ConStr);
ObjCon.Open();
ObjTable = ObjCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (ObjTable != null)
{
String[] Sheets = new String[ObjTable.Rows.Count];
int i = 0;
foreach (DataRow dr in ObjTable.Rows)
{
Sheets[i] = dr["TABLE_NAME"].ToString();
i++;
}
// This List box Used to List Sheet Names in Given Excel File
lstSheetName.Items.AddRange(Sheets);
bflg = true;
return "Sheet Name Retrieved Successfuly.";
}
else
{
bflg =false;
return "Excel Database is Empty!.";
}
}
catch (Exception ex)
{
bflg = false;
return ex.Message;
}
}

read comments Read User's Comments