Monday, 21 March 2016

Difference between SELECT INTO and INSERT INTO SELECT SQL Statement

SELECT INTO and INSERT INTO SELECT are the two sql statements which are quite useful as other statements.


The major difference is,

The INSERT INTO SELECT statement copies data from one table and inserts it into an existing table.

         INSERT INTO Table2 SELECT * FROM Table1;


And,

The SELECT INTO statement copies data from one table and inserts it into a new table (i.e. creates a new object). 

           SELECT ColumnNames INTO FROM Tablename;



So, if you want to copy the data from one table to another existing table then use INSERT INTO SELECT and if you want to create a backup copy or new object of table with same structure and records then use SELECT INTO statement.


 Hope so this might be helpful.




Thursday, 25 February 2016

How to debug the Web API in ASP.NET MVC?


Many  developers are having question of how to debug the Web API from client project or from source that consumes Web API.

 For debugging the Web API there's no need to use any new extension, well you can do this stuff in Visual Studio itself.


  1. Go to  Solution Explorer where you would be having webapi project and the project that consumes web api.
  2. Now right click and select properties or hit Alt+Enter.
  3. Now in Startup Project select multiple  startup project.
  4. Go to Action and select Start in dropdown for both projects.
  5. That's it now click Apply and Ok. 
  6. Now create a breakpoint in both projects and enjoy the debugging.


Monday, 22 February 2016

All Basic examples of C# Programming| Fibonacci Series| Armstrong Number| Swap Numbers| Reverse String| Floyd's Triangle | Pascal Triangle

This may help any beginner, Mid-Level & might some times Experts too. 

This snippet includes:
  1. Odd-Even
  2. Check Vowel
  3. Count Vowels and Consonants
  4. Leap Year
  5. Factorial
  6. HCF & LCM
  7. Decimal to Binary
  8. Summation of n numbers
  9. Swapping with & without 3rd Variable
  10. Reverse
  11. Check Armstrong
  12. Fibonacci Series
  13. Remove Blank Space
  14. Floyd's Triangle
  15. Pascal's Triangle
