22 June, 2011

Joins in MS SQL

Inner JOIN
A JOIN that displays only rows that have a match in both the JOINed tables is known as inner JOIN. This is the default type of JOIN in the Query.

Outer JOIN

A JOIN that includes rows even if they do not have related rows in the joined table is an Outer JOIN. You can create three different outer JOINs to specify the unmatched rows to be included:
Left Outer JOIN: In Left Outer JOIN, all rows in the first-named table, i.e. “left” table, which appears leftmost in the JOIN clause, are included. Unmatched rows in the right table do not appear.

Right Outer JOIN: In Right Outer JOIN, all rows in the second-named table, i.e. “right” table, which appears rightmost in the JOIN clause, are included. Unmatched rows in the left table are not included.

Full Outer JOIN: In Full Outer JOIN, all rows in all the joined tables are included, whether they are matched or not.

Cross JOIN

A cross JOIN devoid of a WHERE clause produces the Cartesian product of the tables involved in the JOIN. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. One common example is when a company lists all its products in a pricing table to compare each product with others prices.

Self JOIN

In this example, we are actually self joining to the HumanResources.Employee table. We are doing this to obtain the information about the Employee and Manager relationship in the HumanResources.Employee table.

–creating table for self join
create table Employe
(
empID int Identity(1,1),
empName Varchar(15),
ManagerID int
)
 -self join for finding manager of a employee
SELECT e.empID ,e.empName as EmpName ,m.empName as ‘Manager name’
FROM Employe e JOIN Employe m
on  e.ManagerID=m.empID

19 June, 2011

MsSQL Bulk Copy With Transaction in C#.NET

private static SqlConnection _oConnection=null;

private static SqlTransaction _oTransaciton=null;

protected int ExecuteBulkCopy(string sTableName,DataTable dtData)

{

int nReturn = 0;

try

{

if (_oConnection == null)

{

_oConnection = new SqlConnection(CONNECTION_STRING);

}

if (_oConnection.State == ConnectionState.Closed)

{

_oConnection.Open();

}

try

{

_oTransaciton = _oConnection.BeginTransaction();

SqlBulkCopy bulkCopy = new SqlBulkCopy(_oConnection,

SqlBulkCopyOptions.TableLock,_oTransaciton);

bulkCopy.DestinationTableName = sTableName;

bulkCopy.WriteToServer(dtData);

_oTransaciton.Commit();

_oTransaciton.Dispose();

_oTransaciton = null;

nReturn = 1;

}

catch {

_oTransaciton.Rollback();

_oTransaciton = null;

nReturn = 0;

}

}

catch (SqlException oSQLException)

{

throw new Exception("SQL ERROR: " + oSQLException);

}

return nReturn;

}

Get data from CSV and Excel File in C#.NET

/*Get data from CSV File*/

public DataTable GetDataFromCSVFile(string sFolderName, string sFileName)

{

DataTable oTable = new DataTable("DFCSVFile");

try

{

String strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data

Source=" + sFolderName + ";Extended Properties='text;HDR=Yes'";

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " +

sFileName , strConn);

da.Fill(ds);

oTable= ds.Tables[0];

}

catch (Exception e)

{

throw new Exception(e.Message);

}

return oTable;

}

/*Get data from Excel File*/

public DataTable GetDataFromExcelFile(string sFilePath, string sSheetName)

{

DataTable oTable = new DataTable("EFile");

try

{

String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

sFilePath + ";Extended Properties=Excel 8.0;";

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM " +

sSheetName + "", strConn);

da.Fill(ds);

oTable = ds.Tables[0];

}

catch (Exception e)

{

throw new Exception(e.Message);

}

return oTable;

}



Auto Email Prepared in C#.NET

/*Add this class*/

using System;

using System.Runtime.InteropServices;

using System.IO;

using System.Collections.Generic;

using System.Windows.Forms;

namespace MyProject

{

public class SendFileTo

{

public class MAPI

{

public bool AddRecipientTo(string email)

{

return AddRecipient(email, HowTo.MAPI_TO);

}

public bool AddRecipientCC(string email)

{

return AddRecipient(email, HowTo.MAPI_CC);

}

public bool AddRecipientBCC(string email)

{

return AddRecipient(email, HowTo.MAPI_BCC);

}

public void AddAttachment(string strAttachmentFileName)

{

m_attachments.Add(strAttachmentFileName);

}

public int SendMailPopup(string strSubject, string strBody)

{

return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);

}

public int SendMailDirect(string strSubject, string strBody)

{

return SendMail(strSubject, strBody, MAPI_LOGON_UI);

}

[DllImport("MAPI32.DLL")]

static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);

int SendMail(string strSubject, string strBody, int how)

{

MapiMessage msg = new MapiMessage();

msg.subject = strSubject;

msg.noteText = strBody;

msg.recips = GetRecipients(out msg.recipCount);

msg.files = GetAttachments(out msg.fileCount);

m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how, 0);

if (m_lastError > 1)

MessageBox.Show("MAPISendMail failed! " + GetLastError(), "MAPISendMail");

Cleanup(ref msg);

return m_lastError;

}

bool AddRecipient(string email, HowTo howTo)

{

MapiRecipDesc recipient = new MapiRecipDesc();

recipient.recipClass = (int)howTo;

recipient.name = email;

m_recipients.Add(recipient);

return true;

}

IntPtr GetRecipients(out int recipCount)

{

recipCount = 0;

if (m_recipients.Count == 0)

return IntPtr.Zero;

int size = Marshal.SizeOf(typeof(MapiRecipDesc));

IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);

int ptr = (int)intPtr;

