20 July 2017

How do you render different layout in ASP.NET MVC

There are several ways to render different layout in ASP.NET MVC. I just give preference to the 2 ways below.


A. By defining the layout on the view. For example:

Placing the below code on top of Index.cshtml of AdminController

@{
 Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

then placing the below code on top of Index.cshtml of EmployeeController

@{
 Layout = "~/Views/Shared/_EmployeeLayout.cshtml";
}


B. By identifying the controller and render the Layout per controller in a single _ViewStart file in the root directory of the Views folder. For example:

@{
 var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
  string layoutSelection = "";
 if (controller == "Admin") 
 {
     layoutSelection = "~/Views/Shared/_AdminLayout.cshtml";
 }
 else
 {
     layoutSelection = "~/Views/Shared/_EmployeeLayout.cshtml";
 }
 Layout = layoutSelection ;
}

14 July 2017

How to register and login a user using ASP.NET Identity and Owin with ASP.NET WebForm

I'll explain to you how to register a new user account and redirect the user to login page using ASP.NET Identity and OWIN.

Here are the simple steps that you may use.

First you need to create an empty WebForm application. In my example, I named it "IdentitySample".

Then, follow the below steps:


Step 1. Install the following NuGet packages:

Microsoft.AspNet.Identity.EntityFramework
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.Cookies


Step 2. Add a Startup.cs class

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

[assembly: OwinStartup(typeof(IndentitySample.Startup))]

namespace IndentitySample
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {           
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Login")
            });
        }
    }
}


Step 3. Add connectionString in web.config file

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=dotnetguru;Initial Catalog=LoginDb;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  

Step 4. Add a Registration page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="IndentitySample.Register" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body style="font-family: Arial, Helvetica, sans-serif; font-size: small">
    <form id="form1" runat="server">
    <div>
        <h4 style="font-size: medium">Register a new user</h4>
        <hr />                     
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="UserName" />                
            </div>
        </div>
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="Password" TextMode="Password" />                
            </div>
        </div>
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="ConfirmPassword">Confirm password</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" />                
            </div>
        </div>
        <div>
            <div>
                <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" />
            </div>
        </div>
        <p>
            <asp:Literal runat="server" ID="StatusMessage" />
        </p>   
    </div>
    </form>
</body>
</html>


Step 5. Modify Register.aspx.cs

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Linq;
using System.Web;

namespace IndentitySample
{
    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser() { UserName = UserName.Text };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                Response.Redirect("~/Login.aspx");
            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }
        }
    }
}


Step 6. Add a Login page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="IndentitySample.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body style="font-family: Arial, Helvetica, sans-serif; font-size: small">
    <form id="form1" runat="server">
        <div>
            <h4 style="font-size: medium">Log In</h4>
            <hr />
            <asp:PlaceHolder runat="server" ID="LoginStatus" Visible="false">
                <p>
                    <asp:Literal runat="server" ID="StatusText" />
                </p>
            </asp:PlaceHolder>
            <asp:PlaceHolder runat="server" ID="LoginForm" Visible="false">
                <div style="margin-bottom: 10px">
                    <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
                    <div>
                        <asp:TextBox runat="server" ID="UserName" />
                    </div>
                </div>
                <div style="margin-bottom: 10px">
                    <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
                    <div>
                        <asp:TextBox runat="server" ID="Password" TextMode="Password" />
                    </div>
                </div>
                <div style="margin-bottom: 10px">
                    <div>
                        <asp:Button runat="server" OnClick="SignIn" Text="Log in" />
                    </div>
                </div>
            </asp:PlaceHolder>
            <asp:PlaceHolder runat="server" ID="LogoutButton" Visible="false">
                <div>
                    <div>
                        <asp:Button runat="server" OnClick="SignOut" Text="Log out" />
                    </div>
                </div>
            </asp:PlaceHolder>
        </div>
    </form>
</body>
</html>


Step 7. Modify the Login.aspx.cs


using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Web;

