Wednesday, August 17, 2011

How to use backgroundworker control

Hi, Please note, The control Backgroundworker is available with Visual Studio 2008 and Visual Studio 2010.

Backgroundworker:
is used when you need to work with Threads parallely.
For Example

1. if you want to show the file names along with files being copied or
2. file content in label (line by line) with Progressbar etc.

I'm using the 2nd example here for demonstration but you can implement with any similar kind of task.

Steps:


1. Start-->Programs-->Microsoft visual Studio 2010-->Microsoft visual Studio 2010.

2. Create new window application by selecting File-->New-->Project-->Windows Form Application.

3. Goto ToolBox, if not visible Select View-->ToolBox from menubar or Press(Ctrl + Alt + X).


4. Scroll to Component, Select BackgroundWorker and drag to Windows application.


5. Now Drag Button, Label and Progressbar on windows form.


6. Inside button clcik event write this code:


With Me.BackgroundWorker1
.WorkerReportsProgress = True
.RunWorkerAsync("C:\crp.txt")
End With
ProgressBar1.Minimum = 1
ProgressBar1.Maximum = 2000
ProgressBar1.Visible = True
ProgressBar1.Value = 1

7. Note, BackgroundWorker control has three event,


1. BackgroundWorker1_DoWork
2. BackgroundWorker1_ProgressChanged
3. BackgroundWorker1_RunWorkerCompleted


Paste these code in your program:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim filename As String = e.Argument
Using reader As New System.IO.StreamReader(filename)
While Not reader.EndOfStream
Me.BackgroundWorker1.ReportProgress(0.0, reader.ReadLine())
System.Threading.Thread.Sleep(1000)
End While
End Using

End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.Label1.Text = e.UserState
ProgressBar1.PerformStep()
End Sub


Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("Done reading the file!")

End Sub

8. Run the application, You may see the screen as shown below:



Your comment will be appreciated.

Saturday, August 6, 2011

Create web page with download links

This article shows how to create web page with download links using ( VB.NET or C# ).

You just need to create two different page
1. Having all download links (e.g; link.aspx).
2. The url to redirect when the download link is clicked (e.g; downloading.aspx).

Steps:


1. Open visual studio with ur choiced version(2003,2005,2008 0r 2010)

Start->Programs->Microsoft Visual Studio 2005->Microsoft Visual Studio 2005.


2. Create new ASP.NET Web application or website

3. Rename the Default.aspx page as link.aspx and open the link.aspx.vb.
paste the below code. in page_load

You must import System.Io namespace
using VB.NET
Imports System.IO

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim di As New DirectoryInfo(Server.MapPath("NudiDownload"))
Dim i As Integer = 0
For Each fi As FileInfo In di.GetFiles()
Dim HL As New HyperLink()
HL.ID = "HyperLink" & System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
HL.Text = fi.Name
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name
Page.Controls.Add(HL)
Page.Controls.Add(New LiteralControl("
"))

Next
End Sub


The code looks similar as below

using C#
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("NudiDownload"));
int i = 0;
foreach (FileInfo fi in di.GetFiles())
{
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
Page.Controls.Add(HL);
Page.Controls.Add(new LiteralControl("
"));
}

}

4. Now right click on the solution and create new folder named(e.g; NudiDownload) and copy the softwares you want to provide for download. see the below picture.


5. Now create the another aspx page (e.g; downloading.aspx). click on downloding.aspx.vb
Imports the two namespaces: Syatem.Io and System.Threading
'-- VB.NET
Imports System.IO
Imports System.Threading


Paste the below code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim filename As String = Request("file").ToString()
fileDownload(filename, Server.MapPath("NudiDownload/" & filename))

End Sub
Private Sub fileDownload(ByVal fileName As String, ByVal fileUrl As String)
Page.Response.Clear()
Dim success As Boolean = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000)
If Not success Then
Response.Write("Downloading Error!")
End If
Page.Response.[End]()

End Sub
Public Shared Function ResponseFile(ByVal _Request As HttpRequest, ByVal _Response As HttpResponse, ByVal _fileName As String, ByVal _fullPath As String, ByVal _speed As Long) As Boolean
Try
Dim myFile As New FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim br As New BinaryReader(myFile)
Try
_Response.AddHeader("Accept-Ranges", "bytes")
_Response.Buffer = False
Dim fileLength As Long = myFile.Length
Dim startBytes As Long = 0

Dim pack As Integer = 10240
'10K bytes
Dim sleep As Integer = CInt(Math.Floor(CDbl(1000 * pack \ _speed))) + 1
If _Request.Headers("Range") IsNot Nothing Then
_Response.StatusCode = 206
Dim range As String() = _Request.Headers("Range").Split(New Char() {"="c, "-"c})
startBytes = Convert.ToInt64(range(1))
End If
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString())
If startBytes <> 0 Then
_Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength))
End If
_Response.AddHeader("Connection", "Keep-Alive")
_Response.ContentType = "application/octet-stream"
_Response.AddHeader("Content-Disposition", "attachment;filename=" & HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8))

