Multiple Excel upload error in ExcelPackage EPPlus - asp.net-mvc

public ActionResult ExcelFile(IEnumerable < HttpPostedFileBase > excelFile) {
try {
if (excelFile != null) {
foreach(var singleExcel in excelFile) {
string path = "~/ExcelFolder/";
singleExcel.SaveAs(Server.MapPath(path + singleExcel.FileName));
using(FileStream fs = new FileStream(Server.MapPath(path + singleExcel.FileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using(ExcelPackage package = new ExcelPackage(fs)) {
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int startRowNumber = sheet.Dimension.Start.Row;
int endRowNumber = sheet.Dimension.End.Row;
int startColumnNumber = sheet.Dimension.Start.Column;
int endColumnNumber = sheet.Dimension.End.Column;
if (endColumnNumber > 26) {
for (int currentColumnNumber = endColumnNumber; startColumnNumber < currentColumnNumber; currentColumnNumber--) {
var cellValue = sheet.Cells[startRowNumber, currentColumnNumber].Value ? .ToString();
if (!string.IsNullOrWhiteSpace(cellValue)) {
if (cellValue == "延人公里小計") {
sheet.DeleteColumn(currentColumnNumber);
sheet.Cells[1, currentColumnNumber].Value = "小計";
//return fsr;
package.SaveAs(
new FileInfo(# "C:\Users\leon0944\Desktop\123\" + singleExcel.FileName));
break;
}
}
}
}
}
}
}
Hello,when I upload many Excel to the file then read every single Excel to do someting.then i got error in ExcelPackage package = new ExcelPackage(fs) this row
error message :System.Runtime.InteropServices.COMException: HRESULT:
0x8003001D (STG_E_WRITEFAULT)
sometime is working normally sometime I got error,Please tell me How Can I fix this. The problem existed for several days.

Related

Download Excel File in .net core web api

I'm trying to create & download the excel file in asp .net core web api. Whenever I hit the service from postman or Advanced Rest Client, Instead of downloading the file I'm getting the JSON data of the file content as response. My code is like below :
[HttpGet]
[Route("GetLogsPdfORExcel")]
public IActionResult GetLogsPdfORExcel()
{
var result = _dataContext.GetLogsPdfORExcel();
if (result != null)
{
this.ExportExcel(result);
}
return Ok(result);
}
public FileStreamResult ExportExcel(DataTable dt)
{
string excelName = "LogsRecord";
ExcelPackage package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
int currentRowNo = 5;
int totalRows = dt.Rows.Count;
int k = 0;
foreach (DataColumn column in dt.Columns)
{
worksheet.Cells[currentRowNo, k + 1].Value = column.ColumnName;
k++;
}
currentRowNo++;
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[currentRowNo, j + 1].Value = Convert.ToString(dt.Rows[i][j]);
}
currentRowNo++;
}
int columnCount = dt.Columns.Count;
for (int i = 1; i <= columnCount; i++)
worksheet.Column(i).AutoFit();
worksheet.Row(1).Height = 55;
worksheet.SelectedRange["A1"].Style.Font.Size = 14;
worksheet.Row(5).Style.Font.Bold = true;
using (var memoryStream = new MemoryStream())
{
memoryStream.Position = 0;
var contentType = "application/octet-stream";
var fileName = "fileName.xlsx";
return File(memoryStream, contentType, fileName);
}
}
Here whenever I hit my service, I need directly my file needs to get download.
Return the file stream result and not the datatable.
[HttpGet]
[Route("GetLogsPdfORExcel")]
public IActionResult GetLogsPdfORExcel() {
var result = _dataContext.GetLogsPdfORExcel();
if (result != null) {
return this.ExportExcel(result);
}
return BadRequest(); //Or some other relevant response.
}
Also no need to dispose of the stream since the FileStreamResult will dispose of it when done
//...
var memoryStream = new MemoryStream();
using (var package = new ExcelPackage(memoryStream)) { //<<< pass stream
//...populate package
package.Save();
}
memoryStream.Position = 0;
var contentType = "application/octet-stream";
var fileName = "fileName.xlsx";
return File(memoryStream, contentType, fileName);

MVC Import .csv

Controller
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelFile)
{
if (excelFile == null || excelFile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file<br>";
return View("Index");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx") || excelFile.FileName.EndsWith("csv"))
{
string fileName = Path.GetFileName(excelFile.FileName);
string path = Path.Combine(Server.MapPath("~/Content"), fileName);
//string path = Server.MapPath("~/Content/" + excelFile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelFile.SaveAs(path);
//Read data from excel file
MExcel.Application application = new MExcel.Application();
MExcel.Workbook workbook = application.Workbooks.Open(path);
MExcel.Worksheet worksheet = workbook.ActiveSheet;
MExcel.Range range = worksheet.UsedRange;
List<PH> publicholidays = new List<PH>();
for (int row = 0; row <= range.Rows.Count; row++)
{
PH ph = new PH();
ph.Subject = ((MExcel.Range)range.Cells[row, 1]).Text;
ph.StartDate = ((MExcel.Range)range.Cells[row, 2]).Text;
ph.EndDate = ((MExcel.Range)range.Cells[row, 4]).Text;
publicholidays.Add(ph);
}
ViewBag.Publicholidays = publicholidays;
return View("Success");
}
else
{
ViewBag.Error = "Incorrect file type<br>";
return View("Index");
}
}
}
I want to import a .csv file but why doesn't it work while when i try to import a normal .xls files, it works? Is there something wrong with my code or is it that I can't import .csv files this way?

Stream file from ftp in localhost working in azure no

Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}
Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.

BlackBerry java.io.IOException: null

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

Moving a work item between projects in TFS

Is it possible to move a work item from one project to another inside TFS? I’ve seen a copy option, but no move. Also, if it is possible, what’s the implication for any of the WI history?
I found this article from 2008 that seem to say it's not, but I wondered if there'd been any progress since then.
It isn't possible to move, just copy. The way we do it, is we do the copy, link the original, then close the original as obsolete. You could also create the copy and TF Destroy the original, but you will lose all history.
If you wanted to, you could get very fancy and create your own "move" utility that copies the workitem and all of the history, then closes out (or destroys) the old one. Seems like overkill for something that you probably shouldn't need to do all that often.
Lars Wilhelmsen wrote a WorkItemMigrator -> http://larsw.codeplex.com/SourceControl/list/changesets
Good starting point for a utility you can customize for your needs. We used it to split off a 100 or so work items to a new project. Here's the program I ended up with. Modify the query to subset the items to migrate.
namespace WorkItemMigrator
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
class Program
{
#region Members
private static readonly Dictionary<Uri, TfsTeamProjectCollection> Collections = new Dictionary<Uri, TfsTeamProjectCollection>();
private static readonly Uri SourceCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
private static readonly Uri TargetCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
private const String Areas = "ProjectModelHierarchy";
private const string Iterations = "ProjectLifecycle";
private const string TargetProjectName = "TargetProject";
private const string MicrosoftVstsCommonStackRankFieldName = "Microsoft.VSTS.Common.StackRank";
private const string MicrosoftVstsCommonPriority = "Microsoft.VSTS.Common.Priority";
private const string TargetWorkItemType = "User Story";
private const string Wiql = "SELECT [System.Id], [System.State], [System.Title], [System.AssignedTo], [System.WorkItemType], [Microsoft.VSTS.Common.Priority], " +
"[System.IterationPath], [System.AreaPath], [System.History], [System.Description] " +
"FROM WorkItems WHERE [System.TeamProject] = 'SourceProject' AND " +
"[System.State] = 'Active' " +
"ORDER BY [System.Id]";
private static WorkItemTypeCollection WorkItemTypes;
private static Dictionary<int, int> WorkItemIdMap = new Dictionary<int, int>();
#endregion
static void Main()
{
var createAreasAndIterations = GetRunMode();
var sourceWorkItemStore = GetSourceWorkItemStore();
var sourceWorkItems = sourceWorkItemStore.Query(Wiql);
var targetWorkItemStore = GetTargetWorkItemStore();
var targetProject = targetWorkItemStore.Projects[TargetProjectName];
WorkItemTypes = targetProject.WorkItemTypes;
foreach (WorkItem sourceWorkItem in sourceWorkItems)
{
if (createAreasAndIterations)
{
Console.WriteLine();
EnsureThatStructureExists(TargetProjectName, Areas, sourceWorkItem.AreaPath.Substring(sourceWorkItem.AreaPath.IndexOf("\\") + 1));
EnsureThatStructureExists(TargetProjectName, Iterations, sourceWorkItem.IterationPath.Substring(sourceWorkItem.IterationPath.IndexOf("\\") + 1));
}
else
{
MigrateWorkItem(sourceWorkItem);
}
}
if (!createAreasAndIterations)
{
var query = from WorkItem wi in sourceWorkItems where wi.Links.Count > 0 select wi;
foreach (WorkItem sourceWorkItem in query)
{
LinkRelatedItems(targetWorkItemStore, sourceWorkItem);
}
}
TextWriter tw = File.CreateText(#"C:\temp\TFS_MigratedItems.csv");
tw.WriteLine("SourceId,TargetId");
foreach (var entry in WorkItemIdMap)
{
tw.WriteLine(entry.Key + "," + entry.Value);
}
tw.Close();
Console.WriteLine();
Console.WriteLine("Done! Have a nice day.");
Console.ReadLine();
}
private static bool GetRunMode()
{
bool createAreasAndIterations;
while (true)
{
Console.Write("Create [A]reas/Iterations or [M]igrate (Ctrl-C to quit)?: ");
var command = Console.ReadLine().ToUpper().Trim();
if (command == "A")
{
createAreasAndIterations = true;
break;
}
if (command == "M")
{
createAreasAndIterations = false;
break;
}
Console.WriteLine("Unknown command " + command + " - try again.");
}
return createAreasAndIterations;
}
private static void MigrateWorkItem(WorkItem sourceWorkItem)
{
var targetWIT = WorkItemTypes[sourceWorkItem.Type.Name];
var newWorkItem = targetWIT.NewWorkItem();
//var newWorkItem = targetWorkItemType.NewWorkItem();
// Description (Task) / Steps to reproduce (Bug)
if (sourceWorkItem.Type.Name != "Bug")
{
newWorkItem.Description = sourceWorkItem.Description;
}
else
{
newWorkItem.Fields["Microsoft.VSTS.TCM.ReproSteps"].Value = sourceWorkItem.Description;
}
// History
newWorkItem.History = sourceWorkItem.History;
// Title
newWorkItem.Title = sourceWorkItem.Title;
// Assigned To
newWorkItem.Fields[CoreField.AssignedTo].Value = sourceWorkItem.Fields[CoreField.AssignedTo].Value;
// Stack Rank - Priority
newWorkItem.Fields[MicrosoftVstsCommonPriority].Value = sourceWorkItem.Fields[MicrosoftVstsCommonPriority].Value;
// Area Path
newWorkItem.AreaPath = FormatPath(TargetProjectName, sourceWorkItem.AreaPath);
// Iteration Path
newWorkItem.IterationPath = FormatPath(TargetProjectName, sourceWorkItem.IterationPath);
// Activity
if (sourceWorkItem.Type.Name == "Task")
{
newWorkItem.Fields["Microsoft.VSTS.Common.Activity"].Value = sourceWorkItem.Fields["Microsoft.VSTS.Common.Discipline"].Value;
}
// State
//newWorkItem.State = sourceWorkItem.State;
// Reason
//newWorkItem.Reason = sourceWorkItem.Reason;
// build a usable rendition of prior revision history
RevisionCollection revisions = sourceWorkItem.Revisions;
var query = from Revision r in revisions orderby r.Fields["Changed Date"].Value descending select r;
StringBuilder sb = new StringBuilder(String.Format("Migrated from work item {0}<BR />\n", sourceWorkItem.Id));
foreach (Revision revision in query)
{
String history = (String)revision.Fields["History"].Value;
if (!String.IsNullOrEmpty(history))
{
foreach (Field f in revision.Fields)
{
if (!Object.Equals(f.Value, f.OriginalValue))
{
if (f.Name == "History")
{
string notation = string.Empty;
if (revision.Fields["State"].OriginalValue != revision.Fields["State"].Value)
{
notation = String.Format("({0} to {1})", revision.Fields["State"].OriginalValue, revision.Fields["State"].Value);
}
//Console.WriteLine("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation);
sb.Append(String.Format("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}<BR />\n", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation));
}
}
}
//Console.WriteLine("Revision {0}: ", revision.Fields["Rev"].Value);
//Console.WriteLine(" ChangedDate: " + revision.Fields["ChangedDate"].Value);
//Console.WriteLine(" History: " + sb.ToString());
}
}
newWorkItem.History = sb.ToString();
// Attachments
for (var i = 0; i < sourceWorkItem.AttachedFileCount; i++)
{
CopyAttachment(sourceWorkItem.Attachments[i], newWorkItem);
}
// Validate before save
if (!newWorkItem.IsValid())
{
var reasons = newWorkItem.Validate();
Console.WriteLine(string.Format("Could not validate new work item (old id: {0}).", sourceWorkItem.Id));
foreach (Field reason in reasons)
{
Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
}
}
else
{
Console.Write("[" + sourceWorkItem.Id + "] " + newWorkItem.Title);
try
{
newWorkItem.Save(SaveFlags.None);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(string.Format(" [saved: {0}]", newWorkItem.Id));
WorkItemIdMap.Add(sourceWorkItem.Id, newWorkItem.Id);
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
private static void CopyAttachment(Attachment attachment, WorkItem newWorkItem)
{
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
client.DownloadFile(attachment.Uri, attachment.Name);
var newAttachment = new Attachment(attachment.Name, attachment.Comment);
newWorkItem.Attachments.Add(newAttachment);
}
}
private static void LinkRelatedItems(WorkItemStore targetWorkItemStore, WorkItem sourceWorkItem)
{
int newId = WorkItemIdMap[sourceWorkItem.Id];
WorkItem targetItem = targetWorkItemStore.GetWorkItem(newId);
foreach (Link l in sourceWorkItem.Links)
{
if (l is RelatedLink)
{
RelatedLink sl = l as RelatedLink;
switch (sl.ArtifactLinkType.Name)
{
case "Related Workitem":
{
if (WorkItemIdMap.ContainsKey(sl.RelatedWorkItemId))
{
int RelatedWorkItemId = WorkItemIdMap[sl.RelatedWorkItemId];
RelatedLink rl = new RelatedLink(sl.LinkTypeEnd, RelatedWorkItemId);
// !!!!
// this does not work - need to check the existing links to see if one exists already for the linked workitem.
// using contains expects the same object and that's not what I'm doing here!!!!!!
//if (!targetItem.Links.Contains(rl))
// !!!!
var query = from RelatedLink qrl in targetItem.Links where qrl.RelatedWorkItemId == RelatedWorkItemId select qrl;
if (query.Count() == 0)
{
targetItem.Links.Add(rl); ;
// Validate before save
if (!targetItem.IsValid())
{
var reasons = targetItem.Validate();
Console.WriteLine(string.Format("Could not validate work item (old id: {0}) related link id {1}.", sourceWorkItem.Id, sl.RelatedWorkItemId));
foreach (Field reason in reasons)
{
Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
}
}
else
{
try
{
targetItem.Save(SaveFlags.None);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(string.Format(" [Updated: {0}]", targetItem.Id));
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
break;
}
default:
{ break; }
}
}
}
}
private static void EnsureThatStructureExists(string projectName, string structureType, string structurePath)
{
var parts = structurePath.Split('\\');
var css = GetCommonStructureService();
var projectInfo = css.GetProjectFromName(projectName);
var parentNodeUri = GetCssStructure(GetCommonStructureService(), projectInfo.Uri, structureType).Uri;
var currentPath = FormatPath(projectName, structureType == Areas ? "Area" : "Iteration");
foreach (var part in parts)
{
currentPath = FormatPath(currentPath, part);
Console.Write(currentPath);
try
{
var currentNode = css.GetNodeFromPath(currentPath);
parentNodeUri = currentNode.Uri;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine(" [found]");
}
catch
{
parentNodeUri = css.CreateNode(part, parentNodeUri);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" [created]");
}
Console.ResetColor();
}
}
private static string FormatPath(string currentPath, string part)
{
part = part.Substring(part.IndexOf("\\") + 1);
currentPath = string.Format(#"{0}\{1}", currentPath, part);
return currentPath;
}
private static TfsTeamProjectCollection GetProjectCollection(Uri uri)
{
TfsTeamProjectCollection collection;
if (!Collections.TryGetValue(uri, out collection))
{
collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
collection.Connect(ConnectOptions.IncludeServices);
collection.Authenticate();
Collections.Add(uri, collection);
}
return Collections[uri];
}
private static WorkItemStore GetSourceWorkItemStore()
{
var collection = GetProjectCollection(SourceCollectionUri);
return collection.GetService<WorkItemStore>();
}
private static WorkItemStore GetTargetWorkItemStore()
{
var collection = GetProjectCollection(TargetCollectionUri);
return collection.GetService<WorkItemStore>();
}
public static NodeInfo GetCssStructure(ICommonStructureService css, String projectUri, String structureType)
{
return css.ListStructures(projectUri).FirstOrDefault(node => node.StructureType == structureType);
}
private static ICommonStructureService GetCommonStructureService()
{
var collection = GetProjectCollection(TargetCollectionUri);
return collection.GetService<ICommonStructureService>();
}
}
}

Resources