I am developing (so new at it) an application with Windows Forms C# in Visual Studio and I need to get a specific commit from a GitLab project.
I have seen many examples about for GitHub. I have tried this way (do not know if is the correct one):
Download repository at a particular commit using the 7-digit SHA1:
var Token = "xxxx";
var url = "http://{my_domain}/{user}/{project_name}/repository/archive/{shor_id}.zip";
var path = #"C:\GitLab\My_Projects";
try
{
using (var client = new System.Net.Http.HttpClient())
{
var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", Token);
credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
var contents = client.GetByteArrayAsync(url).Result;
System.IO.File.WriteAllBytes(path, contents);
}
}
catch (System.UnauthorizedAccessException)
{
backgroundWorker1.CancelAsync();
Console.WriteLine("Problem downloading");
}
But I get this error:
'System.UnauthorizedAccessException' in mscorlib.dll. Access denied to 'C:\GitLab\My_Projects'.
As I said before, I am new at it and probably may have said something stupid, sorry in advance.
If someone knows about the subject, I would love to explain or help me with this concept.
Finally, I achived the solution. I took another direction using GitLab API.
If someone would like to look at the result I arrived, here you have the code:
var url_sha = $"http://{my_gitlab_domain}/api/v4/projects/{id_project}/repository/archive.zip?
private_token={my_token}&sha={short_id_commit}";
var client = new HttpClient();
var response = await client.GetAsync(url_sha);
var local_path = #"C:\GitLab\My_Projects";
using (var stream = await response.Content.ReadAsStreamAsync())
{
var fileInfo = new FileInfo(local_path + ".zip");
using (var fileStream = fileInfo.OpenWrite())
{
await stream.CopyToAsync(fileStream);
}
}
Related
i am using MimeKit 3.2.0 and Google.Apis.Gmail.v1 1.57.0.2622.
i keep getting error `System.FormatException: Failed to parse message headers.`
Here's the code below, what is the problem here? i've searched everywhere and couldn't find a solution
The service here is a GmailService object, totally functional
var requestMessage = _service.Users.Messages.Get("me", message.Id);
requestMessage.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
await using var rawStream = await requestMessage.ExecuteAsStreamAsync();
var mimeMsg = MimeMessage.Load(rawStream);
i also tried to inject the stream into a Filtered stream object , but that didn't help
it looks like this
using (var filtered = new FilteredStream(rawStream))
{
filtered.Add(DecoderFilter.Create(ContentEncoding.Base64));
var mimeMsg = await MimeMessage.LoadAsync(filtered);
}
I've been trying to get a grasp on C#/.NET and UWP applications. At the moment I'm trying to follow this guide to complete CRUD operations against my database. So far so good, but when I come to the part where I want to create I run into som troubles. The code below is where I create a new object and try to post it to the database. Piece in this context is a book.
var newPiece = new Piece
{
PieceTitle = Title.Text,
PieceAuthor = Author.Text,
PieceIsbn = Isbn.Text,
PieceDescription = Description.Text
};
using (var client = new HttpClient())
{
var content = JsonConvert.SerializeObject(newPiece);
Task task = Task.Run(async () =>
{
var data = new HttpFormUrlEncodedContent(
new Dictionary<string, string>
{
["value"] = content
});
await client.PostAsync(App.BaseUri, data);
});
task.Wait();
}
The problem here is that because I am using both HttpClient() and HttpFormUrlEncodedContent() VS is telling me that HttpClient() is "an ambiguous reference" and that I need to specify if it belongs to System.Net.Http; or Windows.Web.Http;. If I choose System.Net.Http then it tells me that Argument 1 in PostAsync() "cannot be converted from 'System.Uri' to 'string'", and that Argument 2 "cannot convert from 'Windows.Web.Http.HttpFormUrlEncodedContent' to 'System.Net.Http.HttpContent'"
If I try letting HttpClient() use Windows.Web.Http; then it doesn't give me any errors while compiling, but after the object has been created and posted it displays as null in my tables.
System.Net.Http name space has FormUrlEncodedContent. You can use that.
var newPiece = new Piece
{
PieceTitle = Title.Text,
PieceAuthor = Author.Text,
PieceIsbn = Isbn.Text,
PieceDescription = Description.Text
};
using (var client = new System.Net.Http.HttpClient()) {
var json = JsonConvert.SerializeObject(newPiece);
var content = new System.Net.Http.FormUrlEncodedContent(
new Dictionary<string, string> {
["value"] = json
});
await client.PostAsync(App.BaseUri, content);
}
Should also try to avoid mixing async and blocking calls like .Wait() or .Result as they can lead to deadlocks.
It was also indicated that the data when received is null. This could be an indication that the format being used does not match the expected format.
Try using a different format. For example the following sends JSON content.
using (var client = new System.Net.Http.HttpClient()) {
var json = JsonConvert.SerializeObject(newPiece);
var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
await client.PostAsync(App.BaseUri, content);
}
I am working on a Windows to UWP app. A web service exists that when called (GET), returns a file. When the web service is triggered using a browser, it successfully downloads a file on the browser.
On the UWP app, I am using Windows.Web.Http to call the web service. I need to save get the file sent by the web service and save it on the device.
I currently have the following code. Not sure how to get the result from the web service and save to the file.
public async Task DownloadFile(string WebServiceURL, string PathToSave)
{
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
using (IInputStream inputStream = await result.Content.ReadAsInputStreamAsync())
{
//not sure if this is correct and if it is, how to save this to a file
}
}
Using System.Web.Http, I am able to easily do this using the following:
Stream stream = result.Content.ReadAsStreamAsync().Result;
var fileStream = File.Create(PathToSave);
await stream.CopyToAsync(fileStream);
fileStream.Dispose();
stream.Dispose();
However, using Windows.Web.Http, I am not sure how I can do this. Please help!
this what you looking for?
like this?
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
//not sure if this is correct and if it is, how to save this to a file
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.tmp", CreationCollisionOption.GenerateUniqueName);
using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await result.Content.WriteToStreamAsync(filestream);
await filestream.FlushAsync();
}
Is there a simple API using which I can get the size of an ADLS directory? preferably something in C#, but it's not a must.
We could use the Get Content Summary of a Directory REST API to do that.
curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=GETCONTENTSUMMARY"
C# code demo
var url = "https://tomdatalake.azuredatalakestore.net/webhdfs/v1/tomtest?api-version=2017-08-01&op=GETCONTENTSUMMARY";
var token = "eyJ0eX.....";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var result = client.GetAsync(url).Result;
var data = result.Content.ReadAsStringAsync().Result;
}
I also test it with PostMan.
Yes, you can use DataLakeStoreFileSystemManagementClient.FileSystem.GetContentSummary:
var client = new DataLakeStoreFileSystemManagementClient(credentials);
ContentSummaryResult result = client.FileSystem.GetContentSummary(dataLakeAccount, path);
var dirSize = result.ContentSummary.Length;
Documentation.
I want to, in code behind, call a Web Api I've built and save some data that I have stored in the following JObject:
var json = new JObject(
new JProperty("firstName", txtFirstName.Text),
new JProperty("lastName", txtLastName.Text),
new JProperty("companyName", txtCompanyName.Text),
new JProperty("email", txtEmail.Text),
new JProperty("phone", txtPhone.Text)
);
Problem is, I'm not sure the best way to go about this. I've found a plethora of examples that are close to the answer, but not quite what I'm looking for. So, how would someone construct an http call to a web api(in C#) and have the aforementioned JObject be posted in the body of the message? I wouldn't necessarily need anything returned, except maybe a generic success or failure message. I appreciate any help given.
Here's an example using System.Net.HttpClient
string jsonText = json.ToString();
using (var client = new HttpClient())
{
var httpContent = new StringContent(jsonString);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage message = await client.PostAsync("http://myWebUrl/send", httpContent);
}
I ended up changing the json into a .net object and got my problem solved.
using System.Net.Http;
using System.Net.Http.Headers;
var userData = new User()
{
firstName = txtFirstName.Text,
lastName = txtLastName.Text,
companyName = txtCompanyName.Text,
email = txtEmail.Text,
phone = txtPhone.Text
};
client.BaseAddress = new Uri("http://yourBaseUrlHere");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("requestUrlHere", user);
if (response.IsSuccessStatusCode)
{
//Success code
}