namespace IndentitySample
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (User.Identity.IsAuthenticated)
                {
                    StatusText.Text = string.Format("Hello {0}!!", User.Identity.GetUserName());
                    LoginStatus.Visible = true;
                    LogoutButton.Visible = true;
                }
                else
                {
                    LoginForm.Visible = true;
                }
            }
        }
        protected void SignIn(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = userManager.Find(UserName.Text, Password.Text);

            if (user != null)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                Response.Redirect("~/Login.aspx");
            }
            else
            {
                StatusText.Text = "Invalid username or password.";
                LoginStatus.Visible = true;
            }
        }

        protected void SignOut(object sender, EventArgs e)
        {
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            authenticationManager.SignOut();
            Response.Redirect("~/Login.aspx");
        }
    }
}


That's it!

13 July 2017

How to add friendly URL to your ASP.NET web application

First you need to install a NuGet package called Microsoft.AspNet.FriendlyUrl.

Then, add a class called RouteConfig.cs and make it similar to the codes below:

using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace WebFormsIndentity
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);

            routes.MapPageRoute("", "MyPage", "~/Page.aspx");
        }
    }
}

**Actually, you can add as many MapPageRoutes as you want in RegisterRoutes. JUst keep the first and second parameters unique.

Finally, in your Global Application class (Global.asax), add the following in the Application_Start() event:

 protected void Application_Start(object sender, EventArgs e)
 {
     RouteConfig.RegisterRoutes(RouteTable.Routes);
 }


And TA-DA.... you now have an SEO-friendly URL!

11 July 2017

DB Context (ASP.NET MVC vs. ASP.NET Core MVC)

ASP.NET MVC

using System.Data.Entity;   

public class ProfileContext : DbContext
{
    public ProfileContext() : base("ProfileConnectionString")
    {
    }

    public DbSet<Profile> Profiles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Profile>().ToTable("Profile");        
    }
}


ASP.NET Core MVC

using Microsoft.EntityFrameworkCore;

public class ProfileContext : DbContext
{
    public ProfileContext(DbContextOptions<ProfileContext> options) : base(options)
    {
    }

    public DbSet<Profile> Profiles { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Profile>().ToTable("Profile");
    }
}


Filtering a List of Results in ASP.NET MVC 5

Here's a simple example on how to filter results based on the given name:


Controller

public ActionResult Index(string searchValue)
{          
    var emp = db.Profiles.Select(y => y);
    if (!String.IsNullOrEmpty(searchValue))
    {
        emp = emp.Where(y => y.Name.Contains(searchValue));
    }      
    return View(emp);

}


View

@using (Html.BeginForm())
{
    <p>
        Search by name: @Html.TextBox("SearchValue")
        <input type="submit" value="Search" />
    </p>
}

<table class="table">
    <tr>
         <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>      
    </tr>
}
</table>

Sorting a List of Results in ASP.NET MVC 5

Here's a simple example:


Controller 

private ProfileContext db = new ProfileContext();

public ActionResult Index(string sortOrder)
{
    ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name" : "";
    ViewBag.AgeSortParm = sortOrder == "Age" ? "age" : "Age";
   
    var emp = db.Profiles.Select(y => y);
   
    switch (sortOrder)
    {
        case "name":
        emp = emp.OrderByDescending(y => y.Name);
        break;
           
        case "age":
        emp = emp.OrderByDescending(y => y.Age);
        break;
           
        default:
        emp = emp.OrderBy(y => y.Name);
        break;
    }
   
    return View(emp);
}


View

<table class="table">
    <tr>
        <th>
            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
        <th>
            @Html.ActionLink("Age", "Index", new { sortOrder = ViewBag.AgeSortParm })
        </th>      
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>      
    </tr>
}
</table>

06 July 2017

When you connect to the database and it throws: "ArgumentNullException: Value cannot be null. Parameter name: connectionString"

Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<SqlServerDbContextOptionsBuilder> sqlServerOptionsAction)
SampleProject.Startup.<ConfigureServices>b__3_0(DbContextOptionsBuilder options) in Startup.cs

It only means you're trying to connect to the database without first "building" the configuration of the appsettings.json with the hosting environment.

The solution to this is to add the following to your Startup class:

         public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
         }  

