Quick Tip

Different MasterPage for Mobile and Desktop in ASP.NET

Now a days more people have been accessing the web on mobile devices as compared to desktops and creating mobile versions of websites have become a necessity. In ASP.NET Web Forms application we can switch between different mastre pages basis which device user is using to access the site. This gives a lot of advantages such as changing layout of the pages, applying different style sheets and even load different content if the need be. To achieve this im ASP.NET Web Forms application simply define a base page as following public partial class BasePage : System.Web.UI.Page { protected void Page_PreInit(Object sender, EventArgs e) { if (Request.Browser.IsMobileDevice) { this.MasterPageFile = “~/Mobile.master”; } else { this.MasterPageFile = “~/Desktop.master”; } } } Now rest of the pages (such as example below) can simply inherit base page and all those pages will have different master pages for mobile and desktop. public partial class MyPage :[…]

Quick Tip

Pass Values from One Page to Another

When we need to pass values from one page to another, two most common ways it is implemented is to either use a query string parameter and append the data to query string in the URL, or use a postback to post the data using form submission. Recently I was required to pass some values from one page to another page so I went ahead and did a quick query string implementation to pass the values which worked pretty well until I looked at the analytics data which reported same page with different query parameter as different URLs. I didn’t like it (neither did my SEO team) since the query string parameters did not change the functionality of the target page. It just happened to be some additional data for the target page so I decided to go for alternate options. Next option was to use session state but that data is stored on the server[…]

Quick Tip

Responsive Image Overlay over Another Image

I was working on a gaming site which would have two modes to play and a title for each game. I decided to display two options on the game logo itself and since the entire website was responsive, I needed to handle some responsive stuff which I wanted to share here. Bootstrap 4 was used for overall responsive behavior in the site and the additional CSS required to handle individual game title is as following .overlay-container { position: relative; overflow: hidden; } .overlay-top{ height: 33%; position: absolute; top: 0; width: 100%; } .overlay-middle{ height: 33%; position: absolute; top: 33%; width: 100%; } .overlay-bottom{ height: 33%; position: absolute; top: 66%; width: 100%; } .title { text-align: center; margin-left: auto; display: block; margin-right: auto; max-width:100%;} .play { text-align: center; margin-left: auto; display: block; margin-right: auto; max-width:80%; } .img-responsive{ width: 100%; } There are 3 overlay images divided equally in height. Top container is set[…]

Quick Tip

Bundling and Minification in ASP.NET Web Forms Application

