How to download a picture from the site? - c#

I am trying to make a parser based on "AngleSharp".
I use the following code for download:
var itemsAttr = document.QuerySelectorAll("img[id='print_user_photo']");
string foto_url = itemsAttr[0].GetAttribute("src");
string path = pathFolderIMG + id_source + ".jpg";
WebClient webClient = new WebClient();
webClient.DownloadFile(foto_url, path);
For pages "type_1" -link - the code works.
For pages "type_2" - link - the code does not work.
How to download photos for pages "type_2"?

Please read the AngleSharp documentation carefully, e.g., looking at the FAQ we get:
var imageUrl = #"https://via.placeholder.com/150";
var localPath = #"g:\downloads\image.jpg";
var download = context.GetService<IDocumentLoader>().FetchAsync(new DocumentRequest(new Url(imageUrl)));
using (var response = await download.Task)
{
using (var target = File.OpenWrite(localPath))
{
await response.Content.CopyToAsync(target);
}
}
where we used a configuration like
var config = Configuration.Default.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }).WithCookies();
var context = BrowsingContext.New(config);

Related

Get "initial Key" value from .mp3 file

I can't find a way to read the "initial key" property from an mp3 file to use the song information in my application.
I've already tried to find libraries which do the job for me. I found TagLib# which is a very cool solution for getting tags/properties of different file formats. (including mp3).
I can use this library to get the title, the artist, the beats per minute and so on.. only the initial key value is missing for my use which isn't featured, unfortunately.
I also tried to find other solutions which support the initial key property but I haven't found one.
I already found a source which seems to address the same issue and solves it with using TagLib#, but I can't figure out how he solved that problem.
Use Ctrl + F and search for "Initial" to find the code block.
You can find the link here
I'll post a short part of my code which can be used to determine different info about one song in a pattern like this: (["bpm"]"title" - "artist")
var file = TagLib.File.Create(filePath);
return $"[{file.Tag.BeatsPerMinute}]{file.Tag.Title} - {file.Tag.FirstPerformer}";
Thanks for any help or recommendations in advance! :)
Try this:
public static void Main(string[] args)
{
var path = …
var file = TagLib.File.Create (path);
var id3tag = (TagLib.Id3v2.Tag)file.GetTag (TagTypes.Id3v2);
var key = ReadInitialKey (id3tag);
Console.WriteLine ("Key = " + key);
}
static string ReadInitialKey(TagLib.Id3v2.Tag id3tag)
{
var frame = id3tag.GetFrames<TextInformationFrame>().Where (f => f.FrameId == "TKEY").FirstOrDefault();
return frame.Text.FirstOrDefault() ;
}
On Windows 10 you can also use:
async Task<string> ReadInitialKey(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
Windows.Storage.FileProperties.MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync();
var props = await musicProperties.RetrievePropertiesAsync(null);
var inkp = props["System.Music.InitialKey"];
return (string)inkp;
}
See here for documentation on MusicProperties object and here for the valid music properties.
You can use the Shell to read all MP3 properties.
Test on Windows 10, VS 2015 =>
// Add Reference Shell32.DLL
string sFolder = "e:\\";
string sFile= "01. IMANY - Don't Be so Shy (Filatov & Karas Remix).mp3";
List<string> arrProperties = new List<string>();
Shell objShell = new Shell();
Folder objFolder;
objFolder = objShell.NameSpace(sFolder);
int nMaxProperties = 332;
for (int i = 0; i < nMaxProperties; i++)
{
string sHeader = objFolder.GetDetailsOf(null, i);
arrProperties.Add(sHeader);
}
FolderItem objFolderItem = objFolder.ParseName(sFile);
if (objFolderItem != null)
{
for (int i = 0; i < arrProperties.Count; i++)
{
Console.WriteLine((i + ('\t' + (arrProperties[i] + (": " + objFolder.GetDetailsOf(objFolderItem, i))))));
}
}
Just borrowing code from nuget: mono TaglibSharp:
var tfile = TagLib.File.Create(#"..");
string initialKey = null;
if (tfile.GetTag(TagTypes.Id3v2) is TagLib.Id3v2.Tag id3v2)
{
/*
// test: add custom Initial Key tag
var frame = TextInformationFrame.Get(id3v2, "TKEY", true);
frame.Text = new[] {"qMMM"};
frame.TextEncoding = StringType.UTF8;
tfile.Save();
*/
var frame = TextInformationFrame.Get(id3v2, "TKEY", false);
initialKey = frame?.ToString();
}

Calling WEB API to download excel file

below is C# WEB API Code to generate Excel :
public class FileExportController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var callerContext = CallerContext.DefaultCallerContext;
ReportingInput userInput = new ReportingInput();
userInput.ClientOneCode = "AVON";
string handle = Guid.NewGuid().ToString();
var #event = new GetJobReprotDataBlEvent(callerContext, userInput);
WebApiApplication.ApplicationInitializerObj.EventBus.Publish(#event);
XLWorkbook wb = new FileExportEngine().ExportExcel(#event.ReportData); //this is returning XLWorkbook
string fileName = "JobReport_" + DateTime.Now.ToString("yyyy -MM-dd HH':'mm':'ss") + ".xlsx";
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
When I call this API from browser, I am able to generate excel file.
http://localhost/ETLScheduler/api/FileExport -- this is working when hit direct in browser
Now I want to use consume this API in angular 5 application.I have a button.On click button I call the component method downloadFile() to download the file.
Below is the code :
downloadReport() {
this._service.downloadJobReport('AVON');
}
where downloadJobReport() is in my service file as below :
downloadJobReport(clientCode: string) {
return this._http.get(APIs.downloadJobReport);
}
When I am running the application and click on Download button, I am getting nothing, I mean file is not downloading. Can anyone have idea,how should I update my angular code to consume the API.
Thanks in advance.
As you mentioned above in comments you are using below angular code to download file:
downloadFile(data: Blob) {
const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const blob = new Blob([data], { type: contentType });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
As I also have tried this code, it is working in chrome browser but not working in IE and edge.
You may update your method somthing like below:
var downloadFile=function (file_name, content) {
var csvData = new Blob([content], { type: 'text/csv' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
window.navigator.msSaveOrOpenBlob(csvData, file_name);
} else { // for Non-IE (chrome, firefox etc.)
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var csvUrl = URL.createObjectURL(csvData);
a.href = csvUrl;
a.download = file_name;
a.click();
URL.revokeObjectURL(a.href)
a.remove();
}
};
you can refer below link for more information:
Open links made by createObjectURL in IE11
Problem is, that Angular expects JSON as a result. You need to configure your GET request so, that it expects something different.
public downloadJobReport(clientCode: string)): Observable<Blob> {
return this._http.get(APIs.downloadJobReport, { responseType: 'blob' });
}
Just a tiny question, you pass an argument clientCode to the downloadJobReport, but never use it. Maybe wise to leave that out?

Get image download url from firebase storage Xamarin

Im trying to get the image url from a photo I uploaded to firebase storage so I can store the reference to the image in another table which will allow me to be able to display the image elsewhere throughout the app.
I currently have
private void UploadPhoto()
{
if (filePAth != null)
{
progressDialog = new ProgressDialog(this);
progressDialog.SetTitle("Uploading...");
progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
progressDialog.Show();
var images = storageRef.Child("images/" + Guid.NewGuid().ToString());
images.PutFile(filePAth)
.AddOnProgressListener(this)
.AddOnSuccessListener(this)
.AddOnFailureListener(this);
}
}
public async void OnSuccess(Java.Lang.Object result)
{
try
{
var newImageDetails = storageRef.Child("images" + "/" + filePAth);
Photo photos = new Photo();
photos.categoryName = spinner.SelectedItem.ToString();
photos.photoId = newImageDetails.Name;
photos.ImageUrl = storageRef.DownloadUrl.ToString();
photos.tagName = addTag.Text;
if (user != null)
{
var uid = user.Uid;
//set the users id to the category
photos.uid = uid;
}
var firebase = new FirebaseClient(FirebaseURL);
var item = await firebase.Child("photos").PostAsync(photos);
}
}
The storageref.DownloadUrl does not give me the correct url
This is what I am looking for
I think that the trouble is Guid.NewGuid().
It generates a new code each time you insert a new image and your storageref points to it (image/GUID code).
In your OnSuccess you get image info from "images/" + filePath, that's different from upload path.
Why you use a new GUID? You can't determinate it, it will create a different path each time.
Consider then that your download url contains the media token too, it's not simply the clean path as you expect
I got a solution in debugging mode
i saw the downloadurl's properties and found the Scheme and SchemeSpecificPart
Scheme = "https"
SchemeSpecificPart = "//firebasestorage.googleapis.com/v0/b/maplog-e4ba5.appspot.com/o/-L0AMbihF23YKxsL1uss?alt=media&token=5c7ccef1-c857-4982-a288-fded2f0ff1aa"
so here is my code:
void IOnSuccessListener.OnSuccess(Java.Lang.Object result)
{
var snapShot = (UploadTask.TaskSnapshot)result;
string imgUrl = snapShot.DownloadUrl.Scheme
+ ":"
+ snapShot.DownloadUrl.SchemeSpecificPart;
}
and it works! i was looking for the solution :(( but i finally found it myself XD

(C#) How to GET a download url to a certain path?

So let's say I have a download url that when you GET it, it downloads a file.
Now, this file is not a txt or anything, it has no extension.
How would I code a GET request to the URL, but make it download to a certain path?
EDIT: Also, how would I convert it to a TXT and read from the txt afterwards?
NOTE: It's a get request site that instantly downloads the file, not a file on a site you can open in your browser
EDIT 2: It actually returns xml, not the file, sorry
just using a browser downloads it.
What is the real content of that file?
You can try to configure the content-type as "application/octet-stream".
It asks the server for byte content.
If the content is regular text already, you can simply add ".txt" to the file name and you can read it whenever you want.
You do it like this it shouldn't matter if your link has a clear ending like the one I have used. Or if you are really serious about making the GET part explicit use RestSharp. Look now you can even change the file extensions from within the code not that it would matter the least bit. I tossed in some Linq2Xml since you mentioned your file was xml and I thought you possible needed to do something with it.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Xml.Linq;
using System.Linq;
using RestSharp;
namespace Get2File
{
internal class Program
{
private const string FallbackUrl = #"https://gist.github.com/Rusk85/8d189cd35295cfbd272d8c2121110e38/raw/4885d9ba37528faab50d9307f76800e2e1121ea2/example-xml-with-embedded-html.xml";
private string _downloadedContent = null;
private const string FileNameWithoutExtension = "File";
private static void Main(string[] args)
{
var p = new Program();
p.Get2FileWithRestSharp(fileExtensions:".xml");
p.UseLinq2XmlOnFile();
}
private void Get2File(string altUrl = null, string fileExtensions = ".txt")
{
var url = !string.IsNullOrEmpty(altUrl)
? altUrl
: FallbackUrl;
var client = new HttpClient();
var content = client.GetStringAsync(url).Result;
_downloadedContent = content;
var outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{FileNameWithoutExtension}{fileExtensions}");
File.WriteAllText(outputPath, content);
}
private void Get2FileWithRestSharp(string altUrl = null, string fileExtensions = ".txt")
{
var url = !string.IsNullOrEmpty(altUrl)
? altUrl
: FallbackUrl;
var urlAsUri = new Uri(url);
var client = new RestClient(urlAsUri);
var request = new RestRequest(Method.GET);
var content = string.Empty;
var result = client.Execute(request);
content = result.Content;
_downloadedContent = content;
var output = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{FileNameWithoutExtension}{fileExtensions}");
File.WriteAllText(output, content);
}
private void UseLinq2XmlOnFile()
{
XElement xElement = XElement.Parse(_downloadedContent);
var elements = xElement.Elements();
var StringElement = elements.FirstOrDefault(e => e.Name == "String");
var tranlateXAttribute = StringElement.Attributes().FirstOrDefault(attr => attr.Name == "translate");
Debug.WriteLine(tranlateXAttribute.Value);
}
}
}

Cannot Update SharePoint Publishing Page Image

I am trying to update publishing Page image url but somehow after execute query command. its value saved as null
ClientContext targetContext = new ClientContext ("REAL URL");
Microsoft.SharePoint.Client.File targetFile = targetContext.Web.GetFileByServerRelativeUrl ("REAL URL");
var targetPublishingPage = PublishingPage.GetPublishingPage (targetContext, targetFile.ListItemAllFields);
targetContext.Load (targetPublishingPage.ListItem);
targetContext.ExecuteQuery ();
targetFile.CheckOut ();
targetPublishingPage.ListItem["PublishingPageImage"] = "REAL URL";
targetPublishingPage.ListItem.Update ();
targetContext.ExecuteQuery ();
Publishing Image field value is expected to be specified in the folliowing format: <img src='{imageurl}'>
Example
using (var ctx = new ClientContext(webUri))
{
var pageFile = ctx.Web.GetFileByServerRelativeUrl(pageUrl);
var pageItem = pageFile.ListItemAllFields;
pageItem["PublishingPageImage"] = "<img src='/PublishingImages/PageLogo.png'>";
pageItem.Update();
ctx.ExecuteQuery();
}

Categories