Sunday, October 25, 2015

Create a New SQL Server Database basing from a renamed DB (mdf/ldf) files

I recently created a copy of Northwind database and called it NorthwindBootstrap. This database has a built-in membership tables added to it. The copy includes both of mdf and ldf files. My next step is to create a new database based from the recently copied/renamed files in which I have no idea on how to do it.
After doing some research, I stumbled upon a t-sql script based from my requirement.
 USE [master]  
 GO  
 CREATE DATABASE [NorthwindBootstrap] ON   
 ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\NorthwindBootstrap.mdf' ),  
 ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\NorthwindBootstrap.ldf' )  
 FOR ATTACH  
 GO  

Cheers! :)

Wednesday, October 21, 2015

The specified cast from a materialized 'System.Int16' type to a nullable 'System.Int32' type is not valid.

Based from the issue, the fix is to check the database field against the view model class. In my case, the database field is smallint (nullable).
So, the fix is to change the model code from:
 public int? StockOnHand { get; set; }  
to:
 public Int16? UnitsInStock { get; set; }  
:-)

Tuesday, October 20, 2015

Draggable is not a function in ASP.NET MVC

Here's what I did in order to recognize the draggable function in one of my asp.net mvc page.
1. Add jquery-ui.js to scripts folder.
2. Bundle the js file in BundleConfig.cs
3. Render the bundled script in _Layout.cshtml.


Cheers! :-)

Check if images are not rendered correctly to the browser using JavaScript

Hello,
Here's a function to hide divs if it's children specifically images does not render correctly to the browser or an error has occured.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function ImageDivHandler() {    
   $("div.gallery").each(function () {  
     if ($(this).children().length == 0) {  
       $(this).hide();  
     }  
     else {  
       var img = $(this).find(".image-responsive");  
       if (img != null || img != undefined) {  
         imgSrc = $(this).find(".image-responsive").attr("src");  
         if (imgSrc == "" || imgSrc == null || imgSrc == "null") {  
           $(this).find(".image-responsive").closest("div.gallery").hide();  
         }  
         else {  
           $(this).find(".image-responsive").error(function () {  
             $(this).closest("div.gallery").hide();  
           });  
         }  
       }  
     }  
   });  
 }  
Note: I may change the logic from time to time depending on the layout of the image container. But the concept is pretty much the same.
Greg

Sunday, October 18, 2015

jQuery Intellisense not working in external Javascript file using Visual Studio 2013

Hello,

In order for the jQuery intellisense to work in Visual Studio 2013, perform the following steps.
1. Proceed by clicking Tools -> Options -> Text Editor -> JavaScript -> Intellisense -> References.
2. Change Reference Group to Implicit (Web)
  By default a reference has been added to _references.js. If not, add a new reference file under Scripts folder.
3. Open _references.js file using your Visual Studio IDE or any text editor software.
4. Add reference path to jquery files (.js, .min.js, and .intellisense.js).

5. Close Visual Studio and Open it again. (I was struggling for hours as to why performing steps 1 through 4 didn't work. This step fixed the issue)

Reference: jQuery intellisense not working in VS 2012
Regards,
:)

Wednesday, September 9, 2015

ASP.NET Change GridView Sort Link Color

Here's how to change the color of GridView SortLink using CSS.
ASPX Markup
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<asp:GridView ID="GridVwPagingSorting" runat="server" AutoGenerateColumns="False" Font-Names="Verdana" AllowPaging="True" AllowSorting="True" PageSize="5" Width="75%" OnPageIndexChanging="PageIndexChanging" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" OnSorting="Sorting">
    <AlternatingRowStyle BackColor="#BFE4FF" />
    <PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
    <HeaderStyle CssClass="gridViewHeader" />
    <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
    <Columns>
        <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" SortExpression="EmployeeID" />
        <asp:BoundField DataField="Emp_Name" HeaderText="Employee Name" SortExpression="Emp_Name" />
        <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
        <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
    </Columns>
</asp:GridView>
CSS
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.gridViewHeader 
 {
    height: 30px;
    background-color: #6DC2FF;
    font-size: 15px;
    border-color: #CCCCCC;
    border-style: Solid;
    border-width: 1px;
}

.gridViewHeader a {
    color: rgb(218, 81, 81);
}
Output

