Tuesday, August 10, 2021

Communication between components using data service in angular

 We can establish communication between components using data service. To understand this concept  lets take below example. Here we can add user with there status and display users in active/inactive list. we can also change the status of any existing user.


Lets start to build our example.

Step 1 : Create user.model.ts

export class User{
    status string;
    user : string;
    constructor(user : string , status : string){
        this.user = user;
        this.status = status;
    }
}

Step 2 : Generate components

ng g c create-user

ng g c active-user

ng g c inactive-user

Step 3 : create-user.comopnent.ts

import { ComponentOnInitfrom '@angular/core';
import { AccountService } from '../services/account.service';
import { User } from '../shared/user.model';

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: ['./create-user.component.css']
})
export class CreateUserComponent implements OnInit {
  userNamestring = '';
  statusstring = '';
  constructor(private accountServiceAccountService) { }

  ngOnInit(): void {
  }

  onAdd() {
    this.accountService.onAdd({ user: this.userNamestatus: this.status });
  }

  onRemove() {
    this.accountService.onRemove({ user: this.userNamestatus: this.status });
  }
}

Step 4 : create-user.component.html

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <label for="UserName">User Name</label>
            <input type="text" for="userName" [(ngModel)]="userName" class="form-control">
            <label for="Status">Status</label>
            <select class="form-control" for="status" [(ngModel)]="status">
                <option>Active</option>
                <option>Inactive</option>
            </select>
        </div>
        <div class="col-xs-5">
            <span class="span">
                <button type="button" class="btn btn-primary" 
                (click)="onAdd()">Add</button></span>
            <span><button type="button" class="btn btn-warning"
                    (click)="onRemove()">Remove</button></span>
        </div>
    </div>
</div>

Step 5 : Build active-user.component.ts

