Monday, 20 February 2012

How to get the current controller and action names in View Mvc3

In MVC we can use the partial views to avoid the redundant code. I have one requirement that the action names are same in two different controllers and there is partial view which has one link which needs to point to the current controller with the same action. I want to access the controller name in View to avoid the redundant code. The solution to get the Controller and Action names in View as follows. Solution:
 @{
        var controller = this.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
    
        Change password
        }
If you want to access the action name
var action=this.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();

Jquery Ajax Request and Unauthorized Access handling in MVC3

When we are posting the data through jquery $.ajax and  we are using asp.net forms authentication, if the user is not authorized then we will redirect to the login page. the same login page response is return result as on jquery ajax success. If we throw any exception in controller or any custom authorize attribute then ajax request returns the 500 status code internal server exception as its default behaviour. 500 status code reruns any exception in the request processing. But our view is to return the 401 as the status code. I research about many hours to get this solution.

Solution1:

1. Custom authentication attribute
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }

}
If the user is not authenticated the reruns to logon action as i am using forms authentication in asp.net.
2. In the controller action result write the following
 public ActionResult Logon()
 {
  if (Request.IsAjaxRequest())
  {
 
  //this is used when the authentication fails in the ajax request
  //this returns the httpstatus code 401 to the browser.
 
   ControllerContext.HttpContext.Response.StatusCode = 401;
 
   return Content(string.Empty);
  
   }

 } 
3. Handle the status codes in jquery $.ajaxSetup
$.ajaxSetup({
             statusCode: {
                        401: function () {
 
                            // Redirect the to the login page.
                            window.location = "/login/";
 
                        }
                    }
            });
Solution2:
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }


public override void OnAuthorization(AuthorizationContext filterContext)
{
   base.OnAuthorization(filterContext);

  // If its an unauthorized/timed out ajax request go to top window and redirect to logon.
    if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
    {
filterContext.Result = new JavaScriptResult() { Script = "top.location.reload()"    };
    }

  // If authorization results in HttpUnauthorizedResult, redirect to error page instead of Logon page.
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                if (ClientContext.Current.User == null)
                {
                    filterContext.Result =
                        new RedirectResult(
                            string.Format(
                                "~/logon/logon?ReturnUrl={0}",
                                HttpUtility.HtmlEncode(filterContext.HttpContext.Request.RawUrl)));
                }
                else
                {
                    filterContext.Result =
                       new RedirectResult(string.Format("~/error/unauthorized"));
                }
            }
        }
}
I hope this will help you. 

Friday, 14 October 2011

Windows User Account Control (UAC) restrictions have been addressed

When you are working with the SQL Server Reporting services on windows server 2008 R2 and Window7 then you may encounter the following exception

User ‘Domain\User’ does not have required permissions. Verify that sufficient permissions have been granted and Windows User Account Control (UAC) restrictions have been addressed


To overcome that issue we nee to set the User Account Control settings. The steps to set the User Access Control as follows

  1. Open control panel
  2. Click on System and Security
  3. Click on User Account Control Settings

    4.  Slide down the User Account Control up to never notify. Then Click on Ok.

   5. Restart the system now.
   6. Open the Report server url in browser(Ex: http://systemname/Reports)

I hope this will helps to you.



Replacing special characters while creating directory or file

When we are creating directory in windows it could not accept the spacial character for directory name.
If folder name string is dynamic( we don't know which string it is) then we need to write the spacial character from that string. To repalce special characrers while creating directory as follows(this step must be added if we don't confirm that string)
directoryname=System.Text.RegularExpressions.Regex.Replace(directoryname,@"[*?:\|<>\\/]", "-");

Monday, 3 October 2011

How to get comma separated string from the list of object for specified property

I have a one requirement that I have list of objects with that object have properties(ID, Name, Description). I want a comma separated string from the list of object for ID property.
We can achieve this by using Reflection classes.

The solution for the requirement has follows

Create a generic method to get the Comma separated string
 public static string GetCommaSeparatedString<T>(List<T> list, string property)
        {
                string value = string.Empty;
                PropertyInfo info = typeof(T).GetProperties().Where(i => i.Name == property).FirstOrDefault();
                if (info != null)
                {
                    foreach (T listItem in list)
                    {
                        value += info.GetValue(listItem, null).ToString() + ",";
                    }
                }
            return value.Substring(0,value.Length-1);
        }
Usage:
Take an example with Category class with the properties ID,Name
public class Category
{      
    public int ID { get; set; }
    public string Name { get; set; }
}
Create a list with Category objects
List<category> categories=new List<category>();
categories.Add(new Catagory {ID=1, Name = "abc" });
categories.Add(new Catagory {ID=10, Name = "pqr" });
Call the method as follows
GetCommaSeparatedString<Category>(categories,"ID");
//output: 1,10

Thursday, 15 September 2011

HTTP Error 500.21 - Internal Server ErrorHandler "PageHandlerFactory-Integrated" has a badmodule "ManagedPipelineHandler" in its module list

This is the error due to not installing the .net frame work 4.0 on IIS7.x server. To install the .net 4.0 frame work run the following on command prompt.
on 32-bit operating system
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i


on 64-bit operating system
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –i

If the above solution not worked then apparently, the reason for recieving the Internal Server error message was that installed SQL Server 2008, after installing Visual Studio 2010 vice versa, and because of this it corrupted the IIS Machine level configuration files ("If you install VS2010 and then install VS2008 and VS2008 SP1, the configuration files for ASP.NET in IIS only include about 1/2 of the correct .Net 4.0 configuration sections." read more here).

To repair this problem run a full silent repair of the .NET Framework 4.0.   Here's how on either a 32 bit or 64 bit computer:
  1. Click Start -> All Programs -> Accessories -> Run
  2. In the Open textbox paste in the following line (see list of all .NET Framework version install, repair and unistall command lines here):
    For silent repair on 32 bit computer with .Net Framework version 4.0.30319 use:
    %windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

    For silent repair on 64 bit computer with .Net Framework version 4.0.30319 use:
    %windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

  3. Click OK to start the repair
  4. After, the repair ran for a few minutes, I restarted IIS 7.5, and things began to work correctly!

Hopefully, this will work for you...

Sunday, 4 September 2011

How to start microsoft single sign-on service

Use the following procedure to start the Single Sign-On service.

Start the Single Sign-On service

  1. From Administrative Tools, click Services.
  2. Double-click Microsoft Single Sign-On Service.
  3. On the Log On tab of the Single Sign-On Service Properties page, click This account, and then type the domain, user name, and password that you have used to install and manage your server.
  4. Click Apply.
  5. On the General tab of the Single Sign-On Service Properties page, change the startup type to Automatic, click Start, and then click OK.