Welcome

Welcome Anonymous

Friday, December 10, 2010

Difference between two Dates in C#.NET ?

To find the difference between two dates is very simple in VB — By using DateDiff method. But in C#, there is no direct method to do so. but there is a way to achive this. For this we need to understand TimeSpan Class.

The following code snippet will show you how to find the difference.

DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( “Time Difference (seconds): ” + span.Seconds );
Console.WriteLine( “Time Difference (minutes): ” + span.Minutes );
Console.WriteLine( “Time Difference (hours): ” + span.Hours );
Console.WriteLine( “Time Difference (days): ” + span.Days );

By concatenating all this you will get the difference between two dates. You can also use span.Duration().

There are certain limitations to. The TimeSpan is capable of returning difference interms of Days, Hours, mins and seconds only. It is not having a property to show difference interms of Months and years.

Hope this will help you…

Wednesday, November 3, 2010

Running a program at startup

You need to use the Registry for running a program at startup. You can use the RegistryKey class that's in the System.Win32 namespace. The following code shows how to do this:

RegistryKey rk = Registry.CurrentUser;
RegistryKey StartupPath;
StartupPath = rk.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
if (StartupPath.GetValue("ProjectName") == null)
{
StartupPath.SetValue("ProjectName", Application.ExecutablePath, RegistryValueKind.ExpandString);
}

Wednesday, October 6, 2010

Splash Screen in Visual Studio 2008 using C#.NET

Creating Splash Screen is now very easy
just follow these steps to make your application look very rich.

1.Suppose, Welcome.cs is your main form and SplashScreen.cs is your splash screen form.
2.Write the following code in the page_load event of your Welcome.cs form

Hide();
bool done = false;
ThreadPool.QueueUserWorkItem((x) =>
{
using (var splashForm = new SplashForm())
{
splashForm.Show();
while (!done)
Application.DoEvents();
splashForm.Close();
}
});

Thread.Sleep(3000); // Emulate hardwork
done = true;
Show();
3. It's done!!

Monday, September 20, 2010

How to edit GridView manually

Filling, Editing, Updating, Deleting from a GridView is quite easy now.
Just follow these steps.
1. Open Visual Studio create a web based project.
2. Go to design view of Default.aspx page and then drag&drop a GridView control from standard Visual Studio Toolbox.
3.Right click on GridView goto properties and then disable AutoGeneratedColumns property to false.
4. Navigate to your source page (default.aspx).
then we will found the tags look like

asp:gridview id="GridView1" runat="server" autogeneratecolumns="False">

5. Now, open tab in gridview and wirte the following code.


6. Save the File. Now goto your codebehind file(Default.aspx.cs)
7. Replace your Page_Load event with the following

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();

}
}
8. And write the Grid method

private void fillgrid()
{
con.Open();
da = new SqlDataAdapter("select * from login", con);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}

9. For GridView Editing Right click on GridView goto events and click in GridViewRowEditing event, it will generates a GridView1_RowEditing method in your codebehind file.
10. Now, in codebehind file write the following code

int i = Convert.ToInt32(e.NewEditIndex);

LinkButton lb1 = (LinkButton)GridView1.Rows[i].FindControl("LinkButton1");
LinkButton lb2 = (LinkButton)GridView1.Rows[i].FindControl("LinkButton2");
LinkButton lb3 = (LinkButton)GridView1.Rows[i].FindControl("LinkButton3");
lb2.Visible = lb3.Visible = true;
lb1.Visible = false;
Label l1 = (Label)GridView1.Rows[i].FindControl("Label1");
Label l2 = (Label)GridView1.Rows[i].FindControl("label2");
l1.Visible = l2.Visible = false;

TextBox t1 = (TextBox)GridView1.Rows[i].FindControl("TextBox1");
TextBox t2 = (TextBox)GridView1.Rows[i].FindControl("Textbox2");
t1.Visible = t2.Visible = true;

11. For GridViewUpdating right click on gridview goto properties and then events double click on
GridViewUpdating event it'll generates a GridView1_RowUpdating event in your codebehind file.
12. Write the following code in that method

int i = e.RowIndex;
TextBox t1 = (TextBox)GridView1.Rows[i].FindControl("TextBox1");
TextBox t2 = (TextBox)GridView1.Rows[i].FindControl("Textbox2");
con.Open();
SqlCommand cmd = new SqlCommand("update login set name='" + t1.Text + "' where psw='" + t2.Text + "'",con );
t1.Visible = t2.Visible = false;

