Monday, June 27, 2016

Show IP Address in ASP.NET MVC

Here's a simple tutorial on how to get a user's IP address using ASP.NET MVC and jQuery. The fetching of record is triggered when the textbox receives focus.
HTML Code
1
<input id="txtID" type="text" />

JavaScript Code
1
2
3
4
5
6
7
8
$(document).ready(function () {
    $('#txtID').focus(function () {            
        $.getJSON('@Url.Action("GetIPAddress","getipaddress")'
                 , function (result) {
            $("#txtID").val(result);
        });
    });
});

C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public JsonResult GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current;
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    string output = string.Empty;
 
    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            output = addresses[0];
        }
    }
    else
    {
        output = context.Request.ServerVariables["REMOTE_ADDR"];
    }
 
    return Json(output, JsonRequestBehavior.AllowGet);
}  

Sunday, June 26, 2016

Operating system error 5(Access is denied.) "Cannot open backup device" in SQL Server

Here's how I manage to solve the issue Cannot open backup device with status Operating system error 5(Access is denied.)
Steps
1. Right Click the Folder which is the backup destination
2. Click Properties -> Security Tab -> Click Advanced Button
3. On Permissions Tab -> choose Add -> Select Principal
4. In the "Enter the object name to select", type "NT Service\MSSQLSERVER". -> OK
    Note: NT Service\MSSQLSERVER is the Log On As value of     MSSQLSERVER service under Services. See screenshot below
5. In Multiple Names Found choose MSSQLSERVER.
6. Click OK
7. In Basic permissions panel, Choose Full Control
8. Click Apply -> OK -> OK to close Folder Properties dialog box
SQL Server Service

Friday, June 24, 2016

Unpivot in SQL Server Example

Given the following records below, you may want to show them in a vertical manner instead of horizontal view of columns.


To achieve the desired result, you use UNPIVOT clause in your query.
1
2
3
4
5
6
7
8
Use testdatabase
Go
SELECT [Subject],
       Grade
FROM StudentReportCard 
UNPIVOT (Grade FOR [Subject] IN (English, Math, Literature, Biology)) 
        AS U_SubjectGrade
WHERE StudentId = 1

Screenshot

Tuesday, June 21, 2016

Webbrowser GetAttribute("class") method not working

When working with Webbrowser's GetAttribute() method, you often encountered an issue wherein GetAttribute("class") does not work as expected.
1
2
3
if (Element.GetAttribute("class").Contains("_textFontColor")) {
    //other codes here
}

After investigating from MSDN docs, I found out a comment below the documentation which states that you have to use classNameinstead of class. Well, that did the trick. :-)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
HtmlElementCollection elements = WebBrowser1.Document.GetElementsByTagName("A");
foreach (HtmlElement Element in elements) {
    if (Element.GetAttribute("className").Contains("_textFontColor")) {
        //other codes here
    }
}
 
HtmlElementCollection elements = WebBrowser1.Document.GetElementsByTagName("a");
foreach (HtmlElement Element in elements) {
    if (Element.GetAttribute("className").Contains("_textFontColor")) {
        //other codes here
    }
}
Reference (See Bottom Comment of the page): HtmlElement.GetAttribute Method

Thursday, June 16, 2016

Bootstrap DatePicker Control in ASP.NET Webforms

Here's how to integrate Bootstrap DatePicker widget in you ASP.NET Webforms Project. First, you need to add reference to the following JS and CSS files: bootstrap.min.css, bootstrap-datepicker3.standalone.css, jquery-1.11.1.min.js, bootstrap.min.js, bootstrap-datepicker.min.js.
1
2
3
4
5
<link rel="stylesheet" href="Content/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/css/bootstrap-datepicker3.standalone.css" />
<script type="text/javascript" src="Scripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.1/js/bootstrap-datepicker.min.js"></script>
Create a simple registration form with Bootstrap classes.
 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
 <div class="container">
    <div class="row">               
        <div class="col-sm-6">
            <fieldset>
                <legend>Registration Form</legend>
                <div class="form-group">                        
                        <label for="usr">Name:</label>
                        <input type="text" class="form-control" id="name" />
                 </div>
                <div class="form-group">                        
                        <label for="usr">Age:</label>
                        <input type="text" class="form-control" id="age" />
                 </div>
                <div class="form-group">                        
                        <label for="usr">Address:</label>
                        <input type="text" class="form-control" id="address" />
                 </div>
                <div class="form-group">  
                        <label for="usr">Birthdate:</label>                      
                        <div class='input-group date' id='birthdate'>
                            <input type='text' class="form-control" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>
                    </div>
            </fieldset>                    
        </div>
    </div>
</div>

Your JavaScript code will initialize the datepicker control with common properties such as autoclose, format, todayHighlight, clearBtn and orientation. However, you might add several properties as per your needs which is stated in the documentation of the control.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<script type="text/javascript">
    $(document).ready(function () {            
        $("#birthdate").datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
            todayHighlight: true,
            clearBtn: true,
            orientation: 'bottom'
        });
    });
</script>

Screenshot
That's it.. :-)

Wednesday, June 8, 2016

WPF DataGrid Excel Comment Indicator