05 July 2017

'No executable found matching command "dotnet-aspnet-codegenerator"'

When I created a new controller with the built in scaffolding, I got the following error:

'No executable found matching command "dotnet-aspnet-codegenerator"'

To resolve the issue, I just edited the .csproj file and added the following:

<ItemGroup> <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" /> </ItemGroup>

Then, everything worked fine.

04 July 2017

ArgumentNullException: Value cannot be null. Parameter name: connectionString

So I posted it.

It happened to me twice this morning.

In my first thought, I said, "What?"

On my second attempt, I still got the same error.

And I said to myself, "What the f*?"

Then, finally I found that in my appSettings.json, I misspelled the ConnectionStrings to ConnectionString.

Now, I realize that too much coffee is not a replacement to lack of sleep and not an excuse for stupidity, lol!

Anyway, I'm just having fun working on my dotNet Core project 😁



03 July 2017

'EntityTypeBuilder' does not contain a definition for 'ToTable'

While utilizing the EF 7 with dotNet core apps, I got an error that says:

'EntityTypeBuilder<T>' does not contain a definition for 'ToTable' and no extension method 'ToTable' accepting a first argument of type  'EntityTypeBuilder<T>' could be found ....

Installing the Nuget package Microsoft.EntityframeworkCore.SqlServer solved the issue.

30 June 2017

'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'

When you try to connect to SQL Server database using Entity Framework and you got the following error message:

'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer' and no extension method 'UseSqlServer' accepting a first argument of type 'DbContextOptionsBuilder' could be found .....

A simple way to get around with this error is to simply add or install a NuGet package Microsoft.Entityframeworkcore.Sqlserver

19 June 2017

HTTP Error 403.14 - Forbidden

When I published my web application this morning, I got this Error:

HTTP Error 403.14 - Forbidden

The Web server is configured to not list the contents of this directory.


Luckily, I remembered the one-liner script that I added to web.config 2 years ago when I experienced the same error when I published and deployed my ASP.NET MVC application for one of my clients.

Okay, to fix this error, simply add the script below to your web.config file:

<system.webServer>
    <directoryBrowse enabled="true" />
</system.webServer>

15 June 2017

Detect Changes Automatically with dotnet watch

Whenever you're running a .NET Core application and you want to detect source file changes and restart the app automatically, simply use dotnet watch command.

Just add Microsoft.DotNet.Watcher.Tools to the .csproj file like the one below:

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0-msbuild3-final" />
</ItemGroup>

Then, run the dotnet restore command to add the package to your project.

Next time you run your application, just add watch to your command like: dotnet watch run to detect changes and restart your application automatically.

14 June 2017

What else can I ask for?

ASP.NET Core has it all!


Work as a Dev Coach for .NET projects

Just an ordinary day as a development coach of Grosvik Phil., Inc., a startup company in Makati City, Philippines.


13 June 2017

ASP.NET Core rocks!

Yeah, ASP.NET Core really rocks!!!

After topping the TechEmpower plaintext benchmarks in November 2016, ASP.NET Core 2 now offers more performance improvements by reducing application startup time once your app is published.

You may try ASP.NET Core 2.0.0-preview and see for yourself.

08 May 2017

How Do We Get The Parameter Value from a URL?

Here's a quick and easy way to read and display the paramater value from a URL.

Ex:
var sampleUri = new Uri("http://www.mysite.com/default.aspx?ID=21");
string getParam = HttpUtility.ParseQueryString(sampleUri.Query).Get("ID");

20 April 2017

System.InvalidCastException: Specified cast is not valid.

When you try to map bigint in SQL to int in C#, you will get an error equivalent to "System.InvalidCastException: Specified cast is not valid."

You need to map the bigint to long, which is equal to 64-bit integer in C# or Int64, because Int32 cannot store the maximum value of bigint.

19 April 2017

How To Find Duplicate Record in SQL

Whenever I need to delete duplicate records in database, I try to find them first and identify the number of times the same row occurs.

Here's a simple way to find them:

