Free Information Technology Magazines and eBooks

Saturday, May 23, 2009

ASP.NET: How to export crystal report to PDF, Excel or Word using C#

Most of system end-users, prefer their report in PDF, Excel or Word format over Crystal Report. The reason is they have more control over the report specially if they need to modify the report and add more information. This is where export facility comes handy. For todays article, you will learn How to export crystal report to PDF, Excel or MS Word document.


First we need to include the following namespaces on your Using directives.

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports;


Next is to setup the database connection using TableLogOnInfo class.

TableLogOnInfo LogInfo = new TableLogOnInfo();
LogInfo.ConnectionInfo.ServerName = "mnlho8ap33";
LogInfo.ConnectionInfo.UserID = "sa";
LogInfo.ConnectionInfo.Password = "12345678";
LogInfo.ConnectionInfo.DatabaseName = "Access";



Then connect to the database and load the report.

CrystalDecisions.CrystalReports.Engine.ReportDocument O_Report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
//Load the report
O_Report.Load(Server.MapPath(Request.QueryString["file"].ToString()));
O_Report.Database.Tables[0].ApplyLogOnInfo(LogInfo);


After loading the report, pass the parameters required.

//pass the parameters
ParameterDiscreteValue discreteVal = new ParameterDiscreteValue();
discreteVal.Value = Request.QueryString["parameter1"].ToString();
O_Report.SetParameterValue("parameter1", discreteVal);


Then finally, export the crystal report using ExportToHttpResponse method.

string exportfilename = "DMR" + Request.QueryString["parameter1"].ToString();
switch (cboFormat.Text.ToLower())
{
case "microsoft word":
O_Report.ExportToHttpResponse(ExportFormatType.WordForWindows, Response, true, exportfilename);
break;
case "microsoft excel":

O_Report.ExportToHttpResponse(ExportFormatType.Excel, Response, true, exportfilename);
break;
default:
O_Report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, exportfilename);
break;
}


You can also download the Export to PDF/Excel/Word VB 2005 sample project.


For more ASP.NET coding tips, subscribe now

PDF to TXT Converter

PDF to TXT Converter FreewareLast night, I was looking for a freeware that can convert PDF files to plain TXT and luckily I stumbled with this cool freeware called Zilla PDF to TXT Converter. Although the freeware is limited to converting pdf files to plain text format files only, it is still notable because it can process conversion in batch mode (multiple PDFs). Another important feature is that Zilla PDF to TXT Converter also support conversion of specific pages range to txt files.


I tested converting a 10MB PDF file and the software gave me just 800KB of text file. This is a great tool to extract information from PDF and use it for whatever purpose you want.

PDF to TXT Converter


For more Cool softwares, subscribe now.


New at Gmail Labs: Inbox Preview

Inbox Preview on GmailYou can now see the preview of your message by enabling the new Gmail Labs feature that just launched called Gmail Inbox Preview. As Gmail goes through its initial boot, Inbox Preview will show a plaintext version of your ten most recent message subject lines. The feature is most notable to people who still using quirky mobile connections or dial up service.


Grabbed from GMail Blog

To ease this pain a bit, we created a new feature in Gmail Labs called Inbox Preview. While Gmail is loading, a simple, static preview of your inbox with your ten most recent messages is displayed. Turn it on from the Labs tab under Settings, and if you're on a slow connection you'll know from the start if it's worth the wait.


For more Technology news, subscribe now.


Friday, May 22, 2009

How to use delegates in C#

A Delegate is something like function pointers. It is an object that is created to refer to a static method and then used to call this method. Using a delegate allows the coder to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method without knowing at compile time which method will be invoked. But Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.


For this article, I will demonstrate How to use delegates using a very simple C# example.

Let's create a sample function and named it as ParseString.

static string ParseString(string str)
{
return str.Replace("'", "");
}


Declare the delegate for the ParseString function.

public delegate string DelegateParser(string str);


Now instantiate the delegate and invoke the function through the delegate.

string mystring = Console.ReadLine();
//Instantiate the delegate
DelegateParser parser = new DelegateParser(ParseString);
//Call the delegate
Console.WriteLine(parser(mystring));


