Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET MVC 6 Hosting - ASPHostPortal :: Bootstrap Tree View in ASP.Net MVC

clock August 24, 2015 07:42 by author Kenny

Bootstrap Tree View in ASP.Net MVC

The ASP.NET MVC is an almost open source web application framework that implements the model–view–controller (MVC) pattern. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NETfeatures, such as master pages and membership-based authentication. Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites.

We create two classes, one is AuthorViewModel and another is BookViewModel. AuthorViewModel is the main class that has an association with the BookViewModel class. In other words each AuthorViewModel class object has a list of BookViewModel class objects. The following is the code snippet for the BookViewModel class. 

namespace TreeView.Models   
{  
    public class BookViewModel   
    {  
        public long Id   
        {  
            get;  
            set;  
        }  
        public string Title   
        {  
            get;  
            set;  
        }  
        public bool IsWritten   
        {  
            get;  
            set;  
        }  
    }  
}  

The following is the code snippet for the AuthorViewModel class.

using System.Collections.Generic;  
 
namespace TreeView.Models {  
    public class AuthorViewModel   
    {  
        public AuthorViewModel()   
        {  
            BookViewModel = new List < BookViewModel > ();  
        }  
        public int Id   
        {  
            get;  
            set;  
        }  
        public string Name   
        {  
            get;  
            set;  
        }  
        public bool IsAuthor   
        {  
            get;  
            set;  
        }  
        public IList < BookViewModel > BookViewModel   
        {  
            get;  
            set;  
        }  
    }  
}

Now we create a controller “HomeController” that has two action methods for both GET and POST requests. The action method's name is “Index”. The Get request action method returns a tree view in the UI whereas the POST request method gets the posted data from the UI. The following is the code snippet for HomeController.

using System.Collections.Generic;  
using System.Linq;  
using System.Web.Mvc;  
using TreeView.Models;  
 
namespace TreeView.Controllers  
{  
    public class HomeController : Controller  
    {  
        [HttpGet]  
        public ActionResult Index()  
        {  
            List<AuthorViewModel> model = new List<AuthorViewModel>();  
 
            AuthorViewModel firstAuthor = new AuthorViewModel  
            {  
                Id = 1,  
                Name = "User1",  
                BookViewModel = new List<BookViewModel>{  
                    new BookViewModel{  
                        Id=1,  
                        Title = "JQuery",  
                        IsWritten = false  
                    }, new BookViewModel{  
                        Id=1,  
                        Title = "JavaScript",  
                        IsWritten = false  
                    }  
                }  
            };  
 
            AuthorViewModel secondAuthor = new AuthorViewModel  
            {  
                Id = 2,  
                Name = "User2",  
                BookViewModel = new List<BookViewModel>{  
                    new BookViewModel{  
                        Id=3,  
                        Title = "C#",  
                        IsWritten = false  
                    }, new BookViewModel{  
                        Id=4,  
                        Title = "Entity Framework",  
                        IsWritten = false  
                    }  
                }  
            };  
            model.Add(firstAuthor);  
            model.Add(secondAuthor);  
            return View("Index", model);  
        }  
 