SELECT Name, Age, COUNT(*) AS NoOfDuplicateRecords
FROM Table_Name
GROUP BY Name, Age
HAVING COUNT(*) > 1

11 April 2017

How lock(obj) Method Works

I once had a requirement to generate a random integer number from let's say 0 to 10 million. Here's what I did:

public static int GetRandomNumber(int min, int max)
{
    lock (obj)
    {
        //some codes for calling Random method is omitted for brevity      
    }
}

I used lock statement to ensure that the object was locked by the first thread and released the object first before another thread to lock the same object.

I think lock is more concise that using a monitor class in blocking the thread.


10 April 2017

Uploading An Image File with Unique Filename and Save It In A Folder


I just have a requirement to upload an image file in a folder named "UploadedFiles" and replace its file extension from ".whateverFileExtension" to ".jpg".
And to ensure that each picture will have a unique (or at least have a higher probability of a unique filename), I will use SyncLock method and Random class to generate random number (ex. from 1 to 10,000,000) and assign the auto-generated number to every uploaded picture.

Below is my sample code:

<HTML>

<input type="file" id="fileUpload" runat="server" />
<input type="submit" id="btnUploadFile" runat="server" value="Upload" onserverclick="btnUploadFile_OnServerClick" />


<CODE BEHIND>

private string _myRandomNumber;
private static readonly Random Random = new Random();
private static readonly object SyncLock = new object();

public static int RandomNumber(int min, int max)
{
    lock (SyncLock)
    {
        return Random.Next(min, max);
    }
}

protected void btnUploadFile_OnServerClick(object sender, EventArgs e)
{
    _myRandomNumber = RandomNumber(0, 10000000).ToString("D");
    int newPictureId = Int32.Parse(_myRandomNumber);
    string baseDirectory = Server.MapPath("~/UploadedFiles/");
    fileUpload.PostedFile.SaveAs((baseDirectory + (newPictureId + ".jpg")));
}

07 April 2017

How Do You Validate Input Date Programmatically?

When validating a date, I recommend that you use both the client-side and the server side techniques. For client-side, you can use native JS or any JS framework available. For the server-side, you can do it programmatically such as the below sample:

<ASPX page>

Enter a date: <input type="date" id="txtExpirationDate" runat="server" required="" />
<p></p>
<label id="lblMessage" runat="server"></label>


<CODE BEHIND>

DateTime validDate;
if (DateTime.TryParse(txtExpirationDate.Value, out validDate))
{
    //some code goes here
}
else
{
    lblMessage.InnerText = "You entered an invalid date.";
}

05 April 2017

How To Use HTML's Map Area with Pure JavaScript

If you're looking for an easier way to create a clickable area/s in the image (or image map), you might consider using the HTML's <map> tag and JavaScript.

Example:


<!DOCTYPE html>
<html>
<head>
    <title>
        Sample Use of Map Area with JavaScript
    </title>
    <script>
        function writeText(txt) {
            document.getElementById("AboutTheLocation").innerHTML = txt;
        }
    </script>
</head>

<body>

<map name="targetLocation">
    <area shape="poly" coords="74,261,49,250,80,103,117,113" onmouseover="writeText('My home is located somewhere here.')" onmouseout="writeText('')" />
<map name="targetLocation">
    <area shape="circle" coords="124,58,8" onmouseover="writeText('My office is located somewhere here.')" onmouseout="writeText('')" />

<img src ="vs.png" alt="Visual Studio" usemap="#targetLocation" width="145" height="126" />
<p></p>
<p id="AboutTheLocation"></p>

</body>
</html>

In Response.Redirect("URL"), Should We Use True or False?

Response.Redirect("URL", true);
                     or
Response.Redirect("URL", false);


Did you know that using true or false is just a matter of how you control the logic flow of your code? We use true to abort the thread so that nothing will execute once you redirect the page. Then, we use false when you don't want to abort the thread after the Response.Redirect executes.

For some developers, using true is considered a bad practice because it's a sign that you have no control on your code's logic and you're simply aborting the thread and the application will not continue when an error arises.