cmd.ExecuteNonQuery();
con.Close();


Label l1 = (Label)GridView1.Rows[i].FindControl("Label1");
Label l2 = (Label)GridView1.Rows[i].FindControl("label2");
l1.Visible = l2.Visible = true;

refreshgrid();

That's it !! It is that much easy to EDITING GRIDVIEW MANUALLY.
Lets' try to start your own logic to modify GridView

How to Display Image from Database

//Retrieving image from Database
SqlCommand c = new SqlCommand();
c.CommandType = CommandType.StoredProcedure;
c.Connection = con;
c.CommandText = "sp_readImage";

int id =Convert.ToInt16( obj.executescalar("select max(photoid) from Photos"));


c.Parameters.AddWithValue("@id",id );
byte[] imagedata = (byte[])c.ExecuteScalar();
MemoryStream memory = new MemoryStream(imagedata);

// To display the image in the page itself
img =System.Drawing.Image .FromStream(memory);
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg );

// To Disaply image in image control(image1)

BinaryWriter t = new BinaryWriter(File.Open(Server.MapPath("Images\\sample.jpeg"),FileMode.Create ));
t.Write(imagedata);
t.Close();
Image1.ImageUrl = Server.MapPath("Images\\sample.jpeg");

How to store image in a database in binary format

Create one empty web page and do the following things...

1.Drag & Drop FileUpload Control and one Button from standard Toolbox
2.Double click on button control it'll generate a button click event. In that event write the following code
3.business_logic is a class file and which is used for opening database conections, executing database queries,etc. You can may even directly declare directly the connections, commands in codebehind file(*.cs,*.vb)

business_logic obj = new business_logic();

if (FileUpload1.HasFile)
{

// Storing image in Database
BinaryReader reader = new BinaryReader(FileUpload1.PostedFile.InputStream);
byte[] image = reader.ReadBytes(FileUpload1.PostedFile.ContentLength);

string temp= obj.assignconn();
con = new SqlConnection(temp);
con.Open();
cmd.Connection = con;
cmd.CommandText = "sp_imageInsert";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@img", image);
cmd.ExecuteNonQuery();
Label2.Visible = true;
Label2.Text = "File Successfully Uploaded";

how to call code behind function from javascript in asp.net

var str = '<%=deleteFile()%>'

where deleteFile() the function name in
your code behind file(*.cs,*.vb)

How to catch browser close event

There are two events

1) window.onbeforeunload
2) body onbeforeunload="alert('Browser is going to be close');"

Wednesday, July 7, 2010

ASP.NET State Management Overview

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.
To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:
• View state
• Control state
• Hidden fields
• Cookies
• Query strings
• Application state
• Session state
• Profile Properties

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.

Download Professional C#.NET 2008 at
http://www.ziddu.com/download/10795582/rofessionalC2008andtheNET3.5PlatformFourthEdition.pdf.html

Thursday, June 24, 2010

How to Read Mails from Outlook and Checking for particular User Mail

Microsoft.Office.Interop.Outlook .Application oApp;
Microsoft.Office.Interop.Outlook._NameSpace oNS;
Microsoft.Office.Interop.Outlook.MAPIFolder oFolder;
Microsoft.Office.Interop.Outlook._Explorer oExp;

oApp=new Microsoft.Office.Interop.Outlook.Application();
oNS = (Microsoft.Office.Interop.Outlook._NameSpace)oApp.GetNamespace("MAPI");
oFolder=oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.
olFolderInbox);

oExp = oFolder.GetExplorer(false);
oNS.Logon(Missing.Value, Missing.Value, false, true);
Microsoft.Office.Interop.Outlook.Items items = oFolder.Items;

//checking for unread mails

foreach (Microsoft.Office.Interop.Outlook .MailItem mail in items)
{

if (mail.UnRead == true)
{

//Paste the code for already opened mails

if (mail.SenderName.Trim() == "crozzX")
{
//Paste the code for a particular User

}
}
else
{
//Paste the code for already opened mails
}
}

How to Turnoff / Restart Computer using C#.NET

Import System.Diagnostics(using System.Diagnostics)in code behind file

Then in shutdown button onclick event write

Process.Start("shutdown", "/s /f");/Force Shutdown
Process.Start("shutdown", "/s /t");/Normal Shutdown
Process.Start("shutdown", "/r ");/Force Restart


