Monday, October 11, 2021
Custom Observable in Angular
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
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
Step 4 : create-user.component.html
Step 5 : Build active-user.component.ts
Step 6 : active-user.component.html
Step 7 : inactive-user.component.ts
Step 7 : inactive-user.component.html
Step 8 : account.service.ts
Step 9 : app-component.ts
Step 10 : app-component.html
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)
Step 2 : Generate components
ng g c student
ng g c student/student-list
Step 3 : app.component.ts (Parent component)
Step 4 : app.component.html
Step 5 : Add @Input decorator in student-list.component.ts
Step 6 : student-list.component.html
Step 7 : Add @Output decorator in student.component.ts
Step 8 : student.component.ts
Tuesday, March 27, 2018
Calling cross domain asp.net web API using jquery
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#
- Get history(list of all changeset)
- Download and Compare files
Take reference of below dll's.
<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
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
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
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










