How to set up google-diff-match-patch C# library - c#

So I am a newbie and I couldn't find a proper answer to this on the internet.
After digging a little bit here is what I came up with.

Download google-diff-match-patch from here
One you have extracted it, open up your microsoft visual studio project
Go to View->Solution Explorer or press Ctrl+Alt+L
In solution Explorer right click on your project name and go to Add->Existing Item... or press Shift+Alt+A
In the dialog box that appears locate your diff-match-patch folder and go in csharp directory and select DiffMatchPatch.cs and click on Add
Then in solution explorer right click on References->Add Reference...
Search for System.Web and add it.
Now come back to your program (in my case Form1.cs) and type
using DiffMatchPatch;
Now you are ready to use all the functions of the diff-match-patch library in your C# program

Alternatively, add the Nuget Package DiffMatchPatch and add it to your project.
A Demo Code is as follows :
using System;
using System.IO;
using DiffMatchPatch;
namespace ConsoleApp_DMPTrial
{
class Program
{
static void Main(string[] args)
{
var dmp = DiffMatchPatchModule.Default;
string file1Content = "";
string file2Content = "";
using (StreamReader sr = new StreamReader("file1.json"))
{
file1Content = sr.ReadToEnd();
}
using (StreamReader sr = new StreamReader("file2.json"))
{
file2Content = sr.ReadToEnd();
}
var diffs = dmp.DiffMain(file1Content, file2Content);
dmp.DiffCleanupSemantic(diffs);
for (int i = 0; i < diffs.Count; i++)
{
Console.WriteLine(diffs[i]);
}
Console.ReadLine();
}
}
}

Related

Visual Studio 2015 build drop location

Our company recently updated TFS to 2015 update 1. After that context menu item named Drop folder disappeared from completed builds. I found nothing about it and how to bring it back. When I click Open on completed build, VS opens web version of TFS where I forced to click through the menus and copy drop folder path manually. So I decided to write a simple extension that will add this item to the menu.
Some googling brought me to this page. But it seems that the example code is quite old and not working in VS2015:
IVsTeamFoundationBuild vsTfBuild = (IVsTeamFoundationBuild)GetService(typeof(IVsTeamFoundationBuild));
IBuildDetail[] builds = vsTfBuild.BuildExplorer.CompletedView.SelectedBuilds;
Property SelectedBuilds is always empty. I suppose that it relates to old window from VS2010. It returns items that are instance of IBuildDetail interface.
So I found this piece of code here:
var teamExplorer = (ITeamExplorer)ServiceProvider.GetService(typeof(ITeamExplorer));
var page = teamExplorer.CurrentPage;
var buildsPageExt = (IBuildsPageExt)page.GetExtensibilityService(typeof(IBuildsPageExt));
var build = buildsPageExt.SelectedBuilds[0];
Here build is the instance of IBuildModel interface. It lacks DropLocation property.
Is there any way to found drop location of selected build? Or maybe latest build?
You can use IBuildDedetail.DropLocation in .NET client libraries for Visual Studio Team Services (and TFS). Basic code for your reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
namespace BuildAPI
{
class Program
{
static void Main(string[] args)
{
string project = "http://xxx.xxx.xxx.xxx";
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(project));
IBuildServer ibs = tpc.GetService<IBuildServer>();
var builds = ibs.QueryBuilds("TeamProjectName");
foreach (IBuildDetail ibd in builds)
{
Console.WriteLine(ibd.DropLocation);
Console.ReadLine();
}
}
}
}
So, after digging through TFS API, I ended up with this workaround.
private void MenuItemCallback(object sender, EventArgs e)
{
var context = (ITeamFoundationContextManager)ServiceProvider.GetService(typeof(ITeamFoundationContextManager));
IBuildServer buildServer = context.CurrentContext.TeamProjectCollection.GetService<IBuildServer>();
var teamExplorer = (ITeamExplorer)ServiceProvider.GetService(typeof(ITeamExplorer));
var buildsPageExt = (IBuildsPageExt)teamExplorer.CurrentPage.GetExtensibilityService(typeof(IBuildsPageExt));
var menuCommand = (MenuCommand)sender;
if (menuCommand.CommandID.Guid == CommandSetCompleted)
{
foreach (var buildDetail in buildsPageExt.SelectedBuilds)
Process.Start("explorer.exe", GetBuild(buildServer, buildDetail).DropLocation);
}
if (menuCommand.CommandID.Guid == CommandSetFavorite)
{
var definitions = buildsPageExt.SelectedFavoriteDefinitions.Concat(buildsPageExt.SelectedXamlDefinitions).ToArray();
foreach (var build in GetLatestSuccessfulBuild(buildServer, definitions))
Process.Start("explorer.exe", build.DropLocation);
}
}
private IBuildDetail GetBuild(IBuildServer buildServer, IBuildModel buildModel)
{
Uri buildUri = new Uri(buildModel.GetType().GetProperty("UriToOpen").GetValue(buildModel).ToString());
return buildServer.GetBuild(buildUri);
}
private IBuildDetail[] GetLatestSuccessfulBuild(IBuildServer buildServer, IDefinitionModel[] buildDefinitions)
{
var spec = buildServer.CreateBuildDetailSpec(buildDefinitions.Select(bd => bd.Uri));
spec.MaxBuildsPerDefinition = 1;
spec.QueryOrder = BuildQueryOrder.FinishTimeDescending;
spec.Status = BuildStatus.Succeeded;
var builds = buildServer.QueryBuilds(spec);
return builds.Builds;
}

