Monday, July 11, 2011

MVC3 TryUpdateModel() -Update Model for Edit

When we want to update model with edited values we can use TryUpdateModel() method.

example
[Httppost]
public ActionResult edit(int id)
{
    var user= UserRepository.GetUser(id);

    if (TryUpdateModel(user))
    {
        UserRepository.save();
    }

    return view()
}


But some times when we use TryUpdateModel() the model does not update that mean the method return false.So in that case we need to find out the error so we can do that as flowing it will return the list of errors and their corresponding properties.

[Httppost]
public ActionResult edit(int id)
{
    var user= UserRepository.GetUser(id);

    if (TryUpdateModel(user))
    {
        UserRepository.save();
    }
else{
//the tru update method return false
    
    var errors = ModelState
    .Where(m => m.Value.Errors.Count > 0)
    .Select(m => new { m.Key, m.Value.Errors })
    .ToArray();

}

    return view()
}

Why TryUpdateModel() return false ?

Most of the time the TryUpdateModel() method return false when we have not add editable field or hidden filed for all the required fields to view page.
so we can simply add hidden filed to the view which we don't need to change during the update method.

so My user Model
Public Class User{
[Requried]
public int UserId{get;set}
[Requried]
public string UserName {get;set}
[Requried]
pubic string UserCode{get;set}

pubic string Description{get;set}

public string Address{get;set}

}

So if  I want to update UserDescription in my edit page
I have to put UserId,UserName and UserCode as Hidden filed

But if our model content large number of fields and we only need to update few of fields in that case we can do it by specify the fields which we need to update as following

TryUpdateModel(model, new [] {"Description", "Address"}); // In this case the TryUpdate() only  check vaidation "Description","Address"




And also we can do it as fallowing by mentioning the field which should not update
TryUpdateModel(model, null, null, new [] {"UserId","UserName ","UserCode"});//In this case the TryUpdate() ignore "UserId","UserName" and "Usercode" vaidation

Monday, July 4, 2011

Remove Validation Error messege when click Reset Button in MVC3 Razor

The reset button does not clear validation message in mvc3 by default so  we need to do this with jQuery.The fallowing function clear validation messages in MVC3 pages.
.

jQuery(document).ready(function () {

            $("input:reset").click(function () {
                $('.field-validation-error')
               .removeClass('field-validation-error')
                .addClass('field-validation-valid');

                $('.input-validation-error')
                .removeClass('input-validation-error')
                 .addClass('valid');
            });

  });
Professional ASP.NET MVC 3

Monday, June 27, 2011

MVC 3 Razor TextBox max length

@Html.TextBoxFor(model => model.Organization.OrganizationName, new { maxlength = 50 }) 

Applied ASP.NET MVC 3 in Context (Pro)

Sunday, June 12, 2011

MVC 3 Razor Editor Template

Editor Template is very useful future in Asp.net MVC3 Framework.With Editor Template we can create template for model and  It  can be access easily in the application (like user controller in asp.net).
So I'm going to create Editor Template for Book Model in my application.
Book.cs

public class Book
{
public int BookId { get; set; }
public string BookName { get; set; }
public string Description { get; set; }
}
Then I'm going to create folder  as EditorTemplates in Shared folder  and add new view Book.cshtml as following.(The Name of the Template should be same as Class Name)
 .
@model MySimpleEditorTemplate.Models.Book

@Html.DisplayFor(p => p.BookId) @Html.EditorFor(p => p.BookId)
@Html.DisplayFor(p => p.BookName)@Html.EditorFor(p => p.BookName)
@Html.DisplayFor(p => p.Description)@Html.EditorFor(p => p.Description)

Then in view page simply we can add editor for book as

@Html.EditorFor(model => model.Book) 
 
then it will display above block

Wednesday, October 6, 2010

Accsess The Magento Core API With Dot net technologies

Magento is one of the most popular e-commerce platforms.which based  on PHP and Mysql.Magento Core API supports both SOAP and XML RPC protocols. The API is permission based and allows access to the Customer, Catalog and Order modules of Magento. Please reference the documentation for more information.
This article I am going to explaining How to access magento web service from Dot net Technologies .
we can access magento soap api with following url.
http://mymagento.com/api/v2_soap?wsdl (You can see wsdl definition by typing this url in web browser).
So let see how to display Magento customer list in my WindowsFormsApplication project.
To consume to the magento web service in our application we should add web Reference by rigth click on solution .