        [HttpPost]  
        public ActionResult Index(List<AuthorViewModel> model)  
        {  
            List<AuthorViewModel> selectedAuthors = model.Where(a => a.IsAuthor).ToList();  
            List<BookViewModel> selectedBooks = model.Where(a => a.IsAuthor)  
                                                .SelectMany(a => a.BookViewModel.Where(b => b.IsWritten)).ToList();  
            return View();  
        }  
    }  

The preceding code shows how books are associated with an author in the GET action method and how to get a selected tree node (authors and books) in the POST request. 

Bootstrap CSS is already added to the application but we write a new custom CSS for the tree view design. The following is the code snippet for the tree CSS.

.tree li {  
    margin: 0px 0;    
    list-style-type: none;  
    position: relative;  
    padding: 20px 5px 0px 5px;  
}  
 
.tree li::before{  
    content: '';  
    position: absolute;   
    top: 0;  
    width: 1px;   
    height: 100%;  
    right: auto;   
    left: -20px;  
    border-left: 1px solid #ccc;  
    bottom: 50px;  
}  
.tree li::after{  
    content: '';  
    position: absolute;   
    top: 30px;   
    width: 25px;   
    height: 20px;  
    right: auto;   
    left: -20px;  
    border-top: 1px solid #ccc;  
}  
.tree li a{  
    display: inline-block;  
    border: 1px solid #ccc;  
    padding: 5px 10px;  
    text-decoration: none;  
    color: #666;      
    font-family: 'Open Sans',sans-serif;  
    font-size: 14px;  
    font-weight :600;  
    border-radius: 5px;  
    -webkit-border-radius: 5px;  
    -moz-border-radius: 5px;  
}  
 
/*Remove connectors before root*/  
.tree > ul > li::before, .tree > ul > li::after{  
    border: 0;  
}  
/*Remove connectors after last child*/  
.tree li:last-child::before{   
      height: 30px;  
}  
 
/*Time for some hover effects*/  
/*We will apply the hover effect the the lineage of the element also*/  
.tree li a:hover, .tree li a:hover+ul li a {  
    background: #dd4814; color: #ffffff; border: 1px solid #dd4814;  
}  
/*Connector styles on hover*/  
.tree li a:hover+ul li::after,   
.tree li a:hover+ul li::before,   
.tree li a:hover+ul::before,   
.tree li a:hover+ul ul::before{  
    border-color:  #dd4814;  
}  
.tree-checkbox{  
    margin :4px !important;  
}  
 
   
.tree:before {  
    border-left:  1px solid #ccc;  
    bottom: 16px;  
    content: "";  
    display: block;  
    left: 0;  
    position: absolute;  
    top: -21px;  
    width: 1px;  
    z-index: 1;  
}  
 
.tree ul:after {  
    border-top: 1px solid #ccc;  
    content: "";  
    height: 20px;  
    left: -29px;  
    position: absolute;  
    right: auto;  
    top: 37px;  
    width: 34px;  
}  
*:before, *:after {  
    box-sizing: border-box;  
}  
*:before, *:after {  
    box-sizing: border-box;  
}  
.tree {  
    overflow: auto;  
    padding-left: 0px;  
    position: relative;  

Now we create an Index view that renders in the browser and shows the tree view for the author and book. The following is the code snippet for the Index view.

@model List  
<TreeView.Models.AuthorViewModel>  
@section head{  
@Styles.Render("~/Content/css/tree.css")  
}  
    <div class="panel panel-primary">  
        <div class="panel-heading panel-head">Author Book Tree View</div>  
        <div id="frm-author" class="panel-body">  
@using (Html.BeginForm())  
{  
            <div class="tree">  
@for (int i = 0; i < Model.Count(); i++)  
{  
                <ul>  
                    <li>  
                        <a href="#">  
@Html.CheckBoxFor(model => model[i].IsAuthor, new { @class = "tree-checkbox parent", @id = @Model[i].Id })  
                            <label [email protected]>  
                                <strong>Author:</strong>  
@Html.DisplayFor(model => model[i].Name)  
                            </label>  
                        </a>  
                        <ul>  
@for (int j = 0; j < Model[i].BookViewModel.Count(); j++)  
{  
int k = 1 + j;  
@Html.HiddenFor(model => model[i].BookViewModel[j].Id)  
                            <li>  
                                <a href="#">  
@Html.CheckBoxFor(model => model[i].BookViewModel[j].IsWritten, new { @class = "tree-checkbox node-item", @iid = i + "" + j })  
                                    <label [email protected]@j>  
                                        <strong>Book @(k):</strong> @Html.DisplayFor(model => model[i].BookViewModel[j].Title)  
                                    </label>  
                                </a>  
                            </li>  
}  
                        </ul>  
                    </li>  
                </ul>  
}  
            </div>  
            <div class="form-group">  
                <div class="col-lg-9"></div>  
                <div class="col-lg-3">  
                    <button class="btn btn-success" id="btnSubmit" type="submit">  
Submit  
</button>  
                </div>  
            </div>  
}  
        </div>  
    </div>  
@section scripts{  
@Scripts.Render("~/Scripts/tree.js")  

Thereafter we create an important part of this example. We create the JavaScript file tree.js with the following code.

(function($)   
{  
    function Tree() {  
        var $this = this;  
        function treeNodeClick()   
        {  
            $(document).on('click', '.tree li a input[type="checkbox"]', function() {  
                $(this).closest('li').find('ul input[type="checkbox"]').prop('checked', $(this).is(':checked'));  
            }).on('click', '.node-item', function() {  
                var parentNode = $(this).parents('.tree ul');  
                if ($(this).is(':checked')) {  
                    parentNode.find('li a .parent').prop('checked', true);  
                } else {  
                    var elements = parentNode.find('ul input[type="checkbox"]:checked');  
                    if (elements.length == 0) {  
                        parentNode.find('li a .parent').prop('checked', false);  
                    }  
                }  
            });  
        };  
        $this.init = function() {  
            treeNodeClick();  
        }  
    }  
    $(function() {  
        var self = new Tree();  
        self.init();  
    })  
}(jQuery)) 

As in the preceding JavaScript code, the create tree view has the following features.

  1. When we select an author parent node then all the associated books will be selected.
  2. When a book is selected the associated parent author will be selected automatically.
  3. When all child book nodes are selected for a parent author node then the parent node will be selected.
  4. When the parent node is unselected then the child books will be automatically unselected.

Figure 1 shows the parent child (author-book) tree view.



Entity Framework 7 Hosting - ASPHostPortal :: Introduction Entity Framework 7, ASP.NET 5 and ASP.NET MVC 6

clock August 20, 2015 08:44 by author Jervis

Introduction ASP.NET 5 MVC 6 Web API and Entity Framework 7

In this post, we will only show simple example using ASP.NET 5 and new Entity Framework 7. We will cover about:

- Using the ASP.NET 5 empty template to build the Web API from scratch.
- Overview of the new project structure in VS 2015 and how to use the new dependency management tool.
- Configuring ASP.NET 5 pipeline to add only the components needed for our Web API.
- Using EF 7 commands and the K Version Manager (KVM) to initialize and apply DB migrations.

First – Create an Empty Project

Open your Visual Studio 2015 and create new project named “Registration_MVC6WebApi”

Then, select template named “ASP.NET 5 Empty”

Second Step – Adding the Dependencies

Once you have created this project, you will see there is file named “project.json” and this file contains all your project settings along with a section for managing project dependencies on other frameworks/components.

We’ve used to manage packages/dependencies by using NuGet package manager, and you can do this with the new enhanced NuGet package manager tool which ships with VS 2015, but in our case we’ll add all the dependencies using the “project.json” file and benefit from the IntelliSense provided as the image below:

So we will add the dependencies needed to configure our Web API, so open file “project.json” and replace the section “dependencies” with the section below:

"dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
        "EntityFramework": "7.0.0-beta1",
        "EntityFramework.SqlServer": "7.0.0-beta1",
        "EntityFramework.Commands": "7.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta1"
    }

The use for each dependency we’ve added as the below:

  • Microsoft.AspNet.Server.IIS: We want to host our Web API using IIS, so this package is needed. If you are planning to self-host your Web API then no need to add this package.
  • EntityFramework & EntityFramework.SqlServer: Our data provider for the Web API will be SQL Server. Entity Framework 7 can be configured to work with different data providers and not only relational databases, the data providers supported by EF 7 are: SqlServer, SQLite, AzureTableStorage, and InMemory. More about EF 7 data providers here.
  • EntityFramework.Commands: This package will be used to make the DB migrations command available in our Web API project by using KVM, more about this later in the post.
  • Microsoft.AspNet.Mvc: This is the core package which adds all the needed components to run Web API and MVC.
  • Microsoft.AspNet.Diagnostics: Basically this package will be used to display a nice welcome page when you request the base URI for the API in a browser. You can ignore this if you want, but it will be nice to display welcoming page instead of the 403 page displayed for older Web API 2.
  • Microsoft.Framework.ConfigurationModel.Json: This package is responsible to load and read the configuration file named “config.json”. We’ll add this file in a later step. This file is responsible to setup the “IConfiguration” object. 

Last thing we need to add to the file “project.json” is a section named “commands” as the snippet below:

"commands": {
        "ef": "EntityFramework.Commands"
}

We’ve added short prefix “ef” for EntityFramework.Commands which will allow us to write EF commands such as initializing and applying DB migrations using KVM.

Third Step - Adding config.json configuration file

Now right click on your project and add new item of type “ASP.NET Configuration File” and name it “config.json”, you can think of this file as a replacement for the legacy Web.config file, for now this file will contain only our connection string to our SQL DB, I’m using SQL Express here and you can change this to your preferred SQL server.

{
    "Data": {
        "DefaultConnection": {
            "Connectionstring": "Data Source=.\\sqlexpress;Initial Catalog=RegistrationDB;Integrated Security=True;"
        }
    }
}

Step no. 4 – Configure ASP.NET 5 Pipeline

This is the class which is responsible for adding the components needed in our pipeline, currently with the ASP.NET 5 empty template, the class is empty and our web project literally does nothing, I’ll add all the code in our Startup class at once then describe what each line of code is responsible for, so open file Startup.cs and paste the code below:

using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Registration_MVC6WebApi.Models;

namespace Registration_MVC6WebApi
{
    public class Startup
    {
        public static IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EF services to the services container.
            services.AddEntityFramework().AddSqlServer().AddDbContext<RegistrationDbContext>();

            services.AddMvc();

            //Resolve dependency injection
            services.AddScoped<IRegistrationRepo, RegistrationRepo>();
            services.AddScoped<RegistrationDbContext, RegistrationDbContext>();
        }
        public void Configure(IApplicationBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
            app.UseMvc();

            app.UseWelcomePage();

        }
    }
}

Step 5 – Adding Models, Database Context, and Repository

Now we’ll add a file named “Course” which contains two classes: “Course” and “CourseStatusModel”, those classes will represents our domain data model, so for better code organizing add new folder named “Models” then add the new file containing the the code below:

using System;
using System.ComponentModel.DataAnnotations;

namespace Registration_MVC6WebApi.Models
{
    public class Course
    {
        public int Id { get; set; }
        [Required]
        [StringLength(100, MinimumLength = 5)]
        public string Name { get; set; }
        public int Credits { get; set; }
    }

