Tuesday, December 30, 2008

Convert Image to Icon in .Net

  1. ///
  2. /// Converts an image into an icon.
  3. ///
  4. /// The image that shall become an icon
  5. /// The width and height of the icon. Standard
  6. /// sizes are 16x16, 32x32, 48x48, 64x64.
  7. /// Whether the image should be squashed into a
  8. /// square or whether whitespace should be put around it.
  9. /// An icon!!
  10. private Icon MakeIcon(Image img, int size, bool keepAspectRatio) {
  11. Bitmap square = new Bitmap(size, size); // create new bitmap
  12. Graphics g = Graphics.FromImage(square); // allow drawing to it
  13. int x, y, w, h; // dimensions for new image
  14. if(!keepAspectRatio || img.Height == img.Width) {
  15. // just fill the square
  16. x = y = 0; // set x and y to 0
  17. w = h = size; // set width and height to size
  18. } else {
  19. // work out the aspect ratio
  20. float r = (float)img.Width / (float)img.Height;
  21. // set dimensions accordingly to fit inside size^2 square
  22. if(r > 1) { // w is bigger, so divide h by r
  23. w = size;
  24. h = (int)((float)size / r);
  25. x = 0; y = (size - h) / 2; // center the image
  26. } else { // h is bigger, so multiply w by r
  27. w = (int)((float)size * r);
  28. h = size;
  29. y = 0; x = (size - w) / 2; // center the image
  30. }
  31. }
  32. // make the image shrink nicely by using HighQualityBicubic mode
  33. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  34. g.DrawImage(img, x, y, w, h); // draw image with specified dimensions
  35. g.Flush(); // make sure all drawing operations complete before we get the icon
  36. // following line would work directly on any image, but then
  37. // it wouldn't look as nice.
  38. return Icon.FromHandle(square.GetHicon());
  39. }

Sunday, December 28, 2008

Creating CSV file using Oledb object in C#.net

OleDbConnection OleDbCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strCSVPath + ";Extended Properties=\"text;HDR=Yes;FMT=Delimited(,)\"");
OleDbCmd = new OleDbCommand("Create table BundlesTable.csv(ProjectName varchar(250),BundleName varchar(250),BundleItems varchar(250))", OleDbCon);
OleDbCmd.ExecuteNonQuery();

Friday, November 21, 2008

Opening the link or website in .net windows application

System.Diagnostics.Process.Start("http://decidyn.com");

Tuesday, November 4, 2008

Converting String to Datetime in C#.net 2.0

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US", false);
culture.DateTimeFormat.DateSeparator = string.Empty;
culture.DateTimeFormat.ShortDatePattern = "yyyyMMdd";

dateime dt=DateTime.ParseExact(startEndDate[1].ToString(),"yyyyMMdd", culture)

Thursday, October 16, 2008

Getting Unique field of a column form a table( also get distinct count of column of datatable)

public DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
{
DataTable dt = new DataTable(TableName);
dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);

object LastValue = null;
foreach (DataRow dr in SourceTable.Select("", FieldName))
{
if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])))
{
LastValue = dr[FieldName];
dt.Rows.Add(new object[] { LastValue });
}
}
//if (ds != null)
// ds.Tables.Add(dt);
return dt;
}
private bool ColumnEqual(object A, object B)
{

// Compares two values to see if they are equal. Also compares DBNULL.Value.
// Note: If your DataTable contains object fields, then you must extend this
// function to handle them in a meaningful way if you intend to group on them.

if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
return true;
if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
return false;
return (A.Equals(B)); // value type standard comparison
}

Sunday, September 14, 2008

Using Generic lists with crystal reports in .net

Public Sub ReportDocumentListDetails(ByVal rptPath As String, ByVal reportname As String, ByVal rptdoc As CrystalDecisions.CrystalReports.Engine.ReportDocument, _

ByVal arListName As System.Collections.ArrayList, ByVal arListValue As System.Collections.ArrayList)

Dim rptViewer As New CrystalDecisions.Windows.Forms.CrystalReportViewer()

Dim ds As DatasetReport = New DatasetReport

If (arListName.Count = arListValue.Count) Then

For i As Integer = 0 To arListName.Count - 1

rptdoc.SetParameterValue(arListName(i).ToString, arListValue(i))

Next

End If

Dim objExOpt As CrystalDecisions.Shared.ExportOptions

Dim objDiskOpt As New CrystalDecisions.Shared.DiskFileDestinationOptions

objDiskOpt.DiskFileName = "F:\nath\" & reportname & ".pdf"

