About Hasmukh patel

My Photo
Harrow, London, United Kingdom
Dot-Net developer with expertise in Web, WPF, Win-form applications. Have worked on Asp.net,mvc , WPF and Win-forms projects in c#.net language having Sql-Server/Oracle as database with service oriented architecture using test driven development. Having complete knowledge of SDLC and have successfully worked and implemented it on projects.

MVC – Load and Retrieve Data with JSON

MVC – Load and Retrieve Data with JSON

Create a Action filter to execute action

public class JsonFilter : ActionFilterAttribute
{
public string Param { get; set; }
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
{
string inputContent;
using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
inputContent = sr.ReadToEnd();
}
//var result = JavaScriptConvert.DeserializeObject(inputContent, JsonDataType);
//var result = new JavaScriptSerializer().DeserializeObject(inputContent);

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

var result = jsonSerializer.GetType().GetMethod("Deserialize").MakeGenericMethod(new Type[] { JsonDataType }).Invoke(jsonSerializer, new object[] { inputContent });
filterContext.ActionParameters[Param] = result;
}
}
}



Create a model class
public class Task
{
[Required]
[DisplayName("Task Descr")]
public string Text { get; set; }

[DisplayName("Completed?")]
public bool Completed { get; set; }

}


Create a controller for json

public class JsonTestController : Controller
{
private static List taskList = new List();

static JsonTestController()
{
taskList.Add( new Task(){ Completed=false, Text="test1"});
taskList.Add( new Task(){ Completed=false, Text="test2"});
}
//
// GET: /JsonTest/
[HttpGet]
public ActionResult Index()
{
return View();
}

[HttpPost]
[JsonFilter(Param = "tasklist", JsonDataType = typeof(Task[]))]
public JsonResult AddTaskList(Task[] tasklist)
{
if (tasklist != null)
{
taskList.AddRange(tasklist);
}
return Json(new { msg = "record added." });
}

[AcceptVerbs(HttpVerbs.Post)]
[JsonFilter(Param = "task", JsonDataType = typeof(Task))]
public JsonResult AddTask(Task task)
{
if (task != null)
{
taskList.Add(task);
}
return Json(new { msg = "record added." });
}


[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetJsonTaskList()
{
Task[] tasks = taskList.ToArray();
return Json(tasks);
}

}
Add index.aspx in to the view/JsonTest folder

<script type="text/javascript">

function Task(text, completed) {
this.Text = text;
this.Completed = completed;
}

function getTaskList() {

$.ajax({
type: "post", //json
url: "/JsonTest/GetJsonTaskList",
success: function(result) {

var htmlData = ""
for (var i = 0; i < result.length; i++) {
htmlData += "<tr><td>" + result[i].Text + "</td><td>" + result[i].Completed + "</td></tr>";
}
$("#divTodolist").html("<table>" + htmlData + "</table>");
},
error: function(req, status, error) {
alert("Error occured.");
}
});
}
//refresh list
getTaskList();

//add records
function AddTaskList() {
//alert("Text=" + $("#Text").val() + "&Completed=" + $("#Completed").attr('checked') );
var tasklist = new Array();
//todoArray[0] = { Text: $("#Text").val(), Completed: $("#Completed")..attr('checked') };
//var postData = { todos: todoArray };

tasklist.push(new Task($("#Text").val(), $("#Completed").attr('checked')));
var postData = JSON.stringify(tasklist);
alert(postData);

$.ajax({
type: "post", //json
url: "/JsonTest/AddTaskList",
dataType: "json",
contentType: 'application/json',
//data: "Text=" + $("#Text").val() + "&Completed=" + $("#Completed").attr('checked'),
//data: $("#form0").serialize(),
data:postData,
success: function(result) {
alert("Record added.")
getTaskList();
},
error: function(req, status, error) {
alert("Error occured.");
}
});
}

function AddTask() {
//var tasklist = new Array();
//tasklist[0] = { Text: $("#Text").val(), Completed: $("#Completed")..attr('checked') };
//var postData = { todos: todoArray };

var task =new Task($("#Text").val(), $("#Completed").attr('checked'));
var postData = JSON.stringify(task);
alert(postData);

$.ajax({
type: "post", //json
url: "/JsonTest/AddTask",
dataType: "json",
contentType: 'application/json',
//data: "Text=" + $("#Text").val() + "&Completed=" + $("#Completed").attr('checked'),
//data: $("#form0").serialize(),
data: postData,
success: function(result) {
alert("Record added.")
getTaskList();
},
error: function(req, status, error) {
alert("Error occured.");
}
});

}



$(document).ready(function() {
$('#AddTaskList').click(function() {
AddTaskList();
return false;
});

$('#AddTask').click(function() {
AddTask();
return false;
});

});
</script>

<h2>Add a Todo</h2>
<p>
Click on Add to Add a Todo.
</p>
<% Html.EnableClientValidation(); %>

<% using (Html.BeginForm()) { %>

<fieldset>
<legend>Todo Information</legend>
<table>
<tr>
<td>
<div class="editor-label">
<%= Html.LabelFor(m => m.Text)%>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(m => m.Text, new { Width = "100px" })%>
<%= Html.ValidationMessageFor(m => m.Text)%>
</div>
</td>
<td>
<div class="editor-label">
<%= Html.LabelFor(m => m.Completed)%>
</div>
<div class="editor-field">
<%= Html.CheckBoxFor(m => m.Completed)%>
</div>
</td>
<td><input type="submit" id="AddTaskList" value="Add Task List" /> </td>
<td><input type="submit" id="AddTask" value="Add Task" /> </td>
</tr>
</table>
</fieldset>
<div id="divTodolist">

</div>

<% } %>

Client side Drop down validation using jQuery

Client side Drop down validation using jQuery.

For the textbox MVC will write JavaScript
for Required,
RegularExpression
& StringLength attributes but there is no built-in method to validate a
drop down menu, we need to define our own method.

First we need to define a method to
validate dropdown control and define rules for each dropdown controls.


To display your error message still you
need to defile required attribute on your property and include validation
summery on your page. E.g.
<%= Html.ValidationMessageFor(m
=> m.Title) %>


jQuery.validator.addMethod(

"selectNone",

function(value, element) {
if (element.value == "")
{


return false;


}


else return true;

},


"Please select an option."

);

$(document).ready(function() {


$("#form0").validate({


rules: {

"Title.TitleID": {


selectNone: true

},


"SecretQuestion.IntCode":{


selectNone: true


}


}


});

});

For more details click here or for more jQuery
validation
click here

Dependency Properties & Attached Properties


Dependency Properties & Attached properties

Dependency Properties looks similar to normal CLR properties but its more complex and more powerful feature of XAML.
The main difference is, that the normal CLR properties are backed a private variable of your class, whereas the Dependency Properties are backed by DependencyObject’s GetValue and SetValue which resolved value dynamically by calling these two methods.

Getter and setter value mechanism

XML processor resolves the value by the precedence from high to low.

GetValue()
SetValue()
1
Animation

2
Binding Expression

3
Local Value
Local Value
4
Custom Style trigger

5
Custom template trigger

6
Custom Style Setter

7
Default Style Trigger

8
Default Style Setter

9
Inherited Value

10
Default Value


The Advantage of dependency properties

·         Reduce memory footprint:  most of the UI element have a no value just it use the default value.
·         Value inheritance: if there is no value defined then inherit from parents.
·         Change notification: built-in mechanism which binding get notification by registering of property metadata, when the value of the property has been changed.
Example of a Dependency property
To create a Dependency property, add a static type of DependencyProperty and call Register static method of DependencyProperty class to create instance of a dependency property. To create a property of your class, create normal CLR property and replace with GetValue() and SetValue()  instead of private variable like a wrapper  property.
Note : Do not write any logic in getter and setter of the dependency property, because getter might not call some time as explain in above table and setter might not call by XML but it may call SetValue() directly instead of your setter.

public
static readonly DependencyProperty TempratureProperty =
     DependencyProperty.Register( " Temprature", typeof(int),
     typeof(MyClockControl), new FrameworkPropertyMetadata(0));

// .NET Property wrapper
public int Temprature
{
    get { return (int)GetValue(TempratureProperty); }
    set { SetValue(TempratureProperty, value); }
}
Each dependency property provides  Callbacks for value change notification, value coercion and value validation. These callbacks  can be registered with FrameworkPropertyMetadata  object of the dependency property.
public static readonly DependencyProperty TempratureProperty =
     DependencyProperty.Register( " Temprature", typeof(int),
     typeof(MyClockControl),
     new FrameworkPropertyMetadata(0,
                       OnTempraturePropertyChanged, 
                       OnCoerceTempratureProperty),
     OnValidateTempratureProperty);

// .NET Property wrapper
[Bindable(true)]
public int Temprature
{
    get { return (int)GetValue(TempratureProperty); }
    set { SetValue(TempratureProperty, value); }
}
Value Change Callback
private static void OnTempraturePropertyChanged(DependencyObject source, 
        DependencyPropertyChangedEventArgs e)
{
    var control = source as MyTempratureControl;
    var temprature = (int)e.NewValue;
    // write your logic here...
}
Coerce Value Callback
private static object OnCoerceTempratureProperty( DependencyObject sender, object data )
{
    if ((int)data > MaxTemprature )
    {
        data = MaxTemprature;
    } else if ((int)data < MinTemprature )
    {
        data = MinTemprature;
    }
 