Here's how to add a comment indicator to a DataGridCell similar to an Excel functionality using MultiValueConverter. See codefiles and screenshot below.
XAML
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<Window x:Class="WPFExcelCommentIndicator.DataGridCellCommentIndicator"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:WPFExcelCommentIndicator"
        Title="DataGridCellCommentIndicator"  Height="350" Width="500" WindowStartupLocation="CenterScreen" >
    <Window.Resources>
        <src:DataGridCellComment x:Key="DataGridCellComment" />
        <src:StudentList x:Key="StudentListData" />
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="225"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="225"/>
        </Grid.RowDefinitions>       
        <DataGrid Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" AutoGenerateColumns="False" CanUserResizeColumns="True"
                  CanUserAddRows="False" SelectionMode="Single" SelectionUnit="Cell" ItemsSource ="{Binding Path=StudentItems}" 
                  Name="dgStudents">
            <DataGrid.Resources>
                <DataTemplate x:Key="DateTemplate">
                    <Canvas x:Name="pnlContainer" Height="25">
                        <TextBlock x:Name="txtAge" IsEnabled="False" Foreground="Green" Text="{Binding Path=Age, Mode=TwoWay}" />
                        <Polygon IsEnabled="False" ClipToBounds="False" VerticalAlignment="Top" x:Name="polyExcel">
                            <Polygon.Fill>
                                <SolidColorBrush Color="Red" />
                            </Polygon.Fill>
                            <Polygon.Points>
                                <MultiBinding Converter="{StaticResource DataGridCellComment}">
                                    <Binding RelativeSource="{RelativeSource Mode=Self}"/>
                                    <Binding Path="Age"></Binding>
                                </MultiBinding>
                            </Polygon.Points>
                        </Polygon>
                    </Canvas>      
                </DataTemplate>
            </DataGrid.Resources>
            <DataGrid.CellStyle>
                <Style TargetType="DataGridCell">
                    <EventSetter Event="PreviewMouseDown" Handler="CheckPolygon"/>
                    <EventSetter Event="SizeChanged" Handler="Cell_SizedChanged" />
                </Style>
            </DataGrid.CellStyle>
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="100" IsReadOnly="True" />
                <DataGridTemplateColumn Header="Age" CellTemplate="{StaticResource DateTemplate}" Width="100" >
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="100"  IsReadOnly="True" />
                <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" Width="*" IsReadOnly="True"/> 
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

Code Behind
 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
34
35
36
37
public partial class DataGridCellCommentIndicator : Window
{
    public DataGridCellCommentIndicator()
    {
        InitializeComponent();
        this.DataContext = this;
    }
    
    public StudentList StudentItems
    {
        get { return new StudentList(); }
    }
    
    void CheckPolygon(object sender, RoutedEventArgs e)
    {
        
    }
    
    private void Cell_SizedChanged(object sender, SizeChangedEventArgs e)
    {
        DataGridCell cell = (DataGridCell)sender;
        if (cell.Column.Header.ToString().Equals("Age"))
        {
            Polygon poly = ControlExtensions.GetVisualChild<Polygon>(cell);
            TextBlock textAge = ControlExtensions.GetVisualChild<TextBlock>(cell);
 
            if (cell.ActualWidth != 100 && Convert.ToInt32(textAge.Text) >= 30)
            {
                PointCollection myPointCollection = new PointCollection();
                myPointCollection.Add(new Point(cell.ActualWidth - 13, cell.ActualHeight - (cell.ActualHeight + 1)));
                myPointCollection.Add(new Point(cell.ActualWidth - 2, cell.ActualHeight - (cell.ActualHeight + 1)));
                myPointCollection.Add(new Point(cell.ActualWidth - 2, cell.ActualHeight - 20));
                poly.Points = myPointCollection;
            }
        }
    }
}   

DataGridCell Comment Class
 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
public class DataGridCellComment : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        DataGridCell cell = ((Polygon)values[0]).GetAncestor<DataGridCell>();
        TextBlock textAge = ControlExtensions.GetVisualChild<TextBlock>(cell);
        PointCollection myPointCollection = new PointCollection();
        myPointCollection.Add(new Point(cell.ActualWidth - 13, cell.ActualHeight - (cell.ActualHeight + 1)));
        myPointCollection.Add(new Point(cell.ActualWidth - 2, cell.ActualHeight - (cell.ActualHeight + 1)));
        myPointCollection.Add(new Point(cell.ActualWidth - 2, cell.ActualHeight - 20));
 
        if (System.Convert.ToInt32(textAge.Text) >= 30)
        {
            return myPointCollection;
        }
        else
        {
            return null;
        } 
    }
 
    public object[] ConvertBack(object value, Type[] targetTypes, 
          object parameter, CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }
}

Control Extension Method
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public static T GetVisualChild<T>(Visual parent) 
     where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>
            (v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}

StudentList and Student Classes
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class StudentList : ObservableCollection<Student>
{
    public StudentList()
    {
        Add(new Student { ID = 1, Age = 29, Name = "Mike", Address = "Cebu" });
        Add(new Student { ID = 2, Age = 28, Name = "Phil", Address = "Cebu" });
        Add(new Student { ID = 3, Age = 23, Name = "Chelsy", Address = "Leyte" });
        Add(new Student { ID = 4, Age = 33, Name = "Jeff", Address = "Leyte" });
        Add(new Student { ID = 5, Age = 32, Name = "Greg", Address = "Cebu" });
        Add(new Student { ID = 6, Age = 28, Name = "Howard", Address = "Bohol" });
        Add(new Student { ID = 7, Age = 27, Name = "Grant", Address = "Bohol" });
    }
}
 
public class Student
{
    public int ID { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

Screenshot

Tuesday, June 7, 2016

Convert DataTable to List <T> using LINQ

The code below converts a DataTable object to generic list object. It assumes that the DataTable columns match with class properties.
C# Code
1
2
3
4
5
6
7
8
var personEnumerable = table.AsEnumerable();
List<Person> ListPosition = new List<Person>();
ListPosition = (from item in personEnumerable
            select new Person
            {
                ID = item.Field<int>("ID").ToString(),
                Salary = item.Field<double>("Salary").ToString()
            }).ToList();

Class
1
2
3
4
5
public class Person
{
    public string ID { get; set; }
    public string Salary { get; set; }
}