Tuesday, May 22, 2018

Create A NuGet Package Using Visual Studio 2017

Hello all!

You may have noticed that the trend in adding components or dll's to a project is through a technology called NuGet Package and with that I'll demonstrate on how to create a simple C# Library NuGet package using Visual Studio 2017.
Below are the steps to follow.
1. First is to create a C# class library project called StringLib and add a class with a single method to convert the first letter of a string to uppercase.
public class ToUpperCase
    {
        /// <summary>
        /// Change first letter to uppercase
        /// </summary>
        public string ToUpperFirstLetter(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }

            char[] a = s.ToCharArray();
            a[0] = char.ToUpper(a[0]);
            return new string(a);
        }
    }

2. Build the project to generate a .dll file.
3. Copy the .dll or any files to be included in the package to a shared drive.
4. Download nuget.exe file from this website: Nuget.org
5. Copy the nuget.exe file to the root of your project.
6. Open command prompt as an administrator, change the directory to the root of your project and execute statement "nuget spec" to create a Package.nuspec file. 7. Edit the information of the nuspec file based on the project's id, description, authors/owners, version, purpose and location of the files. Make sure that the location of the assembly and file(s) included are correct. 8. Navigate again to the command prompt and execute statement "nuget pack Package.nuspec". This will create a a nuget package file at the root of the project such as "StringLib.1.0.0.nupkg". 9. Copy the newly created nuget package to the shared drive.
Now that we have successfully created the package, we need to add it in Visual Studio's NuGet Package Manager and use it to one of our projects.
1. Open Visual Studio, and go to Tools->Options->NuGet Package Manager-> Package Sources
2. Add the newly created package by adding an appropriate Name and it's location(shared drive). Click Ok. To use the package in a .NET Project:
1. Right click on the project and select "Manage NuGet packages".
2. Click Browse and then select the package from the "Package source:" dropdown.
3. Click Install.

That's it. You should be able to use the string method you created earlier. :-)

Saturday, May 19, 2018

Filtering, Paging and Searching Bootstrap Table by Wenzhixin in ASP.NET MVC

Good afternoon!

The previous two articles on using Bootstrap Tables were simply displaying, sorting and paging records. This tutorial will demonstrate on how apply filtering features to the table. First is to create an ASP.NET MVC project and then add an ADO.NET Entity Data Model that will use the Northwind Database Employees table. Next is to add an EmployeeView model that will be used as field names by the Bootstrap Table. The source code for the View Model and the EmployeeController is presented can be copied from this article Sort Bootstrap Table Date Column By Wenzhixin Using Moment.js In ASP.NET MVC. To enable filtering of the table, obtain the bootstrap-table-filter-control.js from the Bootstrap Table source code at github and reference it in your page as presented below:
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-table.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-table.min.js"></script>
<script src="~/Scripts/bootstrap-table-filter-control.js"></script>
<script src="~/Scripts/moment.js"></script>
In your JavaScript code, set the filterControl and filterShowClear properties of the table to true. And set the filterControl type to a specific column in which you will enable filtering or searching. The example below shows that the filterControl input has been set to EmployeeName and Address while the country has been assigned with select control.
<script type="text/javascript">

$(function () {
 $("#tblEmployee").bootstrapTable({
  url: '/Employee/GetEmployees',
  pageSize: '5',
  search: true,
  pagination: true,
  filterControl: true,
  filterShowClear: true,
  method: 'get',
  columns: [
   {
    field: 'EmployeeID',
    title: 'Employee ID',
    sortable: true
   },
   {
    field: 'EmployeeName',
    title: 'Employee Name',
    filterControl: 'input',
    sortable: true
   },
   {
    field: 'BirthDate',
    title: 'Birth Date',
    sortable: true,
    formatter: DateFormat,
    sorter: DateSorter
   },
   {
    field: 'HireDate',
    title: 'Hire Date',
    sortable: true,
    formatter: DateFormat,
    sorter: DateSorter
   },
   {
    field: 'Address',
    title: 'Address',
    filterControl: 'input',
    sortable: false
   },
   {
    field: 'PostalCode',
    title: 'PostalCode'
   },
   {
    field: 'Country',
    filterControl: 'select',
    title: 'Country'
   }
  ]
 });

 function DateSorter(a, b) {

  var dateA = new Date(moment(a).format('YYYY-MM-DD'));
  var dateB = new Date(moment(b).format('YYYY-MM-DD'));

  return dateA - dateB;
 }

 function DateFormat(value, row, index) {
  return moment(value).format('YYYY-MM-DD');
 }
});

