Tuesday, March 30, 2010

Radio button in Data grid with Single selection

//Posted By Suresh

add radio buttons to datagrid:


OnCheckedChanged="SelectOnlyOne"
id="RadioButton1" Text='hi' runat="server"/>





public void SelectOnlyOne(object sender,EventArgs e)
{
RadioButton rb = new RadioButton();
rb = (RadioButton) sender;
string sRbText = rb.ClientID;

foreach (DataGridItem i in DDLCon.Items)
{
rb = (RadioButton) i.FindControl ("RadioButton1");
rb.Checked = false;
if (sRbText==rb.ClientID)
{
rb.Checked = true;
}
}
}

Friday, March 26, 2010

Read text file as database in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;


namespace SureshApps
{
public class ReadText
{
OleDbConnection oConnection = new OleDbConnection();

private bool OpenConnection(string InputTextFileName)
{
if(!string.IsNullOrEmpty(InputTextFileName))
{
oConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+InputTextFileName+"'; Extended Properties=text;HDR=yes;FMT=Delimited";
oConnection.Open();

if(oConnection.State == System.Data.ConnectionState.Open)
return true;
else
return false;
}

return false;
}

public void BindingDataToGridView(string InputTextFileName, string Query, DataSet ds)
{
try
{
OpenConnection(InputTextFileName);

// Create the data adapter to retrieve all rows from text file.
OleDbDataAdapter da =
new OleDbDataAdapter(Query, oConnection);

// Create and fill the table.
DataSet dt = new DataSet("MyData");
da.Fill(dt);
ds = dt.Copy();

// Bind the default view of the table to the grid.
// DBview.DataSource = dt.DefaultView;


}catch(Exception ex)
{
Console.WriteLine("Error Occured: "+ ex.Message);
}
finally
{
if(oConnection.State == System.Data.ConnectionState.Open)
{
oConnection.Close();
}
}


}


}
}


Format of InputFile

Field1,Name,Fname
IM,XYZ,ABC
IM,SDF,ADFF
IM,DFDD,DFFF

Create a new table with old table structure In SQL SERVER

//Posted By Suresh

Select * into NewTable from OldTable where 1=2

Here the condition "1=2" is false. So the data will not be transfered to new table,
but the structure will be created from the old table.

Friday, March 12, 2010

FTP File Rename In C# Win Application

// Posted By Suresh

FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();

ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

FTP File Delete in C# Win Application

// Posted By Suresh
string ftpServerIP = "192.168.1.25";
string ftpUserID = "SurESH";
string ftpPassword = "xxxxxx";
string fielname = "test.txt"

string uri = "ftp://" + ftpServerIP + "/" + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();

DataBase to Excel In C# Win Application

//Posted By Suresh

string Query = "Select top 100 * From Table";

SqlCommand mycom = new SqlCommand(Query, con);
SqlDataAdapter adapter = new SqlDataAdapter(mycom);
DataSet dataset = new DataSet();
adapter.Fill(dataset);

TimeSpan TS = new TimeSpan(5,30,00);
DateTime DT = new DateTime();
DT = Convert.ToDateTime(System.DateTime.UtcNow.Add(TS));
string fn = "BK" + String.Format("{yyMMddHHmmss}", DT);

string filename = "c:\\suresh\\"+fn+".xls";
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;

// Start Excel and get Application object.
oXL = new Excel.Application();

// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;

// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);

// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Jangid"; //Sheet Name

// Process the DataTable
// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
System.Data.DataTable dt = dataset.Tables[0];

int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}

// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();

// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(filename, Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();

// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

FTP File Uploading Using C# Win Application

// Posted By Suresh

string ftpServerIP = "192.168.1.52";
string ftpUserID = "admin";
string ftpPassword = "xxxxx";
string filename = "c:\\suresh.xls"
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;

// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;

// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Specify the data transfer type.
reqFTP.UseBinary = true;

// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;

// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();

try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);

// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}

Monday, March 8, 2010

INSERT DATA FROM EXCEL TO SQL TABLE USING SINGLE QUERY

//POSETED BY SURESH CHAND JANGID

INSERT INTO SQLTableName(C1, C2, C3, C4, C5)
SELECT C1, C2, C3, C4,GETDATE()
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\MSSQLTips\Examples.xls;',
'SELECT C1, C2, C3, C4 FROM [Sheet1$]')

Saturday, March 6, 2010

Random colour on web page

//Posted By Suresh Chand
//Paste this code in head section in script section



//Enter list of bgcolors:
var bgcolorlist=new Array("#DFDFFF", "#FFFFBF", "#80FF80", "#EAEAFF", "#C9FFA8", "#F7F7F7", "#FFFFFF", "#DDDD00")

document.body.style.background=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]

Quatation " Waqt Nahi"