objExOpt = rptdoc.ExportOptions

objExOpt.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile

objExOpt.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat

objExOpt.DestinationOptions = objDiskOpt

rptdoc.Export(objExOpt)

rptdoc.Close()

End Sub

Export options of crystal reports and passing parameters to crystal reports in .net

Public Sub ReportDocumentDetails(ByVal rptPath As String, ByVal reportname As String, ByVal dtReport As DataTable, _

ByVal arListName As System.Collections.ArrayList, ByVal arListValue As System.Collections.ArrayList)

Dim rptViewer As New CrystalDecisions.Windows.Forms.CrystalReportViewer()

Dim ds As DatasetReport = New DatasetReport

Dim rptdoc As CrystalDecisions.CrystalReports.Engine.ReportDocument = New CrystalDecisions.CrystalReports.Engine.ReportDocument

rptdoc.Load(rptPath)

rptdoc.SetDataSource(CType(dtReport, DataTable))

If (arListName.Count = arListValue.Count) Then

For i As Integer = 0 To arListName.Count - 1

rptdoc.SetParameterValue(arListName(i).ToString, arListValue(i))

Next

End If

Dim objExOpt As CrystalDecisions.Shared.ExportOptions

Dim objDiskOpt As New CrystalDecisions.Shared.DiskFileDestinationOptions

objDiskOpt.DiskFileName = "F:\nath\" & reportname & ".pdf"

objExOpt = rptdoc.ExportOptions

objExOpt.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile

objExOpt.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat

objExOpt.DestinationOptions = objDiskOpt

rptdoc.Export(objExOpt)

rptdoc.Close()

End Sub

Monday, September 8, 2008

Working with Attachments in Outlook Email using .net 2.0

Dim olApp As Microsoft.Office.Interop.Outlook.Application = New ApplicationClass()
Dim oNameSpace As Microsoft.Office.Interop.Outlook.NameSpace = olApp.GetNamespace("MAPI")
Dim oOutL As New Outlook.Application
Dim oMail As Outlook.MailItem

Dim objFolder As MAPIFolder = oNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox)
Dim oItems As Items = objFolder.Items

Dim twmp As Integer = 15
Do While (twmp >= 0)
oMail = CType(objFolder.Items((objFolder.Items.Count - twmp)), MailItem)
If (oMail.UnRead = True) Then
If (oMail.Subject = "Document") Then
oMail.Attachments(1).SaveAsFile("E:\VBABonds\kaushik\" & oMail.Attachments(1).FileName)
End If
End If
twmp = (twmp - 1)
Loop

Friday, September 5, 2008

Open word file using vb.net 2,0 in windows application

To open ms word file using vb.net 2.0 in windows application

Add reference microsoft.word 12.o object from com tab.

If (System.IO.File.Exists(txtBrowse.Text)) Then

Dim test As Microsoft.Office.Interop.Word.Application

test = New Microsoft.Office.Interop.Word.Application

test.Documents.Open(txtBrowse.Text)

test.OpenAttachmentsInFullScreen = True

test.Visible = True

End If

Thursday, September 4, 2008

Storing and Downloading ms word file in ms access file using VB.NET 2.0

Storing a ms word file in access database using VB.NET 2.0


Dim objcon As System.Data.OleDb.OleDbConnection = CommonFunctions.clsCommonFunctions.OleDbConnections()

Dim objcmd As System.Data.OleDb.OleDbCommand = New OleDb.OleDbCommand("", objcon)

Dim par As OleDb.OleDbParameter = New OleDb.OleDbParameter("@Attachment", OleDb.OleDbType.LongVarBinary)

Dim strText As String = "update bonds set Attachment=@Attachment where bondsid=" & txtDBaseRefNo.Text

objcon.Open()

Dim fs As New System.IO.FileStream _

(TextBox1.Text, System.IO.FileMode.OpenOrCreate, _

System.IO.FileAccess.Read)

Dim MyData(fs.Length) As Byte

fs.Read(MyData, 0, fs.Length)

fs.Close()

par.Value = MyData

objcmd.CommandText = strText

objcmd.Parameters.Add(par)

Dim i As Integer = objcmd.ExecuteNonQuery()

fs = Nothing

objcon.Close()


Downloading ms word file from ms access database using VB.NET 2.0


Dim objcon As System.Data.OleDb.OleDbConnection = CommonFunctions.clsCommonFunctions.OleDbConnections()

Dim command As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand( _

"select Attachment from bonds where bondsid=" & txtDBaseRefNo.Text, objcon)

' Writes the BLOB to a file (*.bmp).

Dim stream As System.IO.FileStream

' Streams the binary data to the FileStream object.

Dim writer As System.IO.BinaryWriter

' The size of the BLOB buffer.

Dim bufferSize As Integer = 100

' The BLOB byte() buffer to be filled by GetBytes.

Dim outByte(bufferSize - 1) As Byte

' The bytes returned from GetBytes.

Dim retval As Long

' The starting position in the BLOB output.

Dim startIndex As Long = 0

' The publisher id to use in the file name.

Dim pubID As String = ""

' Open the connection and read data into the DataReader.

objcon.Open()

Dim reader As System.Data.OleDb.OleDbDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess)

