Saturday, September 17, 2011

VB.NET code to check USB drive Plugin


Imports System.Management


Public Class Form2

Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
Public USBDriveName As String
Public USBDriveLetter As String

Private Sub Form2_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

m_MediaConnectWatcher.Stop()
m_MediaConnectWatcher.Dispose()

End Sub


Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

StartDetection()

End Sub


Public Sub StartDetection()

Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")

m_MediaConnectWatcher = New ManagementEventWatcher
m_MediaConnectWatcher.Query = query2
m_MediaConnectWatcher.Start()


End Sub



Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived

Dim mbo As ManagementBaseObject
Dim obj As ManagementBaseObject

mbo = CType(e.NewEvent, ManagementBaseObject)
obj = CType(mbo("TargetInstance"), ManagementBaseObject)

Select Case mbo.ClassPath.ClassName
Case "__InstanceCreationEvent"
If obj.Item("InterfaceType").ToString = "USB" Then
USBDriveName = obj.Item("Caption").ToString
USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString)
MessageBox.Show(USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
End If
Case "__InstanceDeletionEvent"
If obj.Item("InterfaceType").ToString = "USB" Then
MessageBox.Show(USBDriveName & " was disconnected. " & USBDriveLetter & " is now inaccessible.") 'GetDriveLetterFromDisk(obj.Item("Name").ToString))
If obj.Item("Caption").ToString = USBDriveName Then
USBDriveLetter = ""
USBDriveName = ""
End If
End If
Case Else
MessageBox.Show("nope: " & obj.Item("Caption").ToString)
End Select

End Sub



Private Function GetDriveLetterFromDisk(ByVal Name As String) As String

Dim oq_part, oq_disk As ObjectQuery
Dim mos_part, mos_disk As ManagementObjectSearcher
Dim obj_part, obj_disk As ManagementObject
Dim ans As String = ""

Name = Replace(Name, "\", "\\")

oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
mos_part = New ManagementObjectSearcher(oq_part)
For Each obj_part In mos_part.Get()

oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
mos_disk = New ManagementObjectSearcher(oq_disk)
For Each obj_disk In mos_disk.Get()
ans &= obj_disk.Item("Name").ToString & ","
Next
Next

Return ans.Trim(","c)


End Function


End Class

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.

Saturday, July 30, 2011

Your current security settings put your computer at risk

This article explains how to disable IE9 security notification with easy registry edit. You might have noticed whenever we enable activeX control in IE9 from security settings as shown below picture the IE9 starts promting the security notification message every time we open IE.

Pict1. Image showing the security setting screen


IE9 default Security notification :

Pict2. Image of IE9 notification mesage

Easy Step to resolve:

1. Click on start-->Run.
2. Type  regedit
3. it launches the Registry Editor dialog box
4. Inside Computer node, Select HKEY_LOCAL_MACHINE-->SOFTWARE-->Microsoft-->Internet Explorer-->MAIN-->FeatureControl-->FEATURE_SECURITYBAND.
5. Right click on right side panel.
6. Clcik New-->DWORD(32 bit ) value.
7 Rename as iexplore.exe and giv value as 00000000
8.Be sure after all these step the registry value is the same as shown below, if you are seeing same screen, Then you are done. just close the Registry Editor dialog box and open Internet Explorer. You will not find the Notification message again. if you found this article useful your comment will be appreciated.

Wednesday, July 27, 2011

Credit Card Validation

function validateCreditCard(s) {
function cardval(s) {
// remove non-numerics
var v = "0123456789";
var w = "";
for (i=0; i < s.length; i++) { x = s.charAt(i); if (v.indexOf(x,0) != -1) w += x; } // validate number j = w.length / 2; if (j < 6.5 || j > 8 || j == 7) return false;
k = Math.floor(j);
m = Math.ceil(j) - k;
c = 0;
for (i=0; i 9 ? Math.floor(a/10 + a%10) : a;
}
for (i=0; i return (c%10 == 0);
}

Date Validation

function checkDate() {

var myDayStr = document.CheckDate.formDate.value;
var myMonthStr = document.CheckDate.formMonth.value;
var myYearStr = document.CheckDate.formYear.value;
var myMonth = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); var myDateStr = myDayStr + ' ' + myMonth[myMonthStr] + ' ' + myYearStr;

/* Using form values, create a new date object
using the setFullYear function */
var myDate = new Date();
myDate.setFullYear( myYearStr, myMonthStr, myDayStr );

if ( myDate.getMonth() != myMonthStr ) {
alert( 'I\'m sorry, but "' + myDateStr + '" is NOT a valid date.' );
} else {
alert( 'Congratulations! "' + myDateStr + '" IS a valid date.' );
}

}



Back to JavaScript Tutorial Page Back to JavaScript Validations Page

Function to validate Email Address

function Emailchk(email)
{

var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(email) == false)
{

return false;
}
else
{
return true;
}

}



Back to JavaScript Tutorial Page Back to JavaScript Validations Page

Allow only Character in Field

function Char()
{
 w=window.event.keyCode
 if (w>96 & w<123 | w>64 & w<91 | w==8 | w==32)
 {
  return
 }
 else
 {
  window.event.keyCode=null
 }
}



Back to JavaScript Tutorial Page Back to JavaScript Validations Page

Numeric Validation

function IsNumeric(strString)
// check for valid numeric strings
{
var strValidChars = "0123456789.-";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}

}
return blnResult;

}