br.BaseStream.Seek(startBytes, SeekOrigin.Begin)
Dim maxCount As Integer = CInt(Math.Floor(CDbl((fileLength - startBytes) \ pack))) + 1

For i As Integer = 0 To maxCount - 1
If _Response.IsClientConnected Then
_Response.BinaryWrite(br.ReadBytes(pack))
Thread.Sleep(sleep)
Else
i = maxCount
End If
Next
Catch
Return False
Finally
br.Close()
myFile.Close()
End Try
Catch
Return False
End Try
Return True
End Function


'-- C#
Using System.IO;
Using System.Threading;

protected void Page_Load(object sender, EventArgs e)
{
string filename = Request["file"].ToString();
fileDownload(filename, Server.MapPath("NudiDownload/" + "Setup.exe"));

}
private void fileDownload(string fileName, string fileUrl)
{
Page.Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
if (!success)
Response.Write("Downloading Error!");
Page.Response.End();

}
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;

int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; } 6. Save the page and set link.aspx as default page.

7. Run the application.

You will see the below screen.


You are done. Now Click on any of the link. You will be promted to Run or Save the download.


If you liked this article please put your comment.

Friday, August 5, 2011

Create PDF file and send mail using VB.NET

Imports System.Net.Mail
Imports iTextSharp.text
Imports iTextSharp.text.pdf


'your codes go here


Protected Sub CreatePdfandSendMail(ByVal toEmail as String)
'building file data
Dim doc As New Document()
Dim mStream As New MemoryStream
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, mStream)

'capture the object

'working the document

doc.Open()

'add header

doc.Add(New Paragraph("Paragraph 1"))
doc.Add(New Paragraph(" Paragraph 2"))

writer.CloseStream = False
doc.Close()
mStream.Position = 0


'prepare to send e-mails to normal user


Dim subj As String = "Email Confirmation"
Dim body As New StringBuilder("")
body.Append("This is an automated e-mail... ")
body.Append("Please find attached....")
Dim mm As New MailMessage("norely@mydomain.net", toEmail, subj, body.ToString)
mm.IsBodyHtml = True
mm.Attachments.Add(New Attachment(mStream, "filename.pdf"))
Dim client As New SmtpClient()
client.Host = "yourMailHost"
client.Send(mm)


'--- done, clean up resources

If Not mStream Is Nothing Then
mStream = Nothing
End If
mm = Nothing
client = Nothing

End Sub

Export Excel to Database

Public Sub ExportExcelIntoText(ByVal FullFileName As String)
Dim TextFilename As String
TextFilename = Left(TextFilename, Len(TextFilename) – 4) TextFilename += “.txt”
If File.Exists(TextFilename) Then
File.Delete(TextFilename)
End If
Dim fs As FileStream
Dim sWrtier As StreamWriter
Dim da As OleDb.OleDbDataAdapter
Dim ds As DataSetds = Nothing
da = Nothing
sWrtier = Nothing
Tryfs = New FileStream(TextFilename, FileMode.Create, FileAccess.Write)
sWrtier = New StreamWriter(fs)
Dim cnn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FullFileName + ";Extended Properties=""Excel 8.0;HDR=YES;""")

da = New OleDb.OleDbDataAdapter("Select * from [Sheet1$]", cnn)
ds = New DataSet(“ExcelFile”)da.Fill(ds)
Dim rowIndex As DataRow
Dim colIndex As DataColumnsWrtier.BaseStream.Seek(0, SeekOrigin.End)

