How to access WCF Service in Asp.Net Core Application

Introduction

How to access WCF Service in Asp.Net Core Application

Description:

In this article I will explain how to consume WCF Service in Asp.Net Core Web Application. In previous .Net Framework we have multiple options to consume a WCF service.  We have the options like Add Service Reference, SvcUtil,  ChannelFactory etc. However in Asp.Net Core there is a slight difference in Consuming WCF Service. In Asp.Net core you will notice that, we don’t have the option “Add Service Reference like in the older .Net Framework.  The solution for this is WCFConectedService.

WCFConnectedService:

Asp.net Core team has come up with an extension called WCFConnectedService, This is a Visual Studio extension for generating SOAP service references in the Asp.Net Core application. This extension can be used with any project types in asp.net core.

We use ConnectedService to access a WCF Service in Asp.Net Core Web Application.

Installing WCF Connected Service Extension:

Below are the steps to install WCF Connected Service Extension in Asp.Net Core WebApplication

  • Right Click on the Connected Services Option

ConnectedService7

If the Extension is not installed then you will see the below window. User need to click on Find more Services link

ConnectedServices1

Extension and Updates window will be displayed and from this window you can find the Visual Studio WCF Connected Service extension option

ConnectedServices2

Click on Download button to install the extension. You may need to close the VisualStudio instances to complete the VSIX installation.

Simple WCF Service

For this example, we have created a WCF Service. In our service we have a sample method called “GetData(int id)”.  This method will take integer input values and return a string “You entered:1”

ISimpleService Interface

SimpleService  Method Implementation

Above service is for demo purpose, you can use connected service approach with any service as per your design.

Accessing WCF Service in Asp.Net Core Web Application

In your Asp.Net Core web application, you will see a Connected Service Option like below

ConnectedService7

Follow the below steps to Add Service Reference

  • Right Click on the Connected Services Option
  • Select Add Connected Service and Add Connected Services wizard will be displayed and Select the WCF -Service Preview option

ConnectedService4

  • Click on the Configure button. This will bring up Configure WCF Service Reference dialog box. Enter your Service url and Click on Go or Discover, it will discover the ServiceConnectedServices5
  • Click on Next and select appropriate options

ConnectedServices6

  • Click on Finish to generate proxy for WCF Service.

Once after this you will be able to see Service Reference Folder added in our project.

ConnectedService3

Now all you need to is to Create the Client and access the service like below

Result

You can download sample application for this article from here

, , , , ,

Leave a comment

How to populate Angular UIGrid in MVC using AngularJS

Description

In this article I will explain the steps for populating UI-Grid in angularjs from database using WebAPI. UI-grid is a powerfull tool which provides a table like representation. Apart from table like structure Ui-Grid also provides functionality like filtering, sorting, exporting etc.  You can find more details about UI-Grid from here

PreRequisites:

Ui-Grid is dependant on AngularJS.Hence ensure that you have added reference of Angular js on page.

Implementation:

Model:

To load the data from database, we are using EntityFramework and its related method. In this example I have used the DatabaseFirstApporach.  DatabaseFirstApporach lets the EnityData Model to generate classes, dbcontext etc from the database automatically. All other functionalities like database and model sync exists as is.

Follow the below procedures to generate Model for Customer database in Northwind database

  • Right click on the Model folder
  • Select Add option
  • And then select the New Item option
  • Choose Data from Installed Templates group
  • Select the ADO.NET Entity Data Model option and Provide a name for it
  • In the Entity Data Model Wizard, Select EF Designer from database and click on Next
  • Choose the Connection string options
    • If you already have connection string configured then you can select that from the available list.
    • If you don’t have the connection string configured then use the New Connection option and create the connection
  • Expand the Table option and then select the tables which you want
  • Click on Finish

You will have necessary class files generated in your solution now

Northwind

You can get more details about how to use DatabaseFirst approach from this link.

Controller (WebAPI)

In this example we are using WebAPI to load the data. The next procedure is to write code to fetch records from database using WebAPI.  For this demo I have used a basic select operation. You can modify this as per your need.

Another point to note here is UI-grid read data which is in Json format, Hence we need to ensure that the data which we return from controller is of Json format. We will use the JsonResult method for this.

View:

On View we will have the codes for UI-Grid and its related files. If you look at the design of UI-Grid it’s a div which will be styled to look like a table at runtime.

We need to add div with an attribute as ui-grid=”gridOptions”.  We add all the details from angular js code to gridOptions and UI-Grid at runtime uses this div to populate the grid.

RouteConfig Changes:

I have changed the Action Name from “Get” to “GetCustomer” to be more specific with what the method do. In order for api to identify the proper method add the below route setting to web api route config

Angular JS Script

Below are the code to fetch the data from database and populate it to UI-Grid. I have used a factory to call the Get Customer method and used that in the main method.

 

, , , , ,

1 Comment

String or binary data would be truncated error from an Integer Field in SQL Server Database