Back to JavaScript Tutorial Page Back to JavaScript Validations Page

Function to restrict Right Click and Refresh(F5)

function notAllowed()
{
 if(event.ctrlKey)
 {
  alert("This Operation Is Not Allowed");
  event.keyCode=0; 
  return false;
 }
 if ((event.altKey))
 {
  alert("This Operation Is Not Allowed");
  event.keyCode=0; 
  return false;
 }
 if (event.keyCode==112)
 {
  //alert("This Alt Operation Is Not Allowed");
  event.keyCode=0; 
  return false;
 }
 if(event.keyCode==114 )
 {
  alert("This Operation Is Not Allowed");
  event.keyCode=0; 
  return false;
 }
 if(parseInt(event.button)==2)
 {
  alert("This Operation Is Not Allowed"); 
  return false;    
 }
 if((event.keyCode==116)||(event.keyCode==122)||(event.keyCode==18)||(event.keyCode==93)||(event.keyCode==16))
 {
  alert("This Operation Is Not Allowed");
  event.keyCode=0; 
  return false;
 }


 return true;
 }




Back to JavaScript Tutorial Page Back to JavaScript Validations Page

Tuesday, July 26, 2011

JavaScript validations




Back to JavaScript Tutorial Page

JavaScript Features


1. Browser support
To access flash content, you need to install flash plugin in your browser. But to use javascript, you don't have to use any plugin at all. This is because all browsers have accepted javascript as a scripting language for them and provides integrated support for it. All you need to do is to handle some of the tasks that are dependent on DOM (Document Object Model) of different browsers properly.

2. Can be used on client side as well as on server side
As javascript has access to Document object model of browser, you can actually change the structure of web pages at runtime. Due to this, javascript can be used to add different effects to webpages. On the other hand, javascript could be used on the server side as well. For example, in Alfresco which is a popular open source enterprise content management system, javascript is used in creating webscripts. This makes adding custom tasks to alfresco quite simple.

3. Functional programming language
In javascript, function could be assigned to variables just like any other data types. Not only that, but a function can accept another function as a parameter and can also return a function. You can have functions with no name as well. Clearly, this gives you the ability to code in functional programming style.

4. Support for objects
Javascript is an object oriented language. However, the way javascript handles objects and inheritance is bit different from conventional object oriented programming languages like Java. Due to this, javascript supports most of the object oriented concepts while being simple to learn and use.


Back to JavaScript Tutorial Page

JavaScript Tutorial

JavaScript is the Scripting language used to add functionality,Validtae forms,Communicate with the server and much more. JavaScript is an implementation of the ECMAScript language standard, primarily used in the form of client-side Script, implemented as part of a web browser in order to provide enhanced user interfaces and dynamic websites.

ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web.

JavaScript was originally developed by Brendan Eich of Netscape in 1995 under the name Mocha,later LiveScript, and finally renamed to JavaScript.

Javascript key code numbers and the ACSII numbers that represent the character.