In the web reference dialog box type the magento web service URL (http://mymagento.com/api/v2_soap?wsdl) and click Go button then available service method display as following screen.
Then we can change the web service name and click Add Refference button.

 By doing above steps,we can generate  the web service proxy .
C# code to retrieve  customer list.
 using Magento.com.mymagento

public void  showCustomrs(){
   MagentoService ms = new MagentoService();
   string sesion= ms.login("Dinesh", "123456");
   filters myfilter=new filters();//filter criteriya
   customerCustomerEntity[] cusls= ms.customerCustomerList(sesion,myfilter);//get customers
   dgCutomer.ItemsSource = cusls; //display in grid
}









Saturday, August 7, 2010

How to Create WCF Application

Select WCF Service Application from New Project window in Visual Studio and name the project as MyWCFService

Add WCF Service to the “MyWCFService” project and named as Myservice.svc

What is Service Contracts ?
Describe which operations the client can perform on the service. There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

IMyService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;


[ServiceContract]

public interface IService

{

    [OperationContract]

     Employeee GetEmployee(int id);// service method

      

}

Then we can implement above interface

MyService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using Common;

    public class MyService: IMyService

    {


        #region MyService Members


        public Employeee GetEmployee(int id)//service method implimentation

        {

 Employeee emp = new Employeee { EmpId = Guid.NewGuid(),Name="Dinesh",Type=EmployeeTypesEnum.Accounter };

                     return emp;

        }


        #endregion

    }

What is Data contracts?

Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.
Types Supported by the Data Contract Serializer

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties

Add Class Employee to the solution

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

using System.ServiceModel;


    [DataContract]

    public class Employeee

    {

        [DataMember]

        public Guid EmpId { get; set; }

        [DataMember]

        public string Name { get; set; }

        [DataMember]

        public EmployeeTypesEnum Type { set; get; }

    }

How To Pass Enum with WCF services?

To pass Enum the Data contracts should be define with EnumMember() attributes.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;


 [DataContract]

   public enum EmployeeTypesEnum

    {

    [EnumMember()]


          Administrator = 0,


    [EnumMember()]


          Manager = 1,


    [EnumMember()]


          Accounter = 2


}

How to Test WCF application ?

WCF service can test with WCF Test Client (WcfTestClient.exe) by  execute WcfTestClient.exe commond in Visual Studio Command prompt .
 

Sunday, May 16, 2010

DATA ACCESS LAYER

This is base class witch handle common function in Data Access Layer.

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

namespace DAL
{
public class DataHelper
{
private string Conncton_string = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
private SqlConnection sqlConn = new SqlConnection();
public static SqlParameter[] _dataParameters = null;
public DataHelper()
{
}

private SqlConnection openConnection()
{

sqlConn.ConnectionString = Conncton_string;
sqlConn.Open();
return sqlConn;

}
private void CloseConnection()
{
sqlConn.Close();
}

//For a execute non query
public void ExecuteNonQuery(CommandType commandType, string commandText, SqlParameter[] parameterCollection)
{
SqlCommand sqlCmd = new SqlCommand();
try
{
sqlCmd.Connection = openConnection();
sqlCmd.CommandType = commandType;
sqlCmd.CommandText = commandText;
sqlCmd.Parameters.AddRange(parameterCollection);
sqlCmd.ExecuteNonQuery();
sqlCmd.Parameters.Clear();
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
sqlCmd.Dispose();
}
}
//to get DataSet
public DataSet GetData(CommandType commandType, string commandText, SqlParameter[] parameterCollection)
{

SqlDataAdapter sqlAdp = new SqlDataAdapter();
DataSet dsItem = new DataSet();
SqlCommand sqlCmd = new SqlCommand();

try
{
sqlCmd.Connection = openConnection();
sqlCmd.CommandType = commandType;
sqlCmd.CommandText = commandText;
if(parameterCollection !=null)
sqlCmd.Parameters.AddRange(parameterCollection);
sqlAdp.SelectCommand = sqlCmd;
sqlAdp.Fill(dsItem);
return dsItem;
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
sqlCmd.Dispose();
}
}

public int ExecuteScaler(CommandType commandType, string commandText, SqlParameter[] parameterCollection)
{
SqlCommand sqlCmd = new SqlCommand();
try
{
sqlCmd.Connection = openConnection();
sqlCmd.CommandType = commandType;
sqlCmd.CommandText = commandText;
sqlCmd.Parameters.AddRange(parameterCollection);
return Convert.ToInt32(sqlCmd.ExecuteScalar().ToString());

}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
sqlCmd.Dispose();
}
}


}
}

///this is the class derived from above class and execute Stored procedures
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using System.Data.SqlClient;
using System.Data;

namespace DAL
{
public class CustomerData:DataHelper
{
public void Save(Entity.Customer cus)
{
try
{
SqlParameter[] para = new SqlParameter[] { new SqlParameter("@Cus_name", cus.Cus_Name), new SqlParameter("@Cus_address", cus.Cus_Address), new SqlParameter("@Cus_no", cus.Cus_No)};
ExecuteNonQuery(CommandType.StoredProcedure, "INSERT_Customer", para);

}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
}
public void Update(Entity.Customer cus)
{
try
{
SqlParameter[] para = new SqlParameter[] { new SqlParameter("@Cus_name", cus.Cus_Name), new SqlParameter("@Cus_address", cus.Cus_Address), new SqlParameter("@Cus_no", cus.Cus_No) };
ExecuteNonQuery(CommandType.StoredProcedure, "UPDATE_Customer", para);

}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
}


public DataSet SelectCustomerList()
{
try
{
return GetData(CommandType.StoredProcedure, "Select_Customers", null);

}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
}

public Customer SelectCustomer(string id)
{
try
{
SqlParameter[] para = new SqlParameter[] { new SqlParameter("@Cus_No", id) };
DataSet dsCus= GetData(CommandType.StoredProcedure, "Select_Customer", para);
Customer cus = new Customer();
cus.Cus_No = dsCus.Tables[0].Rows[0]["Cus_No"].ToString();
cus.Cus_Name = dsCus.Tables[0].Rows[0]["Cus_Name"].ToString();
cus.Cus_Address = dsCus.Tables[0].Rows[0]["Cus_Address"].ToString();
return cus;

}
catch (SqlException sqlEx)
{
throw sqlEx;
}
catch (Exception ex)
{
throw ex;
}
}
}
}