That's how simple it is. Here is the complete code:

static string ParseString(string str)
{
return str.Replace("'", "");
}

public delegate string DelegateParser(string str);

static void Main(string[] args)
{
string mystring = Console.ReadLine();
DelegateParser parser = new DelegateParser(ParseString);
Console.WriteLine(parser(mystring));
Console.ReadKey();
}


I often often use delegates to encapsulate my libraries so that actual functions names are not visible to other programmers. This is an effective way to standardize coding.

For more C# tips and tricks, subscribe now

The faster Google Chrome 2.0

The faster Google Chrome 2.0March 21, the search giant released the stable version 2.0 of Google Chrome. According to Google, the newest version can run JavaScript-heavy web pages about 30% faster. It is impressive given that Chrome is already run faster compared to other browser in the web. The stable build is a follow-up on the Chrome developer version which Google released at dev channel earlier this month of May.


Comparison from previous stable version
Google Chrome 2.0 Benchmark

Google also added other features such as form autofill, full screen mode, and the ability to remove thumbnails from the New Tab page.

For more Technology news, subscribe now.

Thursday, May 21, 2009

How to reverse string in C#

On this article, I will show you how to reverse a string in C#. Although this function is not often used in business applications, still you might need it someday. One use of it that I can think of, is including it as part of data encryption process. I'll show you two different functions, first the ReverseWord which will reverse a string by word and the ReverseWordChar that reverse string by each character.



Reverse string by word

public static string ReverseWord(string s)
{
int length = s.Length;
int i = 0;

string[] splittedArray = s.Split(' ');
StringBuilder sb = new StringBuilder();
for (i = splittedArray.Length - 1; i >= 0; i--)
{
if (i != 0)
sb.Append(splittedArray[i] + ' ');
else
sb.Append(splittedArray[i]);

}

return sb.ToString();
}


Reverse string by each character

public static string ReverseWordChar(string s)
{
int length = s.Length;
int i = 0,j=0;
StringBuilder sb= new StringBuilder();
int startPos = length - 1;

for (i = length-1; i >=0;i--)
{
if (s[i] == ' ')
{
for (j = i+1; j <= startPos; j++)
{
sb.Append(s[j]);
}
startPos = i;
sb.Append(' ');
}
}

for (j = 0; j < startPos; j++)
{
sb.Append(s[j]);
}

return sb.ToString();
}

For more C# tips and tricks, subscribe now

Visual Studio 2010 Beta 1 now available to all

Visual Studio 2010 Beta 1On Wednesday May 20, Microsoft released the Visual Studio 2010 BETA to the public. It was released two days ago (May 18) to TechNet and MSDN subscribers. Now both MSDN/TechNet subscribers and the public can test all edition of the latest version of Visual Studio 2010 which are Professional, Team Suite, Team Foundation Server and including the .Net Framework 4. Although Microsoft has not yet announce their target ship date, several experts predicts that it might be ship before the end of year 2009.


Here are some notable new features of VS 2010:


  • F# in Visual Studio 2010

  • WPF Data Binding in Visual Studio 2010

  • Office Development in Visual Studio 2010

  • Multi-targeting .NET Framework version

  • Parallel Computing



First Look at Visual Studio 2010

For more Technology news, subscribe now.

Wednesday, May 20, 2009

Crystal Report Printing in VB.NET (With Form Preview)

Crystal Report Printing in VB.NET (With Form Preview)I've been using Crystal Report since VB6 days, the earliest version I handled was Seagate Crystal Report 7.0. Microsoft included the OEM version of Business Objects Crystal Reports on Microsoft Visual Studio as a general purpose reporting tool. Crystal Reports became the de facto report writer when Microsoft released it with Visual Basic. Today, you will learn How to call Crystal Report on your application. This article includes a VB.NET project that you can customize for your own application.



The step-by-step procedure to call Crystal Report
1. Add new form and named it as frmPrinter. This will serve as your Crystal Report Printer module.
2. Add references to CrystalReport.CrystalReport.Engine and CrystalDecisions.Shared
3. Add Crystal Report Viewer on the newly created form. Make sure that the Dock property is set to "Fill"
Crystal Report .NET project

