How to get the client IP address for the current controller call.

This article will show you hoe to get client IP address for the current controller

    private string GetClientIp(HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey("MS_HttpContext"))
        {
            return ((HttpContext)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
        }
        else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
        {
            RemoteEndpointMessageProperty prop;
            prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
            return prop.Address;
        }
        else
        {
            return null;
        }
    }

Note: you have to add using System.ServiceModel.Channels; namespace.
Add a reference to the assembly System.ServiceModel. Select Project-> Add Reference and then select the assembly name System.ServiceModel.

Advertisements
Posted in C#.NET, MVC | Tagged , | Leave a comment

How to access session in web api controller in mvc4

I realize session and REST don’t exactly go hand in hand but it is not possible to access session state using the new Web API. HttpContext.Current.Session is always null. REST is stateless. If you use a session the processing will become stateful, subsequent requests will be able to use state (from a session).

Let’s start by exploring how to extend Routes with Session state.

Web API routing, is operating on the same underlying ASP.NET RouteCollection, and therefore similar principles apply. ASP.NET has a concept of IRouteHandler which is a property on a System.Web.Routing.Route class and is responsible for processing HTTP requests for a route. By default, all Web API routes use HttpControllerRouteHandler which doesn’t do much, except handing over the HttpContexBase to HttpControllerHandler.

In order to provide session support, we will need to create 2 custom components:
– IRouteHandler, to replace the default HttpControllerRouteHandler and to tell the ASP.NET pipeline to go to our custom HttpControllerHandler.
– customized HttpControllerHandler, which will mark the route as being session enabled and then go back to the Web API execution pipeline

So what now? That’s surprisingly easy.

In order to enforce session on the IHttpHandler, we simply implement the interface IRequiresSessionState (more about which you can read here). This is a so-called marker interface – so all you need to do is make the handler use it, and you don’t have to implement any methods.

 public class SessionControllerHandler : HttpControllerHandler, IRequiresSessionState
{
    public SessionControllerHandler(RouteData routeData)
        : base(routeData)
    { }
}

This class does nothing more than introduce the marker interface, and hands the rest of the work to the default HttpControllerHandler which then continues with Web API execution pipeline.

By the way – this solution is inspired by the original proposal by Imran Baloch, who is doing great job for the ASP.NET community so make sure to follow his blog.

Plugging this in

So now we have session enabled, but how to plug this in in the first place?

Well, two steps:
1) create IRouteHandler that points to our new SessionControllerHandler
2) add it to the route when we register routes, so that a given route would use it

public class SessionRouteHandler : IRouteHandler
{
    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
    {
        return new SessionControllerHandler(requestContext.RouteData);
    }
}

And now, in the route registration, we add our route handler:

public static void Register(HttpConfiguration config)
{
    RouteTable.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    ).RouteHandler = new SessionRouteHandler();
}

Note, that I’m registering this against RouteTable.Routes directly, rather than GlobalConfiguration.Configuration.Routes. The reason for this is that the first collection is of type System.Web.Routing.Route (same as MVC) while the latter is of type System.Web.Http.Routing.IHttpRoute, and it does not allow you to set RouteHandler on it. Basically, this is us taking leverage on the fact that I mentioned in the beginning – that Web API routes and MVC routes are ultimately part of the same route collection

Complete Code

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            ).RouteHandler = new SessionRouteHandler();
        }
        
        public class SessionRouteHandler : IRouteHandler
        {
            IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
            {
                return new SessionControllerHandler(requestContext.RouteData);
            }
        }

        public class SessionControllerHandler : HttpControllerHandler, IRequiresSessionState
        {
            public SessionControllerHandler(RouteData routeData)
                : base(routeData)
            { }
        }
    }

Now we are ready, define session Session_Start in global.asax as below

protected void Session_Start()
{
    HttpContext.Current.Session.Add("Admin", "AdminUser");
}

and get this session in webapi as below

 public IEnumerable<Product1> GetAllProducts()
{
    var session = HttpContext.Current.Session;
    if (session != null)
    {
        string Admin = session["Admin"].ToString();
    }
    return products;
}

that’s it

Posted in C#.NET, MVC | Tagged , | 1 Comment

How to set read write permission to directory in C#.NET

While working with files and directory we need read write permission on files and folders, this can be done by manually giving access permission to directory as well as programmatically.

Here is code

Full access control to folder or directory


        private static void SetPermissions(string dirPath)
        {
            DirectoryInfo info = new DirectoryInfo(dirPath);
            WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
            DirectorySecurity ds = info.GetAccessControl();
            ds.AddAccessRule(new FileSystemAccessRule(self.Name, 
            FileSystemRights.FullControl,
            InheritanceFlags.ObjectInherit |
            InheritanceFlags.ContainerInherit,
            PropagationFlags.None,
            AccessControlType.Allow));
            info.SetAccessControl(ds);
        }


