Change MAC Address on Ubuntu

As my IP provider restricts the number of network cards that can access the net so on ubuntu i needed to change the MAC address of my network card. It’s pretty easy, just two lines of command on terminal.

ifconfig eth0 down hw ether 01:02:03:04:05:06
ifconfig eth0 up

1st command down the network and change the MAC to 01:02:03:04:05:06 and 2nd command again up the network

Monthly Presentation : Introduction to iPhone SDK

As a part of monthly Presentation at MRSL, June 2010 i gave a presentation on Introduction to iPhone SDK. download

Monthly Presentation : Introduction to Cryptography

As a part of monthly Presentation at MRSL, May 2010 i gave a presentation on Introduction to cryptography. download

Custom ASP.NET MVC Authorize Attribute

AuthorizeAttribute allows you to secure controller actions. The Authorize attribute lets you indicate that authorization is restricted to predefined roles or to individual users. This gives you a high degree of control over who is authorized to view any page on the site.

public class UserController : Controller
{
    [Authorize]
    public ActionResult Create()
    {
        return View();
    }

}

what this code do? If an unauthorized user tries to access create methods then If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.

public class UserController : Controller
{
    [Authorize(Roles = "Admin")]
    public ActionResult Create()
    {
        return View();
    }

}

Now the user who has admin role can only access to this methods. But what if i want to check this role from my user type enum?

[Serializable]
[Flags] //  When Enum mark with “Flags“ attribute it will work as bit field
public enum UserType
{
    Admin=1,
    PM= 2,
    Developer = 4
}

ok then lets write the custom Authorize Attribute.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
        public new UserType Roles;  // new keyword will hide base class Roles Property
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }

            UserType role = (UserType)Lib.Models.User.CurrentUser.UserType;
                                      // you could get User role or user type from session.

            if (Roles != 0 && ((Roles & role) != role))
            {
                 return false;
            }
            return true;
}

here i just override the AuthorizeCore methods of AuthorizeAttribute class. Now, you have to decorate your controller or action with this custom attribute and use bitwise operators to pass multiple roles.

[CustomAuthorize(Roles = UserType.Admin | UserType.PM)]
public ActionResult Create()
{
	return View();
}

Get All Tables With RowCount

Following query will return all table’s name with rowcount from a database.

SELECT sysobjects.[name],  Max(sysindexes.rows) AS Rows
FROM  sysobjects  INNER JOIN sysindexes ON
sysobjects.id = sysindexes.id WHERE sysobjects.xtype = 'U'
group by sysobjects.[name] 

ASP.NET MVC or Web Form

Web Forms may be better choice if your are building an intranet site with lots of data editing.

ASP.NET MVC may be better choice if you are building a test driven Internet site where HTML, performance, and scalability are main concern.

For more details download

ASP.NET MVC 2 DropDownlist Extensions for Enum

The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view. The DropDownList helper renders a drop-down list.

<%= Html.DropDownList("Products") %>


But the problem is MVC framework doesn’t provide any Helper method to work with Enum Type. So we need to extend Html Helper to work with Enum.

public enum UserType
{
    Admin=1,
    PM= 2,
    Developer = 3
}

public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, Type type)
{
    if (!type.IsEnum) throw new ArgumentException("Type is not an enum.");
    var enums = new List<SelectListItem>();
    foreach (int value in Enum.GetValues(type))
    {
         enums.Add(new SelectListItem { Value = value.ToString(), Text = Enum.GetName(type, value) });
    }
     return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums);
}

For Strongly Typed

public static MvcHtmlString DropDownListFor(this HtmlHelper htmlHelper, Expression<Func> expression,
            Type type, object htmlAttributes)
{
     if (!type.IsEnum) throw new ArgumentException("Type is not an enum.");
     var enums = new List<SelectListItem>();
     foreach (int value in Enum.GetValues(type))
     {
         enums.Add(new SelectListItem { Value = value.ToString(), Text = Enum.GetName(type, value) });
     }
     return System.Web.Mvc.Html.SelectExtensions.DropDownListFor(htmlHelper, expression,
         enums, htmlAttributes);

}

Now let’s use those methods on view.

<%= Html.DropDownList("UserType", typeof(UserType)) %>
<%= Html.DropDownListFor(model=>model.UserType, typeof(UserType), null) %>  //for strongly typed

Get All Tables with Foreign Key status

When i was writing a Code Generator, i needed to get all the table with foreign key status from my database. Following query return that.

select [Name], Case WHEN object_id IN (SELECT parent_object_id
FROM sys.objects WHERE[type] ='F') THEN 1 ELSE 0 END HasFKey from sys.objects
WHERE [type] in('U') order by [Name]

Generate Pdf from URL

A few days ago I needed to write a class to generate pdf file from a given url and then save it to server. It was easy for me cause www.pdfmyurl.com does all the dirty stuff :)

System.IO.Stream stream = System.Net.WebRequest.Create(string.Format(“http://pdfmyurl.com?url={0}”, “www.google.com”)).GetResponse().GetResponseStream();

Then you need to write this steam to server.

Follow

Get every new post delivered to your Inbox.