Har khushi Hai Logon Ke Daman Mein,
Par Ek Hansi Ke Liye Waqt Nahi.
Din Raat Daudti Duniya Mein,
Zindagi Ke Liye Hi Waqt Nahi.

Maa Ki Lori Ka Ehsaas To Hai,
Par Maa Ko Maa Kehne Ka Waqt Nahi.
Saare Rishton Ko To Hum Maar Chuke,
Ab Unhe Dafnane Ka Bhi Waqt Nahi.

Saare Naam Mobile Mein Hain,
Par Dosti Ke Liye Waqt Nahi.
Gairon Ki Kya Baat Karen,
Jab Apno Ke Liye Hi Waqt Nahi.

Aankhon Me Hai Neend Badee,
Par Sone Ka Waqt Nahi.
Dil Hai Gamon Se Bhara ,
Par Rone Ka Bhi Waqt Nahi.

Paison ki Daud Me Aise Daude,
Ki Thakne ka Bhi Waqt Nahi.
Paraye Ehsason Ki Kya Kadr Karein,
Jab Apne Sapno Ke Liye Hi Waqt Nahi.

Tu Hi Bata E Zindagi,
Iss Zindagi Ka Kya Hoga,
Ki Har Pal Marne Walon Ko,
Jeene Ke Liye Bhi Waqt Nahi.........

Funy Quatation about Engineer

Engineer Woh Hai Jo Aksar Phasta Hai
Interviews Ke Sawaal Mae
Badi Companiyon Ki Chaal Mae
Boss Aur Client Ke Bawaal Mae
Engineer Woh Hai Jo Pak Gaya Hai
Meetings Ki Jhelai Mae
Submissions Ki Gehrai Mae
Teamwork Ki Chatai Mae
Engineer Woh Hai Jo Laga Rahta Hai
Schedule Ko Failane Mae
Targets Ko Khiskaane Mae
Roz Naye-Naye Bahane Mae
Engineer Woh Hai Jo
Lunch Time Mae Breakfast Karta Hai
Dinner Time Mae Lunch Karta Hai
Commutation Ke Waqt Soya Karta Hai
Engineer Woh Hai Jo Pagal Hai
Chai Aur Samose Ke Pyar Mae
Cigeratte Ke Khumar Mae
Birdwatching Ke Vichar Mae
Engineer Woh Hai Jo Khoya Hai
Reminders Ke Jawaab Mae
Na Milne Wale Hisaab Mae
Behtar Bhavishya Ke Khwaab Mae
Engineer Woh Hai Jise Intezaar Hai
Weekend Night Manane Ka
Boss Ke Chhutti Jaane Ka
Increment Ki Khabar Aane Ka
Engineer Woh Hai Jo Sochta Hai
Kaash Padhai Pe Dhyaan Diya Hota
Kaash Teacher Se Panga Na Liya Hota
Kaash Ishq Na Kiya Hota
Aur Sabse Behtar To Ye Hota
Kambakht Engineering Hi Na Kiya Hota…….. ….

Draw Bar Graph In C#

//Posted By Suresh Chand Jangid
// A procedure which is get three perameter and return a Bar graph
//1 strTitle - Tile of graph
//2 aX - Array list of X axis
//3 aY - Array list of Y axis



public void DrawBarGraph(string strTitle, ArrayList aX, ArrayList aY)
{
const int iColWidth = 15, iColSpace = 25, iMaxHeight = 400, iHeightSpace = 25, iXLegendSpace = 30, iTitleSpace = 50;

int iMaxWidth = (iColWidth + iColSpace) * aX.Count + iColSpace, iMaxColHeight = 0, iTotalHeight = iMaxHeight + iXLegendSpace + iTitleSpace;

Bitmap objBitmap = new Bitmap(iMaxWidth, iTotalHeight);
Graphics objGraphics = Graphics.FromImage(objBitmap);

objGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, iMaxWidth, iTotalHeight);
objGraphics.FillRectangle(new SolidBrush(Color.Ivory), 0, 0, iMaxWidth, iMaxHeight);

// find the maximum value
//int iValue;
foreach(int iValue in aY)
{
if(iValue > iMaxColHeight) iMaxColHeight = iValue;
}
int iBarX = iColSpace, iCurrentHeight;
SolidBrush objBrush = new SolidBrush(Color.FromArgb(70, 20, 20));
Font fontLegend = new Font("Arial", 11), fontValues = new Font("Arial", 8), fontTitle = new Font("Arial", 14);

