Total Pageviews

Tuesday, May 21, 2013

How to give permissions to a folder pro-grammatically using C# in Windows

Below are the code which gives full control to a folder programmatically


 var dInfo = new DirectoryInfo(@"C:\\MyFolder");
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            dInfo.SetAccessControl(dSecurity);


Enjoy reading

Wednesday, May 1, 2013

Call Restful Service using HttpWebRequest and Post data

Introduction
        This article helps  you call Restful service using HttpWebRequest and Post Data to a particular service.

Our Restful Service
Contract

[ServiceContract]
    public interface IOrionChatService
    {


 [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/PushNotification")]
        [OperationContract]
        void MyServiceMethod(PostedInformation postedInformations);
}

Service Implementation
  public void MyServiceMethod(PostedInformation postedInformations)
{
//do implemention code here
}


DataContract

  [DataContract]
    public class PostedInformation 
    {
        [DataMember]
        public List<string> To { get; set; }
        [DataMember]
        public string SenderEmail { get; set; }
        [DataMember]
        public string Subject { get; set; }
        [DataMember]
        public string SenderFullName { get; set; }

    }


Calling our created Restful service from a Console application using HttpWebRequest

//Create a  new object of the class that we want to post

  PostedInformation postedInformations = new PostedInformation ()
            {
               SenderEmail = "aaa@bbb.com",
               SenderFullName = "test",
                To = new List<string>() { "ccc@eee.com" }
            };
//Serialize the postedInformations to jSon using Newtonsoft.json. You can download dll from here //http://json.codeplex.com/



 var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postedInformations ));
//Passyour service url to the create method
            var req = 
HttpWebRequest.Create("http://localhost/MyServer/YourServiceName.svc/MyServiceMethod");
            req.ContentType = "application/json";
            req.ContentLength = dataToSend.Length;
            req.Method = "POST";
            req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
            var response = req.GetResponse();

Enjoy......


Friday, March 22, 2013

Post data to the action result in jqGrid and ASP.NET MVC

Here when a dropdown change the filter value (what we are selected ) will pass to the action result

Script

 $(".selectRequestType").change(function () {
                 $('#jqgRequests').setGridParam({ postData: { FilterValue: $(this).val() } }).trigger('reloadGrid', [{ page: 1 }]);
            });

Action Result

 [AcceptVerbs(HttpVerbs.Post)]
            public JsonResult LoadRequest(JqGridRequest request, PostDataViewModel postData)
            {
           }

 public class PostDataViewModel
    {
       public string FilterValue { get; set; }
    }


Saturday, March 16, 2013

Html.Partial,Html.RenderPartial,Html.Action and Html.RenderAction in ASP.NET MVC

Html.Partial and Html.RenderPartial
        The Html.Partial helpers renders a partial view in to string.Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads


public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);
Example : 
@Html.Partial("MyPartial")    

The RenderPartial  is similar to Partial, but RenderPartial writes directly to the response
output stream instead of returning a string. For this reason, you must place RenderPartial inside
a code block instead of a code expression
Example : 
@{Html.RenderPartial("MyRenderPartial");}
So, which should you use, Partial or RenderPartial
            In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream.
Html.Action and Html.RenderAction
         Html.Action and Html.RenderAction are similar to Partial and RenderPartial.Action  executes a separate controller action and display the results.the only difference between Action and RenderAction is that RenderAction writes directly to the response.

Example :
      Imagine you are using the following controller

public class ActionDemoController : Controller {
public ActionResult Index() {
return View();
}
[ChildActionOnly]
public ActionResult DisplayMenu() {
var menu = GetMenuFromSomewhere();
return PartialView(menu);
}
}

The Menu action builds a menu model and returns a partial view with just the menu:
@model Menu
<ul>
@foreach (var item in Model.MenuItem) {
<li>@item.Text</li>
}
</ul>
In your Index.cshtml view, you can now call into the Menu action to display the menu:
<html>
<head><title>Index with Menu</title></head>

<body>
@Html.Action("DisplayMenu")
<h1>Welcome to the Index View</h1>
</body>
</html>


       Notice that the Menu action is marked with a ChildActionOnlyAttribute. The attribute prevents the runtime from invoking the action directly via a URL. Instead, only a call to Action or RenderAction can invoke a child action. The ChildActionOnlyAttribute isn’t required, but is generally recommended for child actions.

Passing values to Action
       Sometimes you want to pass parameters in to the action.

Example:

[ChildActionOnly]
public ActionResult Menu(MenuParameters param) {
return PartialView(
param
);
}


@Html.Action("Menu", new {
options = new 

MenuParameters 
{ Width=400, Height=500 } })