Read build configurations programmatically

I want to be able to read the VS build configurations programmatically. That is because I want to create my own builder.
How do I do that? Does anyone have code example?
What i mean is that if I have Debug, Development, Release I want them to be listed in a list box in a Form application. I have tried using the "EnvDTE.dll" class but I am not sure it is what I am looking for. If anyone has a concrete example or link to an example I would be more than grateful.
You can use the msbuild API. In Visual Studio 2015, there is a class called Microsoft.Build.Construction.SolutionFile in the Microsoft.Build.dll that ships with VS2015 that you can use to load a solution.
In VS2013 there is no such thing, but you can do the following:
(reference Microsoft.Build.dll, Microsoft.Build.Engine.dll, Microsoft.Build.Framework.dll)
class Program
{
static void Main(string[] args)
{
string nameOfSolutionForThisProject = #"MySolutionFile.sln";
string wrapperContent = SolutionWrapperProject.Generate(nameOfSolutionForThisProject, toolsVersionOverride: null, projectBuildEventContext: null);
byte[] rawWrapperContent = Encoding.Unicode.GetBytes(wrapperContent.ToCharArray());
using (MemoryStream memStream = new MemoryStream(rawWrapperContent))
using (XmlTextReader xmlReader = new XmlTextReader(memStream))
{
Project proj = ProjectCollection.GlobalProjectCollection.LoadProject(xmlReader);
foreach (var p in proj.ConditionedProperties)
{
Console.WriteLine(p.Key);
Console.WriteLine(string.Join(", ", p.Value));
}
}
Console.ReadLine();
}
}
ConditionedProperties contains a list of platforms and configurations contained in the solution. You can use this to populate your forms.

How to upload a document to SharePoint using WebServices

