Saturday, 29 August 2015

Start Working With NodeJS And SqlLite On Windows using Visual Studio


Assumptions

This article expects that you have at least a minimal understanding of .NET development and object-oriented programming concepts. With a heavy focus on web development,this article also assumes that you have a basic understanding of ASP.NET, including the core concepts of web development contained in ASP.NET, such as clients and servers,HTML, CSS, JavaScript, and HTTP post/get.
The article also assumes that you have an IDE in which to work, specifically a fairly recent version of Visual Studio.

Source code:


Introduction

Well, I believe the first thing which comes in mind here is what is nodeJs and why nodeJS?
If you have working knowledge of JavaScript and some other server side technology like ASP.NET,PHP or JSP then definitely you will understand why nodeJS?

What is NodeJS

Till now we had a concept like javascript is meant for client side scripting only but 'NO'. JavaScript has server side version called nodeJS which behaves or is like other server side technologies like asp.net,php,jsp .Node.js  but allows you to run JavaScript code in the back end, outside a browser. In order to execute the JavaScript you intend to run in the back end, it needs to be interpreted and, well, executed. This is what Node.js does, by making use of Google's V8 VM, the same run-time environment for JavaScript that Google Chrome uses.

Why NodeJS

Simple, Node.js has great capability when implementing real-time web applications using push technology over web-sockets. What is great about it? It is almost after 2 decades we have worked with stateless of web application, we finally have web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely. This is in contrast to the typical web response pattern , where the client always initiates communication. Apart, it’s all based on the open web stack (HTML, CSS and JS) running over the standard port 80.all free :)
Plus, Node.js ships with a lot of useful modules, so you don't have to write everything from scratch, like for example something that outputs a string on the console.
If javascript runs on server side the question arises here is how to install environment to start with  nodeJS .Here are the ways you can setup or install nodeJS
So you can say nodeJS technology is all about real-time applications

Features of Node.js

Following are some of the important features that make Node.js the first choice of software architects.
  • Asynchronous and Event Driven All APIs of Node.js library are asynchronous that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
  • Very Fast Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.
  • Single Threaded but Highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.
  • No Buffering - Node.js applications never buffer any data. These applications simply output the data in chunks.
  • License - Node.js is released under the MIT license

Install Node.js Tools for Visual Studio

Available Releases
  • NTVS 1.1 Beta includes support for Visual Studio 2012, 2013, and 2015 RC
  • NTVS 1.0 includes support for Visual Studio 2012 and 2013
  • Dev Builds include the most recent changes and bugfixes (available for Visual Studio 2012, 2013, and 2015)
  • Older NTVS releases are also available.

Installation Steps:

STEP1 download windows installer on basis of your visual studio version you have from above location .once downloaded you will find below installer like shown below


STEP2
Click on above windows installer, you will see below screen. Accept terms and click Next



STEP3 NTVS requires a Node.js interpreter to be installed. You can use a global installation of Node.js or you can specify the path to a local interpreter in each of your Node.js projects.
Node.js is built for 32-bit and 64-bit architectures. NTVS supports both. Only one is required and the Node.js installer only supports one being installed at a time. NTVS works with Node.js v0.10.20 or later.


Package management

npm is the pre-installed package manager for the Node.js server platform exactly like Nget Package Manager for .Net IDE environment. It is used to install Node.js programs from the npm registry. By organizing the installation and management of third-party Node.js programs, it helps developers build faster. The packages found in the npm registry can range from simple helper libraries like Underscore.js to task runners like Grunt.
Below is the screen shot of NPM

Start a new Node.js project in Visual Studio

Starting a new Node.js project like shown below
  1. Start Visual Studio.On the File menu, click New, and then click Project like other type of projects.
  2. In the New Project window, expand the Installed menu selection, expand Templates, and click JavaScript. In the main window, select Blank Node.js Web Application. Now your choice of choosing a path and name for your project, and then click OK.

  3. You will be presented with the following screen. You will SEE server.js file in the Solution Explorer .You will see sample or default "Hello world" application  like shown below
  4. You can now debug your node.js web application in your preferred browser like shown below.

  5. OUTPUT will be like

LET US ANALYZE A DEFAULT  "Hello World" app in Node.js

Here’s the code used in the server.js file

The generated code example or sample program shows you how to output "Hello World" in the browser. Let me explain how the generated code in server.js works line by line. 

Line 1

