Posts

Showing posts from March, 2014

Donate

Zooming Visual Studio 2012 Code Editor

Image
Just received a newsletter from dotnet videos regarding zooming in/out the code editor. In that email, there were three ways. However, there are several options to do it as presented below: 1). Using the zoom drop down control below the code editor. 2). Using Keyboard combinations: Zoom OUT = Ctrl + Shift + Comma, Zoom IN = Ctrl + Shift + Period 3). Type a zoom level directly in the the zoom control in the bottom left corner of the editor 4). Select a common zoom level from the dropdown list in the zoom control 5). Hold Ctrl key and scroll the mouse wheel (up/down). References: Visual Studio 2012 Zoom In or Zoom Out Visual Studio 2010 Zoom In or Zoom Out Cheers!

ASP.NET MVC 4 Built-in Form Based Authentication

Image
Given that I have some background knowledge of ASP.NET Web Forms Authentication, I decided to try experimenting on MVC 4 authentication/authorization framework. Most of the articles in the internet regarding forms authentication in ASP.NET MVC are custom based approach and less on the built-in technology which is WebData.WebSecurity usage. Not until I found these articles: a. Forms Authentication Customized b. Introduction to forms based authentication in MVC 4 c. Authenticating Users In Asp.net MVC 4 So, to cut the story short, I made an application which utilized the built-in WebMatrix authentication in MVC 4. The first thing to do, is to familiarize those articles to get a good grasp on the topic. The setup of my application are as follows: 1. Web.config      1.1 Added authentication and custom errors <authentication mode= "Forms" > <forms loginUrl= "~/Account/Login" timeout= "2880" /> </authentication>

Redirect Unauthorized Access To A Custom View Instead Of Redirecting To A Login View In ASP.NET MVC 4