4. Switch to "View Code" and include the following namespaces required for this project.


Imports CrystalDecisions
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.CrystalReports
Imports CrystalDecisions.ReportSource
Imports CrystalDecisions.Shared

5. Inside the form class, declare private variables that will hold as crystal report parameters

Private _Parameter1 As String

6. Modify the form's constructor (new) event to include passing of parameters as shown below.

Public Sub New(ByVal prParameter As String)

' This call is required by the Windows Form Designer.
InitializeComponent()

' Add any initialization after the InitializeComponent() call.
_Parameter1 = prParameter
End Sub

7. Add the "SetConnectionInfo" function which will create the Login connection to your database.

Public Shared Sub SetConnectionInfo(ByVal RptDoc As Engine.ReportDocument, ByVal CnnInfo As [Shared].TableLogOnInfo)

For Each TableReport As CrystalDecisions.CrystalReports.Engine.Table In RptDoc.Database.Tables
TableReport.ApplyLogOnInfo(CnnInfo)
Next
For Each SectionReport As CrystalDecisions.CrystalReports.Engine.Section In RptDoc.ReportDefinition.Sections
For Each RptObj As CrystalDecisions.CrystalReports.Engine.ReportObject In SectionReport.ReportObjects
If RptObj.Kind = ReportObjectKind.SubreportObject Then
Dim SubRptObj As CrystalReports.Engine.SubreportObject = RptObj
Dim SubRpt As CrystalDecisions.CrystalReports.Engine.ReportDocument = SubRptObj.OpenSubreport(SubRptObj.SubreportName)
For Each tbl As CrystalDecisions.CrystalReports.Engine.Table In SubRpt.Database.Tables
tbl.ApplyLogOnInfo(CnnInfo)
Next
End If
Next
Next
End Sub


8. On your the "Shown" event of the frmPrinter, Paste the following codes.

Private Sub frmPrinter_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
'Prepare Database Login Info
Dim LogInfo As New TableLogOnInfo()
LogInfo.ConnectionInfo.ServerName = "mnlho8ap33"
LogInfo.ConnectionInfo.DatabaseName = "BS"
LogInfo.ConnectionInfo.UserID = "sa"
LogInfo.ConnectionInfo.Password = "12345678"
Dim oReport As New ReportDocument
oReport.Load("rptSample.rpt")
'Connect to database
SetConnectionInfo(oReport, LogInfo)
'Set Parameters
oReport.SetParameterValue("Parameter1", _Parameter1)
'Open preview
Me.WindowState = FormWindowState.Maximized
CR1.ReportSource = oReport
End Sub


9. Lastly on the form caller, put the code that will call the form printer.

Dim frm As New frmPrinter(txtInvoiceNumber.Text)
frm.MdiParent = Me.ParentForm
frm.Show()


Now Try to run the project, the result should display like the screenshot below.

Crystal Report Printing Result

To customize and make your own Crystal Report printing, download the sample project here.


For more Crystal Reports tips and tricks, subscribe now


GMail can now translate foreign-language email messages

GMail translate foreign-language email messagesThere is a new feature in GMail Labs today, user can now understand foreign-language emails by using Google automatic message translation technology. Simply enable "Message Translation" from the Labs tab under Settings, and when you receive a foreign-language email, Gmail can translate it into a language you can understand in one click.


Grab from GMail Blog:

If all parties are using Gmail, you can have entire conversations in multiple languages with each participant reading the messages in whatever language is most comfortable for them. It's not quite the universal translators we're so fond of from science fiction, but thanks to Google Translate, it's an exciting step in the right direction. I use this feature everyday to help me work with teammates around the globe (they think my Japanese is much better than it really is...shhhh!).


I tried it this morning with an email on my Spam folder. It really works!

GMail automatic translation

Now you can impress your foreign email pals, let them write you in their own language.

For more Technology news, subscribe now.



Tuesday, May 19, 2009

How to map shared network folder using VB.NET

