Posts Tagged .Net

Getting started with MongoDB in Asp.Net Core

Introduction

In this article we will discuss on the procedures to build a simple application in Asp.Net Core which communicates with MongoDB database.

Description

This application will do the CRUD operation on a Mongo database and then displays the details in a table.

ThirdPartyTool Used

Robo 3T – is a third party tool which provides a lightweight MongoDB management tool

Implementation

Setting up MongoDB:

If you have not installed the mongodb exe then download and install the same from MongoDB Download Center

After installation of the database, in order to access the mongodb we have to start the MongoDB Process.

To start MongoDB, run mongod.exe in command prompt. Make sure you are running the command prompt from installation folder of Mongodb.  By default installation path is set as C:\Program Files\MongoDB\Server\3.6\bin\

Additionally we need a data directory to store all data in MongoDB. User can set the path for data files using the –dbpath option to mongod.exe

CommandStart

You can begin using the Robo 3T after starting mongodb process.

For this demo I have created a Collections namely Customer with 3 columns

Robo3T.png

Since the database is ready now we will start building the application. Follow along the article to create sample application

Below is a sample demonstration of the application we are going to make

demo.gif

Create a new Project in Visual Studio

CoreProject

And Select the Template for Asp.Net Core MVC Web Application

MVCCore

To interact with MongoDB from c# code, we need to install .NET MongoDB Driver which provides asynchronous interaction with MongoDB.  I utilized the below nugget commands to add driver into my project

Model Class

Lets make an entity class called “Customer” which fits the schema of the Customer table in the database

The class contains Id property of the type ObjectId. This property is used to match an item in MongoDB collections. We as well have another attribute, namely BsonElement which is applied to represent an “element” in the MongoDB collection.

Controller Methods

In Controller we will add code for reading, editing, creating and deleting records from MongoDB.  I have moved the code to retrieve the mongodb database details to a common method.

Views Code

Since this was a more of a MongoDB demo I have used the scaffolding option available with MVC to generate View. You can modify this as per your needs.

Index View

Create View

Delete View

Details View

Edit View

Conclusion

In this article we have looked into procedures to create a simple application in MVC Core using MongoDB as database.

You can download the source code for Asp.NetCoreMVCMongoDBDemo from GitHub.

 

Advertisements

, , , , , ,

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 populate Dropdownlist from database using AngularJS ng-options Attribute

Introduction:

In this article I am going to explain how to populate dropdownlist control from database using AngularJS. AngularJS lets you extend HTML vocabulary for your application.

Prerequisites:

You need to add the necessary AngularJS files to your page prior to use this plugin. You can either download the file from here and add to your project or use the AngularJS file directly from CDN.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

Implementation:

Here we are make use of Jquery Ajax post method to get the record from database and then pass it to dropdownlist. We will be using $http service function which communicates via the browser’s XMLHttpRequest object or via JSONP.

AngularJS code to populate the dropdownlist.

<script type="text/javascript">
        angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
            $scope.ProductList = null;
            //Declaring the function to load data from database
            $scope.fillProductList = function () {
                $http({
                    method: 'POST',
                    url: 'AngularCascadingDropDownList.aspx/GetProductList',
                    data: {}
                }).success(function (result) {
                    $scope.ProductList = result.d;
                });
            };
            //Calling the function to load the data on pageload
            $scope.fillProductList();
        });
    </script>

Now we will use the ng-options attribute to generate option for dropdownlist from the passed data.

    <div ng-app="drpdwnApp" ng-controller="drpdwnCtrl">
        <select ng-model="drpdpwnvalue" ng-options="item.OrderID for item in ProductList">
            <option value="" label="Select and item"></option>
        </select>
    </div>

HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script type="text/javascript">
        angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
            $scope.ProductList = null;
            //Declaring the function to load data from database
            $scope.fillProductList = function () {
                $http({
                    method: 'POST',
                    url: 'AngularCascadingDropDownList.aspx/GetProductList',
                    data: {}
                }).success(function (result) {
                    $scope.ProductList = result.d;
                });
            };
            //Calling the function to load the data on pageload
            $scope.fillProductList();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div ng-app="drpdwnApp" ng-controller="drpdwnCtrl">
        <select ng-model="drpdpwnvalue" ng-options="item.OrderID for item in ProductList">
            <option value="" label="Select and item"></option>
        </select>
    </div>
    </form>
</body>
</html>

C#:

[System.Web.Services.WebMethod()]
        public static List<OrderList> GetProductList()
        {
            List<OrderList> list = new List<OrderList>();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWINDConnectionString"].ConnectionString))
            {
                conn.Open();
                string strquery = "Select TOP 10 * from Orders";
                using (SqlCommand cmd = new SqlCommand(strquery, conn))
                {
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        OrderList objorder = new OrderList(int.Parse(reader["OrderID"].ToString()), reader["ShipAddress"].ToString(), reader["ShipName"].ToString(), double.Parse(reader["Freight"].ToString()));
                        list.Add(objorder);
                    }
                }
 
            }
            return list;
        }
 
        public class OrderList
        {
            public int OrderID;
            public string ShipName;
            public string ShipAddress;
            public double Freight;
            public OrderList(int orderID, string shipName, string shipAddress, double freight)
            {
                OrderID = orderID;
                ShipName = shipName;
                ShipAddress = shipAddress;
                Freight = freight;
            }
        }

, , , ,

5 Comments

How to highlight the selected rows in Repeater using Jquery

Introduction:

In this article I am going to explain how to highlight the selected row in Repeater control using Jquery.  At runtime Repeater control will render as table we will be manipulating this table structure to access each row and then use the css to highlight the row.

Prerequisites:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

Solution:

We will use the below css to hightlight the rows in gridview.

<style type="text/css">
        .highlightRow
        {
            background-color: #9999FF;
        }
    </style>

Jquery Code:             

Below Jquery function will remove the css from all other rows except the selected row

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
 <script>
    $(function () {
         $(".trclass").click(function () {
            $(this).addClass("highlightRow").siblings().removeClass("highlightRow");
          });
     });
 </script>

HTML

   <asp:Repeater runat="server" ID="Repeater1">
            <HeaderTemplate>
                <table width="500px" border="1px">
                    <tr style="background-color: #fb7700">
                        <td>Value1
                        </td>
                        <td>Value2
                        </td>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr class="trclass">
                    <td>
                        <asp:Label ID="lblValue1" runat="server" Text='<%# Eval("val1") %>'></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="lblValue2" runat="server" Text='<%# Eval("val2") %>'></asp:Label>
                    </td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Below code is to populate dummy data, you dont need this code if you are populating the repeater from database in code behind.

C#:

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable table1 = new DataTable();
                table1.Columns.Add("val1");
                table1.Columns.Add("val2");
                table1.Rows.Add("Value1", "Message1");
                table1.Rows.Add("Value2", "Message2");
                table1.Rows.Add("Value3", "Message3");
                table1.Rows.Add("Value4", "Message4");
                table1.Rows.Add("Value5", "Message5");
                table1.Rows.Add("Value6", "Message6");
                table1.Rows.Add("Value7", "Message7");
                Repeater1.DataSource = table1;
                Repeater1.DataBind();
            }
        }

Demo

, , , , ,

Leave a comment

How to access cells in Telerik Kendo Grid

Introduction:

In this article I am going to explain how to access the cells in Kendo Grid from Telerik.

Description:

Recently I have come across a requirement where I need to access the cells in a Kendo Grid and then based on a value change the color of the cell. The documentation in KendoUI site shows options to access the columns all together.  So I have come up my own custom implementation which I will be explaining below

Installation:

If you are new to KendoUI control and then wondering from where you will get the installer, then you can use the nugget installer. You can use the below command to install Kendo Controls.

PM> Install-Package KendoUICore

Once you execute above command you will see the below items added to your solution

Another option is to use the online CDN for the Kendo Controls

 <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.mobile.all.min.css"
        rel="stylesheet" type="text/css" />
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.mobile.all.min.css"
        rel="stylesheet" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.all.min.js"></script>

Solution:

To access the cells in Kendo Grid we will use the dataBound event. Here first we will loop through the datasource and then loop each items in datasource.

By design Kendo will assign an id (dataItem.uid) field to each row in KendoGrid, we will use this id to access each row in KendoGrid.

Then we can use the textContent property to get the value and based on that color the cell in gridview.

function OnDataBound() {
                //Get the datasource here
                var data = this._data;
                //Loop through each item
                for (var x = 0; x < data.length; x++) {
                    //Get the currently active item
                    var dataItem = data[x];
                    //Access table row basedon uid
                    var tr = $("#grid").find("[data-uid='" + dataItem.uid + "']");
                    //Access cell object
                    var cell = $("td:nth-child(1)", tr);
                    //Get the cell content here
                    //Check if the column values are 
                    if (cell[0].textContent == "Nige") {
                        //Assign the css style to cell
                        //You can hide the cell content using css here
                        cell.addClass("color");
                    }

                }
            }

