TFS 2013 work item change event listener is not working - plugins

I'm trying to listen workitem changes in TFS 2013. I created a c# project and build successfully this code below. Then dll located in tfs server:
I restart machine and I checkin a class in tfs for test with a work item. When I control tfs server there is no any Log folder created in C disk like code. TfsEventHandler project builded with .net framework 4.5
My queston is, why plugin is not working?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using System.Diagnostics;
using System.IO;
namespace TfsEventHandler
{
public class WorkItemChangedEventHandler : ISubscriber
{
public string Name
{
get
{
return "WorkItemChangedEventHandler";
}
}
public SubscriberPriority Priority
{
get
{
return SubscriberPriority.Normal;
}
}
public EventNotificationStatus ProcessEvent(
TeamFoundationRequestContext requestContext,
NotificationType notificationType,
object notificationEventArgs,
out int statusCode,
out string statusMessage,
out Microsoft.TeamFoundation.Common.ExceptionPropertyCollection properties)
{
statusCode = 0;
properties = null;
statusMessage = String.Empty;
WriteLog("WorkItemChangedEventHandler1");
try
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
WorkItemChangedEvent ev = notificationEventArgs as WorkItemChangedEvent;
int workItemId = Convert.ToInt32(ev.CoreFields.IntegerFields[0].NewValue);
WriteLog("WorkItemChangedEventHandler WorkItem " + ev.WorkItemTitle + " - Id " + workItemId.ToString() + " was modified");
EventLog.WriteEntry("WorkItemChangedEventHandler", "WorkItem " + ev.WorkItemTitle + " - Id " + workItemId.ToString() + " was modified");
}
}
catch (Exception)
{
}
return EventNotificationStatus.ActionPermitted;
}
public Type[] SubscribedTypes()
{
return new Type[] { typeof(WorkItemChangedEvent) };
}
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
}
}

Related

Why does Post request to OpenAI in Unity result in error 400?

I am trying to use GPT3 in a game I am making but I can't seem to be able to call the OpenAI API correctly. I got most of this from the Unity docs.
Here is the code I am using:
public class gpt3_complete : MonoBehaviour
{
public string model;
public string prompt;
public int len;
public string temp;
public string api_key = "<key>";
void Start()
{
StartCoroutine(Upload());
}
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("model", model);
form.AddField("prompt", prompt);
form.AddField("max_tokens", len);
form.AddField("temperature", temp);
//form.headers.Add("Authorization", "Bearer "+api_key);
using (UnityWebRequest www = UnityWebRequest.Post("https://api.openai.com/v1/completions", form))
{
www.SetRequestHeader("Authorization", "Bearer " + api_key);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.result);
Debug.Log("Form upload complete!");
}
}
}
}
This always returns: 400 Bad Request.
The GPT3 docs can be found here: https://beta.openai.com/docs/api-reference/completions/create
Any idea why this is?
This is my first time making any web requests in unity so I'm probably missing something obvious.
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
public class OpenAIRequest : MonoBehaviour
{
public string apiKey = "YOUR_API_KEY_HERE";
public string prompt = "Once upon a time, in a land far far away, there lived a brave knight";
public string model = "text-davinci-002";
public int maxTokens = 100;
void Start()
{
StartCoroutine(GetOpenAIResponse());
}
IEnumerator GetOpenAIResponse()
{
string url = "https://api.openai.com/v1/engines/" + model + "/completions";
string requestData = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}";
UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(requestData);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + apiKey);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.Log(request.error);
}
else
{
string response = request.downloadHandler.text;
Debug.Log(response);
}
}
}
result

POST requests to Flask from Unity result in `null` values