Introduction

In this article I am going to explain an interesting problem in SQL Server.

Usually we will see the exception “String or binary data would be truncated” with string datatype columns.

For ex: If you have a column with Datatype Varchar (50) in the table and if you try to insert an entry with more than 50 characters you will get this exception.

To my surprise I faced the same error with an integer column and I tried multiple options to find out from where the exception is thrown. All my changes went in vain and I couldn’t fix with the changes I made in an integer column.

Solution:

After some time I started looking at the Triggers in the table and Bingo, that’s where the problem was and I was able to fix the issue.

In my case when I do an insert to Integer column, I was creating a larger string in trigger and for a particular combination it crossed the allowed 50 character limit which resulted in Error.

Note:

If you face exception during an insert to integer data type column, then First Check the Trigger for your table, the root cause of exception might be in trigger.

, , ,

Leave a comment

How to read Excel files in Javascript/Jquery and convert the value to Json

Introduction

We have multiple ways to read excel file in C# and then convert it to JSON or insert the data in to database etc. However there are not much options available when it comes to reading the Excel file using javascript. In this article I will explain an option using a Jquery Plugin called SheetJS.

SheetJS is Excel parser which supports multiple formats of excel files like 2007, 2010, 2013 office versions etc.

Implementation

To use the SheetJS user need to add the reference files first. You can do this either by downloading files from here and then refer these js files to project. Another option is to use the online CDN available.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js"></script>

Reading the Excel File

To read the excel file we use the read method in SheetJs like below

var workbook = XLSX.read(data, { type: 'binary' });

Converting Excel value to Json
To convert the values to Json will use “sheet_to_json” method

          var sheet_name_list = workbook.SheetNames;
           sheet_name_list.forEach(function (y) { /* iterate through sheets */
                    //Convert the cell value to Json
                    var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
                    if (roa.length > 0) {
                        result = roa;
                    }
                });

Complete Code

Sample Excel I used for this Demo

ujcrvsc

 

, , , ,

1 Comment

Awarded as DotnetFunda Most Valuable Professional (DNF MVP)

I am happy to inform you all that I have been awarded as DotNetFunda Most Valuable Professional (DNF MVP) for the contributions made to DotNetFunda.com.

Thanks Sheo Sir and other judging panel members for selecting me also in this Years’s DotnetFunda MVP.

dnfmvp

Leave a comment

How to hide columns based on values selected in checkbox

Introduction:

How to hide columns based on values selected in checkbox

Description:

In this article I am going to explain how to hide columns in grid view based on user selection in checkbox. We can achieve this requirement with both client side and server side approach. Here I am going to explain the client side approach where we uses Jquery to hide column in gridview.

Gridview will render as table with header and rows at runtime, we will use jquery selector to access this header and calculate selected column index and then hide or show accordingly.

Function to hide and display Column

 <script type="text/javascript">
        $(document).ready(function () {
            //Attach click to checkboxlist
            $("#CheckBoxList1").click(function () {
                //loop through each item in checkboxlist
                $("[id*=CheckBoxList1] input").each(function () {
                    //Get the Gridview header row
                    var tblhead = $("#GridView1 th");
                    //Get the selected column index in gridview
                    var columnIndex = tblhead.index($("table[id*=GridView1] th:contains('" + $(this).next().html() + "')")) + 1;
                    //check if current items in checkboxlist is selected or not
                    if ($(this).is(":checked")) {
                        //if so then hide that column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").hide();
                    } else {
                        //if not then display the column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").show();
                    }
                });
            });
        });
    </script>

Complete Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    	<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    	<link rel="stylesheet" href="/resources/demos/style.css">
    <script type="text/javascript">
        $(document).ready(function () {
            //Attach click to checkboxlist
            $("#CheckBoxList1").click(function () {
                //loop through each item in checkboxlist
                $("[id*=CheckBoxList1] input").each(function () {
                    //Get the Gridview header row
                    var tblhead = $("#GridView1 th");
                    //Get the selected column index in gridview
                    var columnIndex = tblhead.index($("table[id*=GridView1] th:contains('" + $(this).next().html() + "')")) + 1;
                    //check if current items in checkboxlist is selected or not
                    if ($(this).is(":checked")) {
                        //if so then hide that column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").hide();
                    } else {
                        //if not then display the column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").show();
                    }
                });
            });
        });
    </script>