Complete Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.common.min.css" rel="stylesheet"
        type="text/css" />
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.default.min.css" rel="stylesheet"
        type="text/css" />
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.mobile.all.min.css"
        rel="stylesheet" type="text/css" />
    <link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.mobile.all.min.css"
        rel="stylesheet" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.all.min.js"></script>
    <script src="http://demos.telerik.com/kendo-ui/content/shared/js/people.js"></script>
    <script>
        // A $( document ).ready() block.
        $(document).ready(function () {
            var ds = {
                data: createRandomData(20),
                pageSize: 10,
                schema: {
                    model: {
                        fields: {
                            Id: { type: 'number' },
                            FirstName: { type: 'string' },
                            LastName: { type: 'string' },
                            City: { type: 'string' }
                        }
                    }
                }
            };

            var grid = $("#grid").kendoGrid({
                dataSource: ds,
                dataBound: OnDataBound,
                editable: false,
                pageable: true,
                columns:
    [
        { field: "FirstName", width: 90, title: "First Name" },
        { field: "LastName", width: 200, title: "Last Name" },
        { field: "City", width: 200 }
    ]
            }).data("kendoGrid");

            function OnDataBound() {
                //Get the datasource here
                var data = this._data;
                //Loop through each item
                for (var x = 0; x < data.length; x++) {
                    //Get the currently active item
                    var dataItem = data[x];
                    //Access table row basedon uid
                    var tr = $("#grid").find("[data-uid='" + dataItem.uid + "']");
                    //Access cell object
                    var cell = $("td:nth-child(1)", tr);
                    //Get the cell content here
                    //Check if the column values are 
                    if (cell[0].textContent == "Nige") {
                        //Assign the css style to cell
                        //You can hide the cell content using css here
                        cell.addClass("color");
                    }
                }
            }
        });
    </script>
    <style>
        .color {
            background-color: green;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div id="grid">
        </div>
    </form>
</body>
</html>

, , ,

Leave a comment

How to Crop the Image using CropImage.Net tool in Asp.Net

Introduction:

In this article I am going to explain how to crop an Image using CropImage.Net

Prerequisites:

You can download the dll files needed to use CropImage.Net from this link. Once you have a downloaded the files you need to add the dll files to your solution. You can follow the below steps to add the dlls.

  • Open your Project within the Solution Explorer
  • Right-click the References folder and Choose Add Reference options
  • Find and select the dlls which needs to be added to your solution
    • ImageResizer.dll
    • Imazen.Crop.dll
    • System.Web.Extensions.dll (You may need to use the browse button if you are not finding the dll in available list)
  • Click the Ok button to add it to your Project.

Now you have all the files added to your project

Details of CropImage.Net Control:

CropImage.Net exposes method called Crop, which actually Crops the original image and saves it to the specified path. This method have two overrides one with destinationpath as parameter and another one with destinationpath and appendCorrectExtension.

public void Crop(string destPath);
public void Crop(string destPath, bool appendCorrectExtension)

 Implementation:

Here I am going to explain the steps on how to use CropImage.Net tool to crop the images using Asp.Net.

In this demo I will upload a file and then the uploaded file will be shown in an image control. Then with the help of CropImage control the image will be cropped and shown in another image control called result.

First Step is to register the ImageCrop control in your page like given below

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

Then you need add the below CropImage control to your page and then set it Image property to the Image control from which Image is used to crop.

<ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />

Then we use the Crop method to crop and save the image to the destination path provided.

//Save the copy in local folder
CropImage1.Crop(MapPath("~/images"), true);

You also need to add the below configurations to your webconfig file

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" />
    <httpModules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </httpModules>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </modules>
  </system.webServer>
</configuration>

Complete Code:

HTML:

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Croping Image using ImageResizer in .Net</h3>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <asp:Image ID="Image1" runat="server" ImageUrl="" />
            

            <ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />
            

            <asp:Button ID="Button1" runat="server" Text="Crop" OnClick="btnCrop_Click" />
            <h3>The result</h3>
            <asp:Image ID="Result" runat="server" Visible="false" />
        </div>
    </form>
</body>
</html>

C#:

protected void btnCrop_Click(object sender, EventArgs e)
    {

        //Show the Result Image control 
        Result.Visible = true;
        //Assign the image url from CropImage control
        Result.ImageUrl = CropImage1.CroppedUrl;

        //Save the copy in local folder
        CropImage1.Crop(MapPath("~/images"), true);

        //You can also get the coordinates from CropImage if you want to show to the user
        this.Title = CropImage1.X + "," + CropImage1.Y + "," + CropImage1.X2 + "," + CropImage1.Y2;

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Check if file upload is having any value
        if (FileUpload1.HasFile)
        {
            try
            {
                //Get the uploaded filename from FileUpload Control
                string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                //Save the file to folder
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                //Show the uploaded image in Image Control which is tagged to the Image Cropping Control
                Image1.ImageUrl = "~/images/" + filename;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.ToString());
            }
        }
    }

Note that I have used the folder which is inside in my solution.You can see that in the image given above. If you have a different you need to change the path accordingly.

Demo

, , , , ,

3 Comments