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.