How to map shared network folder using VB.NETMicrosoft .NET do not have available namespace or command to directly map shared network folder. To map a shared folder you still need to access the WinAPI or use the NET USE command. Today we will explore the usage of WNetAddConnection2A and how we can use it to map any network shared folder. This article also contains a sample project that you can download and study.



To start, you need to include the following namespace in your VB.NET project:

Imports System.Runtime.InteropServices


Then inside your form class, delare the WNetAddConnection2 and WNetCancelConnection2 WINAPIs.

Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _
(ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, _
ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer

Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" _
(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer


Also after the declaration of WINAPIs, create a public structure like the one below:

<structlayout(layoutkind.sequential)>Public Structure NETRESOURCE
Public dwScope As Integer
Public dwType As Integer
Public dwDisplayType As Integer
Public dwUsage As Integer
Public lpLocalName As String
Public lpRemoteName As String
Public lpComment As String
Public lpProvider As String
End Structure


And then defined some constants that will be used later.


Public Const ForceDisconnect As Integer = 1
Public Const RESOURCETYPE_DISK As Long = &H1


Now after we finished declaring the prerequisites, Lets code the functions to Map an UnMap shared folder.

Function to Map a shared Folder

Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String) As Boolean

Dim nr As NETRESOURCE
Dim strUsername As String
Dim strPassword As String

nr = New NETRESOURCE
nr.lpRemoteName = UNCPath
nr.lpLocalName = DriveLetter & ":"

strUsername = Nothing
strPassword = Nothing
If txtUsername.Text.Length > 0 Then
strUsername = txtUsername.Text
End If
If txtPassword.Text.Length > 0 Then
strPassword = txtPassword.Text
End If

nr.dwType = RESOURCETYPE_DISK

Dim result As Integer
result = WNetAddConnection2(nr, strPassword, strUsername, 0)

If result = 0 Then
Return True
Else
Return False
End If
End Function


Function to Un-Map shared folder

Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean
Dim rc As Integer
rc = WNetCancelConnection2(DriveLetter & ":", 0, ForceDisconnect)

If rc = 0 Then
Return True
Else
Return False
End If

End Function


Map shared network folder

Its finished, you application should be able to map shared network folder. To get the Visual Studio 2005 sample project I created, download it here.

For more VB.NET tips and tricks, subscribe now


Windows Registry Cleanup and Repair Tool

Windows Registry Cleanup and Repair ToolMost common problem of a slow windows PC is cause by registry problems such as Registry Errors, Registry Junk, MRU and History Data and Temp Files. I found a freeware registry cleaner created by Macecraft which is called PowerTools Lite. The program will clean out unneeded files, clean left-over data from the registry and fix registry errors. These features are based on the engine of jv16 PowerTools 2009.


It has an expert mode that allows a user to configure some of the scan rules before the scan is conducted. It has four different configuration settings that allows user to change scan performance, words to ignore or search for and advanced options like removing all found errors automatically or ignoring entries that get recreated by the computer system.

Here are some screenshots of PowerTools Lite:

Quick registry scan

Registry fix

For more Cool softwares, subscribe now.

Mozilla Labs Design Challenge: "Reinventing Tabs"

Mozilla Labs Design Challenge: Summer 2009For this summer 2009, the firefox creator wants itslatest design Challenge to focus on finding creative solutions on how to reinvent Tabs in the browser. Their theme is to find answer on the question "How can we create, navigate and manage multiple web sites within the same browser instance?"



Tabs worked well on slow machines on a thin Internet, where ten browser sessions were "many browser sessions". Today, 20+ parallel sessions are quite common; the browser is more of an operating system than a data display application; we use it to manage the web as a shared hard drive. However, if you have more than seven or eight tabs open they become pretty much useless. And tabs don’t work well if you use them with heterogeneous information. They’re a good solution to keep the screen tidy for the moment. And that’s just what they should continue doing.


If you want participate in the Design Challenge you need to create a mock-up of your proposed solution. It can be anything from a napkin drawing, to a wireframe, to a polished graphic. You also need to create a video that explains your idea(s), presenting the mock-up and showing how your idea works.


Here are the important dates to watch for:
* May 14th, 2009 - Launch of Design Challenge: Summer 09
* June 21st, 2009 - Submission deadline for mockups & videos
* July 8th, 2009 - Announcement of "Best in Class" and "People's Choice" selection

For more Technology news, subscribe now.


Monday, May 18, 2009

VB.NET: How to read a CSV file into an array

How to read a CSV fileA Comma separated values (CSV) file is a computer data file commonly used for exchanging information, for example between a database program and a spreadsheet program. Each line in the CSV file corresponds to a row in the table. Within a line, fields are separated by commas, each field belonging to one table column. Although Comma-separated value lists are very old technology and predate personal computers by more than a decade, it is still widely used today by many applications.


On this article, you will learn how to read a CSV file and put the values in an array. The sample code below uses StreamReader to load the file so you have to include the following imports:


Imports System.IO



Function in reading CSV file using VB.NET

Private Sub ReadCSVFileToArray()
Dim strfilename As String
Dim num_rows As Long
Dim num_cols As Long
Dim x As Integer
Dim y As Integer
Dim strarray(1, 1) As String

' Load the file.
strfilename = "test.csv"

'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strlines() As String
Dim strline() As String

'Load content of file to strLines array
strlines = tmpstream.ReadToEnd().Split(Environment.NewLine)

' Redimension the array.
num_rows = UBound(strlines)
strline = strlines(0).Split(",")
num_cols = UBound(strline)
ReDim strarray(num_rows, num_cols)

' Copy the data into the array.
For x = 0 To num_rows
strline = strlines(x).Split(",")
For y = 0 To num_cols
strarray(x, y) = strline(y)
Next
Next


' Display the data in textbox
For x = 0 To num_rows
For y = 0 To num_cols
TextBox1.Text = TextBox1.Text & strarray(x, y) & ","
Next
TextBox1.Text = TextBox1.Text & Environment.NewLine
Next

End If

End Sub


Here is the result of invoking the VB.NET function:

CSV file to array

Aside from storing the CSV into array, you can also directly store the parsed comma-separated values into database. This method is very useful in integrating two or more systems with different platforms.

You can download the CSV file to array sample project here.

For more VB.NET Coding Tips and Tricks, subscribe now

Sunday, May 17, 2009

SQL: How to get the last datetime updated of a table

For Database administrators, keeping track of the last date time when a table got updated is vital for a database audit. If you have an entry date field on your table that contains default value of GETDATE() then you can make use of it by using ORDER BY entrydate query. But of course we can't expect all tables to have such field. No worry because SQL server has Dynamic Management View (DMV), admin can query on sys.dm_db_index_usage_stats and retrieve the datetime when the table was last updated.


To get the last update from sys.dm_db_index_usage_stats, user can retrieve it from last_user_update field as shown in the SQL script below:


SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'TestDatabase')
AND OBJECT_ID=OBJECT_ID('tblTest')


If you want to get the last update on all tables in a database you can use the sys.tables.

SELECT
b.name
,user_seeks
,user_scans
,user_lookups
,user_updates
,last_user_seek
,last_user_scan
,last_user_lookup
,last_user_update
FROM
sys.dm_db_index_usage_stats a JOIN
sys.tables b ON (b.object_id = a.object_id)
WHERE database_id = db_id()


Please take note that if the SQL Server is restarted all information from DMV will be reset.

For more SQL Coding Tips and Tricks, subscribe now


Free Sql Backup And FTP Tool

Free Sql Backup And FTP ToolI stumbled on this great backup tool for MS SQL Server backup today. It has a free and premium version. SQLBackupAndFTP is MS SQL Server backup software that runs scheduled backups of SQL Server or SQL Server Express databases, zips the backups, stores them on a network or on a FTP server, removes old backups, and sends an e-mail confirmation on job's success or failure. Although it can be used in any SQL Server version, it was especially designed for SQL Server Express 2005 and SQL Server Express 2008, since they don't have built in tools for backup at all.



Free Sql Backup And FTP

You can download this Free SQL Backup And FTP tool.

For more Cool Softwares, subscribe now.