var http = require('http');
Node.js has a simple module and dependencies loading system. You simply call the function "require" with the path of the file or directory containing the module you would like to load at which point a variable is returned containing all the exported functions of that module.

Line 2

var port = process.env.port || 1337;
On this line, we want to determine on which port the HTTP server serving the HTML should run. If a port number is specified in the environment variables, we will use that one or we will simply use 1337.

Line 3

http.createServer(function (req, res) {
We want to create a server to handle HTTP requests. We will also pass the createServer function a function callback containing two parameters to a handle each individual request and return a response.   if you’ve never encountered callback functions in JavaScript. The request received is passed in the req parameter and the response is expected to written to the res parameter.

Line 4

res.writeHead(200, { '
Content-Type’: '
text/plain’ });
Any HTTP response requires a status-line and headers, . In this case, we want to return 200 OK as the status response and to specify the content-type as plain text. We specify this by calling the writeHead function on the response object.

Line 5

res.end('
Hello World\n’);
Once we are done writing the response we want to call the end function. We can also pass the final content through the end function, in this case we want to send the string "Hello World" in plain text.

Line 6

}).listen(port);
We close off the callback and call the function listen at the port we defined earlier, this will start the server and start accepting requests sent to the defined port.
To see the result, you can start debugging by pressing on the button shown in the previous screenshot. You can see "Hello World" in the browser.



 You have now successfully run a Node.js app on Windows 8.1 using Visual Studio 2013.

INTERACTING WITH DATABASE:

For Simplicity I am going to use SQLLite database . you can use any database here is the explanation Database Drivers
SQLite is transaction database engine, it means you can run DDL and DML queries of SQL. DDL queries deal with creation of database, tables, view etc where as DML queries are responsible for CRUD operation (insert,delete,update) etc. Here is a code to create SQLite database and performing SQL operations.

GET SQLLITE PACKAGE FOR NODEJS

Go to nodejs console and run


Modify existing sample code with below line

Just Click on Debug/Run in visual studio and the output will be like shown below

To run and analyse the code, you can simply use breakpoints in visual studio and see whether it creates Employee_Master table  and add two columns[EmployeeId,EmployeeName) with some 10  numbers of rows. You can view number of rows from  console because console.log is displaying all the rows from created table
OR
if you will open sqllite database using admin tool you will see below screen with table name Emplyee_Master

  1.  

    More learning for Node on Azure

    For more in-depth learning on node, my course is available here on Microsoft Virtual Academy.

Saturday, 11 April 2015

CSS3 Explained with live example ? Why it is required?


SEE LIVE Example

What are CSS3 Animations?

The CSS animation feature was introduced into Webkit in 2007. In 2009 a working draft was written and added to the w3c site.
To use CSS animation, the most important and key concept is key-frames.you first specify some keyframes for the animation - basically what styles will the element have at certain times. The browser does the rest for you.
Animation is the process of creating motion and shape change or in real , illusion by means of the rapid display of a sequence of static images that minimally differ from each other. An animation lets an element gradually change from one style to another.
If you want to achieve such motion or movement of elements on web  using css3 (rather than depending on tools like flash,silverlight..) you can define it as CSS3 animation  You can change as many CSS properties you want, as many times you want.To use CSS3 animation, you must first specify some keyframes for the animation.Keyframes hold what styles the element will have at certain times .

Why CSS3 includes animation?

People who have experienced or worked with web they will definitely realize that animation was possible only by using heavy tools like flash ,silverlight..which was more about moving web experiences/website designing to software development components… In other words, we were using above mentioned tools for creating animation components which was heavy ,dependent and cumbersome experience.I don't disagree that Flash, Silver-light, AJAX, CSS – are all merely tools and all of them powerful in their own way – all of them appropriate for certain application.
It is really great and very exciting that CSS3 styling language has support for Animation – Agree,we still have to wait bit to see how the standard is implemented across all browsers
Finally leaving all religious favor-ism to tools  ,we have to agree css3 with animation is big change in web experience and will give boost to web experience

CSS3 ADVANTAGES:


There are mainly three key advantages over traditional Flash/silverlight and JS script-driven animation techniques:
  1. CSS3 Animation is declarative and easy to use for simple animations; you can create them without even having to know JavaScript.
  2. The animations run well because rendering engine can use frame-skipping and other techniques to keep the performance as smooth as possible.
  3. Giving power to browser for control the animation sequence which is surely optimized and efficient, for example, reducing the update frequency of animations running in tabs that aren't currently visible.