read-only on access on file

                        
    FileInfo myFile = new FileInfo(files.FullName);
    myFile.IsReadOnly = false;

or


File.SetAttributes(files.FullName, File.GetAttributes(files.FullName) & ~FileAttributes.ReadOnly);

Create a file with Read Write permission


 FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);

Posted in C#.NET | Tagged | Leave a comment

Fixed header for Webgrid in ASP.NET MVC

One of the very common and useful functionality is to keep fixed header for grid, when we have number of rows on page, Webgrid does not provide fixed header. This article will show you how to create a webgrid with fixed header.

Approach: When we create webgrid it actually create a html table with thead, tbody and tfoot. We will work on this table and split the table in to header, body , footer and put them in to three different div (header, body, footer), using jQuery in $(document).ready(function () {});. Some changes in css required as per our requirement. Newly created Webgrid with fixed header provide sorting and paging feature also.

Fixed Webgrid header

Fixed Webgrid header

Here is code

@model  List<FixedGridHeader.Models.StudentModel>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_MainLayout.cshtml";
}

<script type="text/javascript">
     $(document).ready(function () {
         $("#GridHeader").html("<table>" + $('#gridContent table thead').html() + "</table>");
         $("#GridHeader table tr:first").append("<th style='width:12px;' ></th>");
         $("#GridBody").html("<table>" + $('#gridContent table tbody').html() + "</table>");
         $("#GridFooter").html("<table>" + $('#gridContent table tfoot').html() + "</table>");
         $("#gridContent").hide();
     });
</script>

<style type="text/css">
    .webgrid-table td, th { border: 1px solid #98BF21;   }
    .webgrid-header { background-color: #A7C942; color: #FFFFFF; text-align: left;}
    .webgrid-alternating-row { background-color: #EAF2D3; }
    .colWidth { width: 200px;  }
    #Outer { font-family: "Trebuchet MS" , Arial, Helvetica, sans-serif;}
    #GridBody{width:1020px ;height:200px; overflow-y: scroll; border:solid 1px #e8eef4;  }
    #GridHeader table { width:1022px; text-align:left; margin-top: 0px; border: solid 1px #A7C942; padding:0px; border-collapse:collapse; } 
    #GridFooter  {  border:solid 1px #e8eef4; width:1020px; }
    #GridHeader table th { width: 200px;}
</style>

<h2>Student</h2>

@{
    var grid = new WebGrid(Model);
}

<div  id="gridContent" style=" padding:20px; " >
@grid.GetHtml(
        tableStyle: "webgrid-table",
        headerStyle: "webgrid-header",
        footerStyle: "webgrid-footer",
        alternatingRowStyle: "webgrid-alternating-row",
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
        mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
            grid.Column(columnName: "Name", header: "Name", format: @<text>@item.Name</text>, style: "colWidth"),
            grid.Column(columnName: "SchoolName", header: "School Name", format: @<text>@item.SchoolName</text>, style: "colWidth"),
            grid.Column(columnName: "Address", header: "Address", format: @<text>@item.Address</text>, style: "colWidth"),
            grid.Column(columnName: "City", header: "City", format: @<text>@item.City</text>, style: "colWidth"),
            grid.Column(columnName: "State", header: "State", format: @<text>@item.State</text>, style: "colWidth")
           ))
</div>
 
 <div id="Outer" >
 <div id="GridHeader"></div>
 <div id="GridBody"></div>
 <div id="GridFooter"></div>
 </div>

Complete code

Indexing and searching in Lucene.net (.NET)

Indexing and searching in Lucene.net (.NET)

Posted in ASP.NET MVC Web Grid, css, jQuery | Tagged , , | Leave a comment

How to pass model from view to controller using jQuery

This article will show you how to pass model from view to controller using jQuery. Using the submit button we can do it easily, jQuery use to pass elements as well as we can submit a form using jQuery.

Here is code

Add script “jquery.validate.min.js”

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript" > </script>

View page


@model Sample.Models.UserModel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript">
    $(document).ready(function () {
        $('#adduser').click(function (e) {
            e.preventDefault();
            if ($("#addNewUserForm").valid()) { //if you use validation
                $.ajax({
                    url: $("#addNewUserForm").attr('action'),
                    type: $("#addNewUserForm").attr('method'),
                    data: $("#addNewUserForm").serialize(),
                    success: function (data) {
                        alert(data.Status); 
                    }
                });
            }
        });
    });
</script>

@using (Html.BeginForm("AddUSer", "User", FormMethod.Post, new { id = "addNewUserForm" }))
{
    <div>First Name : @Html.TextBoxFor(x => x.FName)</div>
    <div>Last Name : @Html.TextBoxFor(x => x.LName)</div>
    <input id="adduser" type="button" value="Add User" />
}

One more way to do this, data is a serialized to JSON string. Note the name has to match the parameter name in the Model.

    function AddUser() {
        var UserModel =
        {
            "FirstName": "Abc",
            "LastName": "Pqr"
        };
        $.ajax({
            url: '/User/AddUser/',
            data: JSON.stringify(UserModel),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // return values 
            }
        });
    }

For the reference code of controller and model

Controller

 public class UserController : Controller
    {
        public ActionResult Index()
        {
            UserModel user = new UserModel();
            return View(user);
        }

        public JsonResult AddUser(UserModel user)
        {
            //  Add user model
            return Json(new { Status = "Success" }, JsonRequestBehavior.AllowGet);
        }
    }

Model

    public class UserModel
    {
        public string FName { get; set; }
        public string LName { get; set; }
    }
Posted in Ajax, jQuery, MVC | Tagged , | 3 Comments

Sending email in .NET MVC through Gmail

This articale will show you how to send mail through your gmail account, using your gmail credential.

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail

   public ActionResult Index()
    {
        var fromAddress = new MailAddress("from@gmail.com", "From Name");
        var toAddress = new MailAddress("to@example.com", "To Name");
        const string fromPassword = "fromPassword";
        const string subject = "Subject";
        const string body = "Body";
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment("d:/att/textfile.txt");
        try
        {
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body,

            })
            {
                message.Attachments.Add(attachment);
                smtp.Send(message);
            }
        }
        catch (Exception ex)
        { }
        return View();
    }