09  =
Tab
11  =
Home
13  =
Enter
32  =
Space Bar
33  =   !
34  =   "
35  =   #
36  =   $
37  =   %
38  =   &
39  =   '
40  =   (
41  =   )
42  =   *
43  =   +
44  =   ,
45  =   -
46  =   .
47  =   /
48  =   0
49  =   1
50  =   2
51  =   3
52  =   4
53  =   5
54  =   6
55  =   7
56  =   8
57  =   9
58  =   :
59  =   ;
60  =   <
61  =   =
62  =   >
63  =   ?
64  =   @
65  =   A
66  =   B
67  =   C
68  =   D
69  =   E
70  =   F
71  =   G
72  =   H
73  =   I
74  =   J
75  =   K
76  =   L
77  =   M
78  =   N
79  =   O
80  =   P
81  =   Q
82  =   R
83  =   S
84  =   T
85  =   U
86  =   V
87  =   W
88  =   X
89  =   Y
90  =   Z
91  =   [
92  =  
93  =   ]
94  =   ^
95  =   -
96  =   `
97  =   a
98  =   b
99  =   c
100  =   d
101  =   e
102  =   f
103  =   g
104  =   h
105  =   i
106  =   j
107  =   k
108  =   l
109  =   m
110  =   n
111  =   o
112  =   p
113  =   q
114  =   r
115  =   s
116  =   t
117  =   u
118  =   v
119  =   w
120  =   x
121  =   y
122  =   z
123  =   {
124  =   |
125  =   }
126  =   ~

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions


Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers.

·         What is IL code, CLR,CTS,GAC,GC?>

·         How can we do Assembly versioning?

·         can you explain how ASP.NET application life cycle and page life cycle events fire?

·         What is the problem with Functional Programming?

·         Can you define OOP and the 4 principles of OOP?

·         What are Classes and Objects?

·         What is Inheritance?

·         What is Polymorphism, overloading, overriding and virtual?

·         Can you explain encapsulation and abstraction?

·         What is an abstract class?

·         Define Interface & What is the diff. between abstract & interface?

·         What problem does Delegate Solve ?

·         What is a Multicast delegate ?

·         What are events and what's the difference between delegates and events?

·         How can we make Asynchronous method calls using delegates ?

·         What is a stack, Heap, Value types and Reference types ?

·         What is boxing and unboxing ?

·         Can you explain ASP.NET application and Page life cycle ?

·         What is Authentication, Authorization, Principal & Identity objects?

·         How can we do Inproc and outProc session management ?

·         How can we windows , forms and passport authentication and authorization in ASP.NET ?

·         In a parent child relationship which constructor fires first ?



Complete .NET invoicing project end to end

·         Introduction to .NET Projects

·         Different levels of Programming

·         Necessary Tools

·         What should we learn ?

·         The IIS

·         Making UI using .net IDE

·         Database, The SQL Server

·         Connecting ASP.net with Database

·         Loading the Data Grid

·         Update and Delete

·         Validations

·         Issue with the Code

·         Two Tier Architecture

·         Three Tier Architecture

·         Database Normalization

·         Session and State Management

·         Using Enterprise Application Block

·         Aggregation and Composition

·         Implementing Interfaces and Factory

·         Inheritance relationship

·         Abstract Class Implementation

.NET best practices and SQL Server Training / Interview Questions and Answers

·         Basics :- Query plan, Logical operators and Logical reads

·         Point 1 :- Unique keys improve table scan performance.

·         Point 2 :- Choose Table scan for small & Seek scan for large records

·         Point 3 :- Use Covering index to reduce RID (Row Identifier) lookup

·         Point4:- Keep index size as small as possible.

·         Point5:- use numeric as compared to text data type.

·         Point6:- use indexed view for aggregated SQL Queries

·         Finding high memory consuming functions

·         Improve garbage collector performance using finalize/dispose pattern

·         How to use performance counters to gather performance data

WCF,WPF,Silverlight ,LINQ, Azure and EF 4.0 interview question and answers

·         What is SOA, Services and Messages ?

·         What is the difference between Service and Component?

·         What are basic steps to create a WCF service ?

·         What are endpoints, address, contracts and bindings?

·         What are various ways of hosting WCF service?

·         What is the difference of hosting a WCF service on IIS and Self hosting?

·         What is the difference between BasicHttpBinding and WsHttpBinding?

·         How can we do debugging and tracing in WCF?

·         Can you explain transactions in WCF (theory)?

·         How can we self host WCF service ?

·         What are the different ways of implementing WCF Security?

·         How can we implement SSL security on WCF(Transport Security)?

·         How can we implement transport security plus message security in WCF ?

·         How can we do WCF instancing ?

·         How Can we do WCF Concurency and throttling?

·         Can you explain the architecture of Silverlight ?

·         What are the basic things needed to make a silverlight application ?

·         How can we do transformations in SilverLight ?

·         Can you explain animation fundamentals in SilverLight?

·         What are the different layout methodologies in SilverLight?

·         Can you explain one way , two way and one time bindings?

·         How can we consume WCF service in SilverLight?

·         How can we connect databases using SilverLight?

·         What is LINQ and can you explain same with example?

·         Can you explain a simple example of LINQ to SQL?

·         How can we define relationships using LINQ to SQL?

·         How can we optimize LINQ relationships queries using ‘DataLoadOptions’?

·         Can we see a simple example of how we can do CRUD using LINQ to SQL?

·         How can we call a stored procedure using LINQ?

·         What is the need of WPF when we had GDI, GDI+ and DirectX?

·         Can you explain how we can make a simple WPF application?

·         Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?

·         Can you explain the Architecture of WPF?

·         What is Azure?

·         Can you explain Azure Costing?

·         Can we see a simple Azure sample program?

·         What are the different steps to create a simple Worker application?

·         Can we understand Blobs in steps, Tables & Queues ?

·         Can we see a simple example for Azure tables?

·         What is Package and One click deploy(Deployment Part - 1) ?

·         What is Web.config transformation (Deployment Part-2)?

·         What is MEF and how can we implement the same?

·         How is MEF different from DIIOC?

·         Can you show us a simple implementation of MEF in Silverlight ?

Design pattern, Estimation, VSTS, Project management interview questions and answers

Design Pattern Training / Interview Questions and Answers

·         Introduction

·         Factory Design Pattern

·         Abstract Factory Design Pattern

·         Builder Design Pattern

·         Prototype Design Pattern

·         Singleton Design Pattern

·         Adapter Design Pattern

·         Bridge Design Pattern

·         Composite Design Pattern

·         Decorator Design Pattern

·         Facade Design Pattern

·         Flyweight Design Pattern

·         Proxy Design Pattern

·         Mediator Design Pattern

·         Memento Design Pattern

·         Interpreter Design Pattern

·         Iterator Design Pattern

·         COR Design Pattern

·         Command Design Pattren

·         State Design Pattern

·         Strategy Design Pattern

·         Observer Design Pattern

·         Template Design Pattern

·         Visitor Design Pattern

·         Dependency IOC Design pattern

·         MVC , MVP , DI IOC and MVVM Training / Interview Questions and Answers



UML Training / Interview Questions and Answers

·         Introduction

·         Use Case Diagrams

·         Class Digrams

·         Object Diagrams

·         Sequence Digrams

·         Collaboration Diagrams

·         Activity Diagram

·         State chart Diagrams

·         Component Diagrams

·         Deployment Diagrams

·         Stereo Types Diagrams

·         Package Diagram and UML Project Flow.

Function points Training / Interview Questions and Answers

·         Introduction

·         Application Boundary

·         EI Fundamentals

·         EO Fundamentals

·         EQ Fundamentals

·         EIF

·         Fundamentals

·         ILF Fundamentals

·         GSC Fundamentals

·         Productivity Factor

·         Costing and a complete estimation of customer screen using function points.

·         FXCOP and Stylecop Training / Interview Questions and Answers



VSTS Training / Interview Questions and Answers

·         VSTS questions and answer videos

·         What is Unit Testing & can we see an example of the same?

·         How can we write data driven test using NUNIT & VS Test?

·         Can we see simple example of a unit test for database operation?

·         How can we do automated testing using Visual Studio Test?

·         How can we do Load Testing using VSTS test?

·         Can you explain database unit testing?

·         How can we do test coverage using VSTS system?

·         How can we do manual Testing using VSTS?

·         What is Ordered Test in VSTS test?




Enterprise Application Blocks Training

·         Introduction

·         Validation Application Block

·         Logging Application Block

·         Exception error Handling

·         Data Application Block

·         Caching Application Block

·         Security Application Block

·         Policy Injection Application Block and

·         Unity Application Block

Share point interview Training / Interview Questions and Answers videos

·         What is SharePoint, WSS and MOSS?

·         How does WSS actually work?

·         What is Site and SiteCollection?

·         What is the use of SQL server in SharePoint & use of Virtual path provider?

·         What is Ghosting and UnGhosting in SharePoint?

·         How can we create a site in SharePoint?

·         How can we Customize a SharePoint Site?

·         What kind of readymade functional modules exists collaboration?

·         Can you display a simple Custom Page in SharePoint?

·         How can we implement behind code ASPX pages in SharePoint?

·         What is the concept of features in SharePoint?

·         I want a feature to be only displayed to admin?

·         How do we debug SharePoint error’s?

·         Why customized pages are parsed using no-compile mode?

·         Can you explain WSS model?

·         How can we use custom controls in SharePoint?

·         How can we display ASCX control in SharePoint pages?

·         What are Web Parts?

·         How can we deploy a simple Webpart in SharePoint?

·         How can we achieve customization and personalization using WebParts?

·         How can we create custom editor for WebPart?

·         SharePoint is about centralizing documents, how similar is to the windows folder?

·         What are custom fields and content types?

·         Can you explain SharePoint Workflows?

·         What is a three-state Workflow in SharePoint?

·         How can we create sharepoint workflow using sharepoint designer?