Alphabetical Paging in ASP.NET MVC (C#)

Here's the C# version of Alphabetic Paging in VB.NET Posts:
1. Alphabetical Paging in ASP.NET MVC
2. Alphabetical-Paging-in-ASP-NET-MVC Source Code
Solution Structure
HtmlHelpers.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Text;  
 using System.Web.Mvc;  
 namespace MVCAlphabeticPager.Helpers  
 {  
   public static class HtmlHelpers  
   {  
     public static HtmlString AlphabeticalPager(this HtmlHelper html, string selectedLetter, IEnumerable<string> firstLetters, Func<string, string> pageLink)  
     {  
       var sb = new StringBuilder();  
       var numbers = Enumerable.Range(0, 10).Select(i => i.ToString());  
       var alphabet = Enumerable.Range(65, 26).Select(i => ((char)i).ToString()).ToList();  
       alphabet.Insert(0, "All");  
       alphabet.Insert(1, "0-9");  
       var ul = new TagBuilder("ul");  
       ul.AddCssClass("pagination");  
       ul.AddCssClass("alpha");  
       foreach (var letter in alphabet)  
       {  
         var li = new TagBuilder("li");  
         if (firstLetters.Contains(letter) || (firstLetters.Intersect(numbers).Any() && letter == "0-9") || letter == "All")  
         {  
           if (selectedLetter == letter || string.IsNullOrEmpty(selectedLetter) && letter == "All")  
           {  
             li.AddCssClass("active");  
             var span = new TagBuilder("span");  
             span.SetInnerText(letter);  
             li.InnerHtml = span.ToString();  
           }  
           else  
           {  
             var a = new TagBuilder("a");  
             a.MergeAttribute("href", pageLink(letter));  
             a.InnerHtml = letter;  
             li.InnerHtml = a.ToString();  
           }  
         }  
         else  
         {  
           li.AddCssClass("inactive");  
           var span = new TagBuilder("span");  
           span.SetInnerText(letter);  
           li.InnerHtml = span.ToString();  
         }  
         sb.Append(li.ToString());  
       }  
       ul.InnerHtml = sb.ToString();  
       return new HtmlString(ul.ToString());  
     }  
   }  
 }  
HomeController.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using MVCAlphabeticPager.Models;  
 namespace MVCAlphabeticPager.Controllers  
 {  
   public class HomeController : Controller  
   {  
     public ActionResult Index(string selectedLetter)  
     {  
       var model = new AlphabeticalPagingViewModel();  
       model.SelectedLetter = selectedLetter ;  
       using (var context = new AdventureWorks2012Entities())  
       {  
         model.FirstLetters = context.Products  
           .GroupBy(p => p.Name.Substring(0, 1))  
           .Select(x => x.Key.ToUpper())  
           .ToList();  
         //initialize model  
         model.Products = new List<ProductModel>();  
         if (string.IsNullOrEmpty(selectedLetter) || selectedLetter == "All")  
         {  
           model.Products  
             .AddRange(  
               (from item in context.Products  
                join category in context.ProductSubcategories  
                 on item.ProductSubcategoryID equals category.ProductSubcategoryID into ProductCategory  
                 from category in ProductCategory.DefaultIfEmpty()                       
                 select new ProductModel()   
                 {  
                   ProductName = item.Name,  
                   ProductID = item.ProductID,  
                   ProductNumber = item.ProductNumber,  
                   Color = (string.IsNullOrEmpty(item.Color)) ? "NA" : item.Color,  
                   StandardCost = item.StandardCost,  
                   ProductCategory = (string.IsNullOrEmpty(category.Name)) ? "NA" : category.Name  
                 }).ToList());   
         }  
         else  
         {  
           if (selectedLetter == "0-9")  
           {  
             var numbers = Enumerable.Range(0, 10).Select(i => i.ToString());  
             model.Products  
               .AddRange(  
                 (from item in context.Products  
                   .Where(item => numbers.Contains(item.Name.Substring(0, 1)))  
                 join category in context.ProductSubcategories  
                   on item.ProductSubcategoryID equals category.ProductSubcategoryID into ProductCategory  
                   from category in ProductCategory.DefaultIfEmpty()                
                 select new ProductModel()  
                 {  
                   ProductName = item.Name,  
                   ProductID = item.ProductID,  
                   ProductNumber = item.ProductNumber,  
                   Color = (string.IsNullOrEmpty(item.Color)) ? "NA" : item.Color,  
                   StandardCost = item.StandardCost,  
                   ProductCategory = (string.IsNullOrEmpty(category.Name)) ? "NA" : category.Name  
                 }).ToList());   
           }  
           else  
           {  
             model.Products  
               .AddRange(  
                 (from item in context.Products  
                   .Where(item => item.Name.Trim().StartsWith(selectedLetter))  
                 join category in context.ProductSubcategories  
                   on item.ProductSubcategoryID equals category.ProductSubcategoryID into ProductCategory  
                   from category in ProductCategory.DefaultIfEmpty()  
                 select new ProductModel()  
                 {  
                   ProductName = item.Name,  
                   ProductID = item.ProductID,  
                   ProductNumber = item.ProductNumber,  
                   Color = (string.IsNullOrEmpty(item.Color)) ? "NA" : item.Color,  
                   StandardCost = item.StandardCost,  
                   ProductCategory = (string.IsNullOrEmpty(category.Name)) ? "NA" : category.Name  
                 }).ToList());   
           }  
         }  
       }  
       return View(model);  
     }  
     public ActionResult About()  
     {  
       ViewBag.Message = "Your application description page.";  
       return View();  
     }  
     public ActionResult Contact()  
     {  
       ViewBag.Message = "Your contact page.";  
       return View();  
     }  
   }  
 }  
ProductModel.cs
  public class ProductModel  
   {  
     public int ProductID { get; set; }  
     public string ProductNumber { get; set; }  
     public string ProductName { get; set; }  
     public decimal StandardCost { get; set; }  
     public string Color { get; set; }  
     public string ProductCategory { get; set; }  
   }  
 }  