But the funny thing is that I've seen a lot of developers not putting either true or false whenever they use Response.Redirect and keep saying that using true is not a good practice. But the truth is that when you don't declare a false value, "true" is the default when you use Response.Redirect.

04 April 2017

Should I go to Parameters.Add or to a simplified Parameters.AddWithValue?

For some developers, choosing between the two is just a matter of preferences because in fact there is no difference in terms of functionality between these two.

I disagree.

Providing only the type Parameters.AddWithValue, the compiler will just try to implicitly convert the input parameter to what is expected and it may cause you a performance issue.

How To Add Google Map with Marker in Pure JavaScript

Okay, I said 'pure' JavaScript. Forgive me if I use a few CSS lines.

Here's my sample webpage displaying a Google map and our sample offices in Norway and in Makati City (Philippines):

<!DOCTYPE html>
<html>

<head>
    <title>Sample Google Map with Marker</title>
    <style type="text/css">
        #place_map_here {
            height: 500px;
            width: 1000px;
        }
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
        function initialize() {
            var pointDestinations = [
                {
                    lat: 61.792135,
                    lon: 8.381478,
                    title: "Grosvik Norway",
                    description: "Norway office"
                },
                {
                    lat: 14.557985,
                    lon: 121.023870,
                    title: "Grosvik Phils.",
                    description: "Makati office"
                }
            ];
            var initialLocation = {
                zoom: 2,
                center: new google.maps.LatLng(61.792135, 8.381478),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("place_map_here"), initialLocation);

            var infoAboutThePlace = new google.maps.InfoWindow({
                content: ''
            });
            var y;
            for (y = 0; y < pointDestinations.length; y++) {

                var marker = new google.maps.Marker({
                    title: pointDestinations[y].title,
                    position: new google.maps.LatLng(pointDestinations[y].lat, pointDestinations[y].lon),
                    map: map
                });
                markerAndInformationBinder(marker, map, infoAboutThePlace, "<p>" + pointDestinations[y].description + "</p>");
            }
        }
        function markerAndInformationBinder(marker, map, infoAboutThePlace, html) {
            google.maps.event.addListener(marker, 'click', function () {
                infoAboutThePlace.setContent(html);
                infoAboutThePlace.open(map, marker);
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>

<body>
    <div id="place_map_here"></div>
</body>

</html>

03 April 2017

How To Enable Paging in ListView

I know it's a bit old, but there are newbies who still had difficulty in adding a pager in their ListView control. So I think that justifies why I should post this blog.

If for example you add a DataPager in you ListView's LayoutTemplate

<asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1" PageSize="5">
    <Fields>
        <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />                                       <asp:NumericPagerField ButtonType="Link" />
        <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
    </Fields>
</asp:DataPager>


First, you need to set the OnPagePropertiesChanging="OnPagePropertiesChanging" on your ListView properties like:

<asp:ListView ID="ListView1" runat="server" OnPagePropertiesChanging="OnPagePropertiesChanging">


Then, from code behind you can do the following:

protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        (ListView1.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

        //call your method in displaying the list
    }

31 March 2017

How To Validate User Input Using Native JavaScript

In the presence of numerous JS frameworks and 'drag n drop' features, I just found that some graduating students of computer science can't write a simple user input validation using a pure JavaScript. What even bothered me was that some web developers can't even write a simple JS script without searching from Google or without using the so-called 'copy-paste programming'!

Okay, I'll just share with you a very simple and neat way to validate a required text entry using our native JavaScript:

Name: <input type="text" id="txtName"  /><br/>
<input type="button" id="btnSubmit"  onclick ="javascript:validate()"  value="Submit" />    


<script type="text/javascript">
        function validate()
        {
           if (document.getElementById("txtName").value=="")
           {
                 alert("Name is required.");
                 document.getElementById("txtName").focus();
                 return false;
           }          
           return true;
        }
</script>

28 March 2017

How To Pass Querystring From One Page to Another Using JavaScript

I used to pass QueryString from one ASP.NET page to another using Hyperlink control. But since I had a requirement to pass the Querystring using pure JavaScript, I used the following code:

<script type="text/javascript">
        $(function () {
            $("#btnSend").bind("click", function () {
                var url = "SecondPage.aspx?name=" + encodeURIComponent($("#txtInput").val());
                window.location.href = url;
            });
        });
</script>


Enter string message: <input type="text" id="txtInput"/>
<input type="button" id="btnSend" value="Submit" />



27 March 2017

How To Disable Bootstrap Modal Window from Closing

In any ordinary day when I need to disable the bootstrap modal window from closing due to my client requirement, I simply make the backdrop to 'static' and set the keyboard property to 'false' like the below sample:

<script type="text/javascript">
    $('#sampleModal').modal({
    backdrop: 'static',
    keyboard: false
    });
</script>


<div class="modal fade" id="sampleModal" tabindex="-1" role="dialog" aria-labelledby="sampleModalLabel" aria-hidden="true">

//some text are omitted here for brevity....

</div>



Autocomplete with Ajax and JSON

Autocomplete with Ajax and JSON is as simple as this:

In your ASPX page:

<script type="text/javascript">
    $(function () {
        $("[id$=txtLastNameSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("Home.aspx/GetLastName") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function(item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }));
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=LastName]").val(i.item.val);
            },
            minLength: 3
        });
    });  