    public class CourseStatusModel
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
}

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “RegistrationDbContext” then paste the code snippet below:

using Microsoft.Data.Entity;
using System;
using Microsoft.Data.Entity.Metadata;

namespace Registration_MVC6WebApi.Models
{
    public class RegistrationDbContext :DbContext
    {
        public DbSet<Course> Courses { get; set; }

        protected override void OnConfiguring(DbContextOptions options)
        {
            options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
        }
    }
}

Basically what we’ve implemented here is adding our Courses data model as DbSet so it will represent a database table once we run the migrations, note that there is a new method named “OnConfiguration” where we can override it so we’ll be able to specify the data provider which needs to work with our DB context.

In our case we’ll use SQL Server, the constructor for “UseSqlServer” extension method accepts a parameter of type connection string, so we’ll read it from our “config.json” file by specifying the key “Data:DefaultConnection:ConnectionString” for the “Configuration” object we’ve created earlier in Startup class.

Lastly we need to add the interface “IRegistrationRepo” and the implementation for this interface “RegistrationRepo”, so add two new files under “Models” folder named “IRegistrationRepo” and “RegistrationRepo” and paste the two code snippets below:

IRegistrationRepo Code

using System;
using System.Collections;
using System.Collections.Generic;

namespace Registration_MVC6WebApi.Models
{
    public interface IRegistrationRepo
    {
        IEnumerable<Course> GetCourses();
        Course GetCourse(int courseId);
        Course AddCourse(Course course);
        bool DeleteCourse(int courseId);
    }
}

RegistrationRepo implementation

using System;
using System.Collections.Generic;
using System.Linq; 


namespace Registration_MVC6WebApi.Models
{
    public class RegistrationRepo : IRegistrationRepo
    {
        private readonly RegistrationDbContext _db;