After getting this demo server working I am able return GET requests from it to Unity, but when I would try to send data from Unity to the local server using POST requests it would only show null values added into the server. This is the code I was using in Unity:
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("charge","+4/3");
form.AddField("name", "doubletop");
using (UnityWebRequest www = UnityWebRequest.Post("http://localhost:5000/quarks/", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}
I would get "Form upload complete!" in the console, and GET requests would work, but those null values kept coming.
I modified my Upload() method to the PostRequest() in this example, and now it works!
Here's the full code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class HTTP : MonoBehaviour
{
void Start()
{
// A correct website page.
StartCoroutine(GetRequest("localhost:5000/quarks"));
PostData();
StartCoroutine(GetRequest("localhost:5000/quarks"));
// A non-existing page.
//StartCoroutine(GetRequest("https://error.html"));
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
[Serializable]
public class Quark
{
public string name;
public string charge;
}
public void PostData()
{
Quark gamer = new Quark();
gamer.name = "doublebottom";
gamer.charge = "4/3";
string json = JsonUtility.ToJson(gamer);
StartCoroutine(PostRequest("http://localhost:5000/quarks", json));
}
IEnumerator PostRequest(string url, string json)
{
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");
//Send the request then wait here until it returns
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
}

Maximum Report Processing has been reached for crystal report

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Xml;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.ReportSource;
using CrystalDecisions.Reporting;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;
public partial class Schools : System.Web.UI.Page
{
ReportDocument crystalReport = new ReportDocument();
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string query = "select * from School Where Designation = 'Public' Order by School ASC";
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
SchReport.ReportSource = crystalReport;
Session["ReportDocument"] = crystalReport;
}
catch (LogOnException ex)
{
//Throws an exception if an error is encountered on retrieval
}
}
else
{
string query = "select * from School Where Designation = " + "'" + drpSchoolDesignation.SelectedValue + "'" + " Order by School ASC";
// ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
TextObject to = (TextObject)crystalReport.ReportDefinition.Sections["Section2"].ReportObjects["Text3"];
to.Text = drpSchoolDesignation.SelectedValue.ToUpper() + " SCHOOLS";
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
SchReport.FindControl("Text3");
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
SchReport.ReportSource = doc;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void OpenNewWindow(string url, string windowName, string windowParams)
{
if (url == null)
throw new ArgumentNullException("url");
if (windowName == null)
windowName = "";
if (windowParams == null)
windowParams = "";
string scriptCode =
string.Format(
"<script>window.open('{0}','{1}','{2}');</script>",
url, windowName, windowParams);
//write the script out to HTTP Response stream
Response.Write(scriptCode);
}
private MPrimary GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["DBConnectionString1"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (MPrimary dsCustomers = new MPrimary())
{
sda.Fill(dsCustomers, "School");
return dsCustomers;
}
}
}
}
protected void drpSchoolDesignation_SelectedIndexChanged(object sender, EventArgs e)
{
drpDisplay.SelectedIndex = 0;
drpSort.SelectedIndex = 0;
string query = "select * from School Where Designation = " + "'" + drpSchoolDesignation.SelectedValue + "'" + " Order by School ASC";
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
TextObject to = (TextObject)crystalReport.ReportDefinition.Sections["Section2"].ReportObjects["Text3"];
to.Text = drpSchoolDesignation.SelectedValue.ToUpper() + " SCHOOLS";
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
Session["ReportDocument"] = crystalReport;
SchReport.ReportSource = crystalReport;
}
protected void CrystalReportViewer1_Unload(object sender, EventArgs e)
{
crystalReport.Close();
crystalReport.Dispose();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Select data from DB
//Action to be added later
}
}
This code is supposed to retrieve and display info using crystal reports.
It seems my object is not been properly disposed. Modifying this code disables the user from ever getting to page 3 of the document. Any help would be appreciated. Thanks guys in advance.

Program crashes when exe is copied to different computer