AlphabeticalPagingViewModel.cs
   public class AlphabeticalPagingViewModel  
   {  
     public List<ProductModel> Products { get; set; }      
     public List<string> FirstLetters { get; set; }  
     public string SelectedLetter { get; set; }      
   }  
Index.cshtml
 @model MVCAlphabeticPager.Models.AlphabeticalPagingViewModel   
 <br />  
 <div class="panel panel-primary">    
   <div class="panel-heading panel-head">Product Listing</div>  
   <div class="panel-body">      
     @Html.AlphabeticalPager(Model.SelectedLetter, Model.FirstLetters, x => Url.Action("Index", new { selectedLetter = x }))  
     <table class="table" style="margin: 4px">  
       <tr>  
         <th>  
           @Html.DisplayName("Product ID")  
         </th>  
         <th>  
           @Html.DisplayName("Product Number")  
         </th>  
         <th>  
           @Html.DisplayName("Product Name")  
         </th>  
         <th>  
           @Html.DisplayName("Standard Cost")  
         </th>  
         <th>  
           @Html.DisplayName("Color")  
         </th>  
         <th>  
           @Html.DisplayName("Category")  
         </th>  
       </tr>  
       @foreach (var item in Model.Products)  
       {  
         <tr>  
           <td>  
             @Html.DisplayFor(modelItem => item.ProductID)   
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.ProductNumber)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.ProductName)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.StandardCost)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.Color)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.ProductCategory)  
           </td>  
         </tr>  
       }  
     </table>  
     @Html.AlphabeticalPager(Model.SelectedLetter, Model.FirstLetters, x => Url.Action("Index", new { selectedLetter = x }))  
   </div>  
 </div>  

Cheers! :)

Saturday, September 5, 2015

Alphabetical Paging in ASP.NET MVC (VB.NET)

   Here's a sample ASP.NET MVC 5 project using Alphabetical Paging concept of Mikesdotnetting. The revisions are made on the Model, User Interface, and the database used. I replaced Northwind db with Adventureworks.

Solution Structure Sample Output

The source code/files and instructions on how to create this project using Visual Studio 2013 are elaborated in VBForums code bank. Alphabetical Paging in ASP.NET MVC

Friday, September 4, 2015

Entity Framework join two tables if the foreign key is a nullable column

   When retrieving records by joining two tables wherein the foreign key of the referenced table is a nullable column, and you want to return all records from the primary table, with or without the matching rows in the right table, the query would be using left join rather than inner join.
So in LINQ expression, rather than join, revise the query to left join as presented below.

Show products with matching categories, disregarding other products without categories
MVC View: Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
model.Products
 .AddRange(
  (from item in context.Products
   .Where(item => item.Name.Trim().StartsWith(selectedLetter)) join category in context.ProductSubcategories on item.ProductSubcategoryID equals category.ProductSubcategoryID select new ProductModel() {
    ProductName = item.Name,
     ProductID = item.ProductID,
     ProductNumber = item.ProductNumber,
     Color = (string.IsNullOrEmpty(item.Color)) ? "NA" : item.Color,
     StandardCost = item.StandardCost,
     ProductCategory = (string.IsNullOrEmpty(category.Name)) ? "NA" : category.Name
   }).ToList());