foreach (MapiRecipDesc mapiDesc in m_recipients)

{

Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);

ptr += size;

}

recipCount = m_recipients.Count;

return intPtr;

}

IntPtr GetAttachments(out int fileCount)

{

fileCount = 0;

if (m_attachments == null)

return IntPtr.Zero;

if ((m_attachments.Count <= 0) || (m_attachments.Count > maxAttachments))

return IntPtr.Zero;

int size = Marshal.SizeOf(typeof(MapiFileDesc));

IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count * size);

MapiFileDesc mapiFileDesc = new MapiFileDesc();

mapiFileDesc.position = -1;

int ptr = (int)intPtr;

foreach (string strAttachment in m_attachments)

{

mapiFileDesc.name = Path.GetFileName(strAttachment);

mapiFileDesc.path = strAttachment;

Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);

ptr += size;

}

fileCount = m_attachments.Count;

return intPtr;

}

void Cleanup(ref MapiMessage msg)

{

int size = Marshal.SizeOf(typeof(MapiRecipDesc));

int ptr = 0;

if (msg.recips != IntPtr.Zero)

{

ptr = (int)msg.recips;

for (int i = 0; i < msg.recipCount; i++)

{

Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiRecipDesc));

ptr += size;

}

Marshal.FreeHGlobal(msg.recips);

}

if (msg.files != IntPtr.Zero)

{

size = Marshal.SizeOf(typeof(MapiFileDesc));

ptr = (int)msg.files;

for (int i = 0; i < msg.fileCount; i++)

{

Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiFileDesc));

ptr += size;

}

Marshal.FreeHGlobal(msg.files);

}

m_recipients.Clear();

m_attachments.Clear();

m_lastError = 0;

}

public string GetLastError()

{

if (m_lastError <= 26)

return errors[m_lastError];

return "MAPI error [" + m_lastError.ToString() + "]";

}

readonly string[] errors = new string[] {

"OK [0]", "User abort [1]", "General MAPI failure [2]", "MAPI login failure [3]",

"Disk full [4]", "Insufficient memory [5]", "Access denied [6]", "-unknown- [7]",

"Too many sessions [8]", "Too many files were specified [9]", "Too many recipients were specified [10]", "A specified attachment was not found [11]",

"Attachment open failure [12]", "Attachment write failure [13]", "Unknown recipient [14]", "Bad recipient type [15]",

"No messages [16]", "Invalid message [17]", "Text too large [18]", "Invalid session [19]",

"Type not supported [20]", "A recipient was specified ambiguously [21]", "Message in use [22]", "Network failure [23]",

"Invalid edit fields [24]", "Invalid recipients [25]", "Not supported [26]"

};

List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();

List<string> m_attachments = new List<string>();

int m_lastError = 0;

const int MAPI_LOGON_UI = 0x00000001;

const int MAPI_DIALOG = 0x00000008;

const int maxAttachments = 20;

enum HowTo { MAPI_ORIG = 0, MAPI_TO, MAPI_CC, MAPI_BCC };

}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

public class MapiMessage

{

public int reserved;

public string subject;

public string noteText;

public string messageType;

public string dateReceived;

public string conversationID;

public int flags;

public IntPtr originator;

public int recipCount;

public IntPtr recips;

public int fileCount;

public IntPtr files;

}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

public class MapiFileDesc

{

public int reserved;

public int flags;

public int position;

public string path;

public string name;

public IntPtr type;

}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

public class MapiRecipDesc

{

public int reserved;

public int recipClass;

public string name;

public string address;

public int eIDSize;

public IntPtr entryID;

}

}

}

/*Then Write this code in your required form*/

SendFileTo.MAPI mapi = new SendFileTo.MAPI();

mapi.AddRecipientTo(“To Address”);

mapi.AddRecipientCC(“CC Address”);

mapi.AddAttachment(“Attachment Path with File name”);

mapi.SendMailPopup(“Mail Subject”, “Mail Body”);

07 June, 2011

Double Click Problem in your Computer..........

Sometimes......when you click your computer drive its not open......
then you open your drive from right button click or browse drive.
now you need to solve this problem . Do following steps:-
  • open command prompt.
  • lets problem in your D drive......
  • write D: and press enter
  • write Attrib –h –r –s autorun.inf and press enter
  • write Del autorun.inf and press enter
  • Restart your PC.....
Enjoy your life...............................Thanks.

Image Type data in MsSQL Show in Crystal Report using C#

1. Add a data set in your project.
- add a data table in this data set.
- add column that you want to show your report.
- go to picture/image type data column properties.
- change data type to System.Byte[].




2. add a crystal report, go expert data source , show the data table.

- design your report... give the picture field...in your crystal report.
3. Add a form than add a crystal report viewer. then write the following code in form load section.

CrystalReport1 objRpt;
private void Form1_Load(object sender, EventArgs e)
{
   objRpt = new CrystalReport1();3
   string connString = "Server=ServerName;Database=DataBase;User
ID=UserID;Password=Password;";
   string query = "Write Your Query";
   using (SqlConnection Conn = new SqlConnection(connString))
   {
       SqlDataAdapter adepter = new SqlDataAdapter(query, connString);
       DataSet DS = new DataSet();
       DataTable DT = new DataTable("DataTable1");
      //DataTable name must mach with Step1 Data table
       adepter.Fill(DS);
       DT = DS.Tables[0];
       objRpt.SetDataSource(DT);
       crystalReportViewer1.ReportSource = objRpt;
   }
}


and then just run your project........and enjoy it!!!!!!!!!!!!!!!!!!!!!
If this post is help you.......comment please......................