Friday, April 10, 2009

Save Images in Access Database : ASP.NET

Using OLE Object we can save images in Access Database, in this example we will select a image and save that image in Access database using ASP.NET.

First we will start creating a table in access database.

Create a table ImageTable with following fields

  1. ID    AutoNumber (Primary Key)
  2. ImageName   Text
  3. ImageValue OLE Object

Now create a WebApplication and add following controls on the Web Form

  1. Upload Control
  2. Button for uploading image and saving into database
  3. DropdownList for listing all the images in Dabase Table
  4. Button for saving the image into a folder
  5. Image to show the image save on the disk

html

Initially we will fetch the image names which are already saved in the table and show in the drop down list,  for that use Page_Load method and insert following code

Page_Load

now double click on upload image button and add following code, in following code we are just reading the image into stream of bytes and we are storing into the database

UploadImage

To resave the image on to the disk we will use following code, once we save image from database to disk we will show that image in image1 control.

SaveImage

now we are ready with our code just build, run and test

hope this helps

Tags: Save images in Access Database, ASP.NET, Save images in Database

Wednesday, April 8, 2009

IsNumeric in C#

In C#.NET we don’t have IsNumeric function; to achieve same functionality as IsNumeric in C# we can make use of Double.TryParse. Please find following example how we can achieve this

double db;
string strInput = "SomeValue";
if (double.TryParse(strInput, out db))
{
Response.Write(db.ToString());
}
else
{
Response.Write("Not a number");
}

Hope this helps.
Tag: IsNumeric in C#, .NET

Monday, April 6, 2009

Get All Sundays in a Year

Following function will return all the Sundays in a specified Year.

/// /// This function will return all the dates of sundays in a Year
/// for example if you pass if year is 2009
/// it will return all the dates of sundays in the year in form of list
///

/// Year
/// List all dates of sundays in form of list string
public List getAllWeekDates(int Year)
{
List strDates = new List();
for (int month = 1; month <= 12; month++)
{
DateTime dt = new DateTime(Year, month, 1);
int firstSundayOfMonth = (int)dt.DayOfWeek;
if (firstSundayOfMonth != 0)
{
dt = dt.AddDays((6 - firstSundayOfMonth) + 1);
}
while (dt.Month == month)
{
strDates.Add(dt.ToString("dd/MMM/yyyy"));
dt = dt.AddDays(7);
}
}
return strDates;
}

Testing above function

List allSundays = getAllWeekDates(DateTime.Now.Year);
DropDownList1.DataSource = allSundays;
DropDownList1.DataBind();

Hope this helps

Tags: .NET, C# DateTime, All Sundays in a Year

Thursday, April 2, 2009

Export to Excel from DataGridView

Here I am explaining, how we can generate Excel file from the DataGridView.

Here I am using DataTable.WriteXML method generate the excel file.

Create a Window Forms Application and on the Form1 add following controls

  1. DataGridView
  2. Button and rename to “Generate Excel File”
  3. FolderBrowserControl

image

Now add following code in Form1_Load Event, in following code I am creating a DataAdapter to get the data from data base and assigning DataGridView’s DataSource.

image

And add following code in Button1_Click event, In following code I getting back the DataSource and converting it into DataTable and using DataTable’s WriteXML method I am generating Excel File.

image

Now we are ready with our code just Build, Run and Test

image

Hope This Helps.

Tags: DataGridView, Excel, Export, C#, windows

Sunday, March 29, 2009

HttpWebRequest and HttpWebResponse

Following example I am trying to explain how we can request to a URL from our coding and read the Header content of the response.

Create a web application and add a Textbox and a Button to Default.aspx and double click on the button and add following code.

protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Create a object for HttpWebRequest using this request object we will
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(TextBox1.Text);
//request a response from the URL
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
//Reading all header content of response
for (int i = 0; i < res.Headers.Count; i++)
{
Response.Write(res.Headers.AllKeys[i] + " : " + res.Headers[i].ToString() + "
");
}
}
catch (Exception ex)
{
//Catch if there are any exception
Response.Write(ex.Message);
}
}

Now we are ready with code, lets build, run and test

Hope this helps.

SatishKumar J
Microsoft MVP(ASP.NET)
Tags : HttpWebRequest, HttpWebResponse, Headers

Wednesday, March 25, 2009

Error Logging Windows Application VB.NET

Logging is very important for debugging exception at run time; normally logging will help us finding out problem in live environment.

I am post here a logging function using VB.NET, Just add this function in you class and create a directory in C: called Logs.

Public Sub Log(ByVal message As String)
             ' Check whether log.txt is already present or not
               If Not File.Exists("C:\Logs\log.txt") Then
                         'Create if not present
                       Dim fs As FileStream = New FileStream("C:\Logs\log.txt",   FileMode.OpenOrCreate, FileAccess.ReadWrite)
                      Dim s As StreamWriter = New StreamWriter(fs)
                           s.Close()
                            s.Dispose()
fs.Close()
fs.Dispose()
End If
'Open log.txt in append mode to log errors
Dim fs1 As FileStream = New FileStream("C:\Logs\log.txt", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = New StreamWriter(fs1)
'Wrting a line with error message
s1.Write("Message: " & message & vbCrLf)
'Logging the Date and Time of error
s1.Write("Date/Time: " & DateTime.Now.ToString() & vbCrLf)
s1.Close()
s1.Dispose()
fs1.Close()
fs1.Dispose()
End Sub


Now testing the above function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim j As Integer = 10
Dim i As Integer = 0
Dim k As Integer = j / i
Catch ex As Exception
Log(ex.Message)
End Try
End Sub


Hope this helps

ASP.NET AJAX and Calendar Control

Normally when we use calendar control in asp.net we see that calendar control occupies lot of space and selecting a date will cause a post back.

To avoid that problem we can use AJAX to select a date from calendar control with out any page post back and hiding the calendar control will save lot of space.

Now lets create a web application and add a script manager and a update panel control, now under update panel add text box, button and a calendar control as shown the below screen shot and make calendar control visible property to false

image

Now lets write logic in .cs file for that double click on Button and add following code

Calendar1.Visible = true;

and double click on calendar control and add following code

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
    Calendar1.Visible = false;
}

 

Now we are ready with our code, lets run build and test.

 

image

 

Hope this helps.