Do While reader.Read()

' Get the publisher id, which must occur before getting the logo.

'pubID = reader.GetString(0)

' Create a file to hold the output.

stream = New System.IO.FileStream( _

"C:\Documents and Settings\Gopinath\Desktop\doccc1111.doc", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)

writer = New System.IO.BinaryWriter(stream)

' Reset the starting byte for a new BLOB.

startIndex = 0

' Read bytes into outByte() and retain the number of bytes returned.

retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize)

' Continue while there are bytes beyond the size of the buffer.

Do While retval = bufferSize

writer.Write(outByte)

writer.Flush()

' Reposition start index to end of the last buffer and fill buffer.

startIndex += bufferSize

retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize)

Loop

' Write the remaining buffer.

writer.Write(outByte, 0, retval - 1)

writer.Flush()

' Close the output file.

writer.Close()

stream.Close()

Loop

' Close the reader and the connection.

reader.Close()

objcon.Close()




Tuesday, September 2, 2008

Run Executable file in ASP.NET

i will provide a code snippet of how to run a process (in this case it is WindowsMediaPlayer.exe) which exists in your application root folder.

// Create An instance of the Process class responsible for starting the newly process.

System.Diagnostics.Process process1 = new System.Diagnostics.Process();

// Set the directory where the file resides

process1.StartInfo.WorkingDirectory = Request.MapPath("~/");

// Set the filename name of the file you want to open

process1.StartInfo.FileName = Request.MapPath("WindowsMediaPlayer.exe");

// Start the process

process1.Start();


Run a .EXE from a VB.NET application?

To run a .EXE file from a VB.NET application you need to import the System.Diagnostics namespace. The following sample shows how to run Notepad from a VB.NET application.

Imports System
Imports System.Diagnostics
Dim program As New Process()
program.StartInfo.FileName = "Notepad.exe"
program.StartInfo.Arguments = " "
program.Start()

Thursday, August 28, 2008

Validating Email id using Regular Expression in vb.net

Dim m As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]" & _

"+\x20*|""((?=[\x01-\x7f])" & _

"[^""\\]|\\[\x01-\x7f])*""\x20*)*(?<))?((?!\.)" & _ "(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|""((?=[\x01-\x7f])[^""\\]" & _

"|\\[\x01-\x7f])*"")@(((?!-)[a-zA-Z\d\-]+(? & _

"{4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$")

Dim isMatch As Boolean = m.IsMatch(txtBrokerEmail.Text) 'INPUT

MsgBox(isMatch.ToString())


Tuesday, August 26, 2008

Excel Reports in ASP.NET 2.0

In this article you will learn how to read data from Excel, generate report using the Response objects and to play with the Microsoft Excel 11.0 objects involved. Indeed, it is impossible to cover all features in this tutorial but many important techniques were covered to help you down the line. It is up to you to be creative and adapt the techniques to your scenarios.


Analyst Real Team System (ARTS) 7.0
Analyst Real Team System (ARTS) provides a complete set of tools for modeling the various artifact types of system development. ARTS provides a uniform approach to modeling use cases, test cases, business rules, bugs, tasks, and more. The result is a unique and coherent framework for successful system development by anyone using the software.

Introduction

Excel is such a powerful tool that almost all companies make extensive use of it for analyzing data. Moreover, the internet is not as it was 10 years ago. Almost all pages that are out there on the internet are dynamic ones, that is, interacts with a database in backend to produce results. Sometimes, data that are displayed, if made available on in an Excel file, proper analysis of the data often helps in making more accurate decisions by using Excel features. In this tutorial, we will learn how to interact with Excel files, both reading and writing.

Excel - ASP.NET Scenarios

For the purpose of this tutorial, an Excel sheet had been prepared that holds record of students and their respective marks in subjects. Please note that these records are fictitious and had been input randomly.

StudentId

StudentName

10001

John Thomas

10002