The Building Blocks of Animations

CSS animations are made up of two basic building blocks.
  1. Keyframes - define the stages and styles of the animation.
  2. Animation Properties - assign the @keyframes to a specific CSS element and define how it is animated.

1 )@keyframes

When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times.To make an animation work on webpage, we must bind bind the animation to respective element like div,span,image...
Let us take simple example to understand css3 animation
The following example binds the "example" animation to the <div> element. The animation will lasts for 4 seconds, and it will gradually reduce the width   of the <div> element from 100px to 10px:

SEE LIVE Example


 


After change animation-count property to infinite




<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 400px;
height: 100px;
background-color: red;
-webkit-animation-name: example; /* Chrome, Safari, Opera */
-webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 4s;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes example {
from {width: 400px;}
to {width: 10px;}
}

/* Standard syntax */
@keyframes example {
from {width: 400px;}
to {width: 10px;}
}
</style>
</head>
<body>


<div></div>

<p><b>See:</b> When an animation is over, it will return its  original style.</p>

</body>
</html>
In the example above we have specified when the style will change by using the keywords "from" and "to" (which represents 0% (start) and 100% (complete)).


2: Animation Properties

Once the @keyframes are defined, the animation properties must be added in order for your animation to function.
Animation properties do two things:
  1. They assign the @keyframes to the elements that you want to animate.
  2. They define how it is animated.
The animation properties are added to the CSS selectors (or elements) that you want to animate. You must add the following two animation properties for the animation to take effect:
  • animation-name: The name of the animation, defined in the @keyframes.
  • animation-duration: The duration of the animation, in seconds (e.g., 5s) or milliseconds (e.g., 200ms).

Delay an Animation

The animation-delay property specifies a delay for the start of an animation.The following example has a 3 seconds delay before starting the animation:
Example
div {
    width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-delay: 3s;
}

Set How Many Times an Animation Should Run

The animation-iteration-count property specifies the number of times an animation should run.
The following example will run the animation 5 times before it stops:
Example
div {
   width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: 5;
}

The following example uses the value "infinite" to make the animation continue for ever:
Example
div {
   width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: infinite;
}

Run Animation in Reverse Direction or Alternate Cycles

The animation-direction property is used to let an animation run in reverse direction or alternate cycles.
The following example will run the animation in reverse direction:
Example
div {
    width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: 3;
    animation-direction: reverse;
}

The following example uses the value "alternate" to make the animation first run forward, then backward, then forward:
Example
div {
    width: 400px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
    animation-iteration-count: 3;
    animation-direction: alternate;
}

Specify the Speed Curve of the Animation

The animation-timing-function property specifies the speed curve of the animation.
The animation-timing-function property can have the following values:
  • ease - specifies an animation with a slow start, then fast, then end slowly (this is default)
  • linear - specifies an animation with the same speed from start to end
  • ease-in - specifies an animation with a slow start
  • ease-out - specifies an animation with a slow end
  • ease-in-out - specifies an animation with a slow start and end
  • cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function
The following example shows the some of the different speed curves that can be used:
Example
#div1 {animation-timing-function: linear;}
#div2 {animation-timing-function: ease;}
#div3 {animation-timing-function: ease-in;}
#div4 {animation-timing-function: ease-out;}
#div5 {animation-timing-function: ease-in-out;}

How to use CSS3 animation


All in one example


The animations presented below involve setting up a transformation to take place in response to a mouseover or other event. Then, rather than applying the effect instantly, we assign a transition timing function which causes the transformation to take place incrementally over a set time period.

This is all illusion what we are creating with below sprite image with all possible steps of human while walking. you can choose horse,tiger .. any sprite image and find same animation.In reality we are showing one image at once with small small delay,which make feeling like an object is walking.
Let's get the  use for step easing out of the way: sprite animation.  The implementation is simple: jump the position of a background-image (which has all the frames of an animation laid out side-by-side) so that we see one "frame" at a time:



 

Steps()

The steps() function controls exactly how many keyframes will render in the animation time-frame.

Complete Stunning Example