        public RegistrationRepo(RegistrationDbContext db)
        {
            _db = db;
        }
        public Course AddCourse(Course course)
        {
            _db.Courses.Add(course);

            if (_db.SaveChanges() > 0)
            {
                return course;
            }
            return null;

        }

        public bool DeleteCourse(int courseId)
        {
            var course = _db.Courses.FirstOrDefault(c => c.Id == courseId);
            if (course != null)
            {
                _db.Courses.Remove(course);
                return _db.SaveChanges() > 0;
            }
            return false;
        }

        public Course GetCourse(int courseId)
        {
            return _db.Courses.FirstOrDefault(c => c.Id == courseId);
        }

        public IEnumerable<Course> GetCourses()
        {
            return _db.Courses.AsEnumerable();
        }
    }
}

The implementation here is fairly simple, what worth noting here is how we’ve passed “RegistrationDbContext” as parameter for our “RegistrationRepo” constructor so we’ve implementedConstructor Injection, this will not work if we didn’t configure this earlier in our “Startup” class.

Step 6 - Installing KVM (K Version Manager)

After we’ve added our Database context and our domain data models, we can use migrations to create the database, with previous version of ASP.NET we’ve used NuGet package manager for these type of tasks, but with ASP.NET 5 we can use command prompt using various K* commands.

What is KVM (K Version Manager)?  KVM is a Powershell script used to get the runtime and manage multiple versions of it being on the machine at the same time, you can read more about it here.

Now to install KVM for the first time you have to do the following steps:

1. Open a command prompt with Run as administrator.
2. Run the following command:

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))"