Show products with or without Categories
Sql Server query using left join MVC View

Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
model.Products
 .AddRange(
  (from item in context.Products
   .Where(item => item.Name.Trim().StartsWith(selectedLetter)) join category in context.ProductSubcategories on item.ProductSubcategoryID equals category.ProductSubcategoryID into ProductCategory from category in ProductCategory.DefaultIfEmpty() select new ProductModel() {
    ProductName = item.Name,
     ProductID = item.ProductID,
     ProductNumber = item.ProductNumber,
     Color = (string.IsNullOrEmpty(item.Color)) ? "NA" : item.Color,
     StandardCost = item.StandardCost,
     ProductCategory = (string.IsNullOrEmpty(category.Name)) ? "NA" : category.Name
   }).ToList());

Thursday, September 3, 2015

ASP.NET Show Tooltip in Gridview Column

Here's how to show tooltip in an asp.net gridview column/cell on mouse hover. This option will set the Tooltip property of a particular gridview cell on RowDataBound event.

C# Code:
1
2
3
4
5
6
7
8
protected void grdCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string str = e.Row.Cells[1].Text;
            e.Row.Cells[1].ToolTip = str;
        }
}

Wednesday, September 2, 2015

Store update, insert, or delete statement affected an unexpected number of rows (0)

As I was creating a simple Create, Update, Delete (CRUD) application in ASP.NET MVC 5 and executing the controller on Edit, I encountered an error called "Store update, insert, or delete statement affected an unexpected number of rows (0)".
After debugging and looking at the stack trace, I found out that the value of the primary key is zero.
  Department: "Education"<br>  
   Designation: "Dean"<br>  
   EmployeeName: "JE"<br>  
   EmployeeID: 0<br>  
   Salary: 25500<br>  
The fix for this issue is to add a hidden field to the edit view referencing to the primary key which in this case is the EmployeeID.
 @Html.HiddenFor(model => model.EmployeeID)  
And now, the model passed to the context now has a value for the EmployeeID field.
  Department: "Education"<br>  
   Designation: "Dean"<br>  
   EmployeeName: "JE"<br>  
   EmployeeID: 2<br>  
   Salary: 25500<br>  
Cheers! :)

Friday, August 21, 2015

Reset Cascading Dropdown Controls using JavaScript

Hi,

Recently, I have encountered an issue on how to reset cascading dropdown controls in cross browsing mode (IE/Firefox/Chrome). After creating code spikes, I come up with a solution that works across major browsers.
Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$(".reset-link").click(function() {
    ResetCascade($(this));
});

function ResetCascade(itemReset) {
    var formID = $(itemReset).closest('.contact-form');
    if (formID != null) {
        var firstDropDown = $(formID).find('.cascading_group').find('.firstDropDownDiv select');
        var secondDropDown = $(formID).find('.cascading_group').find('.secondDropDownDiv select');
        var thirdDropDown = $(formID).find('.cascading_group').find('.thirdDropDownDiv select');
        if (firstDropDown != null) {
            var valueId = $(firstDropDown).val();
            if (valueId != "" && valueId != null) {
                $(".firstDropDownDiv select option:selected").attr('selected', false);
                $(".firstDropDownDiv select option:first").attr('selected', 'selected');
            }
            if (secondDropDown != null) {
                var valueId2 = $(secondDropDown).val();
                if (valueId2 != "" && valueId2 != null) {
                    $(".secondDropDownDiv select option:selected").attr('selected', false);
                    $(".secondDropDownDiv select option:first").attr('selected', 'selected');
                }
            }
            if (thirdDropDown != null) {
                var valueId3 = $(thirdDropDown).val();
                if (valueId3 != "" && valueId3 != null) {
                    $(".thirdDropDownDiv select option:selected").attr('selected', false);
                    $(".thirdDropDownDiv select option:first").attr('selected', 'selected');
                }
            }
        }
    }
}

Cheers! :)

Sunday, August 2, 2015

The type or namespace name 'LineShape' does not exist in the namespace 'Microsoft.VisualBasic.PowerPacks' (are you missing an assembly reference?)

Good day! :)

After migrating and then rebuild the solution of a Windows Forms application from Windows XP machine to Windows 8, I encountered an error as stated on the title of this post. I suspect this has something to do with the old version from the XP machine not recognized on the new machine.