</script>

<div class="container">
    <br />
    <div class="row">
        <table id="tblEmployee"></table>
    </div>
</div>
Initial Loading of Page Filter By Name Filter By Country
Cheers! :-)

Sunday, May 13, 2018

Sort Bootstrap Table Date Column By Wenzhixin Using Moment.js In ASP.NET MVC

Hello,

In this tutorial, I'll demonstrate on how to sort a date column of a Bootstrap Table using Moment.js. First is to create an empty ASP.NET MVC project and then add an ADO.NET Entity Model that references the Employee table of Northwinds database. Next is to define an Employee ViewModel class that will hold the information to be utilized by the Bootstrap table.
public class EmployeeViewModel
{
 public int EmployeeID { get; set; }
 public string EmployeeName { get; set; }
 public DateTime BirthDate { get; set; }
 public DateTime HireDate { get; set; }
 public string Address { get; set; }
 public string PostalCode { get; set; }
 public string Country { get; set; }
}
Then add a new controller called Employee that declares a Northwind context object, queries the database and returns the model object as JSON.
public class EmployeeController : Controller
{
 private NorthwindEntities _context;

 public EmployeeController()
 {
  _context = new NorthwindEntities();
 }

 // GET: Employee
 public ActionResult Index()
 {
  return View();
 }

 public ActionResult GetEmployees()
 {
  var model = (from emp in _context.Employees.AsEnumerable()
     select new EmployeeViewModel()
     {
      EmployeeID = emp.EmployeeID,
      EmployeeName = string.Format("{0},{1}", emp.LastName, emp.FirstName),
      BirthDate =  Convert.ToDateTime(emp.BirthDate),
      HireDate = Convert.ToDateTime(emp.HireDate),
      Address = emp.Address,
      PostalCode = emp.PostalCode,
      Country = emp.Country
     });

  return Json(model, JsonRequestBehavior.AllowGet);
 }
}
Last is to add an Index view based from the Employee controller that references the jQuery, moment.js and bootstrap table .js and .css files.
@model IEnumerable<BootstrapTableNWind.Models.EmployeeViewModel>

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-2.1.1.js"></script>
<script src="~/Scripts/moment.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<link href="~/Content/bootstrap-table.min.css" rel="stylesheet" />
<script type="text/javascript">

    $(function () {
        $("#tblEmployee").bootstrapTable({
            url: '/Employee/GetEmployees',
            pageSize: '5',
            pagination: true,
            method: 'get',
            columns: [
                {
                    field: 'EmployeeID',
                    title: 'Employee ID',
                    sortable: true
                },
                {
                    field: 'EmployeeName',
                    title: 'Employee Name',
                    sortable: true
                },
                {
                    field: 'BirthDate',
                    title: 'Birth Date',
                    sortable: true,
                    formatter: DateFormat,
                    sorter: DateSorter
                },
                {
                    field: 'HireDate',
                    title: 'Hire Date',
                    sortable: true,
                    formatter: DateFormat,
                    sorter: DateSorter
                },
                {
                    field: 'Address',
                    title: 'Address',
                    sortable: false
                },
                {
                    field: 'PostalCode',
                    title: 'PostalCode'
                },
                {
                    field: 'Country',
                    title: 'Country'
                }
            ]
        });

        function DateSorter(a, b) {    
            var dateA = new Date(moment(a).format('MM/DD/YYYY'));
            var dateB = new Date(moment(b).format('MM/DD/YYYY'));
            return dateA - dateB;
        }

        function DateFormat(value, row, index) {          
            return moment(value).format('MM/DD/YYYY');
        }
    });

</script>

<div class="container">
    <br />
    <div class="row">
        <table id="tblEmployee"></table>
    </div>
</div>
The application of moment.js is found on the DataSorter() function.
function DateSorter(a, b) {    
            var dateA = new Date(moment(a).format('MM/DD/YYYY'));
            var dateB = new Date(moment(b).format('MM/DD/YYYY'));
            return dateA - dateB;
        }
Screenshot

Cheers!

Thursday, May 3, 2018

Using Bootstrap Table By Wenzhixin with ASP.NET MVC

