LINQ tutorial Part -VI

Validation in Linq (Business Logic) :-

As a programmer my first intention is to make a bug free code for that one of the part is data validation.What ever we want to insert /Update in database need to check.

For this we use data validation. With linq we can refine data in mainly two way. The first and basic way in which we do not have to do so much is Schema.

What ever OR mapping is done. The schema handle the database type which require to save in database. By this a user can not insert invalid datatype in DataBase.

Second and another important aspect is using validation rules or custom validation. This can be handle in two way

1) custom property validation support.

This can be understand by below example suppose I want to insert email address in database with proper email format. But if there is no validation for format check then user can insert and data in email field for this purpose we require cutome property validation.

As the class genrated with LINQ to sql is partial class so we can use it any where we want with just partial class use.

Imports system

Imports system.text.RegularExpression

Partial Class Customer

Private Sub OnstrEmailChanging(ByVal value As String)

Dim regMailEx As New System.Text.RegularExpressions.Regex(“^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$”)

Dim matchExp As System.Text.RegularExpressions.Match

matchExp = regMailEx.Match(value)

If matchExp.Success =false Then

Throw new applicationException (“e-mail is not valid!”)

end if

End Sub

End class

In the above way we can validate a entry. Main benefit of this we do not have to write on each page and call validation. Its works automatically when user changed the Email.

Another is custom entry object validation.

In this suppose you want to compare two or more than two different object or some other logic then we can use this it can be handle is partial class with onValidate method.

As shown below.

Private Sub OnValidate(ByVal action As System.Data.Linq.ChangeAction)If action = Data.Linq.ChangeAction.Insert OrElse action = Data.Linq.ChangeAction.Update Then

if Me.blnActive = true AndAlso Me.datActiveDate is nothing then

Throw New applicationException (“Activation date is required!”)

End if

End If

End Sub

in this way we can use validation.

So enjoy coding.

Thanks

Rajat

Advertisements

Serialization & De-serialization try it

Serialization :-

Serialization in .NET allows us to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system.

This object will actually be an instance of a custom type, including any properties or fields you may have set.

Serialization is the process of converting an object into a stream of bytes which is easily transferable over the network and storing its current state on any permanent storage media like file or database for later use.

De- Serialization:-

De-serialization is the reverse process of Serialization, where the stored object is taken and the original object is recreated.

.NET provides classes through its System.Runtime.Serialization namespaces that can be used for serializing and de-serializing objects.

Serialization can be divided into following types:

· Binary Serialization: Binary serialization allows the serialization of an object into a binary stream and restoration from a binary stream into an object.

· XML Serialization: XML serialization allows the public properties and fields of an object to be reduced to an XML document that describes the publicly visible state of the object.

· SOAP Serialization: SOAP serialization is similar to XML serialization in that the objects being serialized are persisted as XML.

Below is example how to make a serialize class

And how to serialize and deserialize class.

<Serializable()> _

Private Class pvt_clsTest

Public strName As String = String.Empty

End Class

 

Private Sub pvt_SearializeMe()

Try

Dim cls As New pvt_clsTest

cls.strName = Me.txtNeedToSerialize.Text

Dim mem As New MemoryStream()

Dim binaryFormat As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()

binaryFormat.Serialize(mem, cls)

Session(“arr”) = mem.GetBuffer

Me.txtSerialize.Text = mem.ToString

mem.Close()

Catch ex As Exception

Throw ex

End Try

End Sub

Private Sub pvt_DeserializeMe(ByVal arr As Byte())

Dim ascEn As New ASCIIEncoding

Dim mem As New MemoryStream(arr)

mem.Position = 0

Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()

Dim cls As pvt_clsTest = CType(bf.Deserialize(mem), pvt_clsTest)

Me.txtDeserialize.Text = cls.strName

mem.Close()

End Sub

Thanks & enjoy coding

LINQ tutorial Part -V

store procedures output variable & Functions work with LINQ:-

 

Hello Friends,

Today we will discuss how to handle the function and procedure that have output variable or the procedure that having scalar value.

For that just create a dbml file same as we talked in our privious discussion. On the Method panel just drop all the function and procedures.

Let start with a function