3. The script installs KVM for the current user.
4. Exit the command prompt window and start another as an administrator (you need to start a new command prompt to get the updated path environment).
5. Upgrade KVM with the following command:

KVM upgrade

Next Step - Initializing and applying migrations Database

Now our command prompt is ready to understand K commands and Entity Framework commands, first step to do is to change the directory to the project directory. The project directory contains the “project.json” file as the image below:

So in the command prompt we need to run the 2 following commands:

k ef migration add initial
k ef migration apply

Basically the first command will add migration file with the name format (<date>_<migration name>) so we’ll end up having file named “201411172303154_initial.cs” under folder named “Migrations” in our project. This auto generated file contains the code needed to to add our Courses table to our database, the newly generated files will show up under your project as the image below:

The second command will apply those migrations and create the database for us based on the connection string we’ve specified earlier in file “config.json”.

Note: the “ef” command comes from the settings that we’ve specified earlier in file “project.json” under section “commands”.

Step 8 - Adding GET methods for Courses Controller

The controller is a class which is responsible to handle HTTP requests, with ASP.NET 5 our Web API controller will inherit from “Controller” class not anymore from “ApiController”, so add new folder named “Controllers” then add new controller named “CoursesController” and paste the code below:

using Microsoft.AspNet.Mvc;
using Registration_MVC6WebApi.Models;
using System;
using System.Collections.Generic;

namespace Registration_MVC6WebApi.Controllers
{
    [Route("api/[controller]")]
    public class CoursesController : Controller
    {
        private IRegistrationRepo _registrationRepo;

        public CoursesController(IRegistrationRepo registrationRepo)
        {
            _registrationRepo = registrationRepo;
        }

        [HttpGet]
        public IEnumerable<Course> GetAllCourses()
        {
            return _registrationRepo.GetCourses();
        }

        [HttpGet("{courseId:int}", Name = "GetCourseById")]
        public IActionResult GetCourseById(int courseId)
        {
            var course = _registrationRepo.GetCourse(courseId);
            if (course == null)
            {
                return HttpNotFound();
            }

            return new ObjectResult(course);
        }

    }
}

What we’ve implemented in the controller class is the following:

1. The controller is attribute with Route attribute as the following [Route("api/[controller]")] so any HTTP requests that match the template are routed to the controller. The “[controller]” part in the template URL means to substitute the controller class name, minus the “Controller” suffix. In our case and for “CoursesController” class, the route template is “api/courses”.

2. We’ve defined two HTTP GET methods, the first one “GetAllCourses” is attributed with “[HttpGet]” and it returns a .NET object which is serialized in the body of the response using the default JSON format.

3. The second HTTP GET method “GetCourseById” is attributed with “[HttpGet]“. For this method we’ve specified a constraint on the parameter “courseId”, the parameter should be of integer data type. As well we’ve specified a name for this method “GetCourseById” which we’ll use in the next step. Last thing this method returns object of type IActionResult which gives us flexibility to return different actions results based on our logic, in our case we will return HttpNotFound if the course does not exist or we can return serialized JSON object of the course when the course is found.

4. Lastly notice how we are passing the “IRegistrationRepo” as a constructor for our CoursesController, by doing this we are implementing Constructor Injection.

Last Step - Adding POST and DELETE methods for Courses Controller

Now we want to implement another two HTTP methods which allow us to add new Course or delete existing one, so open file “CoursesController” and paste the code below:

[HttpPost]
public IActionResult AddCourse([FromBody] Course course)
{
                if (!ModelState.IsValid)
                {
                                Context.Response.StatusCode = 400;
                                return new ObjectResult(new CourseStatusModel { Id = 1 , Description= "Course model is invalid" });
                }
                else
                {
                   var addedCourse =  _registrationRepo.AddCourse(course);

                                if (addedCourse != null)
                                {
                                                string url = Url.RouteUrl("GetCourseById", new { courseId = course.Id }, Request.Scheme, Request.Host.ToUriComponent());

                                                Context.Response.StatusCode = 201;
                                                Context.Response.Headers["Location"] = url;
                                                return new ObjectResult(addedCourse);
                                }
                                else
                                {
                                                Context.Response.StatusCode = 400;
                                                return new ObjectResult(new CourseStatusModel { Id = 2, Description = "Failed to save course" });
                                }                
                }

}



