.ics Calendar. Appointment Via Email API Emailing Method - c#

Hello every one I am creating a system that creates a event like an Appointment.Then it sends it to a receiver via Email using This method
It creates a Calendar like this.
string[] contents = { "BEGIN:VCALENDAR",
"PRODID:-//Flo Inc.//FloSoft//EN",
"BEGIN:VEVENT",
"DTSTART:" + schBeginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
"DTEND:" + schEndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
"LOCATION:" + schLocation,
"ORGANIZER:" + "Haseeb",
"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + schDescription,
"SUMMARY:" + schSubject, "PRIORITY:3",
"END:VEVENT", "END:VCALENDAR" };
System.IO.File.WriteAllLines(Server.MapPath("Calendar's//" + txtCelenderName.Text + ".ics"),
contents);
It works all good and sends Email but every time it creates a Event it downloads a file which is a big data a company with 400 users and meetings with customers is going to be over load. Is there any other method to send Calendar reminders without saving it into a path.
This is how i send the Attachment.
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net");
client.Authenticator = new HttpBasicAuthenticator("api", "key-key");
RestRequest request = new RestRequest();
request.AddParameter("domain", "email.com", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
if (!string.IsNullOrEmpty(sFromAlias))
request.AddParameter("from", sFromAlias + " <" + sFrom + ">");
else
request.AddParameter("from", "<" + sFrom + ">");
request.AddParameter("subject", sSubject);
request.AddParameter("html", sBody);
request.AddFile("attachment", Path, "text/calendar"); // This is the Celender that goes along the Email
request.Method = Method.POST;

Related

wrong format of json string in an api call?

I try to bring the pdf file into a standard software, wrote the code, an exception is issued because of wrong format with json although json string corresponds exactly to the specified json of api call of standard software. can you please take a look if I wrote something wrong here or if I forgot something?
I covered some information with a star
Many Thanks
IRestResponse response3;
client = new RestClient("http://***.***.***.*");
client.Authenticator = new HttpBasicAuthenticator("********", "*********");
client.Timeout = -1;
request = new RestRequest("/*****/api/******/*****/***", Method.POST);
request.AddHeader("content-type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("Object", "{" +
"\"cabinet\":\"Posteingang\"," +
"\"name\":\"Posteingang\"," +
"\"objectTypeId\":\"2\"," +
"\"fields\":{" +
"\"Datum\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"}" +
"}" +
"}");
request.AddFile("file","C:/Users/*********/Documents/*********/Org.pdf","Org.pdf");
MultipartFormDataContent multipartForm = new MultipartFormDataContent();
byte[] file_bytes = File.ReadAllBytes("C:/Users/********/Documents/********/Org.pdf");
multipartForm.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "hello1.jpg");
multipartForm.Add(new StringContent("Object"), "{" +
"\"cabinet\":\"Posteingang\"," +
"\"name\":\"Dokument\"," +
"\"objectTypeId\":\"******\"," +
"\"fields\":{" +
"\"Datum\":{\"MAIL_SUBMIT_TIME\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"},\"Typ\":" +
"{\"feld4\":{\"value\": \"Brief\"}},\"Absender\": {\"Mail_FROM\":{\"value\": \"*********\"}}}}}");
response3 = client.Execute(request);
Console.WriteLine(response3.Content);
}
}
}

How can I send or get a file through rest api

How can I move a file (for example: in pdf format) that is in a folder with me locally through an api call in a folder in a document management system?
This is a small cod section of the api call that takes over the task.
client = new RestClient("http://***.***.***.*");
client.Authenticator = new HttpBasicAuthenticator("******", "******");
client.Timeout = -1;
request = new RestRequest("/*****/api/*****/*****/371 ", Method.POST);
request.AddHeader("content-type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("Object", "{" +
"\"****\":\"*****\"," +
"\"name\":\"*******\"," +
"\"******\":\"2\"," +
"\"fields\":{" +
"\"*******\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"}" +
"}" +
"}");
request.AddFile("File", "C:/Users/********/Documents/****/*****/pdf.pdf");
response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I would have to obscure a few places with stars
Thank You

Upload file to OneDrive using RestAPI

