I have a text:
Download it directly to the iTunes Store or Android Market. The application is launched for Swedish app store.
I know how to show a hyperlink in RichTextBox:
http://msdn.microsoft.com/en-us/library/ee681613%28v=vs.95%29.aspx
But how can I make this for everyone link in this code?
You should parse the string maybe with something like RegEx or using a library like html agility pack. This extension method should work, letting you just call richTextBlock.SetLinkedText(htmlFragment);
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
public static class RichTextBlockExtensions
{
public static void SetLinkedText(this RichTextBlock richTextBlock, string htmlFragment)
{
var regEx = new Regex(
#"\<a\s(href\=""|[^\>]+?\shref\="")(?<link>[^""]+)"".*?\>(?<text>.*?)(\<\/a\>|$)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
richTextBlock.Blocks.Clear();
int nextOffset = 0;
foreach (Match match in regEx.Matches(htmlFragment))
{
if (match.Index > nextOffset)
{
richTextBlock.AppendText(htmlFragment.Substring(nextOffset, match.Index - nextOffset));
nextOffset = match.Index + match.Length;
richTextBlock.AppendLink(match.Groups["text"].Value, new Uri(match.Groups["link"].Value));
}
Debug.WriteLine(match.Groups["text"] + ":" + match.Groups["link"]);
}
if (nextOffset < htmlFragment.Length)
{
richTextBlock.AppendText(htmlFragment.Substring(nextOffset));
}
}
public static void AppendText(this RichTextBlock richTextBlock, string text)
{
Paragraph paragraph;
if (richTextBlock.Blocks.Count == 0 ||
(paragraph = richTextBlock.Blocks[richTextBlock.Blocks.Count - 1] as Paragraph) == null)
{
paragraph = new Paragraph();
richTextBlock.Blocks.Add(paragraph);
}
paragraph.Inlines.Add(new Run { Text = text });
}
public static void AppendLink(this RichTextBlock richTextBlock, string text, Uri uri)
{
Paragraph paragraph;
if (richTextBlock.Blocks.Count == 0 ||
(paragraph = richTextBlock.Blocks[richTextBlock.Blocks.Count - 1] as Paragraph) == null)
{
paragraph = new Paragraph();
richTextBlock.Blocks.Add(paragraph);
}
var run = new Run { Text = text };
var link = new Hyperlink { NavigateUri = uri };
link.Inlines.Add(run);
paragraph.Inlines.Add(link);
}
}
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.richTextBlock.SetLinkedText(
"Download it directly to the iTunes Store or Android Market. The application is launched for Swedish app store.");
}
}
Related
Heyyy.. I'm facing a pickle at the moment.
I need to develop a program and one of it many functions is that it could convert JSON files into CSV files..
Here's what I have :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Aspose;
using Aspose.Cells;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string str = File.ReadAllText(#"C:\cpi\log\V510ResultsInfo\cpi001.json");
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
Aspose.Cells.Cells cells = workbook.Worksheets[0].Cells;
Aspose.Cells.Utility.JsonLayoutOptions importOptions = new
Aspose.Cells.Utility.JsonLayoutOptions();
importOptions.ConvertNumericOrDate = true;
importOptions.ArrayAsTable = true;
importOptions.IgnoreArrayTitle = true;
importOptions.IgnoreObjectTitle = true;
Aspose.Cells.Utility.JsonUtility.ImportData(str, cells, 0, 0, importOptions);
workbook.Save(#"C:\cpi\log\V510ResultsInfo\convertedjson.csv");
}
}
}
The problem is 'Utility' in 'Aspose.Cells.Utility' .. Been breaking my head searching online but it seems that there's nothing much going on about this..
All I know is that 'Aspose.Cells.Utility.JsonLayoutOptions' is in the 'Aspose.Cells.Utility' namespace which falls in the Aspose.Cells.dll.. There's nothing wrong with the DLL everything is great.. Just that the error is still there :
Error Message : The type or namespace name 'Utility' does not exist in the namespace 'Aspose.Cells' (are you missing an assembly reference?)
adding to the provided answer of jayrag I would like to say, that Apsose.Cells.Utility seems to be a newer namespace and therefore it's not available for older versions of Aspose. I just checked it for the version 17 and there it is definitely not available. I also couldn't find any alternative method inside Aspose.Cells which could help you. It simply seems that the json support is still quite new and to use it you would need to upgrade the license. In the light of the prices for aspose you should probably go with a work-around. Hope that helps a bit.
Cheers!
i dont think you need Aspose for create csv
Try this:
private void Button_Click(object sender, RoutedEventArgs e)
{
string json = File.ReadAllText(#"C:\cpi\log\V510ResultsInfo\cpi001.json");
var model = JsonConvert.DeserializeObject<MyModel>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
InsertRecordInCsv(model, "convertedjson");
}
public static void InsertRecordInCsv<T>(T model, string fileName)
{
string targetFolder = #"C:\cpi\log\V510ResultsInfo\";//fileSaveFolderName
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
string targetPath = Path.Combine(targetFolder, fileName + ".csv");
if (!File.Exists(targetPath))
{
var fs = new FileStream(targetPath, FileMode.Create);
fs.Close();
string csvHeader = string.Empty;
foreach (PropertyInfo info in typeof(T).GetProperties())
{
csvHeader += (!string.IsNullOrEmpty(csvHeader) ? "," : string.Empty) + info.Name;
}
csvHeader += Environment.NewLine;
File.AppendAllText(targetPath, csvHeader);
}
StringBuilder sbData = new StringBuilder();
string csvModel = string.Empty;
foreach (PropertyInfo info in typeof(T).GetProperties())
{
string value = GetPropValue(model, info.Name) != null ? GetPropValue(model, info.Name).ToString() : string.Empty;
sbData.Append("\"" + value.Replace("\"", "\"\"") + "\",");
}
sbData.Replace(",", Environment.NewLine, sbData.Length - 1, 1);
File.AppendAllText(targetPath, sbData.ToString());
}
public static object GetPropValue(object src, string propName)
{
if (src.GetType().GetProperty(propName) != null)
return src.GetType().GetProperty(propName).GetValue(src, null);
return new object();
}
i want to extract google result links
My code works it does extract links, but these links are not what i expected to be extracted.
My program would extract links inside the "a href" tag but all links in search result are not Appropriate links , ads link , googles link are also included
what should i do?
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace Search
{
public partial class Form1 : Form
{
// load snippet
HtmlAgilityPack.HtmlDocument htmlSnippet = new HtmlAgilityPack.HtmlDocument();
public Form1()
{
InitializeComponent();
}
private void btn1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] ResultsBuffer = new byte[8192];
string SearchResults = "http://google.com/search?q=" + txtKeyWords.Text.Trim();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbb = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbb);
HtmlNode doc = html.DocumentNode;
foreach (HtmlNode link in doc.SelectNodes("//a[#href]"))
{
//HtmlAttribute att = link.Attributes["href"];
string hrefValue = link.GetAttributeValue("href", string.Empty);
// if ()
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
}
}
}
}
if i want to work with "a href" tag i have to add some condition in If
but i dont know what condition i should use here:
if ()
someplace i read about extracting cite tag not ahref tag anybody can help?
To get the links that are contained in the cite elements, simply access their inner text, like:
HtmlWeb w = new HtmlWeb();
var hd = w.Load("http://www.google.com/search?q=veverke");
var cites = hd.DocumentNode.SelectNodes("//cite");
foreach (var cite in cites)
Console.WriteLine(cite.InnerText);
i'm trying to use htmlagility pack to gain links and tites of results
i have this code
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace Search
{
public partial class Form1 : Form
{
// load snippet
HtmlAgilityPack.HtmlDocument htmlSnippet = new HtmlAgilityPack.HtmlDocument();
public Form1()
{
InitializeComponent();
}
private void btn1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] ResultsBuffer = new byte[8192];
string SearchResults = "http://google.com/search?q=" + txtKeyWords.Text.Trim();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbb = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbb);
HtmlNode doc = html.DocumentNode;
foreach (HtmlNode link in doc.SelectNodes("//a[#href]"))
{
//HtmlAttribute att = link.Attributes["href"];
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
}
}
}
}
this code returns result links for a query i want to get title tag for each link too how can i get title for each links?
anybody can help?
If, by 'title', you mean the displayed text of the link, then you can get it from InnerText property of each HtmlNode link :
foreach (HtmlNode link in doc.SelectNodes("//a[#href]"))
{
.....
var title = link.InnerText.Trim();
}
This will give output: links and titles of the links. This will not return the anchor text of links. You will get only the title of each link.
foreach (HtmlNode link in doc.SelectNodes("//a[#href]"))
{
HtmlWeb htmlWeb = new HtmlWeb();
HtmlAgilityPack.HtmlDocument htmlDocument = htmlWeb.Load(link);
var title = htmlDocument.DocumentNode.SelectSingleNode("html/head/title").InnerText;
}
I need a regex pattern for finding links in a string (with HTML code) to get the links with file endings like .gif or .png
Example String:
picture.png
For now I get everything between the " " and the text between the <a> and </a>.
I want to get this:
Href = //site.com/folder/picture.png
String = picture.png
My code so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace downloader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
string s = gethtmlcode(url);
foreach (LinkItem i in LinkFinder.Find(s))
{
richTextBox1.Text += Convert.ToString(i);
}
}
static string gethtmlcode(string url)
{
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString(url);
return htmlCode;
}
}
public struct LinkItem
{
public string Href;
public string Text;
public override string ToString()
{
return Href + "\n\t" + Text + "\n\t";
}
}
static class LinkFinder
{
public static List<LinkItem> Find(string file)
{
List<LinkItem> list = new List<LinkItem>();
// 1.
// Find all matches in file.
MatchCollection m1 = Regex.Matches(file, #"(<a.*?>.*?</a>)",
RegexOptions.Singleline);
// 2.
// Loop over each match.
foreach (Match m in m1)
{
string value = m.Groups[1].Value;
LinkItem i = new LinkItem();
// 3.
// Get href attribute.
Match m2 = Regex.Match(value, #"href=\""(.*?)\""",
RegexOptions.Singleline);
if (m2.Success)
{
i.Href = m2.Groups[1].Value;
}
// 4.
// Remove inner tags from text.
string t = Regex.Replace(value, #"\s*<.*?>\s*", "",
RegexOptions.Singleline);
i.Text = t;
list.Add(i);
}
return list;
}
}
}
}
I can suggest using HtmlAgilityPack for this task. Install using Manage NuGet Packages for Solution menu, and add the following method:
/// <summary>
/// Collects a href attribute values and a node values if image extension is jpg or png
/// </summary>
/// <param name="html">HTML string or an URL</param>
/// <returns>A key-value pair list of href values and a node values</returns>
private List<KeyValuePair<string, string>> GetLinksWithHtmlAgilityPack(string html)
{
var result = new List<KeyValuePair<string, string>>();
HtmlAgilityPack.HtmlDocument hap;
Uri uriResult;
if (Uri.TryCreate(html, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp)
{ // html is a URL
var doc = new HtmlAgilityPack.HtmlWeb();
hap = doc.Load(uriResult.AbsoluteUri);
}
else
{ // html is a string
hap = new HtmlAgilityPack.HtmlDocument();
hap.LoadHtml(html);
}
var nodes = hap.DocumentNode.SelectNodes("//a");
if (nodes != null)
foreach (var node in nodes)
if (Path.GetExtension(node.InnerText.Trim()).ToLower() == ".png" ||
Path.GetExtension(node.InnerText.Trim()).ToLower() == ".jpg")
result.Add(new KeyValuePair<string,string>(node.GetAttributeValue("href", null), node.InnerText));
return result;
}
Then, use it as (I am using a dummy string, just for demo)
var result = GetLinksWithHtmlAgilityPack("picture.pngpicture.bmp");
Output:
Or, with a URL, something like:
var result = GetLinksWithHtmlAgilityPack("http://www.google.com");
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Printing;
using System.IO.Ports;
namespace Printer
{
public partial class portname : Window
{
PrintServer server = new PrintServer();
public portname()
{
this.InitializeComponent();
foreach (PrintQueue queue in server.GetPrintQueues())
{
com_pinter.Items.Add(queue.FullName);
}
var DefaultPrinter = new LocalPrintServer().DefaultPrintQueue;
string default_name=DefaultPrinter.FullName;
txt_dpn.Text = "Default printe is " + " " + default_name.ToUpper();
string default_port = DefaultPrinter.QueuePort.Name;
txt_pn.Text = "PortName is" + " " + default_port.ToUpper();
}
private void com_pinter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (PrintQueue queue in server.GetPrintQueues())
{
string selecteditem = com_pinter.SelectedItem.ToString();
string portname = queue.FullName;
SerialPort mySerialPort = new SerialPort(queue.QueuePort.Name);
btn_br.Content = mySerialPort.BaudRate;
btn_db.Content = mySerialPort.DataBits;
btn_pty.Content = mySerialPort.Parity;
btn_sb.Content = mySerialPort.StopBits;
if (selecteditem == portname)
{
string select_portname = queue.QueuePort.Name;
txt_pn.Text = "PortName is" + " " + select_portname.ToUpper();
}
}
}
}
}
But i don't know whether this way is correct or not to get output like this(above figure).I just messed up
with this.if you know the correct way,please tell me that way i just upgrade it.
finally i need to find flow control(software or hardware).as per the above figure the combobox has to devices which are software device.so i have to dynamically find that value(s/w or h/w).