import { ComponentInputOnInitfrom '@angular/core';
import { AccountService } from '../services/account.service';

@Component({
  selector: 'app-active-user',
  templateUrl: './active-user.component.html',
  styleUrls: ['./active-user.component.css']
})
export class ActiveUserComponent implements OnInit {
  @Input()
  activeUser!: string;

  constructor(private accountService : AccountService) { }

  ngOnInit(): void {
  }

  onSetInActiveUser(userstring) {
    this.accountService.onSetInActiveUser(user);
  } 
}

Step 6 : active-user.component.html

<li class="list-group-item">
    {{activeUser}} |
    <a href="#" (click)="onSetInActiveUser(activeUser)">Set to Inactive</a>
</li>

Step 7 : inactive-user.component.ts

import { ComponentInputOnInit } from '@angular/core';
import { AccountService } from '../services/account.service';

@Component({
  selector: 'app-inactive-user',
  templateUrl: './inactive-user.component.html',
  styleUrls: ['./inactive-user.component.css']
})
export class InactiveUserComponent implements OnInit {
  @Input() inActiveUser !: string;
  constructor(private accountService : AccountService ) { }

  ngOnInit(): void {
  }

  onSetActiveUser(userstring) {
    this.accountService.onSetActiveUser(user);
  }
}

Step 7 : inactive-user.component.html

<li class="list-group-item">
    {{inActiveUser}} |
    <a href="#" (click)="onSetActiveUser(inActiveUser)">Set to Active</a>
</li>

Step 8 : account.service.ts

import { User } from "../shared/user.model";

export class AccountService {
  activeUserListstring[] = ['Max''Chris'];
  inActiveUserListstring[] = ['Rode''Chin'];

  onSetInActiveUser(userstring) {
    this.activeUserList = this.activeUserList.filter(ele => ele !== user);
    this.inActiveUserList.push(user);
  }

  onSetActiveUser(userstring) {
    this.inActiveUserList = this.inActiveUserList.filter(ele => ele !== user);
    this.activeUserList.push(user);
  }

  onAdd(itemUser) {
    if (item.status === 'Active'this.activeUserList.push(item.user);
    else this.inActiveUserList.push(item.user);
  }

  onRemove(itemUser) {
    if (item.status === 'Active'this.activeUserList = this.activeUserList.filter(e => e !== item.user);
    else this.inActiveUserList = this.inActiveUserList.filter(e => e !== item.user);
  }
}

Step 9 : app-component.ts

import { ComponentOnInit } from '@angular/core';
import { AccountService } from './services/account.service';
import { User } from './shared/user.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'ServiceAssignment';
  activeUserList : string[] = [];
  inActiveUserList : string[] = [];

  constructor(public accountServiceAccountService) { }

  ngOnInit(){
     this.activeUserList = this.accountService.activeUserList;
     this.inActiveUserList = this.accountService.inActiveUserList;
  }
}

Step 10 : app-component.html

<app-create-user></app-create-user> 
<div class="container">
    <hr />
    <label for="ActiveUsers">Active Users</label>
    <ul class="list-group">
        <app-active-user 
        *ngFor="let acu of this.accountService.activeUserList" 
        [activeUser]="acu"></app-active-user>
    </ul>
    <label for="InactiveUsers">Inactive Users</label>
    <ul class="list-group">
        <app-inactive-user 
        *ngFor="let incu of this.accountService.inActiveUserList" 
        [inActiveUser]="incu"></app-inactive-user>           
    </ul>
</div>



Thursday, July 29, 2021

Custom Property and Event Binding Using @Input/@Output Decorator

 Using custom property and event binding we can establish communication between parent and child component.

Let take a below example. Here we are adding student name and age in student component and display student details in student-list component.

Now we start to build our example.

Step 1 : Create Student model (student.model.ts)

export class Student{
    name : string;
    age : number;
    constructor(name : string , age : number){
    this.name = name;
    this.age = age;
    }
}

Step 2 : Generate components

ng g c student

ng g c student/student-list

Step 3 : app.component.ts (Parent component)

import { ComponentEventEmitterOutput } from '@angular/core';
import { Student } from './student/student.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  students : Student[] = [];

    addStudent(student : Student){
      this.students.push({name : student.name ,age : student.age});
    }
}


Step 4 : app.component.html

<app-student (buttonClick)="addStudent($event)"></app-student>
        
<app-student-list *ngFor="let student of students"
[studentList] = "student"></app-student-list>

Step 5 : Add @Input decorator in student-list.component.ts

import { ComponentInputOnInit } from '@angular/core';
import { Student } from '../student.model';

@Component({
  selector: 'app-student-list',
  templateUrl: './student-list.component.html',
  styleUrls: ['./student-list.component.css']
})
export class StudentListComponent implements OnInit {
  name : string = '';
  age : number = 0;
  @Input() studentList Student;
  constructor() { }

  ngOnInit(): void {
  }
}

Step 6 : student-list.component.html

<div class="container">
    <div class="row">
        <div class="panel panel-default">
            <div class="panel panel-heading" >
                Student Details
            </div>
            <div class="panel-body">
               <p> {{studentList.name}}</p>
               <p>{{studentList.age}}</p> 
            </div>
        </div>
    </div>
</div>

Step 7 : Add @Output decorator in student.component.ts

import { ComponentEventEmitterInputOnInitOutput } from '@angular/core';
import { Student } from './student.model';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.css']
})
export class StudentComponent implements OnInit {
   studentsStudent[] = [];
   name : string = '';
   age : number = 0;
  @Output() buttonClick = new  EventEmitter<Student>();
  constructor() { 
  }

  ngOnInit(): void {
  }

  onStudentAdd(){
    this.buttonClick.emit({ name : this.name,age : this.age});
  }
}

Step 8 : student.component.ts

<div class="container">
    <div class="row">
      
            <label for="name">Name</label>
            <input type="text" class="form-control" [(ngModel)]="name" >
            <label for="Age">Age</label>
            <input type="number" class="form-control" [(ngModel)]="age" >
        <br/>
        <button type="button" class="btn btn-primary" (click)="onStudentAdd()">Add Student</button>
    </div>
</div>




Tuesday, March 27, 2018

Calling cross domain asp.net web API using jquery

Hi Friends,

Today I am going to show how to call cross domain web API using jquery.

For this, open Visual Studio 2013 for Web and click on File menu and click on New Project. This will open New Project popup as below.


In the New Project popup, expand Visual C# and select Web node in the left pane. Select ASP.NET Web Application template in the middle pane and enter the name of a project and click OK.

 This will open New ASP.NET Project popup as shown below.


