Sunday, August 10, 2014

Get string values from AJAX from MVC5 controller and update DOM elements

DOM ELEMENT
<img id="userImage" src="" class="img-thumbnail" alt="New Company" />   
javascript
    


function loadUserImage() {
            $.ajax({
                url: "@Url.Action("GetUserImageUrl","Account")",
                dataType: "json",
                type: "POST",
                success: function (result) {
                    $("#userImage").attr('src', result);
                }

            });
        }

        function loadCompanyImage() {
            $.ajax({
                url: "@Url.Action("GetUserImageUrl","Account")",
                dataType: "json",
            type: "POST",
            success: function (result) {
                $("#companylogo").attr('src', result);
            }
            });
        }

        $(document).ready(loadUserImage); //Load User Image
    
MVC CONTROLLER ACTION

  [HttpPost]
        public JsonResult GetUserImageUrl()
        {
            return Json(SessionHelper.UserImageUrl);
        }

Thursday, February 24, 2011

DotNetNuke: Enable Human Friendly Urls

DotNetNuke: Enable Human Friendly Urls

 

 DotNetNuke 4.8 added Human Friendly urls, but unlike Friendly URLs, it can only be enabled through the web.config. To enable human friendly urls, replace:

<add name="DNNFriendlyUrl" type="DotNetNuke.Services.Url.FriendlyUrl.DNNFriendlyUrlProvider, DotNetNuke.HttpModules" includePageName="true" regexMatch="[^a-zA-Z0-9 _-]" />

with:

<add name="DNNFriendlyUrl" type="DotNetNuke.Services.Url.FriendlyUrl.DNNFriendlyUrlProvider, DotNetNuke.HttpModules" includePageName="true" regexMatch="[^a-zA-Z0-9 _-]" urlFormat="HumanFriendly" />

 

Wednesday, January 5, 2011

TimeSpan Calculation

If you ever want to calculate the difference between two points of time …

 

 

DateTime startTime = DateTime.Now;

 

…. Your code comes here …..

 

TimeSpan elapsedTime = DateTime.Now - startTime;

 

string TimeSpent = elapsed.ToString(); // ##:##:##

 

 

Roundin Values in C Sharp - RoundOff

If you ever want to round off a value in CSharp … you can always you Math.Round function …

 

e.g.

 

Math.Round(23.435321, 0) // this will round off the figure and remove all figures after decimal points.

 

J

Sunday, January 2, 2011

Dealing with DateTime different timezones

DateTime object gives us the luxury of only converting to and
from Universal Date Time (Formerly GMT) and Local Time (System Time Zone).

// expects DateTimeObject to contain Local Time and converts it to Universal
// Date Time value
DateTimeObject.ToUniversalTime()

// expects DateTimeObject to contain Universal Time and converts it to Local
// Date Time value
DateTimeObject.ToLocalTime()

So apparently there is no way to convert to and from a specific time zone.
But there are certain techinques to acheive what you need.

You can go along the following ways.


1) Use Javascript to pass the clients time zone offset to the server in a
hidden field and compute the British time on the server by first converting
the Server Local Time to Universal time and then adding the client's Time
Zone Offset to the Universal Time.

//javascript on client
dt = new Date();
locOffset = dt.getTimezoneOffset(); // get client's time zone offset
//Now pass this in a hidden feild to the server

//C# on Server
DateTime dt = DateTime.Now;
DateTime desiredTime = dt.ToUniversalTime().AddHours(offset);
//Note: offset is the client's time zone offset passed in the hidden field



2) If you want to perform all the computations on the server side then you
can probably use a class written by a gentleman which makes use of windows
APIs and can convert to any time zone.
http://staceyw.spaces.live.com/blog/cns!F4A38E96E598161E!931.entry

Monday, December 13, 2010

Write your own .Net RSS feed in c#

a very good post to create your very own rss feed in CSharp
 

Sunday, December 12, 2010

asp.net ashx handler

Talking about URL Rewriting, Generic Handlers, Http response the images, and using images in email read notices. all can be addressed in this wonderful article that I found on dot net perls by sam allen.

 

ASP.NET ASHX Handler Tutorial

You want to create an ASP.NET file that is not a typical web forms page. Your file will need to dynamically return an image from a query string, or XML and other non-HTML web pages. Here is a simple tutorial for using an ASHX generic handler in ASP.NET, with code written in the C# programming language.

 

Using ASHX handlers

First we review the goal in using ASHX files in the ASP.NET web development framework. What we will be able to do is use the ASHX file in a URL, and have it return content dynamically. We will use the query string, and the final URLs will look like this:

http://dotnetperls.com/?file=name

Getting started. This part lists the steps you can take to add a new ASHX file. To do this, open your ASP.NET web site. Go to the Website menu and click on the very first menu item there, "Add New Item...". This will present the Add New Item dialog box. Select the "Generic Handler" item, and you will get a new file with some code in it called Handler.ashx.

Autogenerated code

Here we note what the autogenerated code in the ASHX file does. It defines two parts of the IHttpHandler interface. The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested or pointed to. You shouldn't modify the interface inheritance or remove either of the members.