One might encounter when implementing the forms authentication framework(WebMatrix)is that when a user access a specific url/controller and he/she is unauthorized, the application always redirect's to the default log-in view. In order to solve this minor issue, one solution is to develop a custom class that inherit's the AuthorizeAttribute class and override the HandleUnauthorizedRequest method as shown below: public class AuthorizeUsersAttribute : AuthorizeAttribute { private string redirectUrl = "" ; public string NotifyUrl { get { return redirectUrl; } set { redirectUrl = value ; } } public AuthorizeUsersAttribute() : base () { } public AuthorizeUsersAttribute( string redirectUrl) : base () { this .redirectUrl = redirectUrl; } protected override void HandleUnauthorizedRequest(Authorizati

You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class

In the Account Controller Register action (public ActionResult Register(RegisterModel model)) I have a code below that by default assign a Customer Role to a new user during registration. In my database, the defined roles are "Administrator" and "Customer". However, the code below generates exception as stated on the title post. SimpleRoleProvider role = new SimpleRoleProvider(); role.AddUsersToRoles( new string [] { model.UserName }, new string [] { "Customer" }); The solution would be to use the Role class defined in System.Web.Security namespace instead of SimpleRoleProvider: Roles.AddUserToRole(model.UserName, "Customer" ); Reference: Perils of MVC 4 AccountController Cheers! :)

Render ASP.NET MVC 4 Partial View Based From Html.DropdownList() Selected Value Using jQuery

Image
In my previous post on loading items to Select control, I decided to create a more advanced example by rendering an asp.net mvc partial view using jquery based on drop down selection. The mvc application will simply load all orders irregardless of the status made by a particular customer selected from the dropdown list. The application also calculates the total orders made by the customer using jquery numberformatter framework. Partial View: @model IList <ShowWebGridUsingJQuery.Models.SalesOrderHeader> @{ Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml"; } @{ var orderTotal = Model.Sum(o => (float)o.TotalDue); WebGrid grid = new WebGrid(Model); } <script type= "text/javascript" > $(document).ready(function () { var total = 0; $('#divGrid .totalDue').each(function () { total = total + parseFloat($(this)[0].innerHTML.toLocaleString().replace(",", &q

Populate Select/ListBox items From Html.DropdownList() Selected Value Using jQuery In ASP.NET MVC 4

Image
After familiarizing some basic concepts on ASP.NET MVC 4, I decided to create a simple application which populates a listbox control from a DropDownList helper selected value using jQuery. This simple application included the Entity Framework which targets the AdventureWorks DB.Here's the Model Class: public class CountryRegionsContext : Models.AdventureWorks2008Entities { public DbSet<CountryRegion> Country_Regions { get ; set ; } public DbSet<StateProvince> State_Province { get ; set ; } } Here's the View page: @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Adventure Works Country and State Province Information</h2> <script> $(document).ready( function () { $( "#State" ).prop( "disabled" , true ); $( "#Country" ).change( function () { if ($( "#Country" ).val() != "Select&quo

Add Placeholder (Watermark) To Html.TextBoxFor() Helper In ASP.NET MVC 4

Image
After working with simple form html elements, I decided to give it a try applying the placeholder jquery framework to ASP.NET MVC4 application. The steps are similar in this post: Placeholder attribute in HTML5 form Elements except that the target controls are HTML Helpers. Basically, TextBoxFor() helper when rendered to the browser is an input text element. So, let's give it a spin. On your _Layout.cshtml, reference the jquery and placeholder scripts. <script type= "text/javascript" src= "~/Scripts/jquery-1.7.1.min.js" ></script> <script type= "text/javascript" src= "~/Scripts/placeholders.jquery.min.js" ></script> and in your MVC Form, apply it to TextBoxFor() as shown below: @model TextBoxFor.Models.Movie @{ ViewBag.Title = "CreateMovie"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Movi

Change Default Start Page Of ASP.NET MVC 4 Application

Familiarizing myself with ASP.NET MVC 4 made me think, how can I change the default start page of using global.asax? The globax.asax only has declarations that calls methods and lacking the methods as seen in MVC 2-3 versions. Luckily, the structure of the project has been changed since the Routes have been transfered to App_Start folder. Below is the sample code to change the default start page using the the class RouteConfig. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" ); //routes.MapRoute( // name: "Default", // url: "{controller}/{action}/{id}", // defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //); routes.MapRoute( name: "Default" , url: "{controller}/{action}/{id}" , defaults: new { controller = "Movies" , action = "I

Placeholder Attribute In HTML5 Not Showing On IE 9 And Below (Watermark Feature)

Image
Given this html markup for input text element for accepting email value: <input type= "email" name= "inEmail" id= "inEmail" required= "required" placeholder= "yourname@domain.com" /> The place holder shows correctly on firefox and google chrome but not on IE 9. After searching the internet, I found placeholder framework that will fix place holders in IE 9 and below. The steps are as follows: 1. Download the placeholder script here: Placeholder js 2. Add reference to jquery and placeholder on your html file. <script src= "../Scripts/jquery-1.7.1.min.js" type= "text/javascript" ></script> <script src= "placeholders.jquery.min.js" type= "text/javascript" ></script> IE demo: That's it... :)

The type specified in the TypeName property of ObjectDataSource 'ObjectDataSource1' could not be found (ASP.NET Webservice)

As I was updating one of my ASP.NET Web Forms application to 4.5, running the app generates an error as stated above. I remembered that the Object Datasource control was dependent on a webservice. So, after reviewing the new configuration of the webservice, the port, url and namespace have changed. So, here are the steps to make my app work again. Steps: 1. Update the web service .discomap file through Add Service Reference and then choosing advanced to target it as .NET 2.0 platorm. Though Service Reference should be recommended or WCF service. 2. Change Web.Config setting of the web service including it's IP and Port. Example:<br> <add key="localhost.ECommerceService" value="http://192.168.2.1:1448/WebDeployServer/QuotesPaymentService.asmx"/><br> to<br><add key="localhost.ECommerceService" value="http://192.168.2.1:14070/WebDeployServer/QuotesPaymentService.asmx"/> 3. Configure again the obje

Prevent saving changes that require the table re-creation (SQL Server Error in Updating Primary Key Is Identity)

Good Day! I forgot to set the identity of the primary key of field Id in table Products. After inserting records through insert statements, an error occurs since the column Id does not allow null values. So, I tried changing the Is Identity to true but unluckily I'm stuck with the an error "Prevent saving changes that require the table re-creation". Additional details are as follows: ID field has a constraint called PK_Products. So, after googling a while I came up with series of steps. Note: You have to close the design view of the table in the Management Studio to perform the steps below. -- 1 ALTER TABLE Products DROP CONSTRAINT PK_Products GO -- 2 Alter Table Products Drop Column Id Go -- 3 Alter Table Products Add Id_new Int Identity (1,1) Go -- 4 Exec sp_rename 'Products.Id_new' , 'Id' , 'Column' Go -- 5 ALTER TABLE Products Add CONSTRAINT PK_Products Primary Key (ID) GO

Custom Richtextbox Control With Watermark Support In VB.NET

Here's the VB.NET Version of this Custom Control from this post: Custom Richtextbox control with Watermark Support in C# Option Strict On Option Infer On Imports System.Drawing Imports System.ComponentModel ''' <summary> ''' Set Watermark in RichTextbox. ''' </summary> Public Class WatermarkRichTextbox Inherits Windows.Forms.RichTextBox Private m_watermark As String Private m_watermarkColor As Color Private m_foreColor As Color Private empty As Boolean <Browsable( True )> _ Public Property WatermarkColor() As Color Get Return m_watermarkColor End Get Set (value As Color) m_watermarkColor = value If empty Then MyBase .ForeColor = m_watermarkColor End If End Set End Property <Browsable( True )> _ Public Property Watermark() As String

Custom Richtextbox Control With Watermark Support In C#

There was a solution in MSDN Forums on how to add watermark to a Textbox control. I tried replacing the base class if this will work on a RichTextbox control. After testing, the custom control works as expected. /// <summary> /// Set Watermark in RichTextbox. /// </summary> public class WatermarkRichTextbox : RichTextBox { private string watermark; private Color watermarkColor; private Color foreColor; private bool empty; [Browsable (true)] public Color WatermarkColor { get { return watermarkColor; } set { watermarkColor = value ; if (empty) { base .ForeColor = watermarkColor; } } } [Browsable(true)] public string Watermark { get {

Using PATINDEX() In SQL Server As An Alternative To Embedd Regular Expressions In SQL

Image
This was based on a post from SQL Team on how to grab a 5 digit number from the string field which could utilize a regular expression like this: [0-9 ]{5}. The initial solution was given by a forum member named Kristen. It could extract the 5 digit mark on a string field as shown below: DECLARE @strTest varchar(8000) SELECT @strTest = '\\servername\foldername99999\filename.ext' SELECT [ Position ]=PATINDEX( '%[0-9][0-9][0-9][0-9][0-9]%' , @strTest), [ Before ]= SUBSTRING (@strTest, 1, PATINDEX( '%[0-9][0-9][0-9][0-9][0-9]%' , @strTest)-1), [ After ]= SUBSTRING (@strTest, PATINDEX( '%[0-9][0-9][0-9][0-9][0-9]%' , @strTest), LEN(@strTest)) What if the string field would contain two or more 5 digit information, how can you achieve that? The answer is to include while loop in TSQL and some additional string functions to achieve the desired output. Here's a sample stored procedure: USE TESTDB; GO CREATE PROCEDUR

Donate