Next, we’ll create a sample model inside the model folder in the Web API solution. Right click on the Model folder from the solution explorer and select Add.


For this walk-through, I am using the Product model.

public class Product
{
public int Id{ get; set; }
public string Name{ get; set; } 
}
 
Now right click on Controller folder and add DemoController.



Now publish the code and host in the IIS with sample IP : 101.13.547.18:8065.


But when you try to call this Web API through other application it will give you no root element found error. To resolve this error jsonp formatter in WebApiConfig.cs file.

Now the final part, create another asp.net application and add the below code in aspx page.


Tuesday, February 16, 2016

TFS : Compare Changeset in Asp.Net C#

Hi friends, I am going to demonstrate comparing changeset in C#. I will cover following topics.
  1. Get history(list of all changeset)
  2. Download and Compare files
For comparing two file we use Winmerge.
 TFS Demo
Take reference of below dll's.

DLL

 <table width="100%">  
     <tr>  
       <td>  
         <asp:Literal ID="litTfsParentFolderPath" runat="server" Text="TFS Parent Folder Path"></asp:Literal></td>  
       <td>  
         <asp:TextBox ID="txtTfsParentFolderPath" runat="server" Text="$/ParentFolder/*" Enabled="false" Width="400px"></asp:TextBox>  
       </td>  
     </tr>  
     <tr>  
       <td>  
         <asp:Literal ID="litChildFolderName" runat="server" Text="TFS Child Folder Name"></asp:Literal></td>  
       <td>  
         <asp:DropDownList ID="ddlChildFolders" runat="server" Width="410px" OnSelectedIndexChanged="ddlChildFolders_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>  
       </td>  
     </tr>  
     <tr>  
       <td colspan="2">  
         <asp:GridView ID="grvChangeSetData" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"  
           GridLines="None" OnRowDataBound="grvChangeSetData_RowDataBound" OnRowCommand="grvChangeSetData_RowCommand">  
           <AlternatingRowStyle BackColor="White" ForeColor="#284775" />  
           <Columns>  
             <asp:TemplateField HeaderText="Changeset Number" HeaderStyle-Width="10%" ItemStyle-Width="10%" ItemStyle-VerticalAlign="Top">  
               <ItemTemplate>  
                 <asp:Literal ID="litChangeSetNo" runat="server" Text='<%#Bind("ChangeSetNumber") %>'></asp:Literal>  
               </ItemTemplate>  
               <HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>  
               <ItemStyle VerticalAlign="Top" Width="10%"></ItemStyle>  
             </asp:TemplateField>  
             <asp:TemplateField HeaderText="Owner" HeaderStyle-Width="10%" ItemStyle-Width="10%" ItemStyle-VerticalAlign="Top">  
               <ItemTemplate>  
                 <asp:Literal ID="litOwnerDisplayName" runat="server" Text='<%#Bind("OwnerDisplayName") %>'></asp:Literal>  
               </ItemTemplate>  
               <HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>  
               <ItemStyle VerticalAlign="Top" Width="10%"></ItemStyle>  
             </asp:TemplateField>  
             <asp:TemplateField HeaderText="Created Date" HeaderStyle-Width="10%" ItemStyle-Width="10%" ItemStyle-VerticalAlign="Top">  
               <ItemTemplate>  
                 <asp:Literal ID="litCreateDate" runat="server" Text='<%#Bind("CreateDate") %>'></asp:Literal>  
               </ItemTemplate>  
               <HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>  
               <ItemStyle VerticalAlign="Top" Width="10%"></ItemStyle>  
             </asp:TemplateField>  
             <asp:TemplateField HeaderText="Comment" HeaderStyle-Width="10%" ItemStyle-Width="10%" ItemStyle-VerticalAlign="Top">  
               <ItemTemplate>  
                 <asp:Literal ID="litComment" runat="server" Text='<%#Bind("Comments") %>'></asp:Literal>  
               </ItemTemplate>  
               <HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>  
               <ItemStyle VerticalAlign="Top" Width="10%"></ItemStyle>  
             </asp:TemplateField>  
             <asp:TemplateField HeaderText="Files" HeaderStyle-Width="10%" ItemStyle-Width="10%" ItemStyle-VerticalAlign="Top">  
               <ItemTemplate>  
                 <asp:Repeater ID="rpFiles" runat="server" OnItemCommand="rpFiles_ItemCommand">  
                   <HeaderTemplate>  
                     <table width="100%">  
                   </HeaderTemplate>  
                   <ItemTemplate>  
                     <tr>  
                       <td>  
                         <asp:LinkButton ID="lnkFileName" runat="server" Text='<%# Bind("FileName") %>'  
                           CommandName="DownloadFile" CommandArgument='<%# Bind("CommandArgument") %>'></asp:LinkButton>  
                         <asp:LinkButton ID="lnkCompare" runat="server" Text="Compare"  
                           CommandName="CompareFile" CommandArgument='<%# Bind("CommandArgument") %>'></asp:LinkButton>  
                       </td>  
                     </tr>  
                   </ItemTemplate>  
                   <FooterTemplate>  
                     </table>  
                   </FooterTemplate>  
                 </asp:Repeater>  
               </ItemTemplate>  
               <HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>  
               <ItemStyle VerticalAlign="Top" Width="10%"></ItemStyle>  
             </asp:TemplateField>  
           </Columns>  
           <EditRowStyle BackColor="#999999" />  
           <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
           <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
           <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />  
           <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />  
           <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />  
           <SortedAscendingCellStyle BackColor="#E9E7E2" />  
           <SortedAscendingHeaderStyle BackColor="#506C8C" />  
           <SortedDescendingCellStyle BackColor="#FFFDF8" />  
           <SortedDescendingHeaderStyle BackColor="#6F8DAE" />  
         </asp:GridView>  
       </td>  
     </tr>  
   </table>  
