Is there anyway to integrate docushare with a windows store app?
I would like to login, get a file/folder list and have the possibility of downloading and uploading files.
Here is simple code snippet which can be good start to play with DocuShare. All possible request can be found in documentation.
Authentication + fetching properties for Collection-11 object
protected const string UsernameFormFieldName = "username";
protected const string PasswordFormFieldName = "password";
protected const string DomainFormFieldName = "domain";
const string CookieName = "AmberUser";
const string baseAdress = "http://host:port";
const string container = "/docushare";
static Uri CookieUrl = new Uri(new Uri(baseAdress), container);
const string root = "/xcm/v1/shadow/xcmAPI/root";
const string FolderInfoUri = "/xcm/v1/shadow/object/{0}/xcmAPI/properties";
const string ObjectVersion = "/xcm/v1/shadow/object/{0}/xcmAPI/version";
const string ObjectToTest = "Collection-11";
const string suffix = "?properties=title,mimetype";
static void Main(string[] args)
{
var token = Authenticate();
var requestUri = string.Format(container + FolderInfoUri, ObjectToTest) + suffix;
var response = GetResult(token, requestUri);
var content = response.Content.ReadAsStringAsync().Result;
}
private static string Authenticate()
{
const string AuthenticationPath = container + "/dsweb/ApplyLogin";
var form = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>(UsernameFormFieldName, "login"),
new KeyValuePair<string, string>(PasswordFormFieldName, "password"),
new KeyValuePair<string, string>(DomainFormFieldName, "domain"),
});
string authToken = null;
Execute((client, handler) =>
{
var task = client.PostAsync(AuthenticationPath, form, CancellationToken.None);
var response = task.Result;
var content = response.Content.ReadAsStringAsync().Result;
var cookie = handler.CookieContainer.GetCookies(CookieUrl);
authToken = cookie[CookieName].Value;
});
return authToken;
}
private static void Execute(Action<HttpClient, HttpClientHandler> request)
{
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.UseCookies = true;
handler.CookieContainer = new CookieContainer();
client.BaseAddress = new Uri(baseAdress);
request(client, handler);
}
}
private static HttpResponseMessage GetResult(string token, string uri)
{
HttpResponseMessage response = null;
Execute((client, handler) =>
{
handler.CookieContainer.Add(
CookieUrl,
new Cookie(CookieName, token));
var responseTask = client.GetAsync(uri);
response = responseTask.Result;
});
return response;
}
You should be able to do so with Docushare's HTML/XML API. For details on the Docushare API it looks like you'll need to register for the DocuShare Developer Network
Once you know what Docushare expects you should be able to connect to it from your Windows Store app with the HttpClient API. See Connecting to an HTTP server using Windows.Web.Http.HttpClient (XAML)
Related
I'm trying to Get all files from a folder on a SharePoint site AND creating folders on said site. So GET/POST.
When i'm trying to GET the files from the folder https://xxxxxx.sharepoint.com/sites/Test/Syra_Test/
i get a 200 success but nothing in the resulting json.: "{"odata.metadata":"https://xxxxxx.sharepoint.com/_api/$metadata#SP.ApiData.Files12\","value":[]}" i'm guessing its path issues but i don't know.
see function1()
I am now trying to create folders, however i get a 403 error.
see function2()
private static void Function1(){
//string RESTURL = "{0}/_api/web/lists/GetByTitle('Test')/items?$top=1";
string RESTURL = "{0}/_api/web/GetFolderByServerRelativeUrl('/General')/Files";
string webUrl = "https://xxxxxx.sharepoint.com";
string USER = "xxxxx#xxxxx.com";
var passWord = new SecureString();
string PWD = "xxxxx";
PWD.ToList().ForEach(passWord.AppendChar);
var credential = new SharePointOnlineCredentials(USER, passWord);
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Get authentication cookie
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoke REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(string.Format(RESTURL, webUrl)).Result;
response.EnsureSuccessStatusCode();
string jsonData = response.Content.ReadAsStringAsync().Result;
}
}
}
private static void Function2(){
string RESTURL = "{0}/_api/web/folders";
string webUrl = "https://xxxx.sharepoint.com";
string USER = "xxxx#xxxxx.com";
var passWord = new SecureString();
string PWD = "xxxxx";
PWD.ToList().ForEach(passWord.AppendChar);
var credential = new SharePointOnlineCredentials(USER, passWord);
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Get authentication cookie
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoke REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string json = "{'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/shared documents/folderSyraCreated'}";
StringContent strContent = new StringContent(json);
HttpResponseMessage response = client.PostAsync(string.Format(RESTURL, webUrl), strContent).Result;
response.EnsureSuccessStatusCode();
string jsonData = response.Content.ReadAsStringAsync().Result;
}
}
}
Can't use external dll's (csom) in this case (plugin for an economy system)
Hope it makes sense :)
I am implementing c # with FireBase, it sends me error 401 'INVALID_KEY_TYPE'
private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
private static string ServerKey = "AIzaSyA9fL8lPyxcrngIDDsDeUbq9sPTkavXXXX";
public static async Task<bool> SendPushNotification(string deviceTokens, string title, string body, object data)
{
bool sent = false;
if (deviceTokens.Count() > 0)
{
//Object creation
var messageInformation = new
{
to = "fZ0EyxU-tsk:APA91bE3-qo4DwL9phteDJC8pG6iLdr-YSSl-N_2SJne3U6eyUhmEuZNQhJi0YM-XXXXXX",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test miguel",
badge = 1
},
};
//Object to JSON STRUCTURE => using Newtonsoft.Json;
string jsonMessage = JsonConvert.SerializeObject(messageInformation);
//Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage result;
using (var client = new HttpClient())
{
result = await client.SendAsync(request);
sent = sent && result.IsSuccessStatusCode;
}
}
return sent;
}
I have the same problem. The problem is that you take the wrong server key.
The right firebase server key is Project > Settings > Cloud Messaging > Server Key
So, for my homework, I need to make an application that will not use SQL(as I used to), but the rest api. Problem is that I never done this, and I don't know how to configure it.
So far I got this:
string strUrlTest = String.Format("https://test.api.amadeus.com/v1/shopping/flight-offers");
WebRequest requestObjGet = WebRequest.Create(strUrlTest);
requestObjGet.Method = "GET";
requestObjGet.Headers.Add("API KEY",
"API SECRET);
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
string strResultTest = null;
using(Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strResultTest = sr.ReadToEnd();
sr.Close();
}
I just wanted to see with debugger if I got my all my data, but my program crashes at
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
Could you help me figure it out?
I wrote a code example in C#, replace apikey and apisecret by the ones you get on the portal by creating an application. You can find a guide here.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace testApp
{
public class AmadeusTest
{
static void Main()
{
const string URL = "https://test.api.amadeus.com/v1/shopping/flight-destinations?origin=BOS";
string token = getToken();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
Task<HttpResponseMessage> response = client.SendAsync(request);
string myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result).ToString();
JObject jsonObject = JObject.Parse(myJsonResponse);
Console.WriteLine(myJsonResponse);
Console.WriteLine(jsonObject["data"][0]["destination"]);
client.Dispose();
}
private static string getToken()
{
const string apikey = "";
const string apisecret = "";
const string tokenURL = "https://test.api.amadeus.com/v1/security/oauth2/token";
string postData = $"grant_type=client_credentials&client_id={apikey}&client_secret={apisecret}";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(tokenURL);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
request.Content = new StringContent(postData,
Encoding.UTF8,
"application/x-www-form-urlencoded");
Task<HttpResponseMessage> response = client.SendAsync(request);
if (response.Result.IsSuccessStatusCode)
{
string myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result).ToString();
JObject jsonObject = JObject.Parse(myJsonResponse);
client.Dispose();
string token = (string)jsonObject["access_token"];
return token;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.Result.StatusCode, response.Result.ReasonPhrase);
return response.Result.ReasonPhrase;
}
}
}
}
The getToken method is in charge of doing the authorization process (as explained here).
This token is used in the API call (in the Main method). It is added to the Authorization header with the value: Bearer {token}
Firstly, you need to get access token, to retrieve the data. How i accomplish this, you can see in code below.
[HttpGet("[action]")]
public async Task<List<FlightOffersModel>> GetData(string origin, string destination, string departureDate, string returnDate, string adults, string currency)
{
const string client_id = "oqsIlG0xAbnlXXXXXXXXXXg7GdYwemI5";
const string client_secret = "lAcXXXXXXXXX5AD0";
string token = await GetToken(client_id, client_secret);
const string baseUrl = "https://test.api.amadeus.com/v1/";
string urlParams = "shopping/flight-offers?origin=" + origin + "&destination=" + destination + "&departureDate=" + departureDate;
urlParams += returnDate == "" || returnDate == null ? "" : "&returnDate=" + returnDate;
urlParams += "&adults=" + adults + "&nonStop=false¤cy=" + currency + "&max=50";
FlightOffer ff = null;
List<FlightOffersModel> model = new List<FlightOffersModel>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.amadeus+json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.GetAsync(urlParams);
if (response.IsSuccessStatusCode)
{
var x = await response.Content.ReadAsStringAsync();
var xx = JObject.Parse(x);
ff = JsonConvert.DeserializeObject<FlightOffer>(xx.ToString());
foreach (var fo in ff.Data)
{
FlightOffersModel temp = new FlightOffersModel();
foreach (var item in fo.OfferItems)
{
foreach (var service in item.Services)
{
if (item.Services.IndexOf(service) < 1)
{
temp.BrojPresjedanjaPovratak = item.Services.Length > 1 ? GetBrojPresjedanja(item.Services[1]) : 0;
temp.BrojPresjedanjaOdlazak = GetBrojPresjedanja(item.Services[0]);
temp.BrojPutnika = GetBrojPutnika(service.Segments);
temp.UkupnaCijena = item.Price.Total;
temp.Valuta = ff.Meta.Currency;
temp.PolazniAerodrom = GetAerodromName(service.Segments, "departure", ff.Dictionaries.Locations);
temp.OdredisniAerodrom = GetAerodromName(service.Segments, "arrival", ff.Dictionaries.Locations);
temp.DatumPolaska = GetDatumLeta(service.Segments, "departure");
temp.DatumPovratka = GetDatumLeta(service.Segments, "arrival");
model.Add(temp);
}
}
}
}
}
}
return model;
}
This part of code is to get access token
const string client_id = "oqsIlG0xAbnlXXXXXXXXXXg7GdYwemI5";
const string client_secret = "lAcXXXXXXXXX5AD0";
string token = await GetToken(client_id, client_secret);
and this is GetToken function:
private async Task<string> GetToken(string client_id, string client_secret)
{
AccessToken s = null;
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://test.api.amadeus.com/v1/security/oauth2/token"))
{
request.Content = new StringContent("grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
s = await response.Content.ReadAsAsync<AccessToken>();
}
}
}
return s.Access_token;
}
The rest of the code supplies data according to the parameters that user entered.
I am trying to write a local console application which will swap an Azure Web App slot using the Azure REST API. Using the following code I get a 401 (Unauthorized) response:
public async Task Swap(string subscription, string resourceGroup, string site, string slot)
{
var client = new HttpClient();
var url =
$"https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{site}/applySlotConfig?api-version=2016-08-01";
var data = new {preserveVnet = true, targetSlot = slot};
var message = new HttpRequestMessage
{
RequestUri = new Uri(url),
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(message);
Console.WriteLine(response.StatusCode);
}
I know I need to put in some kind of credentials but what I have found seems to apply to apps using Azure AD for authentication. This will be a publicly accessible web app with anonymous authentication.
Generally speaking you need to attach a Authorization header to the request with the Auth token. There are numerous ways of getting it, see this link or this.
This is how I managed to do it (using the provided links):
private async Task<string> GetAccessToken(string tenantName, string clientId, string clientSecret)
{
var authString = "https://login.microsoftonline.com/" + tenantName;
var resourceUrl = "https://management.azure.com/";
var authenticationContext = new AuthenticationContext(authString, false);
var clientCred = new ClientCredential(clientId, clientSecret);
var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientCred);
var token = authenticationResult.AccessToken;
return token;
}
And then in my previous method:
public async Task Swap(string subscription, string resourceGroup, string site, string slot)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken("XXX", "XXX", "XXX"));
var url =
$"https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{site}/applySlotConfig?api-version=2016-08-01";
var data = new {preserveVnet = true, targetSlot = slot};
var message = new HttpRequestMessage
{
RequestUri = new Uri(url),
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(message);
Console.WriteLine(response.StatusCode);
}
I've got the following code that works successfully. I can't figure out how to get the cookie out of the response. My goal is that I want to be able to set cookies in the request and get cookies out of the response. Thoughts?
private async Task<string> Login(string username, string password)
{
try
{
string url = "http://app.agelessemail.com/account/login/";
Uri address = new Uri(url);
var postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password ", password)
};
HttpContent content = new FormUrlEncodedContent(postData);
var cookieJar = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false
};
var client = new HttpClient(handler)
{
BaseAddress = address
};
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
return body;
}
catch (Exception e)
{
return e.ToString();
}
}
Here is the complete answer:
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
Uri uri = new Uri(UrlBase);
var responseCookies = cookieJar.GetCookies(uri);
foreach (Cookie cookie in responseCookies)
{
string cookieName = cookie.Name;
string cookieValue = cookie.Value;
}
To add cookies to a request, populate the cookie container before the request with CookieContainer.Add(uri, cookie). After the request is made the cookie container will automatically be populated with all the cookies from the response. You can then call GetCookies() to retreive them.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync("http://google.com").Result;
Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);
Console.ReadLine();
There's alternative if you don't have access to the HttpClient and can't inject the CookieContainer. This works in .NET Core 2.2:
private string GetCookie(HttpResponseMessage message)
{
message.Headers.TryGetValues("Set-Cookie", out var setCookie);
var setCookieString = setCookie.Single();
var cookieTokens = setCookieString.Split(';');
var firstCookie = cookieTokens.FirstOrDefault();
var keyValueTokens = firstCookie.Split('=');
var valueString = keyValueTokens[1];
var cookieValue = HttpUtility.UrlDecode(valueString);
return cookieValue;
}
You can easily get a cookie value with the given URL.
private async Task<string> GetCookieValue(string url, string cookieName)
{
var cookieContainer = new CookieContainer();
var uri = new Uri(url);
using (var httpClientHandler = new HttpClientHandler
{
CookieContainer = cookieContainer
})
{
using (var httpClient = new HttpClient(httpClientHandler))
{
await httpClient.GetAsync(uri);
var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
return cookie?.Value;
}
}
}
Not in every case you can add httpClientHandler to httpClient. For example, when you use integration tests testServer.CreateClient() or inject httpClient from IHttpClientFactory. So, I have simply read values from header.
public static List<Cookie> GetCookies(this HttpResponseMessage message)
{
message.Headers.TryGetValues("Set-Cookie", out var cookiesHeader);
var cookies = cookiesHeader.Select(cookieString => CreateCookie(cookieString)).ToList();
return cookies;
}
private static Cookie CreateCookie(string cookieString)
{
var properties = cookieString.Split(';', StringSplitOptions.TrimEntries);
var name = properties[0].Split("=")[0];
var value = properties[0].Split("=")[1];
var path = properties[2].Replace("path=", "");
var cookie = new Cookie(name, value, path)
{
Secure = properties.Contains("secure"),
HttpOnly = properties.Contains("httponly"),
Expires = DateTime.Parse(properties[1].Replace("expires=", ""))
};
return cookie;
}
CreateCookie method may be modified to exactly match your cookie properties.