For Each rowIndex In ds.Tables(0).Rows
For Each colIndex In ds.Tables(0).Columns
If rowIndex(colIndex) Is Nothing Then
sWrtier.Write("" + vbTab)
Elses()
Wrtier.Write(rowIndex(colIndex).ToString + vbTab)
End If
Next
sWrtier.WriteLine()
Next
'closing the file

Catch ex As Exception
Console.Write(ex.Message)
Finally
ds.Dispose()
ds = Nothing
da.Dispose()
da = Nothing
sWrtier.Close()
sWrtier.Dispose()
sWrtier = Nothing
End Try
End Sub

Thursday, August 4, 2011

Create Backup file for Sql server database

The easy VB.NET function used to take backup of sql server database.


'Reference added

Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common


'Declare the backup object

Dim WithEvents oBackup As New Backup


'Method to take backup


Private Sub BackupSqlDatabase()


'set SQL server connection given the server name, user name and password

Dim conn As New ServerConnection(serverName, userName, passWd)

'create the SMO server object using connection

Dim oSQLServer As New Server(conn)

'set the path where backup file will be stored

Dim OrigBackupPath As String = oSQLServer.Information.MasterDBPath.Replace("\DATA", "\Backup\DB_BACKUP_NAME.BAK")


'create SMO.Backupdevice object

Dim bkDevItem As New BackupDeviceItem(OrigBackupPath, DeviceType.File)

' Set the backup object property

With oBackup
.Action = BackupActionType.Database
.Database = YOUR_DATABASE_NAME
.Devices.Add(bkDevItem)
.Initialize = True
.Checksum = True
.ContinueAfterError = True
.Incremental = False
.LogTruncation = BackupTruncateLogType.Truncate

'backup SQL database

.SqlBackup(oSQLServer)
End With

End Sub


Your comment will be appreciated.

What is SharePoint?

Microsoft SharePoint is a web application that enables users within an organization to work together, collaborate, more efficiently through its vast number of features.

Although collaboration is at the heart of SharePoint, it includes many other important core features to help in the following business needs:
• Document Management
• Web Content Management
• Business Process Management (Workflows)
• Enterprise Search
• Business Intelligence (Dashboards, Reports)
• Electronic Forms (InfoPath)
• Social Networking
And that’s just out-of-the-box features. Not only can all these features be customized to fit any organization but SharePoint can also serve as a platform to build solutions (custom applications) for any type of organization or need.
Step 1:
Start--> Programs-- >Microsoft Visual Studio 2008-- > Microsoft Visual Studio 2008.
Step 2:
File-- >New Project-- >Web-- >WCF Service Application-- >Name the Solution (e.g. MyFirstWCFApplication) and Save.

It will generate following Files structures.


Step 3:
Click on Default file named (IService1.vb). It creates default
1.

' NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.

_
Public Interface IService1

_
Function GetData(ByVal value As Integer) As String

_
Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType

' TODO: Add your service operations here
End Interface
2.
' Use a data contract as illustrated in the sample below to add composite types to service operations.
_
Public Class CompositeType

Private boolValueField As Boolean
Private stringValueField As String

_
Public Property BoolValue() As Boolean
Get
Return Me.boolValueField
End Get
Set(ByVal value As Boolean)
Me.boolValueField = value
End Set
End Property

_
Public Property StringValue() As String
Get
Return Me.stringValueField
End Get
Set(ByVal value As String)
Me.stringValueField = value
End Set
End Property
End Class


Note:
1. In _ there is one Interface named IService1. This may be changed.
2. Each _ having Interface may have multiple Funtions preceded with _.
3. Add the Functions like to invoke or Expose.
3. All defined or renamed Interfaces references must be updated in Web.config file.





























4. In _ there is one CompositeType class. Inside _ there are many _ which is nothing but the Property of the class used to expose to the outer world. Each Property must precedded with _ else it will not be exposed.








Step 4:
Now Click on Service1.svc.vb a class file that Implement s the defined Contracts. Define the function defined by Interface and save this file.
Step 5:
Build the application.
After Building the application this Application can be used by Client Applications in different ways.
1. By Adding Service reference Locally
2. By Hosting it on IIS

Features of WCF