Good evening guys and gals!

      In this tutorial, I will show you on how to display records in tabular format using Bootstrap Table created by Wenzhixin in ASP.NET MVC. First, you need to have AdventureWorks Database since this is the database used in the demo. Next is to create an ASP.NET MVC project and then add an ADO.NET Entity Model that targets the AdventureWorks DB specifically the tables People, EmployeeDepartmentHistories, Departments, Shifts, BusinessEntityAddresses and Addresses. Proceed by adding an EmployeeViewModel class that contains properties of the Employee. This class will be used by the Bootstrap Table's columns property.
public class EmployeeViewModel
{
 public int BusinessEntityId { get; set; }
 public string EmployeeName { get; set; }
 public string Address { get; set; }
 public string PostalCode { get; set; }
 public string DepartmentName { get; set; }
 public string DepartmentGroupName { get; set; }
 public string ShiftName { get; set; }
}
Add a controller class with an AdventureWorks context object that will read the employee information from AdventureWorks DB. The results list are then converted to JSON object to be used by the Bootstrap Table.
public class EmployeeController : Controller
{
 private AdventureWorks2012Entities _context;

 public EmployeeController()
 {
  _context = new AdventureWorks2012Entities();
 }

 // GET: Employee
 public ActionResult Index()
 {
  return View(); 
 }

 public ActionResult GetEmployees()
 {
  var model = (from person in _context.People.AsEnumerable()
   join empDep in _context.EmployeeDepartmentHistories on person.BusinessEntityID equals empDep
    .BusinessEntityID
   join dep in _context.Departments on empDep.DepartmentID equals dep.DepartmentID
   join shift in _context.Shifts on empDep.ShiftID equals shift.ShiftID
   join busEntAdd in _context.BusinessEntityAddresses on empDep.BusinessEntityID equals busEntAdd
    .BusinessEntityID
   join busAdd in _context.Addresses on busEntAdd.AddressID equals busAdd.AddressID
   select new EmployeeViewModel()
   {
    BusinessEntityId = person.BusinessEntityID,
    EmployeeName = (person.LastName + ", " + person.FirstName + " " + person.MiddleName),
    DepartmentName = dep.Name,
    ShiftName = shift.Name,
    DepartmentGroupName = dep.GroupName,
    Address = busAdd.AddressLine1,
    PostalCode = !string.IsNullOrEmpty(busAdd.PostalCode) ? busAdd.PostalCode : string.Empty
   });

  return Json(model, JsonRequestBehavior.AllowGet);
 }
}
Add an empty View to the Index ActionResult that has a table element with myTable as it's id. And in the ready function of jQuery, set the properties and the columns of the table to match the model object returned by the controller action.
@model IEnumerable<BootstrapTables.Models.EmployeeViewModel>