    return data;
}
Validation Callback
private static bool OnValidateTempratureProperty(object data)
{
    // write your logic here...
    return (int)data>0 && (int)data <100;
}
 

Readonly DependencyProprites

Some dependency properties of UI controls are read only. They are often used to report state of a control, like IsMouseOver property. We can use normal CLR property but  Instead on normal CLR property, we might need trigger to get notification.
private static readonly DependencyPropertyKey IsHotPropertyKey = 
      DependencyProperty.RegisterReadOnly("IsHot", 
      typeof(bool), typeof(MyClass), 
      new FrameworkPropertyMetadata(false));
 
// Register the public property to get the value
public static readonly DependencyProperty IsHotProperty = 
      IsHotPropertyKey.DependencyProperty;    
 
// .NET Property wrapper
public int IsHot
{
   get { return (bool)GetValue(IsHotProperty); }
   private set { SetValue(IsHotPropertyKey, value); }
}

Attached Properties

Attached properties are a special kind of properties. They allow you to attach a value to an object that object doesn’t know anything about this value.
<Grid>
<!—Row s &columns definitions -->
    <Button Grid.Row="0" Grid.Column="0" Content="Click me!"/>
</Grid>
See ClickCommnad in the following example which on click execute a command from viewModel
<ListView x:Name="demoListView" >
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Extensions:ListViewItemBehavior.ClickCommand" Value="{Binding ElementName=demoListView, Path=DataContext.ClickCommand}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListViewItem">
                        <Border>
                            <GridViewRowPresenter Columns="{TemplateBinding GridView.ColumnCollection}" Content="{TemplateBinding Content}" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

public static class ListViewItemBehavior
{
    public static readonly DependencyProperty ClickCommandProperty =
        DependencyProperty.RegisterAttached(
        "ClickCommand",
        typeof(ICommand),
        typeof(ListViewItemBehavior),
        new FrameworkPropertyMetadata(null, ClickCommandChanged));
 