Terry Lane

10003

Anne Marie

10004

Tom Sawyer

10005

Derek Ince

10006

Emerson Boyce

10007

Thommas Kolka

10008

Edison Hall

10009

Teddy Harewood

10010

Williams Yorkshire

Fig 1. Table holding information for students

StudentId

Marks

10001

50

10002

60

10003

75

10004

80

10005

90

10006

95

10007

100

10008

20

10009

48

10010

66

Fig 2. Table holding student marks in Mathematics subject

StudentId

Marks

10001

30

10002

25

10003

65

10004

78

10005

95

10006

64

10007

32

10008

88

10009

95

10010

99

Fig 3. Table holding student marks in Geography subject

Interacting with Excel

Fortunately, there are COM objects that are available to interact with the Excel file. Also, we can make use of the OleDB class to treat the Excel file as a simple table. In this way, we can fire SQL queries to the Excel file so that we can retrieve data from the sheets. An analogy can be made to a database. The Excel Workbook is considered as the Database while the Sheets are considered as tables. Microsoft Excel 11.0 Object Library should be added as Reference to get the features for interacting with Excel.


Fig 4. Adding Microsoft Excel 11.0 Object Library as Reference

The Excel file is then added to the DataSource folder in ASAP.NET to be interacted with. To connect to a certain database, a connection string is needed. The same thing applies for Excel. The following is a key added in the Web.Config file for future reference.

<add name="ExcelConnection" connectionString="Provider=Microsoft.Jet.Oledb.4.0;Data Source=|DataDirectory|\SchoolMgt.xls;Extended Properties=Excel 8.0"/>

Note that our Excel file which contains the necessary data will be SchoolMgt.xls, as written in the connection string.


Fig 5. Excel file illustrating Excel Book containing data sheets with data

Reading data from Excel sheets

Let us build an interface for getting data from the Excel file.


Fig 6. Interface to search records per table selected.

It is important to import the following:

Imports System.Data.OleDb
Imports System.Data

The following code creates the connection and builds the query based on the selected table.

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Try
Dim strExcelConn As String = System.Configuration.ConfigurationManager.ConnectionStrings.Item("ExcelConnection").ToString()
Dim dbConn As New OleDbConnection(strExcelConn)
Dim strSQL As String

strSQL = "SELECT * FROM [" & cmbSheets.SelectedItem.ToString() & "$]"

dbConn.Open()

Dim cmd As New OleDbCommand(strSQL, dbConn)
Dim dsExcel As New DataSet
Dim daExcel As New OleDbDataAdapter(cmd)

daExcel.Fill(dsExcel)

dgResults.DataSource = dsExcel
dgResults.DataBind()
Catch ex As Exception
Throw ex
End Try
End Sub

Please note that the table name in the SELECT query should be in the format [TableName$], which the square brackets and the dollar sign at the end.

Playing with SELECT statements

As you have guessed, the Excel file has turned out to be a normal database. The transparency that the OleDB connection had made is exceptional. Also, note that the first row is taken to contain field names for the columns.

Now, let us get the marks of the students in Mathematics, Geography and Total, sorted in Descending order.

Protected Sub btnGenerateReport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGenerateReport.Click
Try

Dim strExcelConn As String = System.Configuration.ConfigurationManager.ConnectionStrings.Item("ExcelConnection").ToString()
Dim dbConn As New OleDbConnection(strExcelConn)
Dim strSQL As String

strSQL = "SELECT S.StudentId, S.StudentName, M.Marks, G.Marks, (M.Marks+G.Marks) AS Total "& _
"FROM [Students$] S, [Mathematics$] M, [Geography$] G "& _
"WHERE(S.StudentId = M.StudentId And S.StudentId = G.StudentId) " & _
"ORDER BY (M.Marks+G.Marks) DESC"
dbConn.Open()

Dim cmd As New OleDbCommand(strSQL, dbConn)
Dim dsExcel As New DataSet
Dim daExcel As New OleDbDataAdapter(cmd)

daExcel.Fill(dsExcel)

dgReports.DataSource = dsExcel
dgReports.DataBind()

Catch ex As Exception
Throw ex
End Try
End Sub


Fig 7. Report generating the students' marks and total, sorted in descending order.

Generating Excel Reports

Two ways for generating Excel report will be discussed in this tutorial. The first one is using the "Response" class and the second one by manipulating the Excel objects that "Microsoft Excel 11.0" Objects provide.

The following piece of code illustrates how this is done

Protected Sub btnToExcelByResponse_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnToExcelByResponse.Click
' Variables declaration
Dim dsExport As New DataSet()
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()