@{
    ViewBag.Title = "Index";
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<link href="~/Content/bootstrap-table.css" rel="stylesheet" />
<script type="text/javascript">
    $(function () {
        $("#myTable").bootstrapTable({
            url: '/Employee/GetEmployees',
            method: 'get',
            pageSize: 10,
            pageNumber: 1,
            pagination: true,
            columns: [
                {
                    field: 'BusinessEntityId',
                    title: 'Employee ID',
                    sortable: true
                },
                {
                    field: 'EmployeeName',
                    title: 'Employee Name',
                    sortable: true
                },
                {
                    field: 'DepartmentName',
                    title: 'Department Name',
                    sortable: true
                },
                {
                    field: 'ShiftName',
                    title: 'Shift Name',
                    sortable: true
                },
                {
                    field: 'DepartmentGroupName',
                    title: 'Department GroupName',
                    sortable: true
                },
                {
                    field: 'Address',
                    title: 'Address',
                    sortable: true
                },
                {
                    field: 'PostalCode',
                    title: 'Postal Code',
                    sortable: true
                }
            ]
        });
    });

<div class="container">
    <br/>
    <div class="row">
        <table id="myTable"></table>
    </div>
</div>
You should see the output rendered to the browser as presented below.

Tuesday, May 1, 2018

Check If An Email Exists In Active Directory Domain

Good afternoon gents!

Here's a method on checking if an email exists in an Active Directory Domain given the format of an email FirstName.LastName@yourcompanyname.com. If the format of your company email is different from the one presented, just change the logic of the code to extract the family name.
/* 
  Email Format: Gregory.Esguerra@abcbusiness.com
*/
private bool CheckIfEmailExistsInDomain(string email)
{
 string searchName = string.Empty;
 searchName = email.Substring(email.IndexOf('.') + 1, (email.IndexOf('@')-1) - email.IndexOf('.'));
 using (var context = new PrincipalContext(ContextType.Domain, "abcbusiness.corp"))
 {
  using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
  {
   PrincipalSearchResult<Principal> allPrincipal = searcher.FindAll();
   List<Principal> principalObjects = allPrincipal.Where(t => t.Name.Contains(ToUpperFirstLetter(searchName))).ToList();

   if (principalObjects.Count > 0 && principalObjects != null)
   {
    foreach (var principalObject in principalObjects)
    {
     DirectoryEntry dEntry = principalObject.GetUnderlyingObject() as DirectoryEntry;
     if (dEntry.Properties["mail"].Value != null)
     {
      if (dEntry.Properties["mail"].Value.ToString().Equals(email, StringComparison.OrdinalIgnoreCase))
      {
       return true;
      }
     }
    }
   }
   else
   {
    return false;
   }
  }
 }

 return false;
}

Sunday, April 22, 2018

Spatial types and functions are not available for this provider because the assembly 'Microsoft.SqlServer.Types' version 10 or higher could not be found.

Hello,

While working with an ASP.NET MVC app using SQL Server 2016, this error appears in the browser "Spatial types and functions are not available for this provider because the assembly 'Microsoft.SqlServer.Types' version 10 or higher could not be found. ". After searching the forums, the solution that worked for me was to add Microsoft.SqlServer.Types dependentAssembly element inside the assemblyBinding node in the web.config.
<dependentAssembly>
        <assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
        <bindingRedirect oldVersion="10.0.0.0-11.0.0.0" newVersion="14.0.0.0" />
</dependentAssembly>

Chrome Script Debugging in Visual Studio is Enabled Hangs Up

Good morning!

While using the Visual Studio 2017 to debug ASP.NET MVC applications targeting the Chrome browser, one might encounter that both the IDE and browser hangs up. The workaround is to uncheck the Enable JavaScript debuggin for ASP.NET (Chrome and IE).

Thursday, April 19, 2018

Match Item That Exists In A List Using Regular Expression and LINQ

Hi!
Using Any() in LINQ, we can match/find an item that exists in a List<T> or IEnumerable using Regular Expressions.
if(Products.Any(t => Regex.IsMatch(t, ProductsFromFrance.FrenchProdPattern))
{
   //true statement here..
}
Where Products is the List object and ProductsFromFrance.FrenchProdPattern is the Regular Expression pattern.

Match Network Path In A String Using Regular Expression

Hello,

While working on a project, I was confronted with an issue on how to match or extract a network path. Normally, you can use string functions or built-in .NET code to check the validity of a path, but since I'm also refreshing my skills in Regular Expression. I prefer the latter as the solution. So the pattern to match the server path is presented below:
((\\\\)?((?<Folder>[a-zA-Z0-9- _]+)(\\.*[a-zA-Z0-9-_ \\])(?=")))
And to declare that pattern in your C# code, you have to escape the back slash characters.
string ServerPath = "((\\\\\\\\)?((?<Folder>[a-zA-Z0-9- _]+)(\\\\.*[a-zA-Z0-9-_ \\\\])(?=\")))";
The input strings tested are as follows.
Const ImagesPath As String = "\\ImagesServer\Logo Files\InetPub\TempProjects\"
Const docsPath As String = "\\docsPathServer15\Health\Physicians\"
Const vsPath As String = "\\vsServer909\vs2017\Projects"
string manual = "\\manualServer\CompanyRules\EmployeeFiles\Cebu"; 
The referenced post is here: Pattern Matching Path Files but I made some modifications to get the path inside the enclosing quotes.

Cheers!

Friday, April 13, 2018

How To Update Multiple Rows In One SQL Statement

Here's how to update multiple rows in one SQL statement using MSSQL.
UPDATE
  tblEmp
SET
  empSalary = empSrc.empSalary,
  empLevel = empSrc.empLevel
FROM
  dbo.tblEmployees AS tblEmp
  INNER JOIN
  (
    VALUES
    (001, 10000.00, 10),
    (002, 32000.00, 15),
    (003, 9500.00, 3)
  ) AS empSrc (empID, empSalary, empLevel)
    ON tblEmp.empID = empSrc.empID;
Reference: How to update multiple columns of multiple rows in one SQL statement