</script>

Enter Last Name: <asp:TextBox ID="txtLastNameSearch" runat="server" />
<asp:HiddenField ID="LastName" runat="server" />


And in your code behind:

        [WebMethod]
        public static string[] GetLastName(string prefix)
        {
            var lastName = new List<string>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT LastName FROM tbl_Profile WHERE LastName LIKE @SearchText + '%'";
                    cmd.Parameters.AddWithValue("@SearchText", prefix);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            lastName.Add(sdr["LastName"].ToString());
                        }
                    }
                    conn.Close();
                }
            }
            return lastName.ToArray();
        }

05 March 2017

Unit Testing the ASP.NET WebForm (Part 2)

In Unit Testing the ASP.NET WebForm (Part 1), I showed you how to unit test the Create method in our data model or class. This time, I'll show you a simple way to unit test the Generic List<T> method in displaying records from the database and bind the result to GridView.


** Test Class **

[TestClass]
class ProfileTests
{
    [TestMethod]
    public void Get_All_Profile()
    {
        //Arrange
        var profile = new List<Profile>();
    
        //Act
        var results = ProfileData.Get_All_Profile();
    
        //Assert
        Assert.IsTrue(profile.SequenceEqual(results));
        Assert.IsNotNull(results);
    }
}


** Data Model **

public static List<Profile> Get_All_Profile()
{
    var profile = new List<Profile>();
    using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ProfileConnectionString"].ConnectionString))
    {
        string strSelect = "SELECT Name, Age FROM Profile";
        var cmd = new SqlCommand(strSelect, con);
        con.Open();
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            var result = new Profile
            {
                Name = reader.GetString(0),
                Age = reader.GetDecimal(1)
            };
            profile.Add(result);
        }
        reader.Close();
    }
    return profile;



** Business Model **