    public static ICommand GetClickCommand(ListViewItem listViewItem)
    {
        return (ICommand)listViewItem.GetValue(ClickCommandProperty);
    }
 
    public static void SetClickCommand(
        ListViewItem listViewItem, ICommand value)
    {
        listViewItem.SetValue(ClickCommandProperty, value);
    }
 
    static void ClickCommandChanged(
        DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        var item = depObj as ListViewItem;
        if (item == null)
            return;
 
        if (e.NewValue is ICommand)
        {
            item.PreviewMouseDown += OnListViewItemMouseDown;
        }
        else
        {
            item.PreviewMouseDown -= OnListViewItemMouseDown;
        }
    }
 
    static void OnListViewItemMouseDown(object sender, RoutedEventArgs e)
    {
        var item = sender as ListViewItem;
 
        if (item == null)
            return;
 
        var command = GetClickCommand(item);
 
        if (command.CanExecute(item.Content))
            command.Execute(item.Content);
    }
 
}

Clear Local Value

Assign null to dependency property is not really clearing the Locale Value of dependency property because null is also valid local value, there is static object  DependencyProperty.UnsetValue that describe as an unset value. Dependency property’s local value can be clear by invoking listView.ClearValue(ListView.ItemsSourceProperty) method.

MVC-Custom Model Validate

MVC - Custom Model Validate


1. Example 1

Add an attribute to validate your MVC model

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ModelValidateAttribute : ValidationAttribute
{

private string _defaultErrorMessage = string.Empty;

public override string FormatErrorMessage(string name)
{
return _defaultErrorMessage;
}

public override bool IsValid(object value)
{
if (value is ImodelValidator)
{
return (value as ImodelValidator).Valid(out _defaultErrorMessage);
}
else
{
throw new NotImplementedException("ImodelValidator Not Implemented");
}
return false;
}
}

Add an intrface
interface ImodelValidator
{
bool Valid(out string errorMessage);
}
Impliment interface to your model

[ModelValidate()]
public class RegisterModel : ImodelValidator
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }

