Friday, 21 October 2011

Linq To SQL Step By Step in VB.Net

Hi,
Following are steps to  Linq To SQL Step By Step in  VB.Net.


Step 1. Create a New Web Project.
Step 2.Add new item à Dataà Linq To SQL Classes.Name[ConDB.dbml]
Step 3. Add DataBase à NorthWind.Add Tables and Stored Procedures.
Step 4. Add New Web Form Name[LINQTOSQL]
Step5. Add controls  in Winform as Below.
Step 6. Add the below code in codebehind.
Public Class LinqToSql
    Inherits System.Web.UI.Page
    Dim dbcon As New ConDBDataContext()
    Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
        If Not IsPostBack Then
            FillDropDownlist()
        End If
    End Sub
    Private Sub FillDropDownlist()
        ''For Filling the Dropdwonlist
        Dim custQuery = _
        From cust In dbcon.Customers _
        Select cust.CustomerID
        Order By CustomerID
        DropDownList1.DataSource = custQuery
        DropDownList1.DataBind()
    End Sub
 
    Protected Sub CMDGo_Click(ByVal sender As ObjectByVal e As EventArgsHandles CMDGo.Click
        ''For Showing the Company name on the basis of selected customerid 
        Dim custQuery = _
        From cust In dbcon.Customers _
        Where cust.CustomerID = DropDownList1.Text
        Select cust.CompanyName
 
        For Each companyname In custQuery
            txtcustomername.Text = companyname
        Next
 
    End Sub
 
    Protected Sub CMDUpdate_Click(ByVal sender As ObjectByVal e As EventArgsHandles CMDUpdate.Click
        ''For Updating the data
        Dim custQuery = _
        (From cust In dbcon.Customers _
        Where cust.CustomerID = DropDownList1.Text
                Select cust)
 
        For Each Customer In custQuery
            'If Customer.CustomerID = DropDownList1.Text Then
            Customer.CompanyName = txtcustomername.Text
            ' End If
        Next
        dbcon.SubmitChanges()
        FillDropDownlist()
    End Sub
 
    Protected Sub CMDAdd_Click(ByVal sender As ObjectByVal e As EventArgsHandles CMDAdd.Click
        '' For Adding New Data
        Dim cust As New Customer With {.CompanyName = txtcustomername.Text, _
         .City = "London", .CustomerID = txtCompanyid.Text, .PostalCode = 55555, .Phone = "555-555-5555"}
        dbcon.Customers.InsertOnSubmit(cust)
        dbcon.SubmitChanges()
        FillDropDownlist()
    End Sub
 
    Protected Sub CMDDel_Click(ByVal sender As ObjectByVal e As EventArgsHandles CMDDel.Click
        ''For Deleting the Data
        Dim DelQry = From cust In dbcon.Customers _
        Where cust.CustomerID = DropDownList1.Text _
        Select cust
 
        If DelQry.Count > 0 Then
            dbcon.Customers.DeleteOnSubmit(DelQry.First)
            dbcon.SubmitChanges()
            FillDropDownlist()
        End If
 
    End Sub
 
    Protected Sub CMDExecProc_Click(ByVal sender As ObjectByVal e As EventArgsHandles CMDExecProc.Click
        ''For Filling the Gridview by executing the Stored Proc.
        Dim sprocqry = dbcon.SalesByCategory("seafood""1998")
        GridView1.DataSource = sprocqry
        GridView1.DataBind()
    End Sub
End Class


Wednesday, 28 September 2011

Steps to Host WCF Service with netTCPBinding in IIS 7.0

Hi


Step1. Add Non-HTTP Activation from Features Wizard.

Step 2. Following services should be enabled for net.tcp

Net.TCP Listener Adapter and Net TCP Port Sharing Service.


Step 3.  IIS should be enabled with net.tcp Binding. Go to IISàright Click à enable binding à add net.tcp with Port No.


Step 4. Go to your WCf Service in IIS, right Click manage applicationà advance settingsà  add net.tcp  in enabled protocols.

Step 5.  In your WCF service web.config file you should have mex endpoint.

Step 6. TCP Port should be enabled for inbound and out bound calls.
Hopes it will help you.


The remote server returned an error: (415) Cannot process the message because the content type 'application/soap+xml; charset=utf-8' In WCF

Hi,

I Created my WCF Service and it was working properly when i was making its service reference in my local machine.

But the problem came when I hosted this WCF Service in the Production Server.
When I was taking its reference in my local machine  I got following error.

The remote server returned an error: (415) Cannot process the message because the content type 'application/soap+xml; charset=utf-8'  In WCF.

I had   <serviceMetadata httpGetEnabled="true"/>   in the web.config. but still I got the error.

I resolved this issues by adding another endpoint 'mex' as below in my web.config.


<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

after adding above endpoint I got the service reference in my Client Application.

Please try If you face the similar problem.

PS: If this post helps you then please put your comments or mail me at smsaxena19@gmail.com


Happy Coding!

Shailendra Saxena

Monday, 26 September 2011

The server has rejected the client credentials WCF Error NetTCpBinding

Hi,

When I created my WCF Service and Host it on server I found following Error.

“The server has rejected the client credentials”.

I resolved it with following changes.

1. At Server Side in Web.Config i added [<security mode="None"></security>] as example given below.

<netTcpBinding>
        <binding name="netTcpBinding"    maxReceivedMessageSize="2147483647">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="22365478"/>
     <security mode="None"></security>
        </binding>
      </netTcpBinding>

2. On Client Side Also in my App.config [<security mode="None"></security>] as example given below.

 <netTcpBinding>
                <binding name="NetTcpBinding_IService1" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                  <security mode="None"></security>
                </binding>
            </netTcpBinding>

Good Luck.

Happy Coding.

Sunday, 19 June 2011

Developing Will Power and Self Discipline

An effective method for developing and improving these abilities is to perform certain actions or activities, which you would rather avoid doing due to laziness, procrastination, weakness, shyness, etc. Doing things that you usually do not like to do. or feel too lazy to do, you overcome your subconscious resistance, train your mind to obey you, strengthen your inner powers and gain inner strength. Muscles get stronger by resisting the power of the barbells. Inner strength is attained by overcoming inner resistance.
Remember, strengthening one of these abilities, automatically strengthens the other one.

Here are a few exercises:
1) You are sitting in a bus or train and an old man or woman, or a pregnant lady walks in. Stand up and give up your seat, even if you prefer to stay seated. Act so, not just because it is polite, but because you are doing something that you are reluctant to do. This is an exercise in overcoming the resistance of your body, mind and feelings.

2) There are dishes in the sink that need washing, and you postpone washing them for later. Get up and wash them now. Do not let your laziness overcome you. When you know that in this way you are developing your will power, and if you are convinced of the importance of will power in your life, it will be easier for you to do whatever you have to do.
3) You come home tired from work and sit in front of the T.V., because you feel too lazy and too tired to take a shower first. Do not succumb to the desire to sit in front of the T.V, and go and take a shower.
4) You may know your body needs some physical exercise, but instead you keep on sitting doing nothing or watching a movie. Get up and walk, run or do some other physical exercise.
5) Do you like your coffee with sugar? If you do, then for one whole week drink it without sugar. Do you drink three cups of coffee each day? If you do, then drink only two cups a day for one whole week.
6) Sometimes, when you want to say something that is not important, decide not to say it.
7) Don't read some unimportant gossip in the newspaper, even if you want to.
8) You have a desire to eat something not too healthy. For the sake of the exercise refuse the desire.
9) If you find yourself thinking unimportant, unnecessary, negative thoughts, try to develop a lack of interest in them, by thinking about their futility and uselessness.
10) Overcome your laziness. Convince yourself of the importance of what is to be done. Convince your mind that you gain inner strength when you act and do things, in spite of laziness, reluctance or senseless inner resistance.

