Uploading files to SharePoint OnPremise 2016 using .NET Core 5.0 and HttpWebRequest C# - .net-core

SharePoint CSOM is not supported in .NET Core 5.0, so I'm trying to use HttpWebRequest to upload files to SharePoint 2016 on-premise.
This code sample shown here works in .NET 4.7, however it throws errors when run on .NET Core.
public async Task<string> UploadFile(string folderName, string fileName, byte[] file)
{
// Url to upload file
string resourceUrl = _sharePointUrl + $"/_api/web/GetFolderByServerRelativeUrl('/opportunity/{folderName}')/Files/add(url='{fileName}',overwrite=true)";
HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
wreq.Credentials = _credentials;
wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
// Get formdigest value from site
wreq.Headers.Add("X-RequestDigest", GetFormDigest());
wreq.Headers.Add("binaryStringRequestBody", "true");
wreq.Method = "POST";
wreq.Accept = "application/json; odata=verbose";
wreq.ContentLength = file.Length;
wreq.Timeout = 100000;
await wreq.GetRequestStream().WriteAsync(file, 0, file.Length);
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
return response.StatusDescription;
}
Errors are listed below. The errors are happening on the
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
line.
System.AggregateException: 'One or more errors occurred. (An error occurred while sending the request.)'
Inner Exception 1: WebException: An error occurred while sending the request.
Inner Exception 2: HttpRequestException: An error occurred while sending the request.
Inner Exception 3: IOException: The response ended prematurely.
What am I missing?
Does the HttpWebRequest in .NET Core work differently than the .NET framework version?
Do I need to use different headers or configure the request object differently?
Thanks in advance.

Related

WooCommerce rest api access failing with httpWebRequest

I am trying to get WooCommerce data using WooCommerce v3 API from c#.
When I use below url in browser I get the products data as json;
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890
When I use url
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products
and
consumer_key = ck_12345678901234567890 and consumer_secret = cs_12345678901234567890
as Params in Postman then I get the products data as well. So the credentials and url are valid.
However when I try to do this using HttpWebRequest it fails with "The remote server returned an error: (401) Unauthorized" exception. My code is below and the exception appears on the last line of code.
The vales in HttpWebRequest before the GetResponseAsync call can be seen here.
What am I doing wrong?
Thanks
Regards
string wc_url = "https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";
HttpWebRequest httpWebRequest = null;
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url);
httpWebRequest.AllowReadStreamBuffering = false;
WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);

Windows 10 Universal App - Package doesn't work normally as debug mode

public async Task<List<Tip>> GetTips()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://APIURL ");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = await request.GetResponseAsync();
StreamReader sr = new StreamReader(res.GetResponseStream());
string result = sr.ReadToEnd();
List<Tip> tips = JsonConvert.DeserializeObject<List<Tip>>(result);
return tips;
}
I am working on a project which need to consume an enterprise Web API(Https) and display the data on Win 10 live tile, it’s an UWP application.
But I found it only works when I ran it in IDE(Visual Studio 2015 debug mode) .
When I created a package for this app and run it by powershell for installation, request.GetResponseAsync method throws exception “The login request was denied”.
I tried to check Enterprise Authentication and Private Networks(Client & Server) options in Package.appxmanifest. But there was no effect.
Any idea how to make it work normally? Thanks.

Do I need to investigate HTTP 401 cached by Fiddler during the HttpWebRequest post to ASP.NET WebApi server

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;

Unregistered SOAP Client 3.0 on Windows Server