SQL Hosting with ASPHostPortal :: Using SQLBulkCopy and C# to Upload File

clock August 12, 2015 08:17 by author Jervis

In this article I am going to write about SQLBulkCopy and its major properties and methods. This article will give you the code for high performance transfer of rows from XML file to SQL server with SQLBulkCopy and C#.

SQLBulkCopy introduced as part of .Net framework 2.0. It is simple and easy tool to transfer complicated or simple data from one data source to other. You can read data from any data source as long as that data can be load to DataTable or read by IDataReader and transfer the data with high performance to SQL Server using SQLBulkCopy.

In real time applications every day millions of records get transferred from one data store to other. There are multiple ways to transfer the data like command prompt bcp utility of SQL Server, creating INSERT statements, creating SSIS packages and SQLBulkCopy. SQLBulkCopy gives you significant performance gain over other tools.

SQLBulkCopy Constructor

SQLBulkCopy initializes instance in four different way.

1. Accepts already open SqlConnection for destination.
2. Accepts connection string of SQLConnection. This constructor actually opens and initializes new instance of SQLConnection for destination.
3. Accepts connection string of SQLconnection and enum value of SqlBulkCopyOptions. This constructor actually opens and initializes new instance of SQLConnection for destination.
4. Accepts already opened SQLConnection and enum value of SqlBulkCopyOptions.

SqlBulkCopy bulkCopy =
            new SqlBulkCopy(destinationConnection.ConnectionString, 
                SqlBulkCopyOptions.TableLock))

BatchSize

SQLBulkCopy BatchSize is integer property with default value of 0. It decides how many rows need to be send to the server in one batch. If you do not set any value for this property or set it as 0, all the records will be send in single batch.

Following example sets BatchSize property as 50.

bulkCopy.BatchSize = 50;

ColumnMappings

SQLBulkCopy ColumnMappings is a collection of columns which needs to be map from source table to destination table's columns. You do not need to map the columns if column names are same. However it is very important to map the columns if column names are different. If matching SQLBulkCopy does not found the matching column it throws System.InvalidOperationException.

You can map the columns in different ways, giving both column names is easy and readable method.

Below code match the column OrderID from source table with columnNewOrderID of destination column.

bulkCopy.ColumnMappings.Add("OrderID", "NewOrderID");  

Data Type issue while mapping the column

SqlBulkCopy is particular about matching column DataType. Both the columns has to be of same DataType. If you have nullable columns, you explicitly have to convert such columns into desired DataType.

Below code converts Null to varchar(2) and can be mapped to any varchar(2) column of destination table.

SELECT  CAST(ISNULL(ShipRegion,'') as varchar(2))
            as ShipRegion FROM Orders

Quick note: If you are having computed columns like SUM, AVG etc. make sure it returns in expected DataType. If your destination table expects columns with decimal(15,7) you will have to explicitly convert the source column as decimal(15,7) because SUM will by default return decimal(38,7).

DestinationTableName

It sets the name of destination table. The method WriteToServer will copy the source rows to this particular table.

Below code will set the destination table as "TopOrders".

bulkCopy.DestinationTableName = "TopOrders";   

NotifyAfter and SqlRowsCopied

NotifyAfter is an integer property with default value of 0 and SqlRowsCopied is an event. The value of NotifyAfter indicates when to raise eventSqlRowsCopied.

The below code shows after processing 100 rows, event SqlRowsCopied will be executed.

bulkCopy.SqlRowsCopied +=
    new SqlRowsCopiedEventHandler(OnSqlRowsTransfer);
bulkCopy.NotifyAfter = 100;

private static void
    OnSqlRowsTransfer(object sender, SqlRowsCopiedEventArgs e)
{
        Console.WriteLine("Copied {0} so far...", e.RowsCopied);
}

WriteToServer

WriteToServer is a method which actually processes your source table data to destination table. It accepts array of DataRows or DataTable or IDataReader. With DataTable you can also specify the state of the rows that needs to be processed.

The following code will process rows from sourceData DataTable which has RowState as Added to DestinationTable.

bulkCopy.WriteToServer(sourceData, DataRowState.Added);



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in