Application.Exit();

How to store Excel data in Gridview

Import System.Data.OleDb(using System.Data.OleDb)in code behind file

Then in button onclick event write,

OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=D:\status.xls;Extended Properties=Excel 8.0");
OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
OleDbDataReader dr;

connection.Open();
dr = command.ExecuteReader(CommandBehavior.CloseConnection);

DataTable excelData = new DataTable("ExcelData");
excelData.Load(dr);
GridView1.DataSource = excelData;
GridView1.DataBind();

Saturday, May 29, 2010

Difference Between Eval and Bind in ASP.NET

Eval is a protected method defined on the TemplateControl class, from which the Page class is derived.
Bind is a new ASP.NET 2.0 databinding keyword. It's not a method of any specific class.

Eval is used for unidirectional (readonly) data binding, while Bind is for bi-directional (editable) databinding.


ASP.NET supports a hierarchical data-binding model that creates bindings between server control properties and data sources. Almost any server control property can be bound against any public field or property on the containing page or on the server control's immediate naming container.

Data-binding expressions use the Eval and Bind methods to bind data to controls and submit changes back to the database. The Eval method is a static (read-only) method that takes the value of a data field and returns it as a string. The Bind method supports read/write functionality with the ability to retrieve the values of data-bound controls and submit any changes made back to the database.

You can bind to XML data from an XmlDataSource control using the XPath and XPathSelect methods, as well as the XPathBinder class.

Thursday, May 6, 2010

Stored Procedures in SQL SERVER 2005

Step1: Open SQL SERVER 2005
Step2: Create an empty database
Step3: Go to tables and then create an empty table
Let's consider table name as login, the table is look like

Click on Tables
|
Programmability
|
Stored Procedure
|
Create new stored procedure
Step4:create procedure sp_insert(@sno varchar(10), @ sname varchar(10))
as
begin
insert into emp values(@eid,@ename,@esal)
end


Step5: Now open Visual Studio create new website.
Step6: In code behind file write

SqlConnection con;
SqlCommand comm;

con = new SqlConnection("Data Source=BASHA;Initial Catalog=prasad;Integrated Security=True");
con.Open();
comm = new SqlCommand("sp_insert", con);
comm.CommandType =CommandType .StoredProcedure ;
comm.Parameters .AddWithValue ("@eid",TextBox1 .Text );
comm .Parameters .AddWithValue ("@ename",TextBox2 .Text );
comm .Parameters .AddWithValue ("@esal",TextBox3 .Text );
comm.ExecuteNonQuery ();
Response.Write("inserted successfully");



Friday, April 30, 2010

Auto Complete Feature for any control

SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=tts;Integrated Security=True");

//creat auto complete Collection

AutoCompleteStringCollection collection = new AutoCompleteStringCollection();

//get the data from database

SqlDataAdapter da1 = new SqlDataAdapter("select name from contacts ", con);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
for (int i = 0; i < dt1.Rows.Count; i++)
{
//add the student name into auto complete collection
collection.Add(dt1.Rows[i].ItemArray[0].ToString());
}
}

//after adding the student names into auto complete collection bind the collection to Combobox

toolStripComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
toolStripComboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
toolStripComboBox1.AutoCompleteCustomSource = collection;

Saving Text in Wav Format

Include the name space System.Speech
saveFileDialog1.ShowDialog();

string str = saveFileDialog1.FileName;

System.Speech.Synthesis.SpeechSynthesizer synth = new
System.Speech.Synthesis.SpeechSynthesizer();

synth.SetOutputToWaveFile(str+".wav" );
synth.Speak(textBox1.Text);

MessageBox.Show("File Saved Successfully");
synth.Dispose();

Converting Text to Speech

Include the name space System.Speech
System.Speech.Synthesis.SpeechSynthesizer sp = new System.Speech.Synthesis.SpeechSynthesizer();

sp.Volume = 100;
sp.Speak(textBox1.Text);
sp.Dispose();

Serial Port Communication

Include the namespace System.IO.Ports
SerialPort sp = new SerialPort();
Sp.Open();
sp.WriteLine(textBox1.Text);

Image Uploading

string imgpath = this.FileUpload1.FileName;

FileUpload1.SaveAs(Server.MapPath("~//images//" + imgpath.ToString()));

iname = "~/images/" + imgpath.ToString();