I am trying to upload an image to OneDrive using below code. The file was successfully uploaded to the OneDrive folder but when I download the file manually from OneDrive, it opens in black color and shows Invalid Image.
var client = new RestClient("https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", Path.GetExtension(originalFileName).GetMimeType());
request.AddHeader("Authorization", "Bearer " + GetAccessToken());
request.AddFile("content", System.IO.File.ReadAllBytes(filePath), originalFileName);
var response = client.Execute(request);
I really do not know what mistake I am making in here. May you please help me?
Inspired from this SO answer
I need to change it to HttpClient from RestClient. After change the code will like:
using (var client = new HttpClient())
{
var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());
byte[] sContents = System.IO.File.ReadAllBytes(filePath);
var content = new ByteArrayContent(sContents);
var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}

Authenticating with outside REST api

I'm trying to use an outside REST api that was recently developed by an outside company. They provided me with some Java code to show how to connect to it and retrieve data, but so far I'm having no luck getting any results with C# MVC 4. Currently I cannot even login to the system. The credentials are correct, and using examples that I've found elsewhere don't seem to help.
The Java code that works:
try{
ClientConfig client_config = new ClientConfig();
client_config.register(new HttpBasicAuthFilter(username,password));
Client client = ClientBuilder.newClient(client_config);
WebTarget web_target = client.target(url);
Invocation.Builder invocation_builder = web_target.request();
//This GET does the login with basic auth
this.populateFromResponse(invocation_builder.get());
}
catch(final Exception e){
System.out.println(e.toString());
}
Ok, there are objects here that I don't have in C#, clearly, but everything I've tried has yet to work.
I have tried placing info in the header of the request:
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
No cookies, also tried:
request.Credentials = new NetworkCredential(username, password);
Nothing. If I try this, receive no cookies, and still attempt to access any other part of the api, then I get a 401(Not Authorized) error. The request.GetResponse(); doesn't throw an error if I'm simply trying to access the login section of the api.
I'm new to REST services, so any help/direction is appreciated. I'm only asking because everything else that I've looked up doesn't seem to work.
Edit
Here's how I'm building the request:
var request = (HttpWebRequest)WebRequest.Create(HostUrl + path);
request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
var response = request.GetResponse() as HttpWebResponse;
Edit #2
Thanks to #BrianP for his answer, which led me to solving this issue a little better. Below is my current code (along with additions to collect cookies from the response taken from this question) that finally returned a success code:
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
client.BaseAddress = new Uri(HostUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(HostUrl + "/api/login/").Result;
var responseCookies = cookies.GetCookies(new Uri(HostUrl)).Cast<Cookie>()
Please let me know if there are improvements for this code. Thanks again!
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
Pulled from: http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html
EDIT: Based on Comments.
HttpRequestMessage requestMsg = new HttpRequestMessage();
string data = username + ":" + password;
requestMsg.Headers.Authorization = new AuthenticationHeaderValue("Basic", data);

WebView display Loginscreen again after login via basic authentication with HttpClient

i am connecting to a server with basic authentication and after that i am calling the URL in Webview with following code:
WebView.Source(new Uri("https:(//UrlHere"));
The Webview Puts up a Login-Window, but i am already logged in. Why is this happening?
How can i prevent this?
The way i a authenticate to the server:
private async void HttpClientCall(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(this.GetType().Name + ": HTTPCLientCall entered");
//System.Diagnostics.Debug.WriteLine("NetworkConnectivityLevel.InternetAccess: " + NetworkConnectivityLevel.InternetAccess);
//use this, for checking the network connectivity
System.Diagnostics.Debug.WriteLine("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//var msg = new Windows.UI.Popups.MessageDialog("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//msg.ShowAsync();
HttpClient httpClient = new HttpClient();
// Assign the authentication headers
httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("username", "password");
System.Diagnostics.Debug.WriteLine("httpClient.DefaultRequestHeaders.Authorization: " + httpClient.DefaultRequestHeaders.Authorization);
// Call out to the site
HttpResponseMessage response = await httpClient.GetAsync("https://URLHere");
System.Diagnostics.Debug.WriteLine("response: " + response);
string responseAsString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine("response string:" + responseAsString);
//WebViewP.Source = new Uri("https://URLHere");
}
public AuthenticationHeaderValue CreateBasicHeader(string username, string password)
{
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
String logindata = (username + ":" + password);
System.Diagnostics.Debug.WriteLine("AuthenticationHeaderValue: " + new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)));
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
So how can i solve that?
This is a long shot, but you could try setting the credentials on HttpClientHandler and hope that the WebView picks it up.
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username,password);
HttpClient httpClient = new HttpClient(handler);
The problem is the WebView is making it's own independent request, so any requests you make with HttpClient are independent of those made by the WebView

Categories

Resources