Load Partial View as Partial View Result using Ajax in ASP.NET MVC

            In ASP.NET MVC we can return a Partial View in the form of PartialViewResult using the PartialView method.
           The following example shows Partial update scenarios using Ajax.Using jQuery to load the contents of a PartailView in to the current view using an Ajax call. In this example i have load a simple grid using Ajax.
           Controller and Action Result

 public class PartialController : Controller
    {
        //
        // GET: /Partial/

        public ActionResult GetPartialResult()
        {
            var list = new List<Album>
                           {
                               new Album {Title = "Album1"},
                                new Album {Title = "Album2"},
                                 new Album {Title = "Album3"},
                                  new Album {Title = "Album4"}
                           };
            return PartialView(list);
        }

    }

 public class Album
    {
        public string Title { get; set; }
    }


Right click the ActionResult and Create a PartialView like below

@model IEnumerable<Mvc4Demos.Controllers.Album>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
    </tr>
}

</table>

Here from another view when a button click load the PartialViewResult by using Ajax and Append in to a Result div


<script type="text/javascript">
    $(document).ready(function () {
        $('#btn').click(function () {
            $('#result').load('/Partial/GetPartialResult');
        });
    });

</script>


<input type="button" id="btn" value="PartialExample"/>
<div id="result"></div>


Sunday, March 3, 2013

jQuery Type Testing Function

Type testing function

  • Determine the type of an object
  • Useful for optional parameters &amp; validation
Example
             In this example  isNumeric() and isFunction() are used as Type testing function
   
   <head>
    <title></title>
    <script src="script/jquery-1.7.1.js" type="text/javascript"></script>

</head>
<body>
    <script type="text/javascript">
        function callAnotherFunction(arg1,arg2,arg3) {
            var times = $.isNumeric(arg1) ? arg1 : 3;
            var delay = $.isNumeric(arg2) ? arg2 : 1000;
            var functiontocall = $.isFunction(arg1) ? arg1 : $.isFunction(arg2) ? arg2 : arg3;
            var i = 0;
            (function loopIt() {

                i++;
                functiontocall();
                if(i<times) {
                    setTimeout(loopIt, delay);
                }
            })();
        }        
   

        function functionToCall() {
            $('#output').append("<br/>fuction called");
        }

        $(document).ready(function () {
            callAnotherFunction(3, 500, functionToCall);
        });
               
    </script>
    <div id="output"></div>
</body>
</html>

   
   
Output
fuction called
fuction called
fuction called

Monday, December 10, 2012

Single Responsibility Principle



            In this context a responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes. The Single Responsibility Principle is a simple and intuitive principle, but in practice it is sometimes hard to get it right.
Intent
A class should have only one reason to change.
Example
            Let's assume we need an object to keep an email message. We are going to use the IEmail interface from the below sample. At the first sight everything looks just fine. At a closer look we can see that our IEmail interface and Email class have 2 responsibilities (reasons to change). One would be the use of the class in some email protocols such as pop3 or imap. If other protocols must be supported the objects should be serialized in another manner and code should be added to support new protocols. Another one would be for the Content field. Even if content is a string maybe we want in the future to support HTML or other formats.
If we keep only one class, each change for a responsibility might affect the other one:
Ø  Adding a new protocol will create the need to add code for parsing and serializing the content for each type of field.
Ø  Adding a new content type (like html) make us to add code for each protocol implemented.
// single responsibility principle - bad example
interface IEmail {
            public void setSender(String sender);
            public void setReceiver(String receiver);
            public void setContent(String content);
}
class Email implements IEmail {
            public void setSender(String sender) {// set sender; }
            public void setReceiver(String receiver) {// set receiver; }
              public void setContent(String content) {// set content; }
}
We can create a new interface and class called IContent and Content to split the responsibilities. Having only one responsibility for each class give us a more flexible design:
Ø  adding a new protocol causes changes only in the Email class.
Ø  adding a new type of content supported causes changes only in Content class.
// single responsibility principle - good example
interface IEmail {
            public void setSender(String sender);
            public void setReceiver(String receiver);
            public void setContent(IContent content);
}
interface Content {
            public String getAsString(); // used for serialization
}
class Email implements IEmail {
            public void setSender(String sender) {// set sender; }
            public void setReceiver(String receiver) {// set receiver; }
            public void setContent(IContent content) {// set content; }
}
Conclusion
            The Single Responsibility Principle represents a good way of identifying classes during the design phase of an application and it reminds you to think of all the ways a class can evolve. A good separation of responsibilities is done only when the full picture of how the application should work is well understand.