Syntax error in HAP SetAttributeValue or mistake in code - c#

imgs = doc.DocumentNode.SelectNodes("//img");
HtmlNode img in imgs
string imageIdString = image.Id.ToString();
img.SetAttributeValue("src", "/ImageBrowser/ImageById/" + imageIdString);
I get a proper value for the ID, but the img source stays unchanged and I can't find why
tried to manage it like here:
Need to replace an img src attrib with new value
Edit1: The requested code
string input = sectionEditModel.Content;
string htmlstring = sectionEditModel.Content;
string htmlstringdecoded = HttpUtility.HtmlDecode(htmlstring);
HtmlDocument doc = new HtmlDocument();
List<string> urls = new List<string>();
DbImgBrowser.Models.Image image = null;
doc.LoadHtml(htmlstringdecoded);
var files = new FilesRepository();
HtmlNodeCollection imgs = new HtmlNodeCollection(doc.DocumentNode);
imgs = doc.DocumentNode.SelectNodes("//img");
if (imgs != null && imgs.Count > 0)
{
foreach (HtmlNode img in imgs)
{
HtmlAttribute srcs = img.Attributes[#"src"];
urls.Add(srcs.Value);
{
foreach (string Value in urls){
string AttrVal = img.GetAttributeValue("src", null);
if(AttrVal.Contains("base64"))
{
byte[] data = Convert.FromBase64String(Value.Substring(Value.IndexOf(",") + 1));
var pFolder = files.GetFolderByPath(string.Empty);
if (pFolder != null)
{
image = new DbImgBrowser.Models.Image()
{
Name = Guid.NewGuid().ToString(),
Folder = pFolder,
Image1 = data
};
files.Db.Images.Add(image);
files.Db.SaveChanges();
string imageIdString = image.Id.ToString();
img.SetAttributeValue("src", "/ImageBrowser/ImageById/" + imageIdString);
files.Db.SaveChanges();
}
}
Edit2: Example paths: before base64 example image
Path by Url example /ImageBrowser/Image?path=Test2.PNG
Wanted Result src="ImageBrowser/ImageById/"ID" (1-1000)
Edit3: Still all src is not changed

The answer is very simple.
I was on a local doc but I had to return it to the content and save the section
SectionsRepository.SaveSection(Section sec)

Related

Set img src with Html Agility Pack

I have an input string which is html. It contains images and I want to change the src property on the img
My code so far is as below:
if (htmlStr.Contains("img"))
{
var html = new HtmlDocument();
html.LoadHtml(htmlStr);
var images = html.DocumentNode.SelectNodes("//img");
if (images != null && images.Count > 0)
{
for (int i = 0; i < images.Count; i++)
{
string imageSrc = images[i].Attributes["src"].Value;
string newSrc = "MyNewValue";
images[i].SetAttributeValue("src", newSrc);
}
}
//htmlStr= ???
}
return htmlStr;
What I am missing is how to update the htmlStr I am returning with the newSrc value each image.
As far as I can tell, you have two options:
// Will give you a raw string.
// Not ideal if you are planning to
// send this over the network, or save as a file.
var updatedStr = html.DocumentNode.OuterHtml;
// Will let you write to any stream.
// Here, I'm just writing to a string builder as an example.
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
html.Save(writer);
}
// These two methods generate the same result, though.
Debug.Assert(string.Equals(updatedStr, sb.ToString()));

How to store links in DB number wise?

This is my code,
HtmlNodeCollection categorynode = null;
categorynode = doc.DocumentNode.SelectNodes("//div[#class='parentMenu arrow']");//"//div[#class='drop-menu']//a[#href]"
if (categorynode != null)
{
foreach (HtmlNode Node in categorynode)
{
string Html = Node.InnerHtml;
if (Html != null)
{
HtmlDocument Node2 = new HtmlDocument();
Node2.LoadHtml(Html);
foreach (HtmlNode link in Node2.DocumentNode.SelectNodes("//a"))
{
HtmlAttribute att = link.Attributes["href"];
Console.WriteLine(new Regex(#"(?<=[\?&]id=)\d+(?=\&|\#|$)").Match(att.Value).Value);
string Links = att.Value;
Modelclass _ms = new Modelclass();
_ms.link = Links;
_ms.Name = "Apple";
_ms.CID = 0;
_ms.Type = "Categories";
Controller cc = new Controller();
cc.InsertCategories(_ms);
}
}
}
I have tables in my DB were I have set an ID as a primary key but when I store all these links in DB it should be sorted but it is like 1 2 3 9 7 6 ,
is there something wrong with my code or what should i do please guide me
keep an ID in your table where you are storing your links and set ID to auto increment that will help may be

Dynamically assign ContentId and send email with embedded images in c#

How to assign src with content id in dynamically in c#
How to embed multiple images in email body using .NET
But not getting good idea.
When I submit then I would able to get html source and how to assign cid dynmically
> >
> > <html>><body><img src="~/Upload/1.jpg"><br><img src="~/Upload/1.jpg" /><br><img
> src="~/Upload/3.jpg"/><br><br>
> > thanks!!!</body></html>
Need to convert
I want to send email with multiple images
<html>><body><img src=cid:c1 /><br><img src=cid:c2 /><br><img
src=cid:c3/><br><br>
thanks!!!</body></html>
then
if (htmlString == null) return null;
var doc = new HtmlDocument();
doc.LoadHtml(htmlString);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
if (nodes == null) return null;
foreach (HtmlNode node in nodes)
{
if (node.Attributes.Contains("src"))
{
string data = node.Attributes["src"].Value;
string base64Data = Regex.Match(data, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
if (base64Data != "")
{
string cid = Guid.NewGuid().ToString();
byte[] binData = Convert.FromBase64String(base64Data);
var stream = new MemoryStream(binData);
string contenttype = "image/" +
Regex.Match(data, #"data:image/(?<type>.+?);(?<data>.+)").Groups["type"]
.Value;
var inline = new Attachment(stream, new ContentType(contenttype));
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = cid;
inline.ContentType.MediaType = contenttype;
mailMessage.Attachments.Add(inline);
node.Attributes["src"].Value = "cid:" + cid;
}
}
Any good idea to make dynmically assign and add Linked resources and alternative view dynamically,
the given code is workable for static case
string path = System.Web.HttpContext.Current.Server.MapPath("~/images/Logo.jpg"); // my logo is placed in images folder
//var path=""
var logo = new LinkedResource(path);
logo.ContentId = "companylogo";
logo.ContentType = new ContentType("image/jpeg");
//now do the HTML formatting
AlternateView av1 = AlternateView.CreateAlternateViewFromString(
"<html><body><img src=cid:companylogo/>" +
"<br></body></html>" + strMailContent,
null, MediaTypeNames.Text.Html);
//now add the AlternateView
av1.LinkedResources.Add(logo);
//now append it to the body of the mail
msg.AlternateViews.Add(av1);
Here is the complete solution for you.
string inputHtmlContent = "<Your Html Content containing images goes here>";
string outputHtmlContent = string.Empty;
var myResources = new List<LinkedResource>();
if ((!string.IsNullOrEmpty(inputHtmlContent)))
{
var doc = new HtmlDocument();
doc.LoadHtml(inputHtmlContent);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
if (nodes !=null)
{
foreach (HtmlNode node in nodes)
{
if (node.Attributes.Contains("src"))
{
string data = node.Attributes["src"].Value;
string imgPath = System.Web.HttpContext.Current.Server.MapPath(data);
var imgLogo = new LinkedResource(imgPath);
imgLogo.ContentId = Guid.NewGuid().ToString();
imgLogo.ContentType = new ContentType("image/jpeg");
myResources.Add(imgLogo);
node.Attributes["src"].Value = string.Format("cid:{0}", imgLogo.ContentId);
outputHtmlContent = doc.DocumentNode.OuterHtml;
}
}
}
else
{
outputHtmlContent = inputHtmlContent;
}
AlternateView av2 = AlternateView.CreateAlternateViewFromString(outputHtmlContent,
null, MediaTypeNames.Text.Html);
foreach (LinkedResource linkedResource in myResources)
{
av2.LinkedResources.Add(linkedResource);
}
var msg = new MailMessage();
msg.AlternateViews.Add(av2);
msg.IsBodyHtml = true;
<-- Enter Other required Informations and send mail -->
...
}

How to click buttons/links which are in iframe? (GeckoFx)

This code access iframe and gets me source code.
string content = null;
var iframe = browser.Document.GetElementsByTagName("iframe").FirstOrDefault() as Gecko.DOM.GeckoIFrameElement;
if (iframe != null)
{
var html = iframe.ContentDocument.DocumentElement as GeckoHtmlElement;
if (html != null)
content = html.OuterHtml;
textBox1.Text = content;
}
I tried puting some code
string content = null;
var iframe = browser.Document.GetElementsByTagName("iframe").FirstOrDefault() as Gecko.DOM.GeckoIFrameElement;
if (iframe != null)
{
var html = iframe.ContentDocument.DocumentElement as GeckoHtmlElement;
if (html != null)
content = html.OuterHtml;
textBox1.Text = content;
GeckoElementCollection elements = browser.Document.GetElementsByName("username");
foreach (var element in elements)
{
GeckoInputElement input = (GeckoInputElement)element;
input.Value = "Auto filled!";
}
}
But it wont work as code dont find elements. Any ideas?
Tried searching google for any iframe examples but seems that there isnt any good documentation for it.
Why are you looking for in the main document? You should look for in a frame.
string content = null;
var iframe = browser.Document.GetElementsByTagName("iframe").FirstOrDefault() as Gecko.DOM.GeckoIFrameElement;
if (iframe != null)
{
var html = iframe.ContentDocument.DocumentElement as GeckoHtmlElement;
if (html != null)
content = html.OuterHtml;
textBox1.Text = content;
GeckoElementCollection elements = iframe.ContentDocument.GetElementsByName("username");
foreach (var element in elements)
{
GeckoInputElement input = (GeckoInputElement)element;
input.Value = "Auto filled!";
}
}

How can i get a List<string> of images from a website link?

I want to build a List of images from a website link and then later also to save/download the images to the hard disk.
This is how im getting the links from a website/url:
private List<string> getLinks(HtmlAgilityPack.HtmlDocument document)
{
List<string> mainLinks = new List<string>();
var linkNodes = document.DocumentNode.SelectNodes("//a[#href]");
if (linkNodes != null)
{
foreach (HtmlNode link in linkNodes)
{
var href = link.Attributes["href"].Value;
if (href.StartsWith("http://") ==true || href.StartsWith("https://") ==true || href.StartsWith("www.") ==true) // filter for http
{
mainLinks.Add(href);
}
}
}
return mainLinks;
}
Then im using in this test function to build a List of all the links from the url:
private List<string> test(string url, int levels, DoWorkEventArgs eve)
{
HtmlWeb hw = new HtmlWeb();
List<string> webSites;
try
{
doc = hw.Load(url);
webSites = getLinks(doc);
//retriveImages();
So webSites wich is a List will have all the link from the main website url fro example if its google.com then in webSites i will have 19 items each one is a link from google.com
And retrieveImages() is:
private void retrieveImages()
{
var nodes = doc.DocumentNode.SelectNodes("//img");
foreach (var node in nodes)
{
List<string> images = new List<string>();
images.Add(node.Name);
}
}
And retrieveImages() for sure is not good code and also is not working. If im using it moving the // and calling the retrieveImages() nothing happened webSites List is empty.
What i want to do is in the function retrieveImages() to build a list of images from the curretn site/link im in now and then also to download the images to the hard disk the images in the List i built.
private List<string> retrieveImages()
{
List<string> imgList = new List<string>();
HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm"); //or whatever HTML file you have
HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img[#src]");
if (imgs == null) return new List<string>();
foreach (HtmlNode img in imgs)
{
if (img.Attributes["src"] == null)
continue;
HtmlAttribute src = img.Attributes["src"];
imgList.Add(src.Value);
//Do something with src.Value such as Get the image and save it locally
// Image img = GetImage(src.Value)
// img.Save(aLocalFilePath);
}
return imgList;
}
private Image GetImage(string url)
{
System.Net.WebRequest request = System.Net.WebRequest.Create(url);
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
Bitmap bmp = new Bitmap(responseStream);
responseStream.Dispose();
return bmp;
}

Categories

Resources