Suppose we have a function in sql which gives us out put in Upper case which is as below.

 

 if exists (select * from dbo.sysobjects so where id = object_id(N‘[dbo].[fn_MakeUpper]’) and so.xtype = ‘FN’)

drop function [dbo].[fn_MakeUpper]
GO 

CREATE FUNCTION fn_MakeUpper(@strInput AS VARCHAR(50))
RETURNS VARCHAR(50)
AS

BEGIN

RETURN(UPPER(@strInput))

END

GO

SET

QUOTED_IDENTIFIER OFF

GO

 

SET ANSI_NULLS ON
GO

 

Now drop this function on Method Panel of dbml. This function can we be use as below

Dim db as new MyDataBaseContext()

Dim lnq = from c in db.customers SELECT new with {.name= db.fn_MakeUpper(c.strFirstName)}

In the above manner we can use function.

Now we are taking example of output parameter parameter with store procedures suppose we have a output parameter in store procedure that will return total no of rows then.

We do that in following manner.

CREATE PROCEDURE 
@intTotalRecord AS int OUTPUT

Proc_tblProductReadWithCount

ASSELECT

 

lngId,

strCode,

strProductName,

lngProductPackingTypeId,

lngProductTypeId,

lngProductManufacturerId,

strRemark,

blnActive

FROM

tblProduct 

 

SELECT @intTotalRecord= COUNT(*) FROM tblProductGo 

1. drop the store procedure in method panel of database context dbml.

Now you will get method proc_tblProductReadWithCount(byref intTotalRecord As integer?)

To use this you have to declare a nullable integer first which is as follows.

Dim intA as integer ?

The “?” mark represet here that the variable can be nullable.

Dim

db As New BillMasterDataContext

Dim intA As Integer?
Dim lnq = From c In db.Proc_tblProductReadWithCount(intA) Select
cMe.lblText.Text = intA.Tostring()

In this way we can use output variable.

I hope you understand what I want to say

I will upload bunch of code related to article on

 

http://www.indiandotnet.tk in forth coming weeks.

Once again Thanks from

 your host

Rajat Jaiswal

Keep coding and share Knowledge

LINQ tutorial Part -IV

. Linq To XML (Add ,edit ,delete ): –

 

One of the intresting topic is xml. As a programmer I am not using XML in my daily use but I like XML.

Today I just wondering to take a suitable example which will do add,edit & delete with LINQ. So first we have to Create a xml file for that lets we created a xml file with following format.

<?xml version=1.0 encoding=utf-8?>
<Trainings>
<Training>
<Id>2</Id>
<Person>RAJAT JAISWAL</Person>
<FrameWork>2</FrameWork>
<ASPNET>2</ASPNET>
<Communication>4</Communication>
<HTML>5</HTML>
<LogicBuilding>4</LogicBuilding>
<SqlServer>5</SqlServer>
<Remark>testing</Remark>
</Training>
</Trainings>
Now if we want to add new record in this xml file then our first moto is to read the xml using linq . For this we first use a import statement

Imports System.Xml.Linq by this we are able to use Linq over xml.

Now for reading we just do same as we do for database read (linq to sql ) but before that we have to create the object of xdocument from where the data will be fatch. As shown below

Dim TrainXDoc As XDocument = XDocument.Load(Server.MapPath(“MyTraining.xml”))

What this statement does it create same object like dataContext in sql.

And below is linq over this document and the Descendants(“Training”) like table or other object like storeprocedure in dbContext.

Dim lnqTraining = From myTraining In TrainXDoc.Descendants(“Training”) _

Select New With {.Id = myTraining.Element(“Id”).Value, _

.Person = myTraining.Element(“Person”).Value, _

.FrameWork = myTraining.Element(“FrameWork”).Value, _

.ASPNET = myTraining.Element(“ASPNET”).Value, _

.SqlServer = myTraining.Element(“SqlServer”).Value, _

.LogicBuilding = myTraining.Element(“LogicBuilding”).Value, _

.HTML = myTraining.Element(“HTML”).Value, _

.Communication = myTraining.Element(“Communication”).Value, _

.Remark = myTraining.Element(“Remark”).Value}

In the above elements like a row in datatable and we access there column using the tag name like Id, Person,Framework.

Now our second moto is to Add & Update the Add a new record can be done as follows