<html>
<head> 
<title>Hello this is test</title>
<style>
    .runninggirl {
        margin-left: 400px;
        width: 68px;
        height: 100px;
        background-image: url("http://www.shabirhakim.net/img/ladyrun.png");
        -webkit-animation: play .8s steps(5) infinite;
        -moz-animation: play .8s steps(5) infinite;
        -ms-animation: play .8s steps(5) infinite;
        -o-animation: play .8s steps(5) infinite;
        animation: play .8s steps(5) infinite;
    }

    @-webkit-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @-moz-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @-ms-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @-o-keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }

    @keyframes play {
        from {
            background-position: 0px;
        }

        to {
            background-position: -500px;
        }
    }
</style>
</head>

<body>
<div class="runninggirl">
</div>
</body>
</html> 

SEE LIVE Example

 More Resources

Sunday, 21 December 2014

WMI Explained and How to use with .NET

WMI Explained and How to use with .NET

WMI is not new but as old as windows. WMI full form is Windows Management Instrumentation, which is basically an interface to the Windows OS system settings, drivers ,hardware.... .You can use wmi to intrograte windows system and servers along with network . WMI use scripting language like VnScript,JScript(not javaScript) to interact with windows.
Later microsoft integrated WMI namespace available in .NET. So, we  can use WMI with c#,vb.net(all language which work on .net)
A .NET developer can use WMI to obtain information about drivers installed on the client machine, verify whether the system is licensed or not, check for hardware information of each and every deveice and a lot more.
WMI is a very powerfull tool, and once you know how to get what you need, it can be invaluable as a time saver. When developing Windows applications, developers often need information a system, either local or remote, that although commonplace, can be very tough to get. There is using the remote registry, but I myself do not allow remote registry access as do many network admins. WMI is usually wide open on networks, assuming you have the required rights to query it .

WMI Architecture

The purpose of WMI is to present a uniform interface to any local or remote applications or scripts that need to access management data from a computer system, network or application. Thanks to WMI, programs do not have to talk to a wide variety of operating system APIs which can be particularly inconvenient for scripting languages.
All WMI interfaces are based on the Component Object Model (COM), however it is possible to access WMI from .NET thanks to the COM Inter-Op mechanism, as our diagram shows.




The main parts of WMI are as follows:
Managed objects and providers: A WMI provider is a COM object that monitors one or more managed objects for WMI. Like a driver, a provider extracts WMI data from a managed object and is responsible for passing messages from WMI back to the managed object.
WMI infrastructure: As a Windows component WMI consists of the Windows Management service, which includes the WMI Core, and the WMI repository. The service acts as an intermediary between the providers and the repository. Only static data about objects, such as the classes defined by the providers, are stored in the repository.
Management applications and scripts: A management application queries management information either by calling the COM API for WMI or through the Scripting API for WMI.
Assume you have to Query a database, you will choose SQL to query it likewise  we have WQL to Query a windows system
If you know the provider classes and the fields available, then you can get the info very easily.  For instance, if you wanted to get a list of logical drives from a system you would use the following query:
Select * from Win32_LogicalDisk
You can, however, refine the search by using where clauses and getting specific "fields" in the query. The following query gets the amount of freespace, the size, and the name of all fixed disk drives:
Select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3
As you can see, constructing a simple WMI query is quite easy.  To get results, you need and interface, and in .Net it is provided by the System.Management namespace.  To make it work all you need is a query, and a little bit of code, just as if you were querying a database.
Note : while starting working with WMI make sure you set refrence to system.management.instrumentation. namespace

What Is WMI Provider?

WMI Provider is a software component that functions as a mediator between the CIM Object Manager and managed objects. By using the WMI APIs, providers supply the CIM Object Manager with data from managed objects, handle requests on behalf of management applications, and generate event notifications.

Microsoft WMI Code Creator

The Microsoft WMI Code Creator application  here. once downloaded and ran locally,you will see below screen
 
 “The WMI Code Creator tool allows you to generate VBScript, C#, and VB.NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.”.I you will see below ,it generates code as per your choice
 
 CONTINUE....
Further readings http://msdn.microsoft.com/en-us/library/ms257353%28v=vs.80%29.aspx

Sunday, 7 December 2014

Uploading and Importing CSV file to SQL Server using WebAPI


Uploading and Importing CSV file to SQL Server  using WebAPI

Assumption: Basic knowledge of MVC and WebApi
Download Source code:
Few weeks ago I was working with a WebAPI services . These services are consumed by multiple devices like IOS,Andriod....which involves uploading CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project which i will believe will save somebodies time. In this post I will demonstrate how to create WebApi and upload and import CSV file to SQL Server database.

 Step 1: Create WebApi Service Application using your favourite IDE like shown below