I have written a program in c# on my Windows 7 computer with .NET 4.0 using Sharp Develop 4.2.
I then changed it to a release within Sharp Develop, built it, and copied the .exe in the bin\Release folder to another Windows 7 computer with .NET 4.0. It crashes immediately without loading the initial form and gives no specific error. My MainForm method is like this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Drawing.Printing;
using System.Diagnostics;
using System.Text;
namespace BiasTracker1._
{
public partial class MainForm : Form
{
//Here are my initial variables
public static SqlConnectionStringBuilder sqlBldr = new SqlConnectionStringBuilder();
public static DataSet ds = new DataSet();
public static DataTable DisplayTable = ds.Tables.Add("DisplayTable");
SqlDataAdapter RawDataDA;
SqlCommandBuilder RawSampleSCB;
public static DataTable InstrumentDetail = ds.Tables.Add("InstrumentDetail");
public static string DatabaseOwner;
System.Windows.Forms.DataVisualization.Charting.Chart CurrentChart;
public static DataTable ImportDataTable = new DataTable();
public static string NewTransfer;
public static bool ValidatePerCell = true;
public static Image chart1Image;
public static string Title;
public static string NIRLabString;
bool ChangesNotDisplayed = false;
Point PreviousChartLocation;
List<System.Windows.Forms.DataVisualization.Charting.DataPoint> SelectedPoints = new List<System.Windows.Forms.DataVisualization.Charting.DataPoint>();
List<DataRow> SelectedRows = new List<DataRow>();
static double EPS = 2.22045e-016;
double FPMIN = 2.22507e-308 / EPS;
public static CustomPrintDoc pd = new CustomPrintDoc();
int NumOfParametersInReport = 0;
public static SqlConnectionStringBuilder SimPlusConn;
public static string SimPlusProductGUID;
public static string SimPlusSiteCode;
public double[] cof = new double[] {-1.3026537197817904,0.64196979235649026,0.019476473204185836,-0.009561514786808631,-0.000946595344482036,0.000366839497852761,0.000042523324806907,-0.000020278578112534,-0.000001624290004647,0.00000130365583558,0.000000015626441722,-0.000000085238095915,0.000000006529054439,0.000000005059343495,-0.000000000991364156,-0.000000000227365122,0.000000000096467911,0.000000000002394038,-0.000000000006886027,0.000000000000894487,0.000000000000313092,-0.000000000000112708,0.000000000000000381,0.000000000000007106,-0.000000000000001523,-0.000000000000000094,0.000000000000000121,-0.000000000000000028};
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
public MainForm()
{
try
{
InitializeComponent();
}
catch(Exception ex)
{
MessageBox.Show("Failed in Initialization.\n" + ex.ToString());
}
//Test SQL Connection
FileStream ConnectionStream;
try
{
ConnectionStream = new FileStream(#"C:\BiasTracker\settings.ini",FileMode.OpenOrCreate);
}
catch(DirectoryNotFoundException ex)
{
MessageBox.Show("Not able to find ini... Creating one.");
Directory.CreateDirectory(#"C:\BiasTracker");
ConnectionStream = new FileStream(#"C:\BiasTracker\settings.ini",FileMode.OpenOrCreate);
}
try
{
StreamReader ConnectionRdr = new StreamReader(ConnectionStream);
string line = null;
if((line = ConnectionRdr.ReadLine()) != null)
{
sqlBldr.DataSource = line;
sqlBldr.Password = ConnectionRdr.ReadLine();
sqlBldr.UserID = ConnectionRdr.ReadLine();
sqlBldr.InitialCatalog = ConnectionRdr.ReadLine();
}
else
{
sqlBldr.DataSource = ".\\SQLEXPRESS";
sqlBldr.Password = "password";
sqlBldr.UserID = "sa";
sqlBldr.InitialCatalog = "BiasMaster";
StreamWriter ConnectionWtr = new StreamWriter(ConnectionStream);
ConnectionWtr.WriteLine(".\\SQLEXPRESS");
ConnectionWtr.WriteLine("password");
ConnectionWtr.WriteLine("sa");
ConnectionWtr.WriteLine("BiasMaster");
ConnectionWtr.WriteLine("applications\\SQLEXPRESS");
ConnectionWtr.WriteLine("password");
ConnectionWtr.WriteLine("sa");
ConnectionWtr.WriteLine("BiasMaster");
ConnectionWtr.Dispose();
}
ConnectionStream.Close();
ConnectionStream.Dispose();
ConnectionRdr.Dispose();
}
catch(Exception ex)
{
MessageBox.Show("Not Able to read connection string\n" + ex.ToString());
}
System.Data.SqlClient.SqlConnection tmpConn;
tmpConn = new SqlConnection(sqlBldr.ConnectionString);
try //Test the connection and existence of the database
{
tmpConn.Open();
tmpConn.Close();
}
catch
{
MessageBox.Show("Database Connection not Found.");
tmpConn.Close();
}
SqlDataAdapter SettingsDA = new SqlDataAdapter("SELECT * FROM Settings WHERE SettingDesc = 'Owner'",sqlBldr.ConnectionString);
DataTable SettingsTable = new DataTable();
SettingsDA.Fill(SettingsTable);
DatabaseOwner = SettingsTable.Rows[0][1].ToString();
MakeTreeView();
}
MakeTreeView is surrounded by a try catch with a messagebox.
My Form loads these controls:
privateSystem.Windows.Forms.ToolStripMenuItemsimPlusImportToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripStatusLabeltoolStripStatusLabel1;
privateSystem.Windows.Forms.ToolStripMenuItemsyncWithSharedServerToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsyncToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsetDBConnectionToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtestToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemdetectOutliersToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsaveToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemexcludeSelectedToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemgraphActionsToolStripMenuItem;
privateSystem.Windows.Forms.ComboBoxcomboBox7;
privateSystem.Windows.Forms.ToolStripMenuItemprintReportToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddToReportToolStripMenuItem;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart4;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart3;
privateSystem.Windows.Forms.Panelpanel2;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart2;
privateSystem.Windows.Forms.ComboBoxcomboBox6;
privateSystem.Windows.Forms.Labellabel7;
privateSystem.Windows.Forms.Buttonbutton3;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart1;
privateSystem.Windows.Forms.Buttonbutton2;
privateSystem.Windows.Forms.ToolStripMenuItemremoveProductFormInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcopyInstrumentProductListToAnotherInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddProductToInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddParameterToProductToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtablesToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtXTToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcSVToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItembiasDataToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemimportToolStripMenuItem;
privateSystem.Windows.Forms.Labellabel1;
privateSystem.Windows.Forms.ComboBoxcomboBox1;
privateSystem.Windows.Forms.Labellabel2;
privateSystem.Windows.Forms.ComboBoxcomboBox2;
privateSystem.Windows.Forms.Labellabel3;
privateSystem.Windows.Forms.ComboBoxcomboBox3;
privateSystem.Windows.Forms.Labellabel4;
privateSystem.Windows.Forms.ComboBoxcomboBox4;
privateSystem.Windows.Forms.Labellabel5;
privateSystem.Windows.Forms.ComboBoxcomboBox5;
privateSystem.Windows.Forms.Labellabel6;
privateSystem.Windows.Forms.DateTimePickerdateTimePicker1;
privateSystem.Windows.Forms.DateTimePickerdateTimePicker2;
privateSystem.Windows.Forms.ToolStripMenuItemparameterToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemproductToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuIteminstrumentToolStripMenuItem1;
privateSystem.Windows.Forms.ToolStripMenuItemlocationToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcompanyToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemnewToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemfileToolStripMenuItem;
privateSystem.Windows.Forms.MenuStripmenuStrip1;
privateSystem.Windows.Forms.StatusStripstatusStrip1;
privateSystem.Windows.Forms.TabPagetabPage2;
privateSystem.Windows.Forms.DataGridViewdataGridView1;
privateSystem.Windows.Forms.TreeViewtreeView1;
privateSystem.Windows.Forms.Buttonbutton1;
privateSystem.Windows.Forms.Panelpanel1;
privateSystem.Windows.Forms.TabPagetabPage1;
privateSystem.Windows.Forms.TabControltabControl1;
The only thing I can think is that I am using a reference to something that the other computer does not have access to. I thought it was the chart controls, but .NET 4.0 has those included. Any help would be immensely appreciated.
I found the culprit. It was the line:
DatabaseOwner = SettingsTable.Rows[0][1].ToString();
I found it using AppDomain.UnhandledException. It was a great tool if anyone else is running into a similar issue.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

List changed files in TFS but ordered by number of changes applied

Is there a way of listing all the files that have changed on a project, but ordered by the number of changes made to each file?
I want to do a code review but only from a selection of the most active files.
You may try to use Excel as a TFS reporting tool like in this blog post:
http://www.woodwardweb.com/vsts/getting_started.html
ps. I found that link in this question.
I searched different ways and finally I found that best way is using TFS API
here is the code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace VControl
{
class Program
{
class SourceElement
{
public string filename;
public int numberOfModification;
}
static void Main(string[] args)
{
TfsTeamProjectCollection projectCollection = new
TfsTeamProjectCollection(new Uri("http://server:8080/tfs/ProjectCollection/"),
new System.Net.NetworkCredential("username", "password"));
projectCollection.EnsureAuthenticated();
Workspace workspace = null;
Boolean createdWorkspace = false;
String newFolder = String.Empty;
VersionControlServer versionControl = projectCollection.GetService<VersionControlServer>();
var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));
String workspaceName = String.Format("{0}-{1}", Environment.MachineName, "TestWorkspace");
try
{
workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);
}
catch (WorkspaceNotFoundException)
{
workspace = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser);
createdWorkspace = true;
}
var serverFolder = String.Format("$/{0}", teamProjects[0].Name) + "/solutionFolder/";
var localFolder = Path.Combine(Path.GetTempPath(), "localFolder") + "/solutionFolder/";
var workingFolder = new WorkingFolder(serverFolder, localFolder);
// Create a workspace mapping.
workspace.CreateMapping(workingFolder);
if (!workspace.HasReadPermission)
{
throw new SecurityException(
String.Format("{0} does not have read permission for {1}",
versionControl.AuthorizedUser, serverFolder));
}
// Get the files from the repository.
workspace.Get();
string[] directories = Directory.GetDirectories(workspace.Folders[0].LocalItem);
FileStream outputFile = new FileStream("result.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(outputFile);
List<SourceElement> fileLiset = new List<SourceElement>();
foreach (string dir in directories)
{
foreach (string file in Directory.GetFiles(dir))
{
string filenamae = System.IO.Path.GetFileName(file);
Item source = versionControl.GetItem(file);
System.Collections.IEnumerable history = versionControl.QueryHistory(file,
VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 300, true, true, false, false);
int numberOfModification = 0;
foreach (var item in history)
numberOfModification++;
SourceElement fileElement = new SourceElement();
fileElement.filename = filenamae;
fileElement.numberOfModification = numberOfModification;
fileLiset.Add(fileElement);
}
}
var sortedList = fileLiset.OrderBy(x=> x.numberOfModification);
// Loop through keys.
foreach (var key in sortedList)
{
writer.WriteLine("{0}: {1}", key.filename, key.numberOfModification);
}
writer.Close();
}
}
}