ASP.NET has in-built for bundling of multiple resources such as js or css files into one file and then minifiy the files to reduce the number of calls made to the server and total data size downloaded from the server thus reducing the total download time and enhanding application’s performance.  In order to use this in web forms application which target version .NET 4.5 and higher, following steps are required 1. Go to NuGet Package Manager and install Microsoft.AspNet.Web.Optimization and Microsoft.AspNet.Web.Optimization.WebForms packages 2. Check web.config to make sure “webopt” tag prefix is added (once you install Microsoft.AspNet.Web.Optimization.WebForms) <pages> <namespaces> <add namespace=”System.Web.Optimization” /> </namespaces> <controls> <add assembly=”Microsoft.AspNet.Web.Optimization.WebForms” namespace=”Microsoft.AspNet.Web.Optimization.WebForms” tagPrefix=”webopt” /> </controls> </pages> 3. Add a class file as following and define the resources you want to bundle public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { Bundle cs = new Bundle(“~/bundles/cssv1”, new CssMinify()); cs.Include(“~/Resources/css/bootstrap.min.css”, “~/Resources/css/app.css”); bundles.Add(cs); bundles.Add(new ScriptBundle(“~/bundles/jsv1”).Include( “~/Resources/js/jquery.min.js”, “~/Resources/js/bootstrap.min.js”)); BundleTable.EnableOptimizations = true;[…]

Quick Tip

Block libwww-perl attack in ASP.NET Application hosted in IIS

Libwww-perl (LWP) is a WWW client/server library for perl which can be used by hackers, spammers or automated bots to attack a website to steal information so we need to apply security to our web application to eliminate many simpler attacks on the website. In order to fix this issue in an ASP.NET web application we can use the following code. Add the code in Application_BeginRequest method of Global.asax file in your web application protected void Application_BeginRequest(object sender, EventArgs e) { string userAgent = HttpContext.Current.Request.ServerVariables[“HTTP_USER_AGENT”]; if (!string.IsNullOrEmpty(userAgent)) { if (“Libwww-perl”.ToLower().Equals(userAgent.ToLower())) { Send403(Response); } } } internal void Send403(HttpResponse response) { SendResponse(response, 0x193, “403 FORBIDDEN”); } internal void SendResponse(HttpResponse response, int code, string strBody) { HttpContext current = HttpContext.Current; object obj2 = current.Items[“ResponseEnded”]; if ((obj2 == null) || !((bool)obj2)) { current.Items[“ResponseEnded”] = true; response.StatusCode = code; response.Clear(); if (strBody != null) { response.Write(strBody); } response.End(); } } Another option is to disallow Libwww-perl user[…]

SEO Tip: Set Preferred URL in ASP.NET Application

Search engines treat website URL with and without “www” differently. Though both URLs point to the same destination, it’s important to pick one and set as your preferred URL so that search engines don’t two URLs as duplicate content. Websites use 301 redirect for this. The example code to redirect non-www URL to www URL in an ASP.NET application would be as following. Add following code snippet in Application_BeginRequest method of your Global.asax. Replace URL (somewebsite.com) with your website URL in the code and you are all set. protected void Application_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith(“http://somewebsite.com”)) { string newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace(“http://somewebsite.com”, “http://www.somewebsite.com”); Response.Status = “301 Moved Permanently”; Response.AddHeader(“Location”, newUrl); } } If you want to do the opposite and direct www URL to non-www URL simply change the code as following protected void Application_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith(“http://www.somewebsite.com”)) { string newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace(“http://www.somewebsite.com”, “http://somewebsite.com”); Response.Status = “301 Moved Permanently”;[…]

Add SEO Friendly URL’s to ASP.NET Application

It’s very important for a web site to create SEO friendly URL’s and remove page extensions such as .aspx. When search engines look at a site, the first thing they analyze is the page URL which help them ascertain what the page content is about. In ASP.NET application Routes can be used for this which are URL patterns used for processing requests and can be used to construct URLs dynamically. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event in Global.asax. In order to do so add Global Application Class (Global.asax) to your ASP.NET Web Application if it is not created yet. The following example shows how to add a route. protected void Application_Start(object sender, EventArgs e) { try { RegisterRoutes(RouteTable.Routes); } catch (Exception ex) { // Log Exception here } } protected static void RegisterRoutes(RouteCollection routes) { if[…]

Publish an ASP.NET website without roslyn folder

If you create a ASP.ENT website using Visual Studio 2015 or higher and .NET Framework 4.5.2, it by default uses Roslyn which is a set of open-source compilers and code analysis APIs for C# and Visual Basic. Publishing this would also include “roslyn” folder in bin directory containing a bunch of libraries and exe files which creates issues if you are using a shared hosting service as normally shared hosting do not run under full trust. We can simply remove this by going to Tools -> NuGet Package Manager -> Manager NuGet Packages for Solution -> Uninstall following packages Microsoft.CodeDom.Providers.DotNetCompilerPlatform Microsoft.Net.Compilers Check web.config and make sure the following section was removed by the NuGet package uninstall. If it did not get removed for any reason, then clean it up manually <system.codedom> <compilers> <compiler language=”c#;cs;csharp” extension=”.cs” type=”Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ warningLevel=”4″ compilerOptions=”/langversion:6 /nowarn:1659;1699;1701″/> <compiler language=”vb;vbs;visualbasic;vbscript” extension=”.vb” type=”Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ warningLevel=”4″ compilerOptions=”/langversion:14[…]

Quick Tip

Convert C# Object to JSON and create object from JSON string

Json.Net is the preferred way to go about it because of performance gain it gets compared to JavascriptSerializer. Download and install Newtonsoft.Json using Nuget Now in order to create Json for an object simply use SerializeObject method as following Product product = new Product(); product.Name = “Apple”; product.Expiry = new DateTime(2008, 12, 28); product.Sizes = new string[] { “Small” }; string json = JsonConvert.SerializeObject(product); // { // “Name”: “Apple”, // “Expiry”: “2008-12-28T00:00:00”, // “Sizes”: [ // “Small” // ] // } In order to convert Json to the object use DeserializeObject method as following string json = @”{ ‘Name’: ‘Bad Boys’, ‘ReleaseDate’: ‘1995-4-7T00:00:00’, ‘Genres’: [ ‘Action’, ‘Comedy’ ] }”; Movie m = JsonConvert.DeserializeObject<Movie>(json); string name = m.Name; // Bad Boys  

Commenting Etiquettes While You are on Web !!

Now a days commenting on posts or blogs is not just what people do out of their interests only but also it is really important to be an active commenter on the social media to mark your presence known and maintain overall awareness about the updates. It helps in building links with others, building a community and sharing your views. Comments also reveal the engagement of your content. While sharing your views anywhere be it on a blog or some social networking post, you have to make sure that your comments are expressed in a good way. There are certain things to be taken care of before you comment. Here they are: • Make Valuable Comments: Make sure to never comment without proper knowledge about the subject and reading of the content. Comments should not be done just to make noise but to add on to the information. You can add a story related to a post[…]