WCF includes the following set of features.

· Service Orientation

One consequence of using WS standards is that WCF enables you to create service oriented applications. Service-oriented architecture (SOA) is the reliance on Web services to send and receive data. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met.

· Interoperability

 WCF implements modern industry standards for Web service interoperability.

· Multiple Message Patterns

Messages are exchanged in one of several patterns. The most common pattern is the request/reply pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. There are other patterns such as a one-way message in which a single endpoint sends a message without any expectation of a reply. A more complex pattern is the duplex exchange pattern where two endpoints establish a connection and send data back and forth, similar to an instant messaging program.


· Service Metadata

WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically generate and configure clients for accessing WCF services. Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard.


· Data Contracts

Because WCF is built using the .NET Framework; it also includes code-friendly methods of supplying the contracts you want to enforce. One of the universal types of contracts is the data contract. In essence, as you code your service using Visual C# or Visual Basic, the easiest way to handle data is by creating classes that represent a data entity with properties that belong to the data entity. WCF includes a comprehensive system for working with data in this easy manner. Once you have created the classes that represent data, your service automatically generates the metadata that allows clients to comply with the data types you have designed.


· Security

Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-Secure Conversation.


· Multiple Transports and Encodings

Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the Hypertext Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM standard. If none of the provided transports or encodings suit your needs you can create your own custom transport or encoding.


· Reliable and Queued Messages

WCF supports reliable message exchange using reliable sessions implemented over WS-Reliable Messaging and using MSMQ.


· Durable Messages

A durable message is one that is never lost due to a disruption in the communication. The messages in a durable message pattern are always saved to a database. If a disruption occurs, the database allows you to resume the message exchange when the connection is restored. You can also create a durable message using the Windows Workflow Foundation (WF).


· Transactions

WCF also supports transactions using one of three transaction models: WS-AtomicTtransactions, the APIs in the System. Transactions namespace, and Microsoft Distributed Transaction Coordinator.

· AJAX and REST Support

REST is an example of an evolving Web 2.0 technology. WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON).


· Extensibility

The WCF architecture has a number of extensibility points. If extra capability is required, there are a number of entry points that allow you to customize the behavior of a service.

Windows Communication Foundation Definition

Windows Communication Foundation

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data. A few sample scenarios include:
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

WCF is designed to offer a manageable approach to creating Web services and Web service clients.

Windows Communication Foundation features

generate verification code character string as exported image

To generate verification code character string as exported image we have to create two simple function:

1. public string CreateRandomCode(int codeCount)

This function is used to genearare random number with codeCount digit
and return string.

2. private void CreateImage(string checkCode)

This function is used to generate image by passing Random code generated by function CreateRandomCode(int codeCount).


1. Here's the CreateRandomCode function code

Function Using C#

public string CreateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;

Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{ if (temp != -1)
{ rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(36);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
} temp = t; randomCode += allCharArray[t];
} return randomCode;
}



Function Using VB.NET

Public Function CreateRandomCode(ByVal codeCount As Integer) As String
Dim allChar As String = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
Dim allCharArray As String() = allChar.Split(","c)
Dim randomCode As String = ""
Dim temp As Integer = -1

Dim rand As New Random()
For i As Integer = 0 To codeCount - 1
If temp <> -1 Then
rand = New Random(i * temp)
End If
Dim t As Integer = rand.[Next](36)
If temp <> -1 AndAlso temp = t Then
Return CreateRandomCode(codeCount)
End If
temp = t
randomCode += allCharArray(t)
Next
Return randomCode
End Function


2. 1. Here's the CreateImage function code

Function Using C#

private void CreateImage(string checkCode)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
Graphics g = Graphics.FromImage(image);

try
{
Random random = new Random();
g.Clear(Color.AliceBlue);

for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width); int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}

Font font = new System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);

for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}

g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray());

}

finally
{
g.Dispose();
image.Dispose();
}

}


Function Using VB.NET

Public Sub CreateImage(ByVal checkCode As String)
Dim image As System.Drawing.Bitmap = New System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(checkCode.Length * 14))), 22)

Dim g As Graphics = Graphics.FromImage(Image)
'test
Try
Dim random As Random = New Random()
g.Clear(Color.AliceBlue)
Dim i As Integer = 0