Thursday, 9 June 2011

LINQ Basics


LINQ BASICS

Language-Integrated Query (LINQ) is a new feature introduced in visual studio 2008 and .NET Framework 3.5. Developers can write the queries in the code to retrieve the data from various types of data sources like SQL, XML and XQuery.

Earlier developers have to learn the syntax for writing queries for each data source. LINQ simplifies by offering a model to work with the data across various kinds of data sources.

LINQ Architecture

LINQ Flavours


When generating database mappings using LINQ to SQL, which tool allows you to create entity classes using a convenient graphical interface?

The Object Relational Designer (O/R Designer) provides a visual design surface for creating LINQ to SQL entity classes and associations (relationships) that are based on objects in a database
Below is the three advantages of LINQ over stored procedures.

Debugging - As debug point concern, as LINQ is part of .NET, we can use the visual studio's debugger to debug the queries but it is tough to debug the Stored procedure as it will not support the visual studio debugger.

Deployment - In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will complie into single DLL hence deployment becomes easier.

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest to use LINQ because it helps to encounter an error at the compile time rather than at runtime exception.

 The disadvantage with LINQ is, it is not a precompiled statement whereas stored procedures are precompiled. In case of LINQ the queries needs to be compile before the execution. So according to this, I can say stored procedures are faster in performance as compared to LINQ.

What are the advantages and disadvantages of LINQ.
Adv. of LINQ:
  • Supports type safety
  • Supports abstraction and hence allows developers to extend features such as multi-threading.
  • Easier to deploy
  • Simpler and easier to learn
  • Allows for debugging through .NET debugger.
  • Support for multiple databases
Disad. of LINQ:
  • LINQ needs to process the complete query, which might have a performance impact in case of complex queries
  • LINQ is generic, whereas stored procedures etc can take full advantage of database features.
  • If there has been a change, the assembly needs to be recompiled and redeployed. 

Can   LINQ  be used with databases other than SQL Server?   

LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with other databases through LINQ to Objects or LINQ to Datasets, where the objects and datasets then take care of database specific operations and LINQ only needs to deal with those objects, not the database operations directly. 

What are the three main components of LINQ or Language Integrated Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Provider

How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface.

What are the steps to use LINQ to SQL in .Net Project.

Steps.

1.      Create a connection to a database

1.       Right-click Data Connections in Server Explorer/Database Explorer and then click Add Connection.
2.       Add LINQ to SQL file.
1.       The Object Relational Designer (O/R Designer) is opened for the DBNAME.dbml file.
3.       To add Table to OR Designer.
1.       Select the table from the data connection and drag it to left pane of OR Designer.
4.       Save the Project
5.       Once you save the project DataContext object for the project. DBNAMEDATACONTEXT gets created.

Following is the code in vb to fill a datagridview.
Dim db As New northwindDataContext

Dim londonCusts = From cust In db.Customers _
                  Where cust.City = "London" _
                  Select cust

DataGridView1.DataSource = londonCusts