// loop through and draw each bar
int iLoop;
for(iLoop = 0; iLoop <= aX.Count - 1;iLoop++)
{
iCurrentHeight = Convert.ToInt32( ((Convert.ToDouble(aY[iLoop]) / Convert.ToDouble(iMaxColHeight)) * Convert.ToDouble(iMaxHeight - iHeightSpace)));
objGraphics.FillRectangle(objBrush, iBarX, iMaxHeight - iCurrentHeight, iColWidth, iCurrentHeight);
objGraphics.DrawString(aX[iLoop].ToString(), fontLegend, objBrush, iBarX, iMaxHeight);
objGraphics.DrawString(aY[iLoop].ToString(), fontValues, objBrush, iBarX, iMaxHeight - iCurrentHeight - 15);
iBarX += (iColSpace + iColWidth);
}
objGraphics.DrawString(strTitle, fontTitle, objBrush, (iMaxWidth / 2) - strTitle.Length * 6, iMaxHeight + iXLegendSpace);
//objBitmap.Save("C:\inetpub\wwwroot\graph.gif", ImageFormat.GIF)
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
objGraphics.Dispose();
objBitmap.Dispose();
}

Auto Increament Field and Constant value Through Bulk COPY IN SQL

//Posted By Suresh Chand Jangid
//Auto Increament Field and Constant value Through Bulk COPY IN SQL
//complete text file copy in sql table

CREATE PROCEDURE ps_StudentList_Import
@PathFileName varchar(100),
@OrderID integer,
@FileType tinyint
AS

--Step 1: Build Valid BULK INSERT Statement
DECLARE @SQL varchar(2000)
IF @FileType = 1
BEGIN
-- Valid format: "suresh","jangid","suresh@jangid.com"
SET @SQL = "BULK INSERT TmpStList FROM '"+@PathFileName+"' WITH (FIELDTERMINATOR = '"",""') "
END
ELSE
BEGIN
-- Valid format: "suresh","jangid","suresh@jangid.com"
SET @SQL = "BULK INSERT TmpStList FROM '"+@PathFileName+"' WITH (FIELDTERMINATOR = ',') "
END

--Step 2: Execute BULK INSERT statement
EXEC (@SQL)

--Step 3: INSERT data into final table
INSERT StudentList (StFName,StLName,StEmail,OrderID)
SELECT CASE WHEN @FileType = 1 THEN SUBSTRING(StFName,2,DATALENGTH(StFName)-1)
ELSE StFName
END,
SUBSTRING(StLName,1,DATALENGTH(StLName)-0),
CASE WHEN @FileType = 1 THEN SUBSTRING(StEmail,1,DATALENGTH(StEmail)-1)
ELSE StEmail
END,
@OrderID
FROM tmpStList

--Step 4: Empty temporary table
TRUNCATE TABLE TmpStList
Go

Folder / Directory Information in C#

// Posted By Suresh Chand Jangid
// Folder / Directory Infortion in C#
DirectoryInfo objDirectoryInfo = new DirectoryInfo "C://IndDBF/");
FileInfo []oFileInfo = objDirectoryInfo.GetFiles();
for(int i=0;i{
if(oFileInfo[i].Exists)
{
Path = oFileInfo[i].FullName;
FileName = oFileInfo[i].Name;
CreateDate = oFileInfo[i].CreationTime;
Size = Convert.ToString(oFileInfo[i].Length;
//oFileInfo[i].Delete(); // For Delete
}
}

Easy Encryption and Decryption Funda in C#

// Posted By Suresh Chand Jangid
//Encrytion In C#
Byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(TextBox1.Text);
TextBox2.Text = Convert.ToBase64String(b);

//Decryption In C#
Byte[] b = Convert.FromBase64String(TextBox2.Text);
TextBox4.Text = System.Text.ASCIIEncoding.ASCII.GetString(b); }

Web Site Developed by Me

www.deepyoginterior.com

Read Excel File Through SQL Commands SELECT / INSERT / UPDATE in C#

// Posted By Suresh Chand Jangid
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;data source=c:/NameAndAddress.xls;Extended Properties=Excel 8.0";
OleDbConnection objConn = new OleDbConnection(strConn);
string strSql = "Select LastName, FirstName, Address, City, State From [Sheet1$]";
lblSql1.Text = strSql;
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
objConn.Open();
dtgAddresses1.DataSource = objCmd.ExecuteReader();
dtgAddresses1.DataBind();
objConn.Dispose();
objConn = new OleDbConnection(strConn);
strSql = "Select * From [Sheet1$] Where State='CA'";
lblSql2.Text = strSql;
objCmd = new OleDbCommand(strSql, objConn);
objConn.Open();
dtgAddresses2.DataSource = objCmd.ExecuteReader();
dtgAddresses2.DataBind();
objConn.Dispose();
objConn = new OleDbConnection(strConn);
strSql = "UPDATE [Sheet1$] SET LastName='CHAND' where FirstName='Suresh'";
objCmd = new OleDbCommand(strSql, objConn);
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Dispose();
objConn = new OleDbConnection(strConn);
strSql = "INSERT INTO [Sheet1$] (LastName, FirstName, Address, City, State) VALUES ('a','b','c','d','e')";
objCmd = new OleDbCommand(strSql, objConn);
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Dispose();