Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, 29 December 2019

Cannot Bind Multiple Parameters To Request Content | WebApi

I was working on one of my projects last week and stuck in a problem. I was trying to pass a class object and List of a class object to the Asp.Net Web API controller from my Jquery Ajax method (maybe you also encounter it while working with Angular and ASP.NET MVC or any other technology). After some research, I got to know that the Web API controller can’t accept multiple complex objects, so we must send it as a single object. Let me illustrate with my example and its resolution.

Jquery Code : -



  var SaleModel = new Object();  
       SaleModel.id = “1”;  // for example
       SaleModel.customer_id = $("#ddlCustomer").val(); 
   
  var SaleDetailModel = new Object();
    SaleDetailModel.id = “1”;
    SaleDetailModel.quantity = “10”;
  var lstSaleDetail = [];   // javascript array
    lstSaleDetail.push(SaleDetailModel);

 $.ajax({
      type: 'POST',
      data: 
      "{'obj': '"+JSON.stringify(SaleModel) + "',
      'lstSaleDetail':  '"+JSON.stringify(lstSaleDetail)+ "' }",
      headers: {
                 'Authorization': 'Bearer ' + authData.token
             },
      url: 'http://localhost:53807/api/sale/addsale',
      dataType: 'json',
      contentType: 'application/json',
      success: function (data) {
                if (data == true) {
                    alert("Sale Added Successfully!!!");
                }
            },
      error: function (xhr) {
                alert(xhr.responseText);
          }
  });

C# Code : -



       public class SaleModel
       {
          public int id {get;set;}
          public int customer_id {get;set;}
       }

       public class SaleDetailModel
       {
         public int id {get;set;}
         public int quantity {get;set;}
       }

       [HttpPost]
       public bool AddSale(SaleModel obj, List<SaleDetailModel> lstSaleDetail)
       {            
          SaleBusService objSale = new SaleBusService();
          return objSale.saveSale(obj, lstSaleDetail);           
       }

Solution : -

To fix the problem, we need to pass it as a single object that requires a modification in the above code. Below is the C# code. I have added the List Object of the SaleDetailModel class to the SaleModel Class as per my needs. You can create a new request class that contains both SaleModel and SaleDetailModel Objects.

C# Code :


public class SaleModel
{
   public int id {get;set;}
   public int customer_id {get;set;}
   // I have added the list here
   public List<SaleDetailModel> lstSaleDetail {get;set;} 
}

public class SaleDetailModel
{
   public int id {get;set;}
   public int quantity {get;set;}
}


[HttpPost]
public bool AddSale(SaleModel obj)
 {            
      SaleBusService objSale = new SaleBusService();
      return objSale.saveSale(obj, obj.lstSaleDetail);           
 }

Jquery Code :


var SaleModel = new Object();  
       SaleModel.id = “1”;  // for example
SaleModel.customer_id = $("#ddlCustomer").val(); 
   
var SaleDetailModel = new Object();
    SaleDetailModel.id = “1”;
    SaleDetailModel.quantity = “10”;
var lstSaleDetail = [];   // javascript array
lstSaleDetail.push(SaleDetailModel);

 $.ajax({
            type: 'POST',
     data: JSON.stringify(SaleModel) ,
            headers: {
                 'Authorization': 'Bearer ' + authData.token
             },
            url: 'http://localhost:53807/api/sale/addsale',
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                if (data == true) {
                    alert("Sale Added Successfully!!!");
                }
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });

Friday, 10 March 2017

Value Type VS Reference Type

It is shown by the name which variable store information or data directly that is a value type and which store a reference to information or data that is a reference type.

Let’s see a little more details: Value types are always stored on the stack and reference types address on the heap. In general int, enum, struct, etc. are simple examples of data type that store directly data are value type examples whereas reference type keep reference to data like class, interface, delegate, object, Arrays, etc.

In value type we can't store null value on the other hand reference type can have null. However, in value type, we can also achieve this by using nullable types.

Value type does not require garbage collectors they automatically popped/vanish when they go out of their scope whereas reference type requires garbage collectors to free up space.
Value types are assigned memory at compile time whereas in reference type memory assigned at run time.

Value Type:-

        int amount = new int();
        amount = 20;
        int total = new int();
        total = amount;
        y = 30;
        return amount;

--amount will return 20 because it has its location on the stack which is not affected so it keeps old value.

Reference Type:-

        public class Student
         {
                public int Marks;
         }
      
        Student john = new Student();
        john.Marks = 10;
        Student mushi = new Student();
        mushi = john;
        mushi.Marks = 40;
        Console.WriteLine(john.Marks);

--Output will be 40. Both student John and Mushi are referring to the same memory location on the heap.

Difference Between Object, Var, Dynamic Keywords In C#

C# has prosperous data types for storing any data/information. We have three sorts Object, Var, and Dynamic for storing any data in C#. So how about we observe how these three separate with each other with cases.

Object:

It was first introduced in C# version 1.0. An Object is a base class of .Net as we all know, its purpose is the same, it can store all kinds of data. It is a compile-time variable. We can also pass objects as method arguments because methods can return Object type. At compile time compiler doesn't have much information for the use type, so it is very productive when we don't know the type of data. But when we have to use data inside an object we need to cast it to the required data type. The object is the most abstraction for all types in C# and its reference type. An object can box any type of data. When using an object to store data that is called boxing and for using that data need to unbox it.

        Object emp_id = 10; // int 
        Object order_porduct = new Order(); //order object
        Object customer_name = "John"; //string
        //unbox
        string customer = customer_name.ToString();
        //perform string operation now
        customer.Trim();
object-c#-example

Var:

It comes in C # 3.0 versions. Var is a compile-time variable. It is also used to store any type of data, but the additional work is that declaration time we have to initialize the var type is mandatory. So that's why var type can only work within the specified scope not out of this because its method does not return object type and also cannot be passed as a method argument, but it's a type-safe and compiler know all data, which is stored in var type. That's why while using we are not required to cast var type we can directly use it.

        var qty = 10; // int
        var brder_ID = 10d; // double
        var brand = "samsung"; // string 
var-c#-example

Dynamic:

In C# 4.0 we got dynamic a run-time variable that can store all kinds of data. The dynamic keyword has some same characteristics as Object that it doesn't have any information about data and not type-safe, but an advantage we have that it can be passed as a method argument in return it gives dynamic type. It does not require cast when using its data, but we should have knowledge that which properties and methods are linked with stored data type because if we use any other property or method, then it will throw an error. We can use it when doing code with reflection, dynamics, or playing COM objects because in a very short time we can code big tasks with fewer lines.

         dynamic employee = new Class();
         employee.Age = 30;
         employee.Name = "John Doe";
         employee.Course = new Course();

         employee.Name; // read a string
         employee.Age; // read an int
         employee.Course.Name; // read a property

Saturday, 11 February 2017

Difference Between ToString() and Convert.ToString()

This article is about the Difference Between ToString and Convert.ToString Method in C#.

ToString and Convert.ToString Method in C#

Both methods have the ability to convert a value to a string. The main difference between the two methods is that ToString() method can’t handle Null values, so if you use this method, you will experience a Null Reference Exception in your code at some point in time (as shown below Example). On the other hand Convert.ToString() method can handle Null values. So, as a good coding practice and to be on the safe side, experts recommend always use Convert.ToString() method.

We have used below mentioned examples to demonstrate the difference between ToString and Convert.ToString methods.

.ToString() Example:

In C#, if you declare a string variable and do not assign any value to the variable, the variable takes a null value by default. In this case, if you use the ToString() method, the program will raise a null reference exception.


 using System;

namespace DemoToString
{
    public class Program
    {
        static void Main(string[] args)
        {
            Object objStr = null;
            //Below line will throw NullReference Exception
            //Because .ToString() can't handle Null values
            string val = objStr.ToString(); 
            Console.WriteLine(val);
            Console.ReadLine();
        }
    }
}
tostring-and-convert-tostring

When we run the program it will give us null reference exception because the ToString() method in C# expects that the object cannot be NULL when called on it. In our example, the object objStr is Null, and we call ToString() on the NULL object, so it gives a NULL Reference exception.

Convert.ToString() Example:

Let's see what happens when we utilize the Convert.Tostring() method in the above example. Now, after making the changes, run the program, and it should execute correctly. So to put it plainly, the Convert.ToString() method handles null, and the ToString() method does not deal with Null and tosses an exception.


using System;

namespace DemoConvertToString
{
    public class Program
    {
        static void Main(string[] args)
        {
            Object objStr = null;
            //Below line will Return Null Or Blank
            string val = Convert.ToString(objStr);
            Console.WriteLine(val);
            Console.ReadLine();
        }
    }
}

Convert is a static class in the .Net System namespace, and if you noticed that when you write.ToString() It is in a dark blue color(which means that this method is only available in C#) and Convert.ToString() is in light blue color which means it is global and available in other .Net languages as well.

I will go through the difference between object, var, and dynamic keywords through some examples in my next article. Today, I have tried to explain the difference between .tostring and convert.tostring methods. I trust this article will assist you with your requirements. I hope to receive your feedback. Please post your criticism, questions, or remarks on this article.

Tuesday, 5 January 2016

Error While Importing Excel(2007) "The 'Microsoft.ACE.OLEDB.12.0' Provider is not Registered on the Local Machine"

Yesterday I was in database team with my friend to import an excel file of 3 million records in a table. While importing we got any error message “The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine”. Here I just want to tell you that we have to do this activity every month and from past 6 months we were doing it successfully until yesterday when we ran into an error “The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine”.

We were in a hurry so we tried another system to import our file but same error come in front of us and in short span we tried three systems but no success. At last I have researched about this error and got to know that we need to install “2007 Office System Driver: Data Connectivity Components”. So I have installed it from this Microsoft link: Click Here on one of our system and then tried importing the excel file into database table and that's it. Yahooooo it was successful. We've spent a lot of time that is why i have decided to write this post so if anyone ran into this problem will solve it by himself after five minutes of searching on Google.

Hope this article will solve your problem and save your time.