'While i < 25

Dim x1, x2, y1, y2 As Integer
x1 = random.Next(image.Width)
x2 = random.Next(image.Width)
y1 = random.Next(image.Height)
y2 = random.Next(image.Height) g.DrawLine(New Pen(Color.Silver), x1, y1, x2, y2)

'End While

Dim font As Font = New System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold) Dim brush As System.Drawing.Drawing2D.LinearGradientBrush = New System.Drawing.Drawing2D.LinearGradientBrush(New Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, True)

g.DrawString(checkCode, font, New SolidBrush(Color.Red), 2, 2)

For i = 0 To 100
Dim x As Integer = random.Next(image.Width)

Dim y As Integer = random.Next(image.Height) image.SetPixel(x, y, Color.FromArgb(random.Next())) Next g.DrawRectangle(New Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1)

'Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream() 'image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif) image.Save(Server.MapPath("~/KoneServices/k1images/RandomWord.gif"), System.Drawing.Imaging.ImageFormat.Gif) Me.ImgVerify.Src = Server.MapPath("~/KoneServices/k1images/RandomWord.gif")

'Response.ClearContent() 'Response.ContentType = "image/Gif"
'Response.BinaryWrite(ms.ToArray())

Catch ex As Exception

'ex code

Finally

g.Dispose()
image.Dispose()

End Try End Sub

Now just call these functions on your desired event. I have used Page_Load event here.

Using C#

protected void Page_Load(object sender, EventArgs e)
{
string checkCode = this.CreateRandomCode(6);
Session["CheckCode"] = checkCode;
CreateImage(checkCode);
}



Using VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim checkCode As String = Me.CreateRandomCode(6)
Session("CheckCode") = checkCode
CreateImage(checkCode)

End Sub

Just run the page you can find the generated image as shown below with different generated code.



If you feel this article usefull please put a comment.

Tuesday, August 2, 2011

Create custom popup window

Here's the easiest way to create popup window using javascript function. before you use this code i assume that you have already created html page and you are better aware of <head></head> tag.


Copy this code in the <head></head> section of you html page.

<head runat="server">
  <title>Custom LightBox example</title>
  <script type="text/javascript">
  function showBox()
  {
    var width = document.documentElement.clientWidth + document.documentElement.scrollLeft;
    var layer = document.createElement('div');
    layer.style.zIndex = 2;
    layer.id = 'layer';
    layer.style.position = 'absolute';
    layer.style.top = '0px';
    layer.style.left = '0px';
    layer.style.height = document.documentElement.scrollHeight + 'px';
    layer.style.width = width + 'px';
    layer.style.backgroundColor = 'black';
    layer.style.opacity = '.6';
    layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
    document.body.appendChild(layer);
  
    var div = document.createElement('div');
    div.style.zIndex = 3;
    div.id = 'box';
    div.style.position ='absolute';
    div.style.top = '200px';
    div.style.left = (width / 2) - (400 / 2) + 'px';
    div.style.height = '100px';
    div.style.width = '400px';
    div.style.backgroundColor = 'white';
    div.style.border = '2px solid silver';
    div.style.padding = '20px';
    document.body.appendChild(div);
  
    var p = document.createElement('p');
    p.innerHTML = '<b>This is my first custom dialog box</b><br/>';
    div.appendChild(p);
  
    var a = document.createElement('a');
    a.innerHTML = 'Close window';
    a.href = 'javascript:void(0)';
    a.onclick = function()
    {
      document.body.removeChild(document.getElementById('layer'));
      document.body.removeChild(document.getElementById('box'));
    };
    
    div.appendChild(a);
  }
  </script>  
</head>

Now paste the below code in <body></body> section.

<body>

  <a href="javascript:void(showBox())">Toggle box</a>
    
</body>


You are done, run the page and click on Toggle box link
You will see the below screen.


Note you can customise the popup by changing the div style:

 div.style.zIndex = 3;
div.id = 'box';
div.style.position ='fixed';
div.style.top = '300px';
div.style.left = (width / 2) - (100 / 2) + 'px';
div.style.height = '300px';
div.style.width = '400px';
div.style.backgroundColor = 'yellow';
div.style.border = '2px solid red';
div.style.padding = '20px';

Hope you found this article useful.