Posted in C#.NET, MVC | Tagged , | Leave a comment

Filter in lucene based on field value

filter in lucene based on field value
This article will show you how to customize the lucene search based on indexed Field. When we index a document we are adding

number of fields on document e.g. I am indexing a document with filed “Text” and “ID” as below.


    var doc = new Document();
    // Read file text and Pass it to the indexer
    string document_Content = "microsoft office";
    doc.Add(new Field("text", document_Content, Field.Store.YES, Field.Index.ANALYZED));
    doc.Add(new Field("ID", "1", Field.Store.YES, Field.Index.ANALYZED));
    writer.AddDocument(doc);

    var doc1 = new Document();
    string document_Content1 = "microsoft outlook";
    doc1.Add(new Field("text", document_Content1, Field.Store.YES, Field.Index.ANALYZED));
    doc1.Add(new Field("ID", "2", Field.Store.YES, Field.Index.ANALYZED));

    writer.AddDocument(doc1);

    var doc2 = new Document();
    string document_Content2 = "microsoft powerpoint";
    doc2.Add(new Field("text", document_Content2, Field.Store.YES, Field.Index.ANALYZED));
    doc2.Add(new Field("ID", "3", Field.Store.YES, Field.Index.ANALYZED));

    writer.AddDocument(doc2);

We added 3 document with 3 different IDs and want to search text where ID from 1 to 2.

Now I want to do search on field “Text” with the range of “ID” 1 to 2. For this we have to define filter using “FieldCacheRangeFilter” as below


    var parser = new QueryParser(Version.LUCENE_29, "text", analyzer);
    Query query = parser.Parse("microsoft");

    var filter = FieldCacheRangeFilter.("ID",
    lowerVal: 1, includeLower: true,
    upperVal: 1, includeUpper: true);

    TopDocs topDocs = searcher.Search(query, filter, 10);

Complete Code


 private static void SearchText()
    {
        Lucene.Net.Store.Directory directory = FSDirectory.Open(new DirectoryInfo(@"C:\LuceneIndex"));
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
        var searcher = new IndexSearcher(directory);

        var parser = new QueryParser(Version.LUCENE_29, "text", analyzer);
        Query query = parser.Parse("microsoft");

        var filter = FieldCacheRangeFilter.NewIntRange("ID",
        lowerVal: 1, includeLower: true,
        upperVal: 2, includeUpper: true);

        TopDocs topDocs = searcher.Search(query, filter, 10);

        int results = topDocs.ScoreDocs.Length;
        Console.WriteLine("Found {0} results", results);

        for (int i = 0; i < results; i++)
        {
            ScoreDoc scoreDoc = topDocs.ScoreDocs[i];
            float score = scoreDoc.Score;
            int docId = scoreDoc.Doc;
            Document doc = searcher.Doc(docId);

            Console.WriteLine("Result num {0}, score {1}", i + 1, score);
            Console.WriteLine("ID: {0}", doc.Get("text"));
            Console.WriteLine("Text found in: {0}\r\n file", doc.Get("FileName"));
        }

        searcher.Close();
        directory.Close();
    }

If you run the application you will see only two results where as we have “microsoft” word three times in indexing.
Lucene Version : v4.0.30319

Posted in lucene, MVC | Tagged | Leave a comment