Sunday, December 8, 2013

C# Searching Data form DataTable does not work as expected

An XML file was loaded to the datatable and performed a search for the member id as shown bellow. For a few it was returning records and for the few while the data exists it did not return the data.

string path = WebConfigurationManager.AppSettings.Get("xmlFilePath");
 if (path.Length > 0)
 {
    ds.ReadXml(path);
    if (ds.Tables.Count > 0)
    {
       DataRow[] result = ds.Tables[0].Select(
                     string.Format("member_id={0}", memberID));
       if (result.Length > 0)
       {
          lblCardNumber.Text = result[0]["card_no"].ToString();
          lblPointsBalance.Text = result[0]["closing_balance"].ToString();
       }
    }
 }

The reason being member_id column was a string column and if the change was as shown below it did return the data.

       DataRow[] result = ds.Tables[0].Select(
                     string.Format("member_id='{0}'", memberID));

I am yet to find the reason for this issue. The correct way to find the string value is to add (') before and after the value. 

Sunday, October 27, 2013

ASP.NET MVC Structure Map, No parameter less constructor defined for this object.

While using Structure Map with ASP.NET MVC there was a error "No parameter less constructor defined for this object" for the already working controller. 

 [HttpPost]
        public ActionResult CreateBranch(mBranch branch)
        {
            _service.CreateBranch(branch);
           
            return new JsonResult { Data = "Registered", JsonRequestBehavior = JsonRequestBehavior.AllowGet };

        }


The Structure map Controller factory were configured properly and once this method is commented everything working except when this post method was called the error was thrown.

Reason why it threw the exception was that the class mBranch had only once constructor with a parameter when the method is called mBranch is instantiated it there was no constructor without parameter and resulted in this error.

public class mBranch
    {
        public mBranch(int companyId)
        {
            CompanyID = companyId;

            BranchContact = new mContactInfo();
        }


             //error thrown due to this constructor was missing
        public mBranch()
        {
            BranchContact = new mContactInfo();
        }

      }

Tuesday, October 1, 2013

Editing a macro which automatically open and close after the macro runs

I spend hours trying to edit my macro which when opened it will run the macro and create a separate file and then closes by it self.

Thanks for this post to same my time.

All you need to do is to 

  1. Open the excel application 
  2. Go to File
  3. Go to Open
  4. Pres on Shift Button
  5. Then select the macro file
  6. Go to view
  7. Select the view macro to see the code
:)

Friday, June 7, 2013

Multiple foreign keys within same table using CodeFrist Enitty Framework and Fluent API

This example shows how to work with multiple foreign key referred to the same table using CodeFirst Entity Framework (Inverse Navigation Properties 
)

Parent Table (Branch) has two foreign keys (Primary Contact and Secondary Contact) referring to the Child Table (Contact).


Branch
BranchIDguid
Branch Namevarchar
PrimaryContactIDguid,null
SecondaryContatIDguid,null



Contact
ContactIDguid
Firstnamevarchar
LastNamevarchar
Addressvarchar
Genderchar
First of all we need to create the Branch Class

 public class Branch
    {
        public Guid BranchID { get; set; }
        public string BranchName { get; set; }
        public Nullable<Guid> PrimaryContactID { get; set; }
        public Nullable<Guid> ScondaryContactID{ get; set; }
        public Contact PrimaryContact { get; set; }
        public Contact SecondaryContact { get; set; }
        
    }

Then creating the Contact Class


 public class Contact
    {
        public Guid ContactID { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }        public ICollection<Branch> PrimaryContactFor { get; set; }
        public ICollection<Branch> ScondaryContactFor{ get; set; }
        
    }


When configuring in the fluent API below shown coding is used.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Branch>().HasOptional(b => b.PrimaryContact).WithMany(a => a.PrimaryContactFor).HasForeignKey(b=>b.PrimaryContactID);
            modelBuilder.Entity<Branch>().HasOptional(b => b.SecondaryContact).With Many (a => a.ScondaryContactFor).HasForeignKey(b=>b.ScondaryContactID);

        }

Happy Coding :)





Wednesday, May 8, 2013

Shortcut Keys in Visual Studio Editor

Some Useful Visual Studio shortcut keys


I would like to share some on the shortcut keys that are available in visual studio that will be very useful for the developers for fast codeing. I have segregated them into different parts.

VS Tools and Explore Bars (Windows) Related



Solution ExplorerCtrl +W, S 
Server ExplorerCtrl + W, L
Error ListCtrl + W, E
Output WindowCtrl + W, O
Property WindowCtrl + W, P
Tool BoxCtrl + W, X

Code File Related 



Comment SelectionCtrl +E, C or Ctrl + K, C 
Uncomment SelectionCtrl + E, U or Ctrl + K, U
Format DocumentCtrl + E, D
Make UPPERCASECtrl + Shit, U
Make lowercaseCtrl + U
Place BookmarkCtrl + B + E
Clear BookmarkCtrl + B + C
Toggle BookmarkCtrl + B + T
Previous BookmarkCtrl + B + P
Next BookmarkCtrl + B + N

Project Related 



Add New ClassShift + Alt + C
Add New ItemCtrl + Shift + A
Add Existing ItemShift + Alt + A

I use these shortcuts daily in my coding life and makes my life easy and fast to code. Hope this will effect your coding life and i would like to hear your feedback on this and please suggest if you have any. 

Your feedbacks are warmly welcomed.

Happy Coding :)

Friday, April 5, 2013

ASP.NET MVC Call multiple collection parameter action method from AJAX

Call multiple collection parameter action method using AJAX
This example is used to demonstrate how to send multiple collection data to a action method in MVC. 
First i have defined the View Model which is the type of the collection that is used as the parameter of the action method.
Second the Controller Action Method is defined to show that it takes to List<Employee> collections.
Third listing explains the View - javascript which stringify the object and send a AJAX request to the server.
View Model
public class Employee
{
  public int ID{get;set;}
  public string Name{get;set;}
  public string Age{get;set;}
}  
 
Controller Action Method

public ActionResult SaveData(List<Employee> updateEmployee, List<Employee> deleteEmployee)
{

 try
 {
   //Do your processing
 } 
 catch(exception)
 {
   // do your loggin
 }


View - javascript 
$(document).ready(function(){
 // Here i would like to simulate the collections by adding them statically for simplicity
 var uEmployee = new Object();
 var dEmployee = new Object();
//Create update employees
 var ut1Emp = new Object();
 ut1Emp.ID = 1; ut1Emp.Name="Desmond"; ut1Emp.Age="27";
 var ut2Emp = new Object();
 ut2Emp.ID = 2; ut2Emp.Name="Maria"; ut2Emp.Age="1";
 uEmployee.Push(ut1Emp );
 uEmployee.Push(ut2Emp );
 //Create delete employees
 var dt1Emp = new Object();
 dt1Emp.ID = 3; dt1Emp.Name="Jacintha"; dt1Emp.Age="25";
 var dt2Emp = new Object();
 dt2Emp.ID = 4; dt2Emp.Name="Angel"; dt2Emp.Age="1";
 dEmployee.Push(dt1Emp );
 dEmployee.Push(dt2Emp );

 var param = { 'updateEmployee': uEmployee, 'deleteEmployee': dEmployee}; 

 $.ajax({ url: "SaveData",
          type: 'POST',
          contentType: "application/json; charset=utf-8" , // this is important
          data: JSON.stringify(param), // This is important
          failure: function (errorMSG){
              alert('Error occurred on saving data');

          },
          success: function (data) {
              alert('Successfully saved');

          }
        });

});