Step 2:Modify Web.Config with sql connection details






Step 3: Modify UploadController with below class


public class UploadController : ApiController
    {
        [Route("api/Device/PostUpload")]
        [HttpPost]
        [ActionName("PostUpload")]
        public string PostUpload()
        {
            string individualExtractPath = null;
            StreamReader sr = null;
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                //making file unique,you can use GUID also
                string fileName = request.Files[0].FileName + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
                string DeviceId = request.Form["DeviceId"];
                //check for column key id
                if (DeviceId == null || "null".Equals(DeviceId.ToLower()))
                {
                   return "UnRegistered";

                }   
                string strFileExtractPath = HttpRuntime.AppDomainAppPath;
                strFileExtractPath = Path.Combine(strFileExtractPath, "UploadExtract");

                if (!Directory.Exists(strFileExtractPath))
                {
                    Directory.CreateDirectory(strFileExtractPath);
                }

                individualExtractPath = Path.Combine(strFileExtractPath, fileName);
                Directory.CreateDirectory(individualExtractPath);
                request.Files[0].SaveAs(individualExtractPath + "\\" + request.Files[0].FileName);
                string strUnzipedFilesLocation = Path.Combine(individualExtractPath, "unzipedFiles");
                Directory.CreateDirectory(strUnzipedFilesLocation);
                ZipFile.ExtractToDirectory(individualExtractPath + "\\" + request.Files[0].FileName, strUnzipedFilesLocation);
                ArrayList fileList = new ArrayList();
                // Get the files in the Directory
                string[] files = Directory.GetFiles(strUnzipedFilesLocation);

                int len = files.Length;

                for (int i = 0; i < len; i++)
                {
                    string filename = files[i];

                    // Add into the ArrayList
                    fileList.Add(System.IO.Path.GetFileName(filename));
                    FileInfo uploadFile = new FileInfo(filename);
                    sr = new StreamReader(filename);
                    DataTable oDataTable = null;
                    int RowCount = 0;
                    string[] ColumnNames = null;
                    string[] oStreamDataValues = null;
                    //using while loop read the stream data till end
                    while (!sr.EndOfStream)
                    {
                        String oStreamRowData = sr.ReadLine().Trim();
                        if (oStreamRowData.Length > 0)
                        {
                            oStreamDataValues = oStreamRowData.Split(',');
                            //Bcoz the first row contains column names, we will poluate 
                            //the column name by
                            //reading the first row and RowCount-0 will be true only once
                            if (RowCount == 0)
                            {
                                RowCount = 1;
                                ColumnNames = oStreamRowData.Split(',');
                                oDataTable = new DataTable();
                                //using foreach looping through all the column names
                                foreach (string csvcolumn in ColumnNames)
                                {
                                    DataColumn oDataColumn = new DataColumn(csvcolumn.ToUpper(), typeof(string));
                                    //setting the default value of empty.string to newly created column
                                    oDataColumn.DefaultValue = string.Empty;
                                    //adding the newly created column to the table
                                    oDataTable.Columns.Add(oDataColumn);
                                }
                            }
                            else
                            {
                                //creates a new DataRow with the same schema as of the oDataTable            
                                DataRow oDataRow = oDataTable.NewRow();
                                //using foreach looping through all the column names
                                for (int c = 0; c < ColumnNames.Length; c++)
                                {
                                    oDataRow[ColumnNames[c]] = oStreamDataValues[c] == null ? string.Empty : oStreamDataValues[c].ToString();
                                }
                                //adding the newly created row with data to the oDataTable       
                                oDataTable.Rows.Add(oDataRow);
                            }
                        }
                    }
                    //close the oStreamReader object
                    sr.Close();
                    //release all the resources used by the oStreamReader object
                    sr.Dispose();
                    //Creating two additinal columns dynamically because mobile trip file doesn't provide that

               
                    DataTable dtFinal = oDataTable;
                    //Class Bulk Insert here
                    BulkInsertTripFile(oDataTable);

                }

                return "File SuccessFully Posted";
            }
            finally
            {
                try
                {
                  
                    if (!string.IsNullOrEmpty(individualExtractPath) && Directory.Exists(individualExtractPath))
                    {
                        //If any such directory then creates the new one
                        DeleteDirectory(individualExtractPath);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// After uploading file ,just need
        /// </summary>
        /// <param name="target_dir"></param>
        private static void DeleteDirectory(string target_dir)
        {
            string[] files = Directory.GetFiles(target_dir);
            string[] dirs = Directory.GetDirectories(target_dir);

            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }

            Directory.Delete(target_dir, false);
        }
        /// <summary>
        /// Method for Trip Detail bulk insert with datatable as parameter
        /// </summary>
        /// <param name="dt"></param>
        private void BulkInsertTripFile(DataTable dt)
        {

            string connString = System.Configuration.ConfigurationManager.AppSettings["BulkDemo"];

            // Copy the DataTable to SQL Server
            using (SqlConnection dbConnection = new SqlConnection(connString))
            {
                dbConnection.Open();
                using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
                {
                    s.DestinationTableName = "TripTable";
                    foreach (var column in dt.Columns)
                        s.ColumnMappings.Add(column.ToString(), column.ToString());
                    s.WriteToServer(dt);
                }
            }
        }
    }

step 4:Create view based on html page or you can create android or ios page for uploading/posting file
   
Hope this helps ... Shabir

Friday, 28 November 2014

C# Important Code Snippets and Utility Function


      public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }
        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

       public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
 
      public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
      public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }
  
     public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }
  
  public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }
  
  public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
  
   public class PGUtil
    {
        private static WindowsImpersonationContext impersonationContext;

        public PGUtil()
        {
        }

        public static string[] AppendArrayElement(string[] array, object param)
        {
            string[] strArrays;
            if ((array == null ? false : param != null))
            {
                List list = array.ToList();
                list.Add(param.ToString());
                strArrays = list.ToArray();
            }
            else
            {
                strArrays = array;
            }
            return strArrays;
        }

        public static string ArraytoString(object[] strArr)
        {
            string str;
            string str1;
            string returnString = string.Empty;
            if (strArr != null)
            {
                for (int i = 0; i < (int)strArr.Length; i++)
                {
                    if (strArr[i] == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = strArr[i].ToString();
                    }
                    if (!string.IsNullOrEmpty(str1))
                    {
                        returnString = string.Concat(returnString, strArr[i], (i < (int)strArr.Length - 1 ? "," : ""));
                    }
                }
                str = returnString;
            }
            else
            {
                str = null;
            }
            return str;
        }

      

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
        public static extern bool CloseHandle(IntPtr handle);

        public static DataSet CreateDummyScalarDataSet(string columnValue)
        {
            return PGUtil.CreateDummyScalarDataSet(null, columnValue);
        }

        public static DataSet CreateDummyScalarDataSet(string columnName, string columnValue)
        {
            DataSet ds = null;
            try
            {
                ds = new DataSet();
                DataTable tbl = new DataTable();
                tbl.Columns.Add("Id");
                tbl.Rows.Add(new object[] { columnValue });
                ds.Tables.Add(tbl);
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return ds;
        }

        public static int dateComparison(DateTime date1, DateTime date2)
        {
            return DateTime.Compare(date1, date2);
        }

        

        public static string FormatCSVstring(string inputString)
        {
            string str;
            string outPutString = string.Empty;
            try
            {
                inputString = PGUtil.escapeSpecialChar(inputString);
                string[] arrData = inputString.Split(new char[] { ',' });
                for (int i = 0; i < (int)arrData.Length; i++)
                {
                    string tempString = string.Format("'{0}'", arrData[i]);
                    outPutString = (i != 0 ? string.Concat(outPutString, ",", tempString) : tempString);
                }
                str = outPutString;
            }
            catch
            {
                str = inputString;
            }
            return str;
        }

        public static string FormatOracleDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("dd-MMM-yyyy");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(string date)
        {
            string str;
            string str1;
            try
            {
                if (!date.Equals("NULL"))
                {
                    if (date == null)
                    {
                        str1 = null;
                    }
                    else
                    {
                        str1 = PGUtil.ToDateTime(date).ToString("yyyy-MM-dd");
                    }
                    str = str1;
                }
                else
                {
                    str = null;
                }
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatSQLDate(DateTime date)
        {
            string str;
            try
            {
                str = date.ToString("yyyy-MM-dd");
            }
            catch
            {
                str = date.ToString();
            }
            return str;
        }

        public static string FormatString(string formatString, params string[] values)
        {
            string str;
            if (!string.IsNullOrEmpty(formatString))
            {
                if (values == null)
                {
                    throw new ArgumentNullException("values");
                }
                for (int index = 0; index < (int)values.Length; index++)
                {
                    formatString = formatString.Replace(string.Concat("{", index, "}"), values[index]);
                }
                str = formatString;
            }
            else
            {
                str = formatString;
            }
            return str;
        }

        public static DateTime GetCurrentIndiaDate()
        {
            return DateTime.UtcNow.AddHours(5.5);
        }

        public static TimeSpan GetCurrentIndiaTime()
        {
            return DateTime.UtcNow.AddHours(5.5).TimeOfDay;
        }

        public static object GetDataFromSession(string key)
        {
            object returnValue = null;
            try
            {
                returnValue = HttpContext.Current.Session[key];
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            return returnValue;
        }

        public static T GetDataFromSession(string key)
        {
            T item;
            T returnValue = default(T);
            try
            {
                if (HttpContext.Current.Session[key] is T)
                {
                    item = (T)HttpContext.Current.Session[key];
                    return item;
                }
            }
            catch (Exception exception)
            {
                LogHandler.getInstance().Log(exception);
            }
            item = returnValue;
            return item;
        }

        public static int getMonthsBetweenDates(DateTime startDate, DateTime endDate)
        {
            int count = 0;
            if (endDate > startDate)
            {
                int year = endDate.Year - startDate.Year;
                int month = endDate.Month - startDate.Month + 1;
                count = year * 12 + month;
            }
            return count;
        }
 

        public static bool isValidEmail(string email)
        {
            bool flag;
            string MatchEmailPattern = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?\r\n\t\t\t\t                [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
            flag = (email == null ? false : Regex.IsMatch(email, MatchEmailPattern));
            return flag;
        }

        public static bool isValidURL(string url)
        {
            return Regex.IsMatch(url, "(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
        }

        public static string[] LASTMONTH()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int year = dateTime.Year;
            dateTime = DateTime.UtcNow.AddHours(5.5);
            int month = dateTime.Month;
            DateTime lastDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            lastDate = lastDate.AddDays(-1);
            if (month != 1)
            {
                month--;
            }
            DateTime firstDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTQTR()
        {
            string[] dates = new string[2];
            DateTime dateTime = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (dateTime.Month - 1) / 3 + 1;
            if (quarterNumber != 1)
            {
                quarterNumber--;
            }
            dateTime = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(dateTime.Year, (quarterNumber - 1) * 3 + 1, 1);
            dateTime = firstDate.AddMonths(3);
            DateTime lastDate = dateTime.AddDays(-1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

        public static string[] LASTYEAR()
        {
            string[] dates = new string[2];
            int year = DateTime.UtcNow.AddHours(5.5).Year;
            year--;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            DateTime lastDate = new DateTime(Convert.ToInt32(year), 12, 31);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            dates[1] = PGUtil.FormatSQLDate(lastDate);
            return dates;
        }

       
        public static string[] QTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int quarterNumber = (utcNow.Month - 1) / 3 + 1;
            utcNow = DateTime.UtcNow.AddHours(5.5);
            DateTime firstDate = new DateTime(utcNow.Year, (quarterNumber - 1) * 3 + 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }

        public static void ReDimArray(ref string[] sourceArray, int newLength)
        {
            if (newLength >= (int)sourceArray.Length)
            {
                string[] newArray = new string[newLength];
                for (int i = 0; i < (int)sourceArray.Length; i++)
                {
                    newArray[i] = sourceArray[i];
                }
                sourceArray = newArray;
            }
        }

       

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body)
        {
            bool flag = PGUtil.SendEmail(server, AuthUser, password, subject, from, recipients, body, null);
            return flag;
        }

        public static bool SendEmail(string server, string AuthUser, string password, string subject, string from, string recipients, string body, string fileNames)
        {
            int i;
            bool status = true;
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(server);
                mail.From = new MailAddress(from);
                char[] chrArray = new char[] { ',' };
                string[] strArrays = recipients.Split(chrArray);
                for (i = 0; i < (int)strArrays.Length; i++)
                {
                    string eachRecipient = strArrays[i];
                    if (!string.IsNullOrEmpty(eachRecipient))
                    {
                        mail.To.Add(eachRecipient);
                    }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                body = HttpUtility.HtmlDecode(body);
                mail.Body = body;
                if (!string.IsNullOrEmpty(fileNames))
                {
                    Attachment attachment = null;
                    chrArray = new char[] { ',' };
                    strArrays = fileNames.Split(chrArray);
                    for (i = 0; i < (int)strArrays.Length; i++)
                    {
                        string eachAttachment = strArrays[i];
                        if ((string.IsNullOrEmpty(eachAttachment) ? false : File.Exists(eachAttachment)))
                        {
                            attachment = new Attachment(fileNames);
                            mail.Attachments.Add(attachment);
                        }
                    }
                }
                SmtpServer.Port = 25;
                SmtpServer.Credentials = new NetworkCredential(AuthUser, password);
                SmtpServer.EnableSsl = false;
                SmtpServer.Send(mail);
            }
            catch (Exception exception)
            {
                Exception e = exception;
                status = false;
                LogHandler.getInstance().Log(e);
            }
            return status;
        }

        public static int timeComparison(TimeSpan time1, TimeSpan time2)
        {
            return TimeSpan.Compare(time1, time2);
        }

        public static bool ToBoolean(object str)
        {
            bool flag;
            try
            {
                flag = Convert.ToBoolean(str);
                return flag;
            }
            catch
            {
            }
            flag = false;
            return flag;
        }

        public static DateTime ToDateTime(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            string strDate = str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(strDate);
            }
            catch
            {
            }
            return dateTime;
        }

        public static string ToDBString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) || string.IsNullOrEmpty(obj.ToString()) ? "NULL" : obj.ToString());
        }

        public static double ToDouble(object str)
        {
            double num;
            try
            {
                num = Convert.ToDouble(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static int ToInt(object str)
        {
            int num;
            try
            {
                num = Convert.ToInt32(str);
                return num;
            }
            catch
            {
            }
            num = 0;
            return num;
        }

        public static long ToInt64(object str)
        {
            long num;
            try
            {
                num = Convert.ToInt64(str);
                return num;
            }
            catch
            {
            }
            num = (long)0;
            return num;
        }

        public static string ToString(object obj)
        {
            return (obj == null || Convert.IsDBNull(obj) ? "" : obj.ToString());
        }

        public static bool TryParseDate(object str)
        {
            DateTime dateTime = DateTime.MinValue;
            bool flag = true;
            str.ToString();
            try
            {
                dateTime = Convert.ToDateTime(str);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool tryParseInt(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToInt32(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseRealNumber(object num)
        {
            bool flag = true;
            try
            {
                Convert.ToDouble(num);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool TryParseWholeNumber(object num)
        {
            bool flag1;
            bool flag = true;
            if (!(num as string).Contains("."))
            {
                try
                {
                    Convert.ToInt32(num);
                }
                catch
                {
                    flag = false;
                }
                flag1 = flag;
            }
            else
            {
                flag1 = false;
            }
            return flag1;
        }

        public static void UndoImpersonation()
        {
            PGUtil.impersonationContext.Undo();
        }

        public static string[] YTD()
        {
            string[] dates = new string[2];
            DateTime utcNow = DateTime.UtcNow.AddHours(5.5);
            int year = utcNow.Year;
            DateTime firstDate = new DateTime(Convert.ToInt32(year), 1, 1);
            dates[0] = PGUtil.FormatSQLDate(firstDate);
            utcNow = DateTime.UtcNow;
            dates[1] = PGUtil.FormatSQLDate(utcNow.AddHours(5.5));
            return dates;
        }
  

     private string GetActiveDirUserDetails(string userid)
    {
 System.DirectoryServices.DirectoryEntry dirEntry = default(System.DirectoryServices.DirectoryEntry);
 System.DirectoryServices.DirectorySearcher dirSearcher = default(System.DirectoryServices.DirectorySearcher);
 string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
 try {
  dirEntry = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainName);
  dirSearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
  dirSearcher.Filter = "(samAccountName=" + userid + ")";

  dirSearcher.PropertiesToLoad.Add("GivenName");
  //Users e-mail address
  dirSearcher.PropertiesToLoad.Add("sn");
  //Users last name
  SearchResult sr = dirSearcher.FindOne();
  //return false if user isn't found 
  if (sr == null) {
   return false;
  }
  System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();
  dynamic userFirstLastName = de.Properties("sn").Value.ToString() + ", " + de.Properties("GivenName").Value.ToString();
  return userFirstLastName;
 // return false if exception occurs 
 } catch (Exception ex) {
  return ex.Message;
 }
    }
 
 }
  
  
  
  
  

How to Build a Full-Stack Web App with Blazor

  Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...