</head>
<body>
<form id="form1" runat="server">
        <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Value="AddressID">AddressID</asp:ListItem>
            <asp:ListItem Value="AddressLine1">AddressLine1</asp:ListItem>
            <asp:ListItem Value="City">City</asp:ListItem>
            <asp:ListItem Value="StateProvinceID">StateProvinceID</asp:ListItem>
            <asp:ListItem Value="PostalCode">PostalCode</asp:ListItem>
            <asp:ListItem Value="ModifiedDate">ModifiedDate</asp:ListItem>
        </asp:CheckBoxList>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True" DataSourceID="SqlDataSource2">
            <Columns>
                <asp:BoundField DataField="AddressID" HeaderText="AddressID" />
                <asp:BoundField DataField="AddressLine1" HeaderText="AddressLine1" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="StateProvinceID" HeaderText="StateProvinceID" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
                <asp:BoundField DataField="ModifiedDate" HeaderText="ModifiedDate" />
            </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT top 20 [AddressID], [AddressLine1],City,StateProvinceID,PostalCode,ModifiedDate FROM Person.Address"></asp:SqlDataSource>
    </form>

</body>
</html>

demo

, , , , , ,

Leave a comment

How to load data from database to Asp.Net Gridview using WebAPI

Introduction:

In this article we are discussing how to load data from database to Asp.Net Gridview using WebAPI.

Description:

We use WebAPI to get the data from database and then use the Jquery getJSON() method to Load JSON-encoded data from the server using a GET HTTP request.

Implementation:

In the New ASP.NET Project dialog, select the Empty template. Under “Add folders and core references for”, check WebForms , Web API. Click OK.

2016-04-30 19_11_49-Microsoft Visual Studio (Administrator)

When using WEBAPI you will get data in client side and you need to manipulate it at client side so that the data will get populated in Gridivew. Point to note here is we cannot go with the normal approach of setting DataSource and calling DataBind method. We have various options to load data into grid like AngularJs, Jquery etc.

As mentioned earlier in this article I am using getJSON() method to fetch the value and then populate the data in gridview. Gridview will load as table at runtime we will access this table and then append the values to it.

2016-04-30 14_29_24-http___localhost_52678_WebForm1.aspx - Internet Explorer

Sample Code:

HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script type="text/javascript">
        //Code to load the data to gridview on pageload
        $(document).ready(function () {
           //Here you need to provide the webapi address
            $.getJSON('api/Customer')
                .done(function (data) {
                    $.each(data, function (key, item) {
                        //Add the result to gridview
                        $("#GridView1").append("

<tr>

<td>" + item.CustomerID + "</td>


<td>" + item.CompanyName + "</td>


<td>" + item.ContactName + "</td>


<td>" + item.ContactTitle + "</td>


<td>" + item.Address + "</td>

</tr>
");
                    });
                })
            .fail(function (d) {
                alert("error occured" + d.responseText);
            });
        });
    </script>
</head>
<body>
<form id="form1" runat="server">
<div>
            <asp:GridView ID="GridView1" runat="server" Width="1000px" ShowHeaderWhenEmpty="true"                 CellPadding="0" CellSpacing="0">
            </asp:GridView></div>
</form>

</body>
</html>

C#:

First we need to populate an empty row in GridView. Reason behind this is if we didn’t assign any datasource then the GridView won’t populate at runtime and we won’t be able to access it at client side.

protected void Page_Load(object sender, EventArgs e)
        {
            //Load and empty row to gridview
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(&quot;CustomerID&quot;);
                dt.Columns.Add(&quot;CompanyName&quot;);
                dt.Columns.Add(&quot;ContactName&quot;);
                dt.Columns.Add(&quot;ContactTitle&quot;);
                dt.Columns.Add(&quot;Address&quot;);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

WebAPI Code:

When we add the WebAPI references in your project you will see a Model folder and Controller folder.

2016-04-30 19_20_50-WebAPISample - Microsoft Visual Studio (Administrator)

Model

Here we add the Model classes which basically represents data in WebAPI. For this article we add Customer class. Right Click on the Model folder and choose Add and then select class file. Name it like Customer

public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
    }

Controllers:

In controller we will add the code to fetch values from database. Right click on the Controllers folder and Choose Add and then select Controller. In code you can see an HttpGet entry added above to GetCustomers method. This is because Rest WebAPI is making use of verbs(Get,Post,Put,Delete) for each actions in Read,Create,Update,Delete respectively. You can get more details from here

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiSample.Models;

namespace WebApiSample.Controllers
{
    public class CustomerController : ApiController
    {
        [HttpGet]
        public IEnumerable<Customer> GetCustomers()
        {
            Customer[] aryCustomers = null;
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWINDConnectionString"].ToString()))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "SELECT TOP 10 CustomerID,CompanyName,ContactName,ContactTitle,Address FROM Customers";
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        List<Customer> lstcustomers = new List<Customer>();
                        while (reader.Read())
                        {
                            lstcustomers.Add(new Customer
                            {
                                CustomerID = reader["CustomerID"].ToString(),
                                CompanyName = reader["CompanyName"].ToString(),
                                ContactName = reader["ContactName"].ToString(),
                                ContactTitle = reader["ContactTitle"].ToString(),
                                Address = reader["Address"].ToString()
                            });
                            aryCustomers = lstcustomers.ToArray();
                        }
                    }
                }
            }
            return aryCustomers;
        }
    }
}

, , , , , , ,

Leave a comment