public class Profile
{
    public int ProfileId { get; set; }
    public string Name { get; set; }
    public decimal Age { get; set; }



** Code Behind **

void Display_Profile()
{
    Profiles = ProfileData.Get_All_Profile();
    GridView1.DataSource = Profiles.ToList();
    GridView1.DataBind();
}

Unit Testing the ASP.NET WebForm (Part 1)

Unit testing an ASP.NET Webform gives us more challenging job than a loosely coupled MVC. In practice, we just unit test custom controls and the methods that perform actual logic. In doing so, we try to minimize the code behind and put all those logic in separate libraries or classes.

In my example below, I try to write a unit test (using MSTest) on a method that inserts a new record to the database:


** Test Class **

[TestClass]
class ProfileTests
{
    [TestMethod]
    public void Create_New_Profile_Should_Save_New_Record()
    {
        //Arrange
        var content = new Profile { ProfileId = 1, Name = "Bob", Age = 21m};

        //Act
        var results = ProfileData.Create_New_Profile(content);

        //Assert
        Assert.IsNotNull(results);
    }
}


** Data Model **

public class ProfileData
{
    public static Profile Create_New_Profile(Profile profiles)
    {
        using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ProfileConnectionString"].ConnectionString))
        {
            string strInsert = "INSERT INTO Profile (Name, Age) VALUES(@Name, @Age)";
            var cmd = new SqlCommand(strInsert, con);
            cmd.Parameters.AddWithValue("@Name", profiles.Name);
            cmd.Parameters.AddWithValue("Age", profiles.Age);
            con.Open();
            var profile = new Profile
                {
                    Name = profiles.Name,
                    Age = profiles.Age
                };
            cmd.ExecuteNonQuery();
            con.Close();
            return profile;
        }
    }
}


** Business Model **

public class Profile
{
    public int ProfileId { get; set; }
    public string Name { get; set; }
    public decimal Age { get; set; }



** Code Behind **

protected void btnSave_Click(object sender, EventArgs e)
{
    var profile = new Profile
    {
        Name = txtName.Text,
        Age = Decimal.Parse(txtAge.Text)
    };
    Profiles = ProfileData.Create_New_Profile(profile);
}

19 February 2017

"Resources was specified more than once” or "Resource name xxx cannot be used more than once"

Have you experienced getting an error that says, "Resources was specified more than once” or "Resource name xxx cannot be used more than once"?

Usually it happened when you just copy/paste a form from your old project to the new one. Or sometimes if you "accidentally" include the obj folder to your existing project.

In any case, the simplest solution to this is by simply removing the obj folder to your project or solution.

Hope it helps you.

17 February 2017

Creating a Table With a Column Value to be Generated Automatically as GUID

Let's say you want to create a table tbl_Users with columns Id, UserId, and Name.

To generate a GUID (uniqueidentifier) automatically for column UserId, you simply need to add DEFAULT NEWSEQUENTIALID() to the UserId column when you create a table like the sample below:

CREATE TABLE [dbo].[tbl_Users]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY,
    [UserId] UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
    [Name] VARCHAR(50) NULL
)

16 February 2017

Calling Stored Procedure from Entity Framework

Let's say we have a simple stored procedure that displays all the records from tbl_Sales table:

CREATE PROCEDURE [dbo].[sp_DisplayRecord]
AS
BEGIN
    SELECT * FROM tbl_Sales
END


Assuming that ctx is our DbContext, we can call the stored procedure from EF using the following command:

var query = ctx.Database.SqlQuery<tbl_Sales>("sp_DisplayRecord").AsEnumerable();

15 February 2017

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

Have you experienced this problem when you browsed your website or web application using Visual Studio 2013 or 2015?

A simple solution to this issue is to add something like the one below on your web.config file:

<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

06 February 2017

Filtering The Result Based On Specific User

In one of my seminars, one student asked me how to filter the result of database query to specific user and display it in GridView.

Okay, here's what we did:


Assuming that  we have a table named tbl_Profile with columns Name (varchar), Age (int), Address (varchar), Birthdate (date), and UserId (uniqueidentifier)

Now, if we want to display the records that belong to the specific user, we simply add a Label on the page and set its visibility to false.

ex. Label1.visible = false;

Then in our query, we filter the result using WHERE clause like this:


SELECT Name, Age, Address, Birthdate FROM tbl_Profile WHERE UserId=@UserId

07 December 2016

ASP.NET Essential Training for Developers

Conducted a successful training on ASP.NET Essential Training for software developers of Manly Plastics, Inc.


27 November 2016

Seminar on Cloud Computing with Microsoft Azure

Had a great experience sharing the basics of cloud computing with Microsoft Azure to hundreds of students and faculty members of Colegio de Porta Vaga in Imus City, Cavite, Philippines.




18 November 2016

ASP.NET in Practice goes to AMA Computer College - Parañaque City (Philippines)

Sharing my real-life experiences as .NET developer, as well as my in-depth knowledge in ASP.NET, to our young developers is fun and fulfilled!




16 November 2016

Inserting Null Value from Code Behind

Just so happened to check some old codes and found out how we assigned null values from code behind. The code looks like this:

System.Data.SqlTypes.SqlDateTime getDate;
getDate = SqlDateTime.Null;
    if (DateDelivered.Text == "")
    {
        cmd.Parameters.Add(new SqlParameter("@DateDelivered ", SqlDbType.DateTime)).Value = getDate;
    }
    else
    {
        cmd.Parameters.Add(new SqlParameter("@DateDelivered ", SqlDbType.DateTime)).Value = DateTime.Parse(DateDelivered.Text);
    }


I know it works fine. But I'm looking for ways for a better (or maybe shorter) approach.

13 November 2016

Unable to cast object of type 'System.Int32' to type 'System.String'.

I attended a student brainstorming session this morning. One of the students asked a question to the group about the possible reason why this error appeared on the screen:

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.

Many newbies assumed that it's a casting error. They even offered him numerous solutions without first inspecting the program.

10 minutes later, they still couldn't figure out the solution to the error.

When I checked it, my first instinct was to read his codes and inspect his SQL query. Then I found that the error appeared simply because he forgot the comma (,) between the two columns in his SQL query!

My advice: Read codes when debugging (and minimize the talking).


22 October 2016

ASP.NET in Practice goes to DFCAITTI (Philippines)

Teaching our today's generation about the power of ASP.NET is fun!






20 October 2016

Adding Decimal Numbers in String Format

In one of my seminars, a high school student asked me what's a simple way to add two decimal numbers from the two textbox and display the result on the third textbox.

I know it's so simple and we have 'shortcuts' in doing this task. But since I found that it's a common question by some public high school studs who attended my seminars, I decided to post here a simple solution that can be easily understood by students:


decimal num1 = 0;
decimal num2 = 0;

if (txtValue1.Text != "")
    {
        decimal value1 = Decimal.Parse(txtValue1.Text);
        num1 = value1;
    }

if (txtValue2.Text != "")
    {
        decimal value2 = Decimal.Parse(txtValue2.Text);
        num2 = value2;
    }

var total = num1 + num2;

txtTotal.Text = total.ToString();



25 February 2015

Converting String To Integer Properly

If I have a string myNumber = '21' and I want it to convert to an integer, the proper way to do this is to use TryParse like this:

int x = 0;

Int32.TryParse(myNumber, out x);

By using TryParse, it won't throw exceptions if in case your string (text) is non-numeric.

24 February 2015

Accessing The Label Inside The DetailsView DataBound

