Tuesday, June 27, 2017

Export ASP.NET GridView To Excel and Preserve Leading Zeros

Hi,
There was a question raised on how to export data from ASP.NET Gridview to Microsoft Excel and preserve leading zeros of numeric values. A workaround that we have is to insert an   character before the cell value if that value starts with zero (0). So if the value starts with zero such as 0001, the result would be " 0001". Thus when exported to Excel, the leading zero is kept.
cell.Text = string.Format(" {0}", cell.Text);
A suggested solution is to insert a Tab character ( ) but this fails on some occasions. After doing some research, replacing the tab character with   or   would also fix the issue.
cell.Text = string.Format(" {0}", cell.Text);
//or
cell.Text = string.Format(" {0}", cell.Text);

ASP.NET GridView Export Excel Report
Cheers!

Sunday, June 25, 2017

WPF DataGrid Databinding using MVVM Pattern

Hello,

I've been developing WPF applications before but not having applied the MVVM design pattern and have been wanting to create a simple program that loads data into the DataGrid control. According to Wikipedia, the components of an MVVM pattern are:
Model
Model refers either to a domain model, which represents real state content (an object-oriented approach), or to the data access layer, which represents content (a data-centric approach).
View
As in the MVC and MVP patterns, the view is the structure, layout, and appearance of what a user sees on the screen.
View model
The view model is an abstraction of the view exposing public properties and commands. Instead of the controller of the MVC pattern, or the presenter of the MVP pattern, MVVM has a binder. In the view model, the binder mediates communication between the view and the data binder.The view model has been described as a state of the data in the model.
Binder
Declarative data and command-binding are implicit in the MVVM pattern. In the Microsoft solution stack, the binder is a markup language called XAML.
Given the explanations above, here's the code that applies a plain MVVM approach.
ViewModel (CustomerViewModel.cs)
The model used here is the Northwind Customer
public class CustomerViewModel : ViewModelBase
    {
        private ObservableCollection<Customer> _cusGridData;
        private NorthwindEntities _context;

        public CustomerViewModel()
        {
            _context = new NorthwindEntities();
            LoadInitialData();
        }

        private void LoadInitialData(){
            CustomerData = new ObservableCollection<Customer>(from c in _context.Customers select c);
        }

        public ObservableCollection<Customer> CustomerData
        {
            get 
            { 
                return _cusGridData; 
            }
            set
            {
                _cusGridData = value;
                OnPropertyChanged("CustomerData");
            }
        }
    }
View (XAML)
<Window x:Class="WPFMVVMDataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewModel="clr-namespace:WPFMVVMDataGrid"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <ViewModel:CustomerViewModel/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding Path=CustomerData}" x:Name="dgCustomer"
             AutoGenerateColumns="False"
             SelectionMode="Single"
             SelectionUnit="FullRow"
             GridLinesVisibility="Horizontal"
             CanUserDeleteRows="True"
             CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Width="SizeToCells" MinWidth="125" Binding="{Binding CustomerID}" />
                <DataGridTextColumn Header="Age" Width="SizeToCells" MinWidth="200" Binding="{Binding ContactName}"/>
                <DataGridTextColumn Header="Description" Width="SizeToCells" MinWidth="200" Binding="{Binding Address}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>
For the details on how MVVM works see this thread WPF Having Trouble with binding a Datagrid control on load

Source Code: DataGridMVVMWPF In Github

Cheers! :-)

Monday, June 5, 2017

Disable button in AngularJS using ng-disabled on it's first page load in ASP.NET MVC

Hello,
One might notice that during page load of an ASP.NET MVC application, the button with ng-disabled attribute and have values such as $invalid or $dirty does not disable the button. Thus, this will enable the user to submit the form with empty values to the controller method. In order to disable the button on page load, add $pristine values in the ng-disabled attribute such as the code below.
Original Code
<input type="submit" id="btnAddEmployee" class="btn btn-primary" value="Save" ng-click="Save()" 
 ng-disabled="AddEmp.fname.$dirty && AddEmp.fname.$invalid
     || AddEmp.lname.$dirty && AddEmp.lname.$invalid
     || AddEmp.salary.$dirty && AddEmp.salary.$invalid" />
Modified code with $pristine
<input type="submit" id="btnAddEmployee" class="btn btn-primary" value="Save" ng-click="Save()" 
 ng-disabled="AddEmp.fname.$dirty && AddEmp.fname.$invalid || AddEmp.fname.$pristine
     || AddEmp.lname.$dirty && AddEmp.lname.$invalid || AddEmp.lname.$pristine
     || AddEmp.salary.$dirty && AddEmp.salary.$invalid || AddEmp.salary.$pristine" />

Saturday, June 3, 2017

$location.path() method not reloading new data in ASP.NET MVC Web API with AngularJS

Hello,
I was trying to integrate AngularJS into a simple ASP.NET MVC Web API application with Save functionality. Basically, when you have finished posting data the next logic will be to redirect the user to the display all page. However, I stumbled into an issue in which the $location service does not reload data.
According to the docs,the $location service allows you to change only the URL; it does not allow you to reload the page. So after placing breakpoints in the Api Controller, I noticed that the GetAll() method is called first next is the Save() method. The solution to this dilemma is to transfer the $location.path() method inside the success function so that the Save() method in the Api Controller is executed first.
Code With Issue: $location.path() is outside the success function.
 $scope.Add = function () {
  $http({ method: "POST", data: $scope.employee, url: "/api/employees" })
  .then(function (response) {
   $scope.employees = response.data;
   $scope.employee = {
    "FirstName": "",
    "LastName": "",
    "Age": "",
    "Salary": ""
   };   
  });
  $location.path('/allemployees'); 
}
Fix: $location.path() is inside the success function.
$scope.Add = function () {
  $http({ method: "POST", data: $scope.employee, url: "/api/employees" })
  .then(function (response) {
   $scope.employees = response.data;
   $scope.employee = {
    "FirstName": "",
    "LastName": "",
    "Age": "",
    "Salary": ""
   };
   $location.path('/allemployees'); 
  });  
}

Cheers! :-)