Mapping handler

It is often desirable to map an older URL or path to your new ASHX file. For backwards compatibility and for search engine optimization, you will probably want the new handler to take over an old URL in your site. To do this, use urlMappings; alternatively, you can use more complex RewritePath methods.

--- Part of Web.config file (XML) ---  <system.web>     <urlMappings enabled="true">         <add url="~/Default.aspx" mappedUrl="~/Handler.ashx"/>     </urlMappings>     ...

URL mappings. The above Web.config markup will automatically link one URL to another. Now, when the Default.aspx page is requested, your Handler.ashx file will take over. This means you can map the default page in a directory to your handler.

See urlMappings for Redirects.

Adding example image

Here we mention what you can do with the ASHX file involving images. Find your favorite image on your disk or on the Internet and add it to your website project. For my example, the image I chose was "Flower1.png". Next we will use this image in the Handler.ashx file.

Modifying Handler.ashx

Your handler has two parts, and here we must modify the ProcessRequest() method. We can change the ContentType of the file and the Response content. Modify your Handler.ashx to be similar to the following, with your image ContentType and file name.

~~~ ASHX code-behind file (C#) ~~~  <%@ WebHandler Language="C#" Class="Handler" %>  using System; using System.Web;  public class Handler : IHttpHandler {      public void ProcessRequest (HttpContext context) {         // Comment out these lines first:         // context.Response.ContentType = "text/plain";         // context.Response.Write("Hello World");          context.Response.ContentType = "image/png";         context.Response.WriteFile("~/Flower1.png");     }      public bool IsReusable {         get {             return false;         }     } }

Testing handler

Here we test the new configuration and ASHX file on the local machine. Now click the green arrow to run your website on the development server. You should see the image in your browser. This is the result of writing the image to the response in the handler.

 

Adding functionality

The example here so far is relatively useless. All it does is allow us to pipe an image through an ASHX handler. Note that you can add any logging code or referrer logic to the handler in the C# language. Developers commonly need to use the QueryString collection on the Request. You can use the Request.QueryString in the Handler just like you would on any ASPX web form page.

=== ASHX modified code-behind (C#) ===  <%@ WebHandler Language="C#" Class="Handler" %>  using System; using System.Web;  public class Handler : IHttpHandler {      public void ProcessRequest (HttpContext context) {          HttpResponse r = context.Response;         r.ContentType = "image/png";         //         // Write the requested image         //         string file = context.Request.QueryString["file"];         if (file == "logo")         {             r.WriteFile("Logo1.png");         }         else         {             r.WriteFile("Flower1.png");         }     }      public bool IsReusable {         get {             return false;         }     } }

What this does. The above code receives requests and then returns a different file based on the QueryString collection value. It will return one of two images from the two query strings. The strings it returns are shown next here.

              URL: http://dotnetperls.com/?file=logo File query string: logo      File written: Logo1.png                URL: http://dotnetperls.com/?file=flower File query string: flower      File written: Flower1.png

Testing query string

Does all this really work? Yes, it does, but it is always important to test it. Open your browser and on the path add query strings like shown in the above table. What happens is that ASP.NET internally maps the Default.aspx page to your Handler.ashx. Then, it receives the query string and write the appropriate file.

 

Uses

The code here could be used as a hit tracker that counts visitors and logs referrers. This could provide a more accurate visit count than server logs, because of browser and bot differences.

Handlers vs. web pages. ASP.NET web forms inherit from the Page class. This provides them with many events and a very detailed initialization and event model. You don't need that for dynamic images, XML, or binary files.

Performance

You are likely wondering if there is any performance advantage or change to using ASHX files. Here I mention Robbe Morris' benchmarking work, where he found that generic handlers are 5-10% faster than ASPX web forms that do the exact same operations—even without server controls. It is faster because it does a lot less. As you can imagine firing 10+ events each time a request is handled is a fair amount more expensive than only firing one event.

Choosing handlers

Here the author wants to propose some guidelines about when to use custom handlers and when to use ASPX web form pages. Handlers are better for binary data, and web forms are best for rapid development.

Use Web Forms: If you have simple HTML pages                ASP.NET custom controls                Simple dynamic pages  Use handlers: If you have binary files               Dynamic image views               Performance-critical web pages               XML files               Minimal web pages

Control trees

In the ASP.NET framework, web forms use a concept called control trees where the parts of web pages are stored in an object model. Use custom handlers when you do not require the custom control tree or the whole HTML web form framework. This will result in greater performance and much simpler code to debug.

IsReusable property

The author does not know precisely what the IsReusable property does in ASP.NET, as much of the supporting code is not in the ASHX file itself. His reading indicates that it can improve performance and decrease memory pressure by not destroying the handler repeatedly.

Summary

In this article, we saw how you can use ASHX custom handlers in your ASP.NET website. This could be modified to fill in many different important web site functions. Combine urlMappings with query strings on custom handlers to greatly simplify and streamline your back-end web site code.