using System;    
using System.Collections;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
using System.Threading.Tasks;    
    
    
namespace AllBasic    
{    
    class Program    
    {    
        static void Main(string[] args)    
        {    
        Restart:    
            Console.WriteLine("Enter your query \n");    
            string read = Console.ReadLine();    
    
    
            if (read == "Odd-Even")    
            {    
                int range1 = Convert.ToInt32(Console.ReadLine());    
                int range2 = Convert.ToInt32(Console.ReadLine());    
    
                for (int i = range1; i <= range2; i++)    
                {    
                    if (i % 2 == 0)    
                    {    
                        Console.WriteLine(i + " number is Even.\n");    
    
                    }    
                    else    
                    {    
                        Console.WriteLine(i + " number is Odd.\n");    
    
                    }    
                }    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Check Vowel")    
            {    
                string[] vowels = { "a", "e", "i", "o", "u", "A", "E", "I", "O", "U" };    
    
                string getinput = Console.ReadLine();    
    
                if (vowels.Contains(getinput))    
                {    
                    Console.WriteLine("Yes!" + getinput + " is a vowel.");    
    
                }    
                else    
                {    
                    Console.WriteLine("No!" + getinput + " is not a vowel.");    
                }    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Count Vowels & Consonants")    
            {    
                string[] vowels = { "a", "e", "i", "o", "u", "A", "E", "I", "O", "U" };    
    
                string getinput = Console.ReadLine();    
                int vowelscnt = 0;    
                int consonantscnt = 0;    
                foreach (char character in getinput)    
                {    
                    if (vowels.Contains(character.ToString()))    
                    {    
                        Console.WriteLine("Yes!" + character + " is a vowel.");    
                        vowelscnt++;    
                    }    
                    else    
                    {    
                        Console.WriteLine("No!" + character + " is not a vowel.");    
                        consonantscnt++;    
                    }    
                }    
                Console.WriteLine("Total Vowels:" + vowelscnt + " and Consonants are:" + consonantscnt);    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Leap Year")    
            {    
                int getinput = Convert.ToInt32(Console.ReadLine());    
                if (getinput % 4 == 0)    
                {    
                    Console.WriteLine("Yes!" + getinput + " is a leap year.");    
                }    
                else    
                {    
                    Console.WriteLine("No!" + getinput + " is not a leap year.");    
                }    
                Console.ReadLine();    
            }    
            else if (read == "Factorial")    
            {    
                int getinput = Convert.ToInt32(Console.ReadLine());    
                int fact = 1;    
                for (int i = 1; i <= getinput; i++)    
                {    
                    fact = fact * i;    
                }    
                Console.WriteLine("Factorial of " + getinput + "! is:" + fact);    
    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "HCF & LCM")    
            {    
                Console.WriteLine("Enter two numbers:");    
    
                int getinput1 = Convert.ToInt32(Console.ReadLine());    
                int getinput2 = Convert.ToInt32(Console.ReadLine());    
                int temp;    
                int hcf; //  or gcd    
                int lcm, x, y;    
    
                x = getinput1;    
                y = getinput2;    
    
                while (getinput2 != 0)    
                {    
                    temp = getinput2;    
                    getinput2 = getinput1 % getinput2;    
                    getinput1 = temp;    
                }    
    
                hcf = getinput1;    
                lcm = (x * y) / hcf;    
    
    
                Console.WriteLine("Greatest Common Divisor of " + x + " & " + y + " is:" + hcf);    
                Console.WriteLine("Least Common Multiple of " + x + " & " + y + " is:" + lcm);    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "HCF & LCM")    
            {    
                Console.WriteLine("Enter two numbers:");    
    
                int getinput1 = Convert.ToInt32(Console.ReadLine());    
                int getinput2 = Convert.ToInt32(Console.ReadLine());    
                int temp;    
                int hcf; //  or gcd    
                int lcm, x, y;    
    
                x = getinput1;    
                y = getinput2;    
    
                while (getinput2 != 0)    
                {    
                    temp = getinput2;    
                    getinput2 = getinput1 % getinput2;    
                    getinput1 = temp;    
                }    
    
                hcf = getinput1;    
                lcm = (x * y) / hcf;    
    
    
                Console.WriteLine("Greatest Common Divisor of " + x + " & " + y + " is:" + hcf);    
                Console.WriteLine("Least Common Multiple of " + x + " & " + y + " is:" + lcm);    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Decimal to Binary")    
            {    
                Console.WriteLine("Enter one number:");    
                /* Method 1*/    
                int getinput1 = Convert.ToInt32(Console.ReadLine());    
    
                string binary = Convert.ToString(getinput1, 2);    
                Console.WriteLine("Decimal to Binary of " + getinput1 + "by method1 is:" + binary);    
                /* Method 1*/    
                /* Method 2*/    
                const int mask = 1;    
                var binaynum = string.Empty;    
                while (getinput1 > 0)    
                {    
                    // Logical AND the number and prepend it to the result string    
                    binaynum = (getinput1 & 1) + binaynum;    
                    getinput1 = getinput1 >> 1;    
                }    
                Console.WriteLine("Decimal to Binary of same by method2 is:" + binary);    
                /* Method 2*/    
    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Add Numbers")    
            {    
                Console.WriteLine("Enter two numbers:");    
    
                int getinput1 = Convert.ToInt32(Console.ReadLine());    
                int getinput2 = Convert.ToInt32(Console.ReadLine());    
                int sum = 0;    
                for (int i = getinput1; i <= getinput2; i++)    
                {    
                    sum = sum + i;    
                }    
                Console.WriteLine("Addition of n numbers is:" + sum);    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Swap")    
            {    
                Console.WriteLine("Enter two number:");    
    
                int getinput1 = Convert.ToInt32(Console.ReadLine());    
                int getinput2 = Convert.ToInt32(Console.ReadLine());    
    
                int x, y;    
                x = getinput1;    
                y = getinput2;    
    
                /*Method 1->  using third variable*/    
                int temp;    
    
                temp = getinput1;    
                getinput1 = getinput2;    
                getinput2 = temp;    
    
                Console.WriteLine("Numbers swapped as:" + getinput1 + "& " + getinput2);    
                Console.ReadLine();    
                /*Method 1->  using third variable*/    
    
                /*Method 2-> without using third variable*/    
                x = y - x;   // a=> b-a    
                y = x + y;   // b=> a+b    
                x = x + y;  // a=>b-a    
    
                Console.WriteLine("Numbers swapped as:" + getinput1 + "& " + getinput2);    
                Console.ReadLine();    
                goto Restart;    
    
            }    
            else if (read == "Reverse")    
            {    
    
                Console.WriteLine("Enter string:");    
                string input1 = Console.ReadLine();    
                /* Reverse String Method 1*/    
                string reversest = string.Empty;    
                Stack stack = new Stack();    
                foreach (char data in input1)    
                {    
                    stack.Push(data);    
                }    
    
                foreach (var data in stack)    
                {    
                    reversest += data;    
                }    
                Console.WriteLine("Reverse string of:" + input1 + "is " + reversest);    
                /* Reverse String Method 1*/    
    
                /* Reverse String Method 2*/    
                char[] chrarray = input1.ToCharArray();    
                string reversestring = string.Empty;    
                for (int i = chrarray.Length; i >= 1; i--)    
                {    
                    reversestring += chrarray[i - 1];    
                }    
                Console.WriteLine("Reverse string of:" + input1 + "is " + reversestring);    
    
                /* Reverse String Method 2*/    
    
                Console.ReadLine();    
                goto Restart;    
    
            }    
            else if (read == "Armstrong")    
            {    
                Console.WriteLine("Enter Number:");    
                string getinput = Console.ReadLine();    
                char[] input1 = getinput.ToCharArray();    
    
                int length = input1.Length;    
    
                double x = Convert.ToDouble(getinput);    
                double armstrong = 0;    
    
                for (int i = 0; i <= length - 1; i++)    
                {    
                    string num = input1[i].ToString();    
                    int number = Convert.ToInt32(num);    
    
                    armstrong = armstrong + Math.Pow(number, length);    
                }    
    
                if (armstrong == x)    
                {    
                    Console.WriteLine("Yes! it's an Armstrong number.");    
                }    
                else    
                {    
                    Console.WriteLine("No! it's not an Armstrong number.");    
                }    
    
                Console.ReadLine();    
                goto Restart;    
            }    
    
            else if (read == "Fibonacci")    
            {    
                Console.WriteLine("Enter two range as numbers:");    
    
                int getinput1 = Convert.ToInt32(Console.ReadLine());    
                int getinput2 = Convert.ToInt32(Console.ReadLine());    
    
                string fibonacci = string.Empty;    
                int temp = getinput1;    
                fibonacci = temp.ToString() + "," + getinput2.ToString();    
    
                for (int i = 0; i <= 10; i++)    
                {    
    
                    temp = getinput1 + getinput2;    
                    getinput1 = getinput2;    
                    getinput2 = temp;    
                    fibonacci += "," + getinput2;    
                }    
    
                Console.WriteLine("Fibonacci Series between two numbers is:" + fibonacci);    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Blank Space")    
            {    
                Console.WriteLine("Enter string:");    
    
                string getinput1 = Console.ReadLine();    
    
                /* Simple in c# due to function -> Replace*/    
                string newstring = getinput1.Replace(" ", "");    
                Console.WriteLine("String after removing blank space:" + newstring);    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Floyds Triangle")    
            {    
                for (int i = 0; i <= 20; i++)    
                {    
                    for (int j = 0; j <= i; j++)    
                    {    
    
                        Console.Write(j + " ");    
    
                    }    
                    Console.Write("\n");    
    
                }    
                Console.ReadLine();    
                goto Restart;    
            }    
            else if (read == "Pascal Triangle")    
            {    
                for (int i = 1; i <= 10; i++)    
                {    
                    for (int j = 1; j <= 10 - i; j++)    
                    {    
                        Console.Write(" ");    
    
                    }    
                    //for (int k = 20; k >= i; k--)    
                    //{    
                    //    Console.Write(" " + k);    
                    //}    
                    for (int k = 1; k <= i; k++)    
                    {    
                        Console.Write(" " + k);    
                    }    
    
                    Console.Write("\n");    
    
                }    
                Console.ReadLine();    
            }    
        }    
    
    }    
}    

Friday, 19 February 2016

How to scroll the HTML Page Title ?

There are various ways in html to scroll the title in which, one of the way is as shown:

Add the script to head tag in script blog:



        var scrl = " My ASP.NET Application ";
        function marqtitle() {
            scrl = scrl.substring(1, scrl.length) + scrl.substring(0, 1);
            document.title = scrl;
            setTimeout("marqtitle()", 500);
        }

    
And from body call onload="marqtitle()"

That's it done.

Thursday, 18 February 2016

How to get result from ASP.NET Web API in either JSON or XML Format?

Situation may exist some time as we want the data from API in JSON or either in XML format. So how to achieve that in ASP.NET Web API?

Here is the solution:

Add Namespace:

using System.Net.Http.Formatting;
using System.Net.Http.Headers;

Go to ->  Global.asax file and Add following script to Application_Start().

For JSON :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

For XML :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));


Now use query string while calling the API.

as ::

             for xml : http://localhost:49533/api/?type=xml

             for json: http://localhost:49533/api/?type=json
             

That's it this is how we can get data as we want in XML or JSON.

Friday, 12 February 2016

How to use Web Grid in ASP.NET MVC?

Web Grid is easy to use for those who are having complexity in various operations on ASP.NET Table or List View like Sorting, Paging etc.

Let use see how web grid works.

 Here we're having a view model that contains following data. We'll get the data and bind to Web Grid.





































  Now in controller create a ActionResult method in which we'll even call repository method for getting the data from database.



Repository Class Method:
























   
Now once you get the data as shown in Controller store the data in ViewBag and return to View.

In View get that list and bind to grid as shown.



















WebGrid object=new WebGrid(list);
                            
       where: list is Generic List. 

Now it's really interesting and easy to do Sorting, Paging in grid.

  1. Sorting is by default available in grid headers. If you want to disable you can use as:
WebGrid grid=new WebGrid(list,canSort:false);

      2. For paging :


WebGrid grid=new WebGrid(list,rowsPerPage:5);

      3. Display Column you want:

 WebGrid grid = new WebGrid(list,  columnNames: new[] { "E_Name", "E_Contact" });

      4. Change Column Header Name as shown in GetHtml():

@grid.GetHtml(columns:grid.Columns(grid.Column("E_Name","Name"),grid.Column("E_Contact","Contact Number")));



One can also perform many other operations this were the basic of them.
Thanks.

Saturday, 6 February 2016

How to handle multiple button in single view and same form on submit in ASP.NET MVC?

There might be situation where you have to use multiple button in same form. Then what would you do ?

  If you don't want to mess up more in this, then let me scroll you to our main topic and show you how to do it.





































Now you can see in code above I have given  all 4 buttons same name as command.

 <button type="submit" class="btn btn-default" name="command" id="btnMonth" value="Month" style="margin-top:25px;">Submit</button>

<button type="submit" class="btn btn-default" name="command" id="btnDay" value="Day" style="margin-top:25px;">Submit</button>

And on form submit call action as shown:

@using (Html.BeginForm("MultipleCommand", "Default", FormMethod.Post, new { id = "Form1" }))
{
}

So on button click MultipleCommand of Default controller would be called and we can use it in the as shown below.



That's it Over.

Use if else condition as if command =="blabla" {// Your code to execute } and finally return as you want.

Thanks.

Wednesday, 27 January 2016

How to get collection of records to View in ASP.NET MVC? (Dapper ORM)

In previous we seen how CRUD operations are performed in ASP.NET MVC using Dapper ORM.
Now today we'll see how to get a collection of records to View using ViewBag.

Display the collection of records in View is done by various way.

I'll show you how to do it using ViewBag.

I've already shown you how to  install Dapper  and give connection to database. If you are not aware for that than kindly view previous post.

Now I'll continue with creating model. I have a table name District_Master which contains District and it's code.

Model: (District.cs)


using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Web; using Dapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace GetData.Models { [Dapper.Table("District_Matser")]
private string _districtcode;
public class District { private string _district;
get { return _district; }
[Display(Name="District")] public string DISTRICT {
public string DISTRICTCODE
set { _district = value; } } [Display(Name = "DistrictCode")] {
}
get { return _districtcode; } set { _districtcode = value; } }
}



Now we have created a model that will get and set value to database for district_master.
But how would it perform dml or ddl operations?
So we'll create new model and let us call it as MainModel which would contain helper methods.
This method we'll access through controller and get the records to View.


MainModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Web; using Dapper;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data; using System.Data.OracleClient; using System.Configuration;
OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["dbOraConn"].ConnectionString);
namespace GetData.Models { public class MainModel {
public IEnumerable districtdata()
{
string query = "select district,districtcode from district_master";
if (con.State == ConnectionState.Closed) {
var records = con.Query(query);
con.Open(); }
return records;
}
}
}




Controller:

Now create ActionResult method that will access the data and pass the data to view using ViewBag.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using Dapper;
using GetRainData.Models;
public class DefaultController : Controller
namespace GetData.Controllers { {
public ActionResult Index()
// GET: Default {
var district = mm.districtdata().ToList();
MainModel mm = new MainModel();
}
ViewBag.ddldistrict = district; return View(); }
}




View:
Now data is passed to view. So after passing the data we've to cast the viewbag to it's datatype. I've casted to ICollection<T>. And for using models in view we have to import namespace using WebApplication.Models;
Just see now how it is being done.



Now run the application and see the output.




Tuesday, 26 January 2016

How to use Dapper dot Net ORM with ASP.NET MVC??

For comparisons between different ORM kindly refer the previous post of this blog.

Dapper's primary feature is mapping from .NET classes to database tables (and from CLR data types to SQL data types). Dapper also provides data query and retrieval facilities.
Dapper is a micro-ORM: it does not offer the full range of features of a full ORM such as NHibernate or Entity Framework. This is by design. It focuses on simplicity and performance rather than full automation. Dapper does not generate the SQL queries, but only maps the result to Plain Old CLR Objects (POCOs). Third party extensions are available for mapping objects to INSERT and UPDATE queries. It is optimized for use with .NET 4.0 or higher.
The single class ORM is also available on NuGet.

Dapper was started by Sam Saffron and Marc Gravell because of the N+1 and other performance issues with Entity framework. It was written for and is used by Stack Overflow.


Let us now see how to create a web application in ASP.NET MVC using Dapper ORM.

Open Visual Studio (used by me is :2013) -> New Project -> Choose  MVC Project however you want.
Now as you use to give the reference to Entity Framework using Nuget Packet Manager, similarly, go to Manager and search for Dapper & Dapper.SimpleCRUD and install that packages as shown in fig.







I have created a database in Sql Server and given connection string in web.config as we use to do normally. My Connection Name is EmployeeDBContext(* Not necessary to use as DBContext)



Table : Emp_Personal. Column of my tables are as E_Id, E_Name, E_Address, E_Contact, E_DOB.

Now create a model in model folder. I have created Model named Employee and defined the attributes as shown.


Namespace:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


Class:





Now after creating a model we'll create another model in which we would write the methods to get the data from database. 
Let us call that model as MainModel.cs

NameSpace:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using Dapper;


In class first thing we'll give a connection to database and yes welcome back to old format of code again in Dapper.

Now go to controller folder and add a controller. 

Display All Employees:

In controller I've created a method to get all employee details as GetDetails(). 

For details we'll  call the MainModel class and access the method EmployeeDetails() which is as shown :

Now accessing through controller:

Now to view the records add the view by rightclick on Action Method and Add View -> List & select  a model as shown:





Note while running it may ask to map the SQLMAPPER.cs file for that you can goto Git or Google and find out sqlmapper.cs file for dapper or you may comment down.

Insert Records:

Similarly we've to go for all Insert, Edit and delete.

         MainModel Method:



Make sure here values are passed as  "@Columnname" and connection.Execute(query,new {attributes}); we've to pass.

       Controller Method:

In controller first we'll use HTTP GET for redirecting to Create View and from there we'll use HTTP POST on submission. 


   View : (rightclick and details , select model) 

Your view should be something like this.

@model DapperORM.Models.Employee
    
    



Edit Records:

For edit and delete we'll create a method which will get the data by selected id from details page and display the data to view and there after perform the HTTP POST(submission).


        MainModel Method: 

public Employee GetEmployeeList(string E_Id)
{
string query = "select E_Id,E_Name,E_Address,E_Contact,E_DOB from Emp_Personal where E_Id=@E_Id";
var result = con.Query(query, new { E_Id }).Single();
return result;
}




public string Updateemployee(Employee objemp)
{
string query = "update Emp_Personal set E_Name=@E_Name,E_Address=@E_Address,E_Contact=@E_Contact,E_DOB=@E_DOB where E_Id=@E_Id";
con.Execute(query, new { objemp.E_Name, objemp.E_Address, objemp.E_Contact, objemp.E_DOB, objemp.E_Id });
}
string result = "updated";
return result;
        Controller Method: 
        View Method:  (Some thing like this your view should be)




























         

          Delete Records:

                MainModel Method :









              Controller Method :

             View :




















































Note: be sure that while edit and delete GetEmployeeList ()method should be called during httpget. and then perform operation.


That's it. And yes for details of particular employee.

Details of particular employee
               MainModel Method:

                        Same GetEmployeeList as for delete and edit.

              Controller Method:

[HttpGet]
public ActionResult Details(string id)
{
return View(mm.GetEmployeeList(id));
MainModel mm = new MainModel();
}

            View :


































































And you are done.

How To Pass An Array As A Parameter While Calling an ASP.NET Web API C#

Please visit my C# Corner Blog for this, where I have provided better efforts to make this concept more understandable - www.c-sharpcorner....