TrainXDoc .Element(“Trainings”).Add(New XElement(“Training”, New XElement(“Id”, lngId), New XElement(“Person”, Me.txtName.Text.Trim), _

New XElement(“FrameWork”, ddlFramWork.SelectedValue), New XElement(“ASPNET”, ddlAspNet.SelectedValue), _

New XElement(“Communication”, ddlCommunication.SelectedValue), New XElement(“HTML”, Me.ddlHtml.SelectedValue), _

New XElement(“LogicBuilding”, Me.ddlLogicBuilding.SelectedValue), New XElement(“SqlServer”, Me.ddlSqlServer.SelectedValue), _

New XElement(“Remark”, Me.txtRemark.Text.Trim)))

Here it added new record in traindoc’s trainings element which was root element.

After this we use MyTrainXDoc.Save(Server.MapPath(“MyTraining.xml”)) which save in the file.

For update we just find the node using the linq which we want to update then made changes in the particular node elements. And call save method as above.

For delete just find the element from linq then remove like xRoot.Remove() then save the xdoc.

For more detail just download the code from

 

http://www.indiandotnet.tk/

Thanks & Regards

Rajat Jaiswal

LINQ tutorial Part -III

Save,Update, delete & read by Store procedures In Linq
 
 Dear Friends,
Yesterday we take example of how to use linq for insert ,update & delete. But as a programmer you have question like how to handle store procedures for insert update & Delete.
So here I am with this topic.
Today we will look how to update a table data using same linq but with store procedures.
When you see yesterday example’s mydb.dbml file.

You find that there is two panel(if you are not able to see then right click on orm designer screen and select show method panel).

One where you drag table and the another which is blank so here we use that another panel.

That panel is called method panel you can drop store procedures and function over there as shown in below fig- 1

 

 

 

 

LinqWithStoreProcedures1

 

 

 

After getting procedures & function on method panel you have to do just a simple task.

Just assign the insert ,update & delete method to related table using the custom property and map the fields of store procedure.

For that just check the property of table as shown in fig -2

LinqWithStoreProcedure2

Then click on either insert ,update or delete you will get following screen. Fig-3

LinqWithStoreProcedure3

Just map according to your spname.
And rest the code will be same as we did earlier yesterday. So enjoy coding.
Thanks
Rajat
 

 

 

 

 

LINQ tutorial Part -II

4. Save , Update, Delete by LINQ :-  (Attached document :- linq-images )

 

 

Hello friends first of all happy new year to all of you. Today we will work on how to Save ,Update & delete record from database using linq.

For using this you have to work on Linq To sql class Object which you can find when you add new item . Its extension is “DBML”.

When you create object of this then it will add datacontext in end.

Suppose you given name mydb.dbml then its object will be “mydbDataContext”.

You will be find this in attach document (Pic -1). Its basically a ORM (object Relational mapper) just drop the table from database. You will find the relation structure as like in (pic -2) in document.

The drop table is now work as individual class and & the fields of the table work as property of class.

Suppose if you drop table Customer then it will work as customer class and fields are work as property of customer class.

Now suppose you want to add new customer in customer table in database.

Then you have to create a object of customer class like below

Dim dc as new MyDbDataContext (its object of your added dbml)

Dim obj as new customer

Obj.strFirstName = “RAJAT”

Obj.strLastName = “JAISWAL”

Dc.customer.InsertOnSubmit(obj)

Dc.submitOnChanges()

The above code add the data in database.

Now suppose you want to edit the same record from database then you have to write following code

Dim dc as new myDbDataContext

Dim lnq = (from a in dc.customer where lngId = 1).singleOrDefault()

Lnq.strFirstName =”RAJAT”

Lnq.strLastName =”JAI”

Dc.submitChanges()

In that way you can update the customer record.

Now suppouse you want to delete record from database. Then you have to write following code.

Dim dc as new mydbDataContext()

Dim lnq = (from a in dc.customer where lngId = 1) .singleOrDefault()

Dc.customer.DeleteOnSubmit(lnq)

Dc.submitChanges()

In this way we can add edit, delete record.

In next topic we will how to add,edit,delete done by store procedure.

Enjoy Programming

Regards

Rajat