[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }

[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }

#region ImodelValidator Members

public bool Valid(out string errorMessage)
{
if (Password.Contains('.'))
{
errorMessage = "invalid char";
return false;
}
else if (Password != ConfirmPassword)
{
errorMessage = "The password and confirmation password do not match.";
return false;
}
else if(!IsRegister(Email))
{
errorMessage = "Email already Registerd with website";
return false;
}
else
{
errorMessage = string.Empty;
return true;
}
return false;
}

#endregion
private bool IsRegister(string email)
{
return false;
} }
#endregion





2. Example 2

3. Example 3

MVC - Handle Multiple submit Buttons

Handle Multiple submit Buttons

If you are working on MVC asp.net proejct and If your form has mutiple submit buttons then MVC framwork can hadle only one Action, as result you need to add a attribute to handle your button specific action.

1. Add a ActionNameSelectorAttribute derived class.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ButtonHandlerAttribute : ActionNameSelectorAttribute
{
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }

public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (string.IsNullOrEmpty(MatchFormKey) && string.IsNullOrEmpty(MatchFormValue))
{ return false; }
else if (string.IsNullOrEmpty(MatchFormKey) )
{ return actionName == MatchFormValue; }
else if (string.IsNullOrEmpty(MatchFormValue))
{ return controllerContext.HttpContext.Request[MatchFormKey] != null; }
else
{
return controllerContext.HttpContext.Request[MatchFormKey] != null &&
controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
}
}

}

2. Add submit buttons on .ascx

... your code
<p >
<input value="Register" type="submit" name="action" >
<input value="Check" type="submit" name="action" >
</p>

…your code


3. Add your attribut on your controller’s action

public class AccountController : Controller
{
.. . your code
[HttpGet]
public ActionResult Register()
{
.. . your code
}



[HttpPost]
[ButtonHandler(MatchFormKey = "action", MatchFormValue = "Register")]
public ActionResult Register(RegisterModel model)
{
//... your code
}
//your another action
[HttpPost]
[ButtonHandler(MatchFormKey = "action", MatchFormValue = "Check")]
public ActionResult Check(RegisterModel model)
{
//... your code
}


.. . your code
}