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.

Custom Application Configuration

Custom Configuration
Create custom settings in the application settings as below;
    <configSections>
      <!--your other sectiongroups & sections -->
      <section name="viewTypeSettings" type="ConfigTest.ViewTypeSettings,ConfigTest" />        
    </configSections>
 

In order create custom settings in your application config file; create a class which derived from ConfigurationSection class as below


    public class ViewTypeSettings : ConfigurationSection
    {
        static ViewTypeSettings()
        {
            Settings = ConfigurationManager.GetSection("viewTypeSettings"as ViewTypeSettings;
        }
        public static ViewTypeSettings Settings { getprivate set; }
        [ConfigurationProperty("viewTypes")]
        public ViewTypeCollection ViewTypes { get { return this["viewTypes"as ViewTypeCollection; } }
    }
 
Now you can create custom elements as below
 <viewTypeSettings >
    <viewTypes>
      <viewType name="Phone" deviceIdentifiers="iPhone,iPod,Droid,Blackberry"></viewType>
      <viewType name="Tablet" deviceIdentifiers="iPad,Playbook,Transformer,Xoom"></viewType>
    </viewTypes>
  </viewTypeSettings>
 

In order to create custom elements, create a class which derived from ConfigurationElement Class   as below

 
    public class ViewType : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        //[StringValidator(InvalidCharacters = "  ~!@#$%^&*()[]{}/;’\"|\\", MinLength = 1, MaxLength = 256)]
        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\", MinLength = 0, MaxLength = 256)]
        public string Name
        {
            get { return this["name"as string; }
            set { this["name"] = value; }
        }
 
        [ConfigurationProperty("deviceIdentifiers", IsRequired = true)]
        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\", MinLength = 0, MaxLength = 256)]
        public string DeviceIdentifiers
        {
            get { return this["deviceIdentifiers"as string; }
            set { this["deviceIdentifiers"] = value; }
        }
 
    }
 

 In order to create custom element array , create a class which derived from ConfigurationElementCollection   as below

 
    [ConfigurationCollection(typeof (ViewType), AddItemName = "viewType",
        CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class ViewTypeCollection : ConfigurationElementCollectionIEnumerable<ViewType
    {
        #region Constructors
 
        static ViewTypeCollection()
        {
            _properties = new ConfigurationPropertyCollection();
        }
 
        #endregion
 
        #region Fields
 
        private static readonly ConfigurationPropertyCollection _properties;
 
        #endregion
 
        #region Properties
 
        protected override ConfigurationPropertyCollection Properties
        {
            get { return _properties; }
        }
 
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
        }
 
        #endregion
 
        #region indexer
 
        public ViewType this[int index]
        {
            get { return (ViewType) BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }
 
        public new ViewType this[string name]
        {
            get { return (ViewType) BaseGet(name); }
        }
        
        #endregion
 
        #region overriden methods
 
        protected override ConfigurationElement CreateNewElement()
        {
            return new ViewType();
        }
 
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as ViewType).Name;
        }
 
        public new IEnumerator<ViewType> GetEnumerator()
        {
            var baselsit = base.GetEnumerator();
 
            while (baselsit.MoveNext())
            {
                yield return baselsit.Current as ViewType;
            }
        }
 
        #endregion
    }
 


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