Put the below code in .cs file
 using System;  
 using System.Collections.Generic;  
 using System.Collections.ObjectModel;  
 using System.Configuration;  
 using System.Diagnostics;  
 using System.Linq;  
 using System.Net;  
 using System.Text;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using Microsoft.TeamFoundation;  
 using Microsoft.TeamFoundation.Client;  
 using Microsoft.TeamFoundation.Framework.Client;  
 using Microsoft.TeamFoundation.Framework.Common;  
 using Microsoft.TeamFoundation.VersionControl.Client; 
 namespace TFSDemo  
 {  
   public partial class _Default : Page  
   {  
     #region Properties  
     public TfsTeamProjectCollection teamProjectCollection  
     {  
       get { return GetTFS(); }  
     }  
     public string GetTFSPath  
     {  
       get { return ConfigurationManager.AppSettings["URI"]; }  
     }  
     public string GetUser  
     {  
       get { return ConfigurationManager.AppSettings["User"]; }  
     }  
     public string GetPassword  
     {  
       get { return ConfigurationManager.AppSettings["Password"]; }  
     }  
     public string GetDomain  
     {  
       get { return ConfigurationManager.AppSettings["Domain"]; }  
     }  
     #endregion  
     #region PageLoad  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       if (!IsPostBack)  
       {  
         BindSubFolders();  
       }  
     }  
     #endregion  
     #region Events  
     
     protected void ddlChildFolders_SelectedIndexChanged(object sender, EventArgs e)  
     {  
       try  
       {  
         string filePath = ddlChildFolders.SelectedItem.Value.ToStringSafe();  
         List<SubFolderChangeSet> listChangeSet = GetChangeSetBySubFolderName(filePath);  
         grvChangeSetData.DataSource = listChangeSet.Distinct().Select(x => x);  
         grvChangeSetData.DataBind();  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  
     protected void grvChangeSetData_RowDataBound(object sender, GridViewRowEventArgs e)  
     {  
       if (e.Row.RowType == DataControlRowType.DataRow)  
       {  
         Repeater rpFiles = e.Row.FindControl("rpFiles") as Repeater;  
         if (rpFiles != null)  
         {  
           rpFiles.ItemCommand += new RepeaterCommandEventHandler(rpFiles_ItemCommand);  
           List<Change> listChangeset = ((e.Row.DataItem) as SubFolderChangeSet).listChange;  
           List<FileNames> listFileName = new List<FileNames>();  
           if (listChangeset != null && listChangeset.Count > 0)  
           {  
             foreach (Change change in listChangeset)  
             {  
               FileNames file = new FileNames();  
               file.ChangeSetNumber = ((e.Row.DataItem) as SubFolderChangeSet).ChangeSetNumber;  
               file.FileName = change.Item.ServerItem.Substring(change.Item.ServerItem.LastIndexOf('/') + 1);  
               file.CommandArgument = file.ChangeSetNumber + "@" + file.FileName;  
               listFileName.Add(file);  
             }  
             rpFiles.DataSource = listFileName;  
             rpFiles.DataBind();  
           }  
         }  
       }  
     }  
     protected void rpFiles_ItemCommand(object source, RepeaterCommandEventArgs e)  
     {  
       if (e.CommandName.Equals("DownloadFile", StringComparison.OrdinalIgnoreCase))  
       {  
         string[] args = e.CommandArgument.ToStringSafe().Split('@');  
         if (args != null && args.Length > 0)  
         {  
           int changesetId = args[0].ToIntSafe();  
           VersionControlServer vcs = GetVersionServer(teamProjectCollection);  
           if (vcs != null)  
           {  
             Changeset cs = vcs.GetChangeset(changesetId);  
             foreach (Change ch in cs.Changes)  
             {  
               string filename = ch.Item.ServerItem.Substring(ch.Item.ServerItem.LastIndexOf('/') + 1);  
               if (filename.Equals(args[1].ToStringSafe(), StringComparison.OrdinalIgnoreCase))  
               {  
                 ch.Item.DownloadFile(System.IO.Path.GetTempPath() +  
                            ch.Item.ChangesetId +  
                            ch.Item.ServerItem.Split('/')[  
                              ch.Item.ServerItem.Split('/').Length - 1]);  
               }  
             }  
           }  
         }  
       }  
       if (e.CommandName.Equals("CompareFile", StringComparison.OrdinalIgnoreCase))  
       {  
         string[] args = e.CommandArgument.ToStringSafe().Split('@');  
         if (args != null && args.Length > 0)  
         {  
           int changesetId = args[0].ToIntSafe();  
           VersionControlServer vcs = GetVersionServer(teamProjectCollection);  
           if (vcs != null)  
           {  
             Changeset cs = vcs.GetChangeset(changesetId);  
             string matchFile = string.Empty;  
             string filePath = string.Empty;  
             filePath = System.IO.Path.GetTempPath();  
             //filePath = Server.MapPath("~//TFSFiles");  
             foreach (Change ch in cs.Changes)  
             {  
               string filename = ch.Item.ServerItem.Substring(ch.Item.ServerItem.LastIndexOf('/') + 1);  
               if (filename.Equals(args[1].ToStringSafe(), StringComparison.OrdinalIgnoreCase))  
               {  
                 matchFile = ch.Item.ServerItem.ToStringSafe();  
                 ch.Item.DownloadFile(filePath +  
                            ch.Item.ChangesetId +  
                            ch.Item.ServerItem.Split('/')[  
                              ch.Item.ServerItem.Split('/').Length - 1]);  
               }  
             }  
             if (!string.IsNullOrWhiteSpace(matchFile))  
             {  
               Item item = vcs.GetItem(matchFile);  
               item.DownloadFile(filePath + changesetId + "-New-" + matchFile.Split('/')[matchFile.Split('/').Length - 1]);  
               var winmerge = Process.Start(@"C:\Program Files (x86)\WinMerge\WinMergeU.exe",  
                         String.Format("{0}{1} {0}{2}", filePath,  
                                @"\" + changesetId + matchFile.Substring(matchFile.LastIndexOf('/') + 1), @"\" + changesetId + "-New-" +  
                                matchFile.Substring(matchFile.LastIndexOf('/') + 1)));  
             }  
           }  
         }  
       }  
     }  
     protected void grvChangeSetData_RowCommand(object sender, GridViewCommandEventArgs e)  
     {  
     }  
     #endregion  
     #region PrivateMethods  
     private TfsTeamProjectCollection GetTFS()  
     {  
       TfsTeamProjectCollection tpc = null;  
       try  
       {  
         Uri tfsUri = new Uri(GetTFSPath);  
         TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);  
         configurationServer.Credentials = new NetworkCredential(GetUser, GetPassword, GetDomain);  
         configurationServer.Authenticate();  
         ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);  
         foreach (CatalogNode collectionNode in collectionNodes)  
         {  
           Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);  
           tpc = configurationServer.GetTeamProjectCollection(collectionId);  
         }  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
       return tpc;  
     }  
     private VersionControlServer GetVersionServer(TfsTeamProjectCollection teamProjectCollection)  
     {  
       return teamProjectCollection.GetService<VersionControlServer>();  
     }  
     private void BindSubFolders()  
     {  
       try  
       {  
         if (teamProjectCollection != null)  
         {  
           VersionControlServer vcs = GetVersionServer(teamProjectCollection);  
           var subFolders = vcs.GetItems(txtTfsParentFolderPath.Text.ToStringSafe());  
           List<string> listSubFolders = new List<string>();  
           foreach (var item in subFolders.Items)  
           {  
             listSubFolders.Add(item.ServerItem);  
           }  
           ddlChildFolders.DataSource = listSubFolders;  
           ddlChildFolders.DataBind();  
         }  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  
     private List<SubFolderChangeSet> GetChangeSetBySubFolderName(string filePath)  
     {  
       List<SubFolderChangeSet> listChangeset = new List<SubFolderChangeSet>();  
       try  
       {  
         var vsStore = teamProjectCollection.GetService<VersionControlServer>();  
 
         var histories =  
             vsStore.QueryHistory( 
                 filePath,  
                 VersionSpec.Latest, default(int), RecursionType.Full, null, null, null, Int32.MaxValue, true, false, true);  
         foreach (Changeset history in histories)  
         {  
           SubFolderChangeSet sbfChangeSet = new SubFolderChangeSet();  
           sbfChangeSet.ChangeSetNumber = history.ChangesetId;  
           sbfChangeSet.Owner = history.Owner;  
           sbfChangeSet.OwnerDisplayName = history.OwnerDisplayName;  
           sbfChangeSet.Comments = history.Comment;  
           listChangeset.Add(sbfChangeSet);  
           sbfChangeSet.listChange = new List<Change>();  
           sbfChangeSet.listChange.AddRange(history.Changes);  
           foreach (Change change in history.Changes)  
           {  
             sbfChangeSet.CreateDate = change.Item.CheckinDate;  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
       return listChangeset;  
     }  
     #endregion  
   }  
   #region Classes  
   public class SubFolderChangeSet  
   {  
     public int ChangeSetNumber { get; set; }  
     public string Owner { get; set; }  
     public string OwnerDisplayName { get; set; }  
     public string Comments { get; set; }  
     public DateTime CreateDate { get; set; }  
     public List<Change> listChange { get; set; }  
   }  
   public class FileNames  
   {  
     public int ChangeSetNumber { get; set; }  
     public string FileName { get; set; }  
     public string CommandArgument { get; set; }  
   }  
   #endregion  
 }  

Monday, November 2, 2015

row_number() in lambda experssion

Hi friends,

Today I am going to show how row_number() implement in lambda expression.

Suppose a list of customer say List<Customer>. Customer have CustomerId, LoginDate,....

If you want to know the latest login date of each customer.


var customerLoginList = customers.OrderByDescending(x => x.LoginDate).GroupBy(x => x.CustomerId).
                           Select(g => new { g, count = g.Count() }).
                           SelectMany(t => t.g.Select(b => b).
                           Zip(Enumerable.Range(1, t.count), (j, i) => new { j.CustomerId, j.LoginDate, rn = i }));


From the above code you will get list which contains customerid with row number. Now you just filter the list where rn = 1.

Sunday, June 14, 2015

Calculate date difference between two rows of the same table

Hi friends,

Today I am going to demonstrate calculate date difference between two rows of the same table.

Consider the below table.




The query for calculating date difference between 2nd row to 1st row, 3rd row to 2nd row and so on.

Calculate difference in days:

DECLARE @temp1 TABLE (
 StudentID INT
 ,NAME VARCHAR(50)
 ,RN INT
 ,createddate DATETIME
 )

INSERT INTO @temp1 (
  StudentID
 ,NAME
 ,RN
 ,createddate
 )
SELECT [StudentID]
 ,dbo.Student.NAME
 ,RN = ROW_NUMBER() OVER (
  PARTITION BY [StudentID] ORDER BY createddate
  )
 ,createddate
FROM dbo.Student

DECLARE @temp2 TABLE (
 ID INT
 ,StudentID INT
 ,olddate DATETIME
 ,newdate DATETIME
 ,[Difference_InDays] INT
 );

;WITH cte as(
SELECT ROW_NUMBER() OVER(ORDER BY c1.StudentID) AS ID ,c1.StudentID,
       olddate=CASE WHEN c1.createddate=c2.createddate THEN NULL ELSE C1.createddate END,
       newdate=CASE WHEN c1.createddate=c2.createddate THEN NULL ELSE C2.createddate END
FROM @temp1 c1
INNER JOIN @temp1 c2 ON c1.[StudentID] = c2.[StudentID]
 AND c2.RN = c1.RN + 1
 )
INSERT INTO @temp2 (
  ID
 ,StudentID
 ,olddate
 ,newdate
 ,[Difference_InDays]
 )
SELECT *
 ,DATEDIFF(DD, c.olddate, c.newdate) AS [Difference_InDays]
FROM cte c

SELECT *
FROM @temp2 t 

Result:




Calcualte difference in months:

DECLARE @temp1 TABLE (
 StudentID INT
 ,NAME VARCHAR(50)
 ,RN INT
 ,createddate DATETIME
 )

INSERT INTO @temp1 (
  StudentID
 ,NAME
 ,RN
 ,createddate
 )
SELECT [StudentID]
 ,dbo.Student.NAME
 ,RN = ROW_NUMBER() OVER (
  PARTITION BY [StudentID] ORDER BY createddate
  )
 ,createddate
FROM dbo.Student

DECLARE @temp2 TABLE (
 ID INT
 ,StudentID INT
 ,olddate DATETIME
 ,newdate DATETIME
 ,[Difference_InMonth] INT
 );

;WITH cte as(
SELECT ROW_NUMBER() OVER(ORDER BY c1.StudentID) AS ID ,c1.StudentID,
       olddate=CASE WHEN c1.createddate=c2.createddate THEN NULL ELSE C1.createddate END,
       newdate=CASE WHEN c1.createddate=c2.createddate THEN NULL ELSE C2.createddate END
FROM @temp1 c1
INNER JOIN @temp1 c2 ON c1.[StudentID] = c2.[StudentID]
 AND c2.RN = c1.RN + 1
 )
INSERT INTO @temp2 (
  ID
 ,StudentID
 ,olddate
 ,newdate
 ,[Difference_InMonth]
 )
SELECT *
 ,DATEDIFF(MM, c.olddate, c.newdate) AS [Difference_InMonth]
FROM cte c

SELECT *
FROM @temp2 t


Result:



Wednesday, February 25, 2015

Validation Group in MVC

Hi friends,

Today I am going to demonstrate how to implement validation group in MVC.

For this you have to download one validation group jquery and and one validation group dll
Suppose we have customer model, in which we have Name and Email property. We validate this two property on two different buttons.

Step 1 : Add McjDevelopment.Mvc3ValidationGroups.dll in your project.

Step 2 : Add jquery.validate.unobtrusive.validationgroups.js in your project.

Step 3 : Create Customer Model

 public class Customer
    {
        [Required]
        [ValidationGroup("Submit1")]
        public string Name { getset; }
 
        [Required]
        [ValidationGroup("Submit2")]
        public string Email { getset; }
    }

Step 4 : Update your view to use ‘jquery.validate.unobtrusive.validationgroups.js’ immediately after ‘jquery.validate.unobtrusive.js’ (or ‘jquery.validate.unobtrusive.min.js’)








Step 5 : Update your view to include where you want each groups Validation to appear
















and don't forget to add "data-val-valgroup-name" tag at you buttons.

Results : When you click Submit1 button














When you click on Submit2 button













McjDevelopment.Mvc3ValidationGroups.Release.0.3.0.0.zip