How to upload a document to SharePoint using WebServices - c#

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);
}
}
}

Related

MAUI Blazor App Microsoft.CognitiveServices.Speech keyword recognition opening custom table error

I was trying to create simple service that listens for keyword from speech. I was using Microsoft.CognitiveServices.Speech ver 1.24.1 and proceeding with official documentation but got error while trying to read KeywordRecognitionodel from file, file is accessible from that path. Also tried relative and absolute path.
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
namespace HandyCook.Services
{
internal class KeyWordRecognizerService
{
public KeyWordRecognizerService()
{
StartRecognizing();
}
private async void StartRecognizing()
{
var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
var recognizer = new KeywordRecognizer(audioConfig);
recognizer.Recognized += (s, e) =>
{
Console.WriteLine($"{e.Result.Text} DETECTED");
};
var stream = await FileSystem.Current.OpenAppPackageFileAsync("XXX.table"); //accessible
//Exception with an error code: 0x8 (SPXERR_FILE_OPEN_FAILED)
var keywordModel = KeywordRecognitionModel.FromFile(Path.Combine(FileSystem.Current.AppDataDirectory, "XXX.table"));
var result = recognizer.RecognizeOnceAsync(keywordModel);
result.Wait();
}
}
}
To reproduce the error just simply create new MAUI Blazor App, add nuget package 'Microsoft.CognitiveServices.Speech 1.24.1', add service as singleton in MauiProgram then inject in Index.razor. I'm pasting also table file and solution explorer view.
table file: https://sendanywhe.re/18U3PXF8

C# Console app need assistance with main args error

I have the following c# Console app I would run this in ssis but i am using a couple of PDF manipulating librarys. so i am going to call an exe from my ssis package while passing in a file path.
But i am getting the following error when trying to run via the exe.
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at ConsoleApp.program.Main(String[]
args) line 87
BUT if i run in debug it works fine. Once i get it working on its own via the exe, i want to pass the filepath as a parameter in ssis.
see c# below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
using System.IO;
namespace PDF_Read_ConsoleApp
{
class Program
{
public static void FilePath(string path)
{
//Console.WriteLine("Please enter full pdf path \n\n ");
//path = Console.ReadLine();
string fp;
fp = #path;
string[] files = Directory.GetFiles(path, "*.pdf");
foreach (string s in files)
{
string txtOutput = s.Replace(".pdf", ".txt");
if (File.Exists(txtOutput))
{
File.Delete(txtOutput);
}
string output;
PDDocument doc = null;
try
{
doc = PDDocument.load(s);
PDFTextStripper stripper = new PDFTextStripper();
stripper.getText(doc);
output = stripper.getText(doc);
StreamWriter NewFile;
NewFile = new StreamWriter(txtOutput);
//NewFile.Write(output.ToString());
NewFile.Write(output.ToString());
NewFile.Close();
}
finally
{
//if (doc != null)
//{
doc.close();
// Console.WriteLine("\n\n File saveed - ({0} ", txtOutput);
//}
}
}
}
static void Main(string[] args)
{
args[0] = #"C:\SSIS_Packages\PDF_Import\PDF_Import\PO_pdfs"; //// TESTING FILE PATH1
FilePath(args[0]);
}
}
}
Kind Regards
Rob
I have managed to get it working, I need to enter an argument within the debug screen, see information in URL below
Console app arguments, how arguments are passed to Main method
THank you for everyone's comments

C#: How to use Service References in Visual Studio 2015 (Move from Linqpad)

I would like to migrate a C# Program to Visual Studio. I'm fairly new working with C#, however I could have learned some stuff in Linqpad.
In Linqpad I imported my dll as an additional Reference and could use it. The dll was generated with:
"wsdl http://localhost/WebService.asmx"
and
"csc /t:library WebService.cs"
Linqpad Code which worked was like:
WebService ws = new WebService();
void Main()
{
try
{
var connect = ws.Logon("localhost", Port, "", "username", "password);
var morefiles = false;
// do other stuff....
do
{
var results = ws.search(connect, "Culture", "Culture", searchCondition, morefiles);
} while (morefiles == true);
}
catch (Exception x)
{
Console.WriteLine(x.Message);
Console.WriteLine(x.StackTrace);
}
finally {
Console.WriteLine("Search done");
}
}
Now, I would like to use it in Visual Studio. In VS I imported it as a Service References with the given URL, and it showed me the necessary stuff.
Now when I try to use it in my code I get an error message which tells me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Testproject.WebService;
namespace Testproject
{
class Program
{
static void Main(string[] args)
{
WebService ws = new WebService();
Console.WriteLine("Test");
Console.ReadKey();
}
}
}
The error message is in the line:
WebService ws = new WebService();
It shows me this error message:
WebService is a 'namespace' but is used like a 'type'
I also found out, that "Logon" which I used in Line 6 in Linqpad is in:
WebService.WebServiceSoap
However, if I change the line in:
WebService.WebServiceSoap ws = new WebService.WebServiceSoap();
I also get an error message:
Cannot create an instance of the abstract class or interface
I tried different combinations also, but I don't exactly no, what can be wrong. Can you help me?

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;
}

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

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();
}
}
}

Categories

Resources