I've developed a Web Application (web site) using VS 2010 and VB.NET. I'm able to run the application successfully from VS. But when I Publish and upload it on my hosting server this error message occurs.
Retrieving the COM class factory for component with CLSID {7F017F97-9257-11D5-87EA-00B0D0BE6479} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
I've downloaded the SOAP toolkit 3.0 and imported it in my application reference. here is my code:
Imports MSSOAPLib30
Dim objSoapClient As New SoapClient30 '=== Create an instance of SoapClient
'=== Set Client Properties
objSoapClient.ClientProperty("ServerHTTPRequest") = True
'=== Retrieve KWMP web services WSDL
Call objSoapClient.mssoapinit("https://example.com/ReferencePayment?WSDL", "ReferencePayment")
'=== Set connection property to be over SSL
objSoapClient.ConnectorProperty("UseSSL") = False
'=== Now consume the web sevices according to KWMP Specification
Dim output As String = objSoapClient.verifyTransaction(RCode, "00105952-129251")
--Update--
except the method above, I was thinking of using POST web method to consume the SOAP XML.
here is the xml request generated by WCF Test Client:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" />
</s:Header>
<s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<q1:verifyTransaction xmlns:q1="urn:Foo">
<String_1 xsi:type="xsd:string">12345678901234567890</String_1>
<String_2 xsi:type="xsd:string">00109902-129251</String_2>
</q1:verifyTransaction>
</s:Body>
</s:Envelope>
and I have method to consume the SOAP XML which returns Internal Server Error 500 !!!!! You think which part is wrong ?!
Public Function ServiceCall(RefCode As String) As String
Dim resultXml As String
Dim wbrqst As WebRequest = WebRequest.Create("https://modern.enbank.net/ref-payment/ws/ReferencePayment?WSDL")
Dim httpreq As HttpWebRequest = DirectCast(wbrqst, HttpWebRequest)
httpreq.Method = "POST"
httpreq.ContentType = "Content-Type: text/xml; charset=utf-8"
httpreq.Headers.Add("SOAPAction", "https://modern.enbank.net/ref-payment/ws/ReferencePayment")
'httpreq.Headers.Add("<Action s:" + "ReferencePayment>")
httpreq.ProtocolVersion = HttpVersion.Version11
httpreq.Credentials = CredentialCache.DefaultCredentials
Dim requestStream As Stream = httpreq.GetRequestStream()
Dim streamWriter As New StreamWriter(requestStream, Encoding.ASCII)
Dim sb As New StringBuilder()
sb.Append("<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>")
sb.Append("<s:Body s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>")
sb.Append("<q1:verifyTransaction xmlns:q1='urn:Foo'>")
sb.Append("xml:xsd='http://www.w3.org/2001/XMLSchema'")
sb.Append("<verifyTransaction xmlns='urn:Foo'")
sb.Append("<String_1 xsi:type='xsd:string'>12345678901234567890</String_1>")
sb.Append("<String_2 xsi:type='xsd:String'>00109902-129251</String_2>")
sb.Append("</q1:verifyTransaction> </s:Body></s:Envelope>")
streamWriter.Write(sb.ToString())
streamWriter.Close()
Dim wr As HttpWebResponse = DirectCast(httpreq.GetResponse(), HttpWebResponse)
Dim srd As New StreamReader(wr.GetResponseStream())
resultXml = srd.ReadToEnd()
Return resultXml
End Function
There appears to be a problem with that tool, you may want to use the WCFTest Client, which should work with you soap message, thise can be found from within the VS2010 folder
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe
Just add the service you want to open, it should then create a client proxy for you on the fly.
Update:
You may want to use add web reference and create a webservice project as part of a VS project.
Hope this helps.
Cheers

HTML scraping: Forms authentication failed for the request. The ticket supplied has expired

The ActiveForums module we're using as part of our DotNetNuke system has a bug in the XML for it's RSS feed. It doesn't correctly encode ampersands, it leaves them as & rather than encoding them as &
I've reported the bug to the company, but in the mean time I need a fix. So what I've done is create an intermediary page that makes a request to the RSS feed via a System.Net.HttpWebRequest.Create(url) and them performs a Regex.Replace to replaces any unencoded ampersands.
The problem is that when I run the code on our production server I get an exception: The remote server returned an error: (500) Internal Server Error.
The only reason I could think of was around authentication (As the server requires NTLM), however as far as I can tell I'm doing this part of it correctly. My code is shown below:
string html = string.Empty;
string url = "http://intranet.nt.avs/dnn/Default.aspx?tabid=130";
WebResponse response;
WebRequest request = System.Net.HttpWebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
html = sr.ReadToEnd();
}
// Clean invalid XML
html = Regex.Replace( html, "&(?!amp;|gt;|lt;|quot;|apos;)", "&", RegexOptions.Multiline | RegexOptions.IgnoreCase );
Response.ContentType = "text/xml";
Response.Write( html );
Updated: Here's what the event log says
Error code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired

Resources