dgGrid.DataSource = getData()

' Report Header
hw.WriteLine(" Student Marking Report ")

' Get the HTML for the control.
dgGrid.HeaderStyle.Font.Bold = True
dgGrid.DataBind()
dgGrid.RenderControl(hw)

' Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.End()
End Sub

  • First, we create the dataset that will hold the records. Then, a StringWriter object (tw) is also created along with an HtmlTextWriter (hw) which takes as parameter the text writer object. They are important for rendering purposes; i.e. html tags can be applied like bold, italic etc. to the resulting Excel report.

  • Also, a datagrid object which will store the dataset of records.

  • Note that function getData() in the code snippet only contains the codes in the previous example which returns a dataset of records.

  • hw.WriteLine(" Student Marking Report ") shows that you can also combine HTML codes with the output for proper display. In our example, the font size will be 5, underlined and bold.

  • dgGrid.RenderControl(hw) renders the HTML object with the data that the datagrid contains. The result is normally formatted in a tabular format.

  • Response.ContentType = "application/vnd.ms-excel" makes the Reponse object output to Excel.

  • Response.Write(tw.ToString()) outputs the formatted object to Excel.


Figure 8. Output result showing the report that is generated in Excel

The second way for generating Excel reports from ASP.NET is to use the Microsoft Excel 11.0 Objects. This method offers more fallibility in terms of manipulating the features that Excel provides and formatting the report.

The following code snippet makes use of the various Excel objects that Excel provides to generate the report.

Imports System.Reflection
Imports Excel = Microsoft.Office.Interop.Excel

Protected Sub btnToExcelByObjects_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnToExcelByObjects.Click
Try
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet

xlWorkBook = New Excel.Application().Workbooks.Add(Missing.Value)
xlWorkBook.Application.Visible = True
xlWorkSheet = xlWorkBook.ActiveSheet

' Gets the dataset containing the data
Dim dsData As DataSet = getData()
Dim i As Integer = 2

' Outputting the fieldnames in pink bold color
xlWorkSheet.Cells(1, 1) = "Student ID"
xlWorkSheet.Cells(1, 2) = "Student Name"
xlWorkSheet.Cells(1, 3) = "Mathematics"
xlWorkSheet.Cells(1, 4) = "Geography"
xlWorkSheet.Cells(1, 5) = "Total"

xlWorkSheet.Range("$A1:$E1").Font.ColorIndex = Excel.Constants.xlColor1
xlWorkSheet.Range("$A1:$E1").Font.Bold = True

' Outputting the data
For Each dr As DataRow In dsData.Tables(0).Rows
xlWorkSheet.Cells(i, 1) = dr(0)
xlWorkSheet.Cells(i, 2) = dr(1)
xlWorkSheet.Cells(i, 3) = dr(2)
xlWorkSheet.Cells(i, 4) = dr(3)

' Building the formula for calculating the sum
xlWorkSheet.Cells(i, 5).Formula = "=SUM($C{0}:$D{0})".Replace("{0}", i.ToString())

' Going to the next row
i = i + 1
Next

' Auto fit the columns
xlWorkSheet.Columns.AutoFit()

' Generating the graph
Dim chart As Excel.Chart
chart = xlWorkBook.Charts.Add()

With chart
.ChartType = Excel.XlChartType.xlColumnClustered
.SetSourceData(xlWorkSheet.Range("A1:E11"), 2)

.HasTitle = True
.ChartTitle.Characters.Text = "Students' marks"

.Axes(1, Excel.XlAxisGroup.xlPrimary).HasTitle = True
.Axes(1, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "Students"
.Axes(2, Excel.XlAxisGroup.xlPrimary).HasTitle = True
.Axes(2, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "Marks"
End With
Catch ex As Exception
Throw ex
End Try
End Sub

An Excel workbook is first created. Then the active sheet is accessed by xlWorkSheet = xlWorkBook.ActiveSheet. After that, we get the data into the dataset, ready to be processed. Using the Font property, the title is displayed in Pink bold colour. Note how the Formula that Excel provides is properly used to calculate the SUM of the marks for each student xlWorkSheet.Cells(i, 5).Formula = "=SUM($C{0}:$D{0})".Replace("{0}", i.ToString()).


Figure 9. Excel Report having output the list of students and their respective marks.

A chart is also generated using the objects. The x-axis consists of the names and id of each student. The y-axis, the marks for the different students. The chart is always handy for analysis of data.


Figure 10. Chart that is generated using Microsoft Excel 11.0 Objects