 If I have a Label (lblAmount) in my DetailsView's TemplateField, one of the simplest way to access it and modify its format is shown below:

       Label myLabel = dvIncomeSummary.FindControl("lblAmount") as Label;
       string newLabelFormat = myLabel.Text;
       const string fmt1 = "#,##0.00;(#,##0.00)";
       double newAmountFormat = Double.Parse(newLabelFormat);
       string myAmountFormat = newAmountFormat.ToString(fmt1);
       newLabelFormat = myAmountFormat;
       myLabel.Text = newLabelFormat;

       

Accessing The Label Inside The GridView RowDataBound

 If I have a Label (lblAmount) in my GridView's TemplateField, one of the simplest way to access it and modify its format is shown below:

if (e.Row.RowType == DataControlRowType.DataRow)
    {
            Label myLabel = (Label)e.Row.FindControl("lblAmount");
            string newLabelFormat = myLabel.Text;
            const string fmt1 = "#,##0.00;(#,##0.00)";
            double newAmountFormat = Double.Parse(newLabelFormat);
            string myAmountFormat=
newAmountFormat .ToString(fmt1);
            newLabelFormat =
myAmountFormat;
            myLabel.Text = newLabelFormat;
      }

Combining Multiple Rows Into A Single Row With A Common Column Value

Sample:

Harold    ASP.NET
Harold    C#
Harold    LINQ


SELECT X.myName,
   (SELECT ' ,  ' + Y.ProgrammingLanguage
    FROM myTable Y
    WHERE Y.myName = X.myName
    FOR XML PATH('')) [SECTORS/USERS]
FROM myTable X
GROUP BY X.myName
ORDER BY 1



Result:

Harold    ASP.NET, C#, LINQ