I have looked through multiple tutorials and asked many questions with NO result . Here it is step by step :
1) I use Microsoft Visual Studio 2012 . I do NOT have SP server installed and cannot use Microsoft.SharePoint.dll . However , I can use Web Service
2) I create a console project and add a WebReference like this
3) Here is my FULL code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication6;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
string srcUrl = #"C:\\xxx\\test.txt";
System.IO.FileStream fStream = System.IO.File.OpenRead(srcUrl);
string fileName = fStream.Name.Substring(3);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
ServiceWebReference.Lists listService = new ServiceWebReference.Lists(); // "Lists" get underlined with a red line ?
listService.ClientCredentials = System.Net.CredentialCache.DefaultCredentials;
try
{
// adding attachment
string result = listService.AddAttachment("testList", "1", fileName, contents);
Console.WriteLine(result);
}
catch (System.Web.Services.Protocols.SoapException e)
{
Console.WriteLine(e.GetBaseException());
Console.WriteLine(e);
}
}
}
}
Am I adding the reference in a right way ? If yes , then why does the ServiceWebReference.Lists listService ... ... ... get underlined in red (does not recognize namespace ) ?
How to make the code work ?
Since Lists.asmx is a SOAP Web service, it could be referenced as described in article: How to: Add a Reference to a Web Service
How to add Lists.asmx SOAP Web service in Visual Studio:
In Solution Explorer, right-click the name of the project that you want to add the service to, and then click Add Service Reference
The Add Service Reference dialog box appears, in the Service Reference Settings dialog box, click Add Web Reference as demonstrated below
Specify service endpoint Url
Visual Studio
Sample code
namespace SPUpload
{
class Program
{
static void Main(string[] args)
{
var attachmentUrl = UploadAttachment(#"c:\temp\usermanual.rtf","Phones","1");
}
private static string UploadAttachment(string filePath, string listName, string listItemId)
{
var listsSvc = new ListsService.Lists();
listsSvc.Credentials = System.Net.CredentialCache.DefaultCredentials;
var fileName = Path.GetFileName(filePath);
var fileContent = File.ReadAllBytes(filePath);
return listsSvc.AddAttachment(listName, listItemId, fileName, fileContent);
}
}
}

C# Code only getting pagesource for visible page, not for scrolled down page

If you go to http://dota-trade.com/equipment?order=name and scroll down, you can see that if you scroll down to the bottom of the page, it loads more items. The following code grabs all of the links from the webpage and saves it into a text file. Right now it is only grabbing all of the visible links. How is it possible to grab all of the links including the ones that appear as you scroll down?
If you know a better way to describe what I'm asking please edit my post, you have my full permission to edit anything to your desired preference. Thank you.
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
var sourceCode = wc.DownloadString("http://dota-trade.com/equipment?order=name");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(sourceCode);
var node = doc.DocumentNode;
var nodes = node.SelectNodes("//a");
List<string> links = new List<string>();
foreach (var item in nodes)
{
var link = item.Attributes["href"].Value;
links.Add(link.Contains("http") ? link : "http://dota-trade.com" +link);
Console.WriteLine(link.Contains("http") ? link : "http://dota-trade.com" + link);
}
System.IO.File.WriteAllLines(#"C:\Users\Public\WriteLines.txt", links);
}
}
}
Additional Information: Here's everything I did from the start to finish:
I used Microsoft visual Studio Ultimate 2012 RTM. I installed it (took almost 2 hours). I launched Visual Studio 2012. I clicked "File" then "New Project", then under "Installed -> Templates -> Visual C# -> Windows -> Console Application" then press "ok". A new page should appear named Program.cs. Paste the code into the window overwriting what's already there. Download HtmlAgilityPack. I got mine from htmlagilitypack.codeplex.com Now click "Project" then click "Add Reference". Once the Reference Manager pops up click "Browse" and then click "Browse" at the bottom right of the popup. Navigate to the HtmlAgilityPack.dll in the Net45 folder of the HtmlAgilityPack that you downloaded. Now Press "ok" and press F5. Should work like a charm. –
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
var sourceCode = wc.DownloadString("http://dota-trade.com/equipment?order=name");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(sourceCode);
var node = doc.DocumentNode;
var nodes = node.SelectNodes("//a");
List<string> links = new List<string>();
foreach (var item in nodes)
{
var link = item.Attributes["href"].Value;
links.Add(link.Contains("http") ? link : "http://dota-trade.com" +link);
}
int index = 1;
while (true)
{
sourceCode = wc.DownloadString("http://dota-trade.com/equipment?order=name&offset=" + index.ToString());
doc = new HtmlDocument();
doc.LoadHtml(sourceCode);
node = doc.DocumentNode;
nodes = node.SelectNodes("//a");
var cont = node.SelectSingleNode("//tr[#itemtype='http://schema.org/Thing']");
if (cont == null) break;
foreach (var item in nodes)
{
var link = item.Attributes["href"].Value;
links.Add(link.Contains("http") ? link : "http://dota-trade.com" + link);
}
index++;
}
System.IO.File.WriteAllLines(#"C:\Users\Public\WriteLines.txt", links);
}
}
}

How do I restore a file from the recycle bin using C#?

Moving files to the recycle bin and emptying the recycle bin are well documented, but how can a file be programmatically restored from the recycle bin?
There seems not to be a solution in pure C#. You most likely have to resort to P/Invoke.
This article presents a solution in C++ using the SHFileOperation API.
The only other reference to this beyond the previously mentioned link to codeproject that I can see mentions this:
Call SHGetFolderLocation passing CSIDL_BITBUCKET.
Then you can manipulate that folder as usual.
You'll have to create an interop for the SHGetFolderLocation function.
CSIDL_BITBUCKET being the CSIDL ("constant special item ID list") value for the virtual Recycle Bin folder. The quote is taken from here, and will involve interop with the Windows shell. MSDN also mentions that this function has been deprecated in favour of another in Vista.
Hope below code will work to restore the files. Please make sure, STA Calls only supported for shell calls
using System;
using System.Collections;
using System.Windows.Forms;
using System.IO;
using Shell32; //Reference Microsoft Shell Controls And Automation on the COM tab.
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.FileIO;
using System.Threading;
private static void Restore(object param)
{
object[] args = (object[])param;
string filename = (string)args[0];
string filepath = (string)args[1];
Shl = new Shell();
Folder Recycler = Shl.NameSpace(10);
var c = Recycler.Items().Count;
var _recycler = Recycler.Items();
for (int i = 0; i < _recycler.Count; i++)
{
FolderItem FI = _recycler.Item(i);
string FileName = Recycler.GetDetailsOf(FI, 0);
if (Path.GetExtension(FileName) == "") FileName += Path.GetExtension(FI.Path);
//Necessary for systems with hidden file extensions.
string FilePath = Recycler.GetDetailsOf(FI, 1);
if (filepath == Path.Combine(FilePath, FileName))
{
DoVerb(FI, "ESTORE");
break;
}
}
}
private static bool DoVerb(FolderItem Item, string Verb)
{
foreach (FolderItemVerb FIVerb in Item.Verbs())
{
if (FIVerb.Name.ToUpper().Contains(Verb.ToUpper()))
{
FIVerb.DoIt();
return true;
}
}
return false;
}

Categories

Resources