The steps to fix this issue are provided below:
1. Download Microsoft Visual Basic Power Packs 3.0 here: Microsoft Visual Basic Power Packs 3.0
2. Remove the previous Microsoft Visual Basic Power Packs under References in your project
3. Add the MS Power Pack version 3.0 as reference to your project from the default installation folder located here: C:\Program Files (x86)\Microsoft Visual Basic 2005 Power Packs\3.0
4. Rebuild your project.

GregEsguerra:)

Tuesday, June 23, 2015

There is a duplicate scriptResourceHandler section defined (HTTP Error 500.19)

The solution I found so far was to change the Application Pool of the website from DefaultAppPool to .NET v2.0. I also have tried with no luck other solutions based from stackoverflow.
Issue
Fix

Details
Operating System: Windows 8
IIS: Version 8
Default Site Framework: .NET 3.5 SP1

Reference: There is a duplicate scriptResourceHandler section defined

The installer was interrupted before Application could be installed

I have a .msi file created using .NET Framework 3.5 SP1 in which it can't proceed to installation as stated by the title of this post. Since I'm running on IIS 8, there might be some issues communicating with IIS 6. Taken from the point that this application was packaged using Visual Studio 2008.
The fix is to enable IIS Metabase and IIS 6 configuration compatibility through the Control Panel -> Turn Features On/Off.
Details
OS: Windows 8
IIS: 8
.NET Framework: 3.5 SPI
Visual Studio: 2008

Run MSI file as Administrator in Windows 8

Hello,

Right clicking an MSI file through Windows 8 and then "Run As Administrator" isn't supported. After doing some research, I found some steps to achieve it. See instructions below:

1. Start Button / key
2. Type in "cmd" without quotes and press Shift+Enter to open a command prompt as an administrator.
3. Type in the full path to the msi and press enter.
Put the path inside quotes if it has any spaces like "C:\Users\username\My Documents\SoftwarePackage.msi"
4. Press enter and agree to execute the MSI

See Reference here: Run an MSI file as Administrator

Friday, June 19, 2015

Unity already has a dependency defined for CommonServiceLocator (VS 2012 Ultimate)

Hello,

While trying to add Unity to a Console Project, I encountered an error as stated by the title of this post. After doing some research, I found a post in Stack Overflow which is to update Nuget Package Manager. When I checked my VS, the nuget package manager is an older version.

So, I removed/uninstalled it and added the recent version of Nuget package manager through Tools -> Exentsion and Updates then look for Nuget Package Manager. Then install/download it in your VS IDE. See image for current Nuget Package Manager.
That's It.. :)

Thursday, June 18, 2015

Transparent Border Color in Internet Explorer 8 and Below

Normally, the css snippet below paints a transparent border to containers or divs using Mozilla Firefox, Chrome or IE9+.
 .NewsContent {  
  background-color: #fff;  
  border: 10px solid transparent;   
  background-clip: content-box;   
 }  
However, for other IE8 and below, I had a hard time figuring out how to make the border transparent. Luckily, I found a link: Border Color Transparent in IE6 which serves as the basis for the fix below:
 .NewsContent {  
      background-color: #fff;  
      border: 10px solid black;   
      filter: chroma(color=black);   
 }  
Afterwards, the border color changed to transparent. MSDN link: MSDN Chroma Filter
:)

Wednesday, June 17, 2015

Access Is Denied (User.Identity.Name)

Hi,
Given you have an ASP.NET MVC code below that will show the current user logged in a domain:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<div class="content-wrapper">
    <div class="float-left">
        <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
    </div>
    <div class="float-right">
        <section id="login">
            Hello, <span class="username">@User.Identity.Name</span>!
        </section>
        <nav>
            <ul id="menu">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            </ul>
        </nav>
    </div>
</div>

and when you run that project, you encountered an error such as below: The fix is to click on the MVC Project -> Navigate to Properties Window -> Change Windows Authentication from "Disabled" to "Enabled". See image below:
After setting that property, you can now see the user name and the program is running successfully.


Cheers! :)

Saturday, February 21, 2015

Ajax calls not working in IE8

After testing the external js files in IE 8, the calls to post data to a controller does not work. After googling, I found a fix that is to set true to jquery support cors.
jQuery Code:
1
jQuery.support.cors = true;
CORS, INTERNET EXPLORER 8, AND XDOMAINREQUEST
Cheers!