I have this WIQL, who's purpose is to find the user assigned to the work item.
var wiql = string.Format("SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State]" +
" FROM WorkItems" +
" WHERE ([System.TeamProject] = '{0}')" +
" AND ([System.WorkItemType] = 'Task' OR [System.WorkItemType] = 'Bug')" +
" ORDER BY [System.Id]", projectName);
I'm executing it as so...
Wiql wiql = new Wiql() { Query = wiqlQueryString };
using (var workItemTrackingHttpClient = new WorkItemTrackingHttpClient(VstsAccess.AccessUri, VstsAccess.AccessCredentials))
{
var workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;
if (workItemQueryResult != null && workItemQueryResult.WorkItemRelations.Any())
{
List<int> sourceIdList = new List<int>();
foreach (var item in workItemQueryResult.WorkItemRelations)
sourceIdList.Add(item.Target.Id);
int[] arr = sourceIdList.ToArray();
string[] fields = { "System.Id", "System.WorkItemType", "System.AssignedTo", "System.Title", "System.Description", "System.State", "System.IterationPath", "System.TeamProject", "System.ChangedDate", "System.ChangedBy", "System.CreatedDate" };
return workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result;
}
else
return new List<WorkItem>();
}
But the "AssignedTo" and "Description" fields are not showing up in the work items' dictionary field-set. Why is this so and how can I fix this?
The query results will only contain fields that are non-null, i.e. nobody is assigned to the work item, the field won't be in the Fields dictionary at all.
You need to implement a custom check for those fields and assign them to something according to your logic:
int[] arr = ids.ToArray();
string[] fields = new string[] {
"System.Id",
"System.Title",
"System.State",
"System.AssignedTo"
};
var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf);
List<WorkItemData> list = new List<WorkItemData>();
foreach (var workItem in workItems)
{
var wi = new WorkItemData(workItem.Id.Value);
wi.Title = workItem.Fields["System.Title"].ToString();
wi.State = workItem.Fields["System.State"].ToString();
wi.AssignedTo = workItem.Fields.ContainsKey("System.AssignedTo") ? workItem.Fields["System.AssignedTo"].ToString() : "";
list.Add(wi);
}
You could use the code below to query out workitems and it has "AssignedTo" and "Description" field values.
WorkItemStore workItemStore = teamProjectCollection.GetService<WorkItemStore>();
string queryString = string.Format("SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State]" +
" FROM WorkItems" +
" WHERE ([System.TeamProject] = '{0}')" +
" AND ([System.WorkItemType] = 'Task' OR [System.WorkItemType] = 'Bug')" +
" ORDER BY [System.Id]", "Mtt-Scrum"); ;
// Create and run the query.
Query query = new Query(workItemStore, queryString);
WorkItemCollection witCollection = query.RunQuery();
foreach (Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem in witCollection)
{
......
}
Related
I'm attempting to create a cascading drop down in which the first populates a list of Director level employees (directors have multiple managers and the managers have multiple employees) which would then populate the second dropdown through ajax. I'm trying to put together the logic that given a displayname will grab all direct reports and the direct reports of the direct reports. With the logic I've put together it will print everyone im looking for but only returns the reports to the original Director. I'm struggling to put everything together. The code isnt at all pretty and if there's an easier way to do this I'm open for suggestions.
There are three methods in which I'm attempting to populate the directReports list in the DirectReports method with all employees
public List<string> DirectReports(string name)
{
List<string> directReports = new List<string>();
var domain = new PrincipalContext(ContextType.Domain, "somedomain");
UserPrincipal user = new UserPrincipal(domain);
user.DisplayName = name;
PrincipalSearcher ps = new PrincipalSearcher();
ps.QueryFilter = user;
DirectorySearcher ds = ps.GetUnderlyingSearcher() as DirectorySearcher;
ds.SearchScope = SearchScope.Subtree;
ds.Filter = "(&(objectClass=user)(objectCategory=person)(displayName=" + name + "))";
ds.PropertiesToLoad.Add("DirectReports");
SearchResultCollection results = ds.FindAll();
foreach(SearchResult result in results)
{
if (hasDirectReports(result))
{
//directReports.AddRange(GetReportsFinal(GetDirectReportsList(result)));
directReports.AddRange(GetDirectReportsList(result));
directReports.Add(result.Properties["displayname"][0].ToString() + " (" + result.Properties["samaccountname"][0].ToString()+")");
}
else
{
directReports.Add(result.Properties["displayname"][0].ToString() + " (" + result.Properties["samaccountname"][0].ToString() + ")");
}
}
foreach(var item in directReports)
{
Debug.WriteLine(item);
}
return directReports;
}
public bool hasDirectReports(SearchResult result)
{
if(result.Properties["directreports"].Count >= 1)
{
return true;
}
else
{
return false;
}
}
public List<string> GetDirectReportsList(SearchResult result)
{
List<string> formattedDirectReportsList = new List<string>();
foreach (var thing in result.Properties["directreports"])
{
string employeeString = thing.ToString();
//employeeString = employeeString.Split(setp, StringSplitOptions.None)[0];
employeeString = employeeString.Replace("CN=", "");
employeeString = employeeString.TrimEnd(',');
employeeString = employeeString.Replace("\\, ", ", ");
//Debug.WriteLine(employeeString);
if (employeeString.Split(',')[2] == "OU=Users")
{
string fn = employeeString.Split(',')[1];
string ln = employeeString.Split(',')[0];
var domain = new PrincipalContext(ContextType.Domain, "somedomain");
UserPrincipal directreportname = new UserPrincipal(domain);
directreportname.Name = ln + "," + fn;
PrincipalSearcher prinsearcher = new PrincipalSearcher();
prinsearcher.QueryFilter = directreportname;
DirectorySearcher dirsearcher = prinsearcher.GetUnderlyingSearcher() as DirectorySearcher;
Principal reportResults = prinsearcher.FindOne();
formattedDirectReportsList.Add(reportResults.DisplayName + " (" + reportResults.SamAccountName + ")");
DirectReports(reportResults.DisplayName);
}
}
return formattedDirectReportsList;
}
After creating the leaguelist in the code below, how can I access the values in the list in order to populate another list?
I need to pass the values of the list to another list and send it to a view.
List<Notification> notificationlist = new List<Notification>();
notificationlist.Add(new Notification { date = leaguename = leaguevenue = teamwon = })
What i am trying to do is read the values from leaguelist and I need to access the data of that list in notificationlist to populate the values for date, leaguename, leaguevenue, etc.
List<string[]> leaguelist = new List<string[]>();
while (count != 0)
{
Int16 id = Convert.ToInt16(sportds.Tables[0].Rows[count-1]["sports_details_id"].ToString());
using (SqlDataAdapter leagueDetails = new SqlDataAdapter("select league_name, league_details_venue,league_details_date from leagues, league_details where sports_details_id1 in ('" + id+ "') or sports_details_id2 in ('" + id + "')", sqlConnection1))
{
DataSet leagues = new DataSet();
leagueDetails.Fill(leagues).ToString();
lname = leagues.Tables[0].Rows[0]["league_name"].ToString();
lvenue = leagues.Tables[0].Rows[0]["league_details_venue"].ToString();
ldate = leagues.Tables[0].Rows[0]["league_details_date"].ToString();
string[] fields = new string[3];
fields[0] = lname;
fields[1] = lvenue;
fields[2] = ldate;
leaguelist.Add(fields);
}
count = count - 1}
Please help me with this !!
Based on your comment, you can walk through the list and read the values in a foreach loop and add it to the notificationList:
List<Notification> notificationlist = new List<Notification>();
foreach (string[] fields in leagueList)
{
var lname = fields[0];
var lvenue = fields[1];
var ldate = fields[2];
Console.WriteLine($"League {lname} at {lvenue} on {ldate}");
notificationsList.Add(new Notification
{
date = ldate,
leaguename = lname,
leaguevenue = lvenue
};
}
You can also use LINQ, like this:
notificationsList.AddRange(
leagueList.Select(fields => new Notificationnew Notification
{
date = fields[2],
leaguename = fields[0],
leaguevenue = fields[1]
});
This might help, you can select a single element from your list and add it to your notification list. You could use a for loop to iterate through your list and do something like this.
var s = leaguelist[0];
notificationList.Add(new Notification
{
date = s[0],
leagename = s[1],
leaguevenue = s[2]
});
I need a way to retrieve a list of projects using C#.
Tried doing something like this:
DynamicJsonObject sub = restApi.GetSubscription("Projects");
//query the project collection
Request wRequest = new Request(sub["Projects"]);
QueryResult queryResult = restApi.Query(wRequest);
return queryResult.Results.Select(result => new Project()
{
Id = result["ObjectID"],
Name = result["Name"]
}).ToList();
unfortunately with no success.
Can anyone help please?
The code below should print workspaces and projects to which the user whose account is used to authenticate the code has access to.
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
wRequest.Limit = 1000;
QueryResult queryResult = restApi.Query(wRequest);
int allProjects = 0;
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine("Workspace: " + workspaceName);
Request projectsRequest = new Request(result["Projects"]);
projectsRequest.Fetch = new List<string>()
{
"Name"
};
projectsRequest.Limit = 10000; //project requests are made per workspace
QueryResult queryProjectResult = restApi.Query(projectsRequest);
int projectsPerWorkspace = 0;
foreach (var p in queryProjectResult.Results)
{
allProjects++;
projectsPerWorkspace++;
Console.WriteLine(projectsPerWorkspace + " Project: " + p["Name"] + " State: " + p["State"]);
}
}
Console.WriteLine("Returned " + allProjects + " projects in the subscription");
I have LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[System.String] EnumerateFiles(System.String)' method, and this method cannot be translated into a store expression.` error. I need to get links to images from folders, I get ID from the database.
// Collect flat items and add in List<>
var nearestItems = from item in _db.Flats
select new listItem()
{
Price = item.Price,
Address = item.Address,
Bathroom = item.Bathroom,
BesprovodnoiInternet = item.BesprovodnoiInternet,
City = item.City,
FloorAll = item.FloorAll,
FloorCurrent = item.FloorCurrent,
Funiture = item.Funiture,
Kondicioner = item.Kondicioner,
PartyFree = item.PartyFree,
RoomQuantity = item.RoomQuantity,
TipArendy = item.TipArendy,
TV = item.TV,
ImagesString = Directory.EnumerateFiles(Server.MapPath("~/Content/Prop/" + item.FlatID + "/"))
.Select(fn => "~/Content/Prop/" + item.FlatID + "/" + Path.GetFileName(fn)).ToList()
};
Are there fix for this or alternate code?
Your LINQ query should be translated to SQL query to run on SQL Server. It is obvious that the engine cant translate Directory.EnumerateFiles to SQL query.
You can add new property FlatId to your listItem and try this:
// Collect flat items and add in List<>
var nearestItems = (from item in _db.Flats
select new listItem()
{
Price = item.Price,
Address = item.Address,
Bathroom = item.Bathroom,
BesprovodnoiInternet = item.BesprovodnoiInternet,
City = item.City,
FloorAll = item.FloorAll,
FloorCurrent = item.FloorCurrent,
Funiture = item.Funiture,
Kondicioner = item.Kondicioner,
PartyFree = item.PartyFree,
RoomQuantity = item.RoomQuantity,
TipArendy = item.TipArendy,
TV = item.TV,
FlatId = item.FlatID,
}).ToList();
foreach(var item in nearestItems)
{
item.ImagesString = Directory.EnumerateFiles(Server.MapPath("~/Content/Prop/" + item.FlatId + "/"))
.Select(fn => "~/Content/Prop/" + item.FlatId + "/" + Path.GetFileName(fn)).ToList();
}
EntityFramework will build query based on your LINQ which will execute in the database. So there are some constarints while using LINQ to Entity. How must EF convert this code to the database query? Directory.EnumerateFiles
There is no way.
So, you must select only required properties and then change them as you wish in .net:
var nearestItems = (from item in _db.Flats
select new listItem()
{
Price = item.Price,
Address = item.Address,
Bathroom = item.Bathroom,
BesprovodnoiInternet = item.BesprovodnoiInternet,
City = item.City,
FloorAll = item.FloorAll,
FloorCurrent = item.FloorCurrent,
Funiture = item.Funiture,
Kondicioner = item.Kondicioner,
PartyFree = item.PartyFree,
RoomQuantity = item.RoomQuantity,
TipArendy = item.TipArendy,
TV = item.TV,
FlatId = item.FlatID,
}).ToList();
And in you class change the get accessor of your property ImagesString:
public List<string> ImagesString
{
get
{
return Directory.EnumerateFiles(Server.MapPath("~/Content/Prop/" + FlatID + "/"))
.Select(fn => "~/Content/Prop/" + FlatID + "/" + Path.GetFileName(fn))
.ToList();
}
}
I have a Dynamic Linq query, through which am trying to access grouped data, grouped on two columns, and 1 columns on which aggregation function is used.
var gFieldList = new List<string>() { "Supplier", "Country" };
var sFieldList = new List<string>() { "Sales"};
var gField = string.Join(", ", gFieldList.Select(x => "it[\"" + x + "\"] as " + x));
var sField = string.Join(", ", sFieldList.Select(y => "Sum(Convert.ToDouble(it[\""+y+"\"])) as "+y));
var dQueryResult = dataTable
.AsEnumerable()
.AsQueryable()
.GroupBy("new("+gField+")", "it")
.Select("new("+sField+",it.Key as Key, it as Data)");
To access the data from the dQueryResult am using the following code.
var groupedData = (from dynamic dat in dQueryResult select dat).ToList();
foreach (var group in groupedData)
{
var key = group.Key;
var sum = group.Sales;
MessageBox.Show("Supplier : " + key.Supplier + "Country : " + key.Country + " SALES : "+Sale.ToString());
}
The problem is
var gFieldList = new List<string>() { "Supplier", "Country" };
var sFieldList = new List<string>() { "Sales"};
keeps on changing. They both need to be dynamic, which will not allow me to access the values dynamically from the above mentioned code since for now it's been coded as key.Supplier, key.Country and group.Sales .
How can I make the iteration of the result of the dynamic query as dynamic?
I tried using
var groupedData = (from dynamic dat in dQueryResult select dat).ToList();
foreach (var group in groupedData)
{
var key = group.Key;
var sum = group.Sales;
foreach (var v in gFieldList)
{
MessageBox.Show(key.v);
}
}
But it's throwing an exception stating 'DynamicClass1' does not contain a definition for 'v'
you can use reflection like this
foreach (var v in gFieldList)
{
MessageBox.Show(key.GetType().GetProperty(v).GetValue(key,null));
...