I want to ask is there any way to remove the html taq from Rss Reader on windows phone 8.1 I'm working on app that show the topics on any site using Rss on the smartphone " windows phone" but I have this problem can I remove the html taqs
this pic will show u what I mean ??
What control is this? Have you consider using a Web Browser control? Or, if you really need to display it in a TextBox (assuming it's a TextBox), you can convert your HTML into a XAML FlowDocument, using this tutorial.
I follow the same tutorial for create my rss reader.
So, for remove the html code you need create a class to trimmer the description:
Create a class named RssTextTrimmer.cs with the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Text.RegularExpressions;
using Windows.UI.Xaml.Data;
using System.Net;
namespace VEJA_NotÃcias
{
public class RssTextTrimmer : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return null;
int maxLength = 200;
int strLength = 0;
string fixedString = "";
// Remove HTML tags.
fixedString = Regex.Replace(value.ToString(), "<[^>]+>", string.Empty);
// Remove newline characters.
fixedString = fixedString.Replace("\r", "").Replace("\n", "");
// Remove encoded HTML characters.
fixedString = WebUtility.HtmlDecode(fixedString);
strLength = fixedString.ToString().Length;
// Some feed management tools include an image tag in the Description field of an RSS feed,
// so even if the Description field (and thus, the Summary property) is not populated, it could still contain HTML.
// Due to this, after we strip tags from the string, we should return null if there is nothing left in the resulting string.
if (strLength == 0)
{
return null;
}
// Truncate the text if it is too long.
else if (strLength >= maxLength)
{
fixedString = fixedString.Substring(0, maxLength);
// Unless we take the next step, the string truncation could occur in the middle of a word.
// Using LastIndexOf we can find the last space character in the string and truncate there.
fixedString = fixedString.Substring(0, fixedString.LastIndexOf(" "));
}
fixedString += "...";
return fixedString;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
And in your MainPage.xaml you need add the code:
<Page.Resources>
<local:RssTextTrimmer x:Key="RssTextTrimmer" />
</Page.Resources>
To access the method of RssTextTrimmer class in the xaml textblock you need to do so:
<TextBlock x:Name="textTitulo" Text="{Binding title, Converter={StaticResource RssTextTrimmer}}"/>
Related
I'm using String interpolation in the code behind, and now I need to take part of it to a class.
when I do it, I get error "CS1056: Unexpected character '$'"
even a very simple code gives the error right on running (not on build):
string MailSubject = $"this is your score: {userScore}";
this part of code is part of the FaceClass.CS file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace ns.App_Code
{
public class FakeClass
{
public static void Check_Next_In_Line(int score)
{
int temp = Fake2Class.GetData();
if (temp == 0)
{
string MailSubject = "";
string MailBody = "";
MailBody = $"Your score: {score}";
/*
mail send function
*/
}
}
}
}
I'm using .NET Framework 4.8
String Interpolation works for me in a aspx code behind but not in a method within a class. If I want to refactor a part of code becuase it is needed more than once - it won't work
Hi an alternative solution to what you are looking for may be would be to use string format. Something like below
int userscore;
string MailSubject = string.Format("this is your score: {0}", userscore);
This code is replacing the text with an image but its placing the multiple copies of an image and placing them in the beginning of the document. I want the image to be placed at the same position where text was present. My find text is available in the table cell. Is it due to that?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
//using System.Drawing;
namespace WritingIntoDocx
{
[ComVisible(true)]
public interface IMyClass
{
void DocumentDigitalSign(string filep,string findt,string replacet);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Program : IMyClass
{
public void DocumentDigitalSign(string filep, string findt, string imagepath)
{
string filepath = filep;
string Findtext = findt;
word.Application app = new word.Application();
word.Document doc = app.Documents.Open(filepath);
word.Range myStoryRange = doc.Range();
//First search the main document using the Selection
word.Find myFind = myStoryRange.Find;
myFind.Text = Findtext; myFind.Replacement.Application.Selection.InlineShapes.AddPicture(imagepath);
myFind.Forward = true;
myFind.Wrap = word.WdFindWrap.wdFindContinue;
myFind.Format = false;
myFind.MatchCase = false;
myFind.MatchWholeWord = false;
myFind.MatchWildcards = false;
myFind.MatchSoundsLike = false;
myFind.MatchAllWordForms = false;
myFind.Execute(Replace: word.WdReplace.wdReplaceAll);
//'Now search all other stories using Ranges
foreach (word.Range otherStoryRange in doc.StoryRanges)
{
if (otherStoryRange.StoryType != word.WdStoryType.wdMainTextStory)
{
word.Find myOtherFind = otherStoryRange.Find;
myOtherFind.Text = Findtext; myOtherFind.Replacement.Application.Selection.InlineShapes.AddPicture(imagepath);
myOtherFind.Wrap = word.WdFindWrap.wdFindContinue;
myOtherFind.Execute(Replace: word.WdReplace.wdReplaceAll);
}
// 'Now search all next stories of other stories (doc.storyRanges dont seem to cascades in sub story)
word.Range nextStoryRange = otherStoryRange.NextStoryRange;
while (nextStoryRange != null)
{
word.Find myNextStoryFind = nextStoryRange.Find;
myNextStoryFind.Text = Findtext;
myNextStoryFind.Replacement.Application.Selection.InlineShapes.AddPicture(imagepath);
myNextStoryFind.Wrap = word.WdFindWrap.wdFindContinue;
myNextStoryFind.Execute(Replace: word.WdReplace.wdReplaceAll);
nextStoryRange = nextStoryRange.NextStoryRange;
}
}
app.Documents.Save();
app.Documents.Close();
}
}
}
Replacement.Application is a reference to the application object. When you call AddPicture() on that, the picture is immediately inserted at the current position before the find operation is even executed.
I see two possibilities:
Load the picture, place it into the Windows clipboard and then execute the find operation specifying "^c" as replacement text. Word will replace "^c" with the current content of the clipboard. This is what the documentation says:
ReplaceWith
Type: System.Object
Optional Object.
The replacement text. To delete the text specified by the Find argument, use an empty string (""). You specify special characters and advanced search criteria just as you do for the Find argument. To specify a graphic object or other non-text item as the replacement, move the item to the Clipboard and specify "^c" for ReplaceWith.
Do not use wdReplaceAll, but wdReplaceNone, so that the find operation itself does not do any replacing. But you then have the chance to insert your content at the place found. Do that in a loop until no more occurrence is found.
I have a Visio ER diagram and want to read the database properties (Columns, Primary, Foreign key, data type) information from an Entity. Also want to find the parent and child tables associated. How can I programmatically achieve it using C#?
I am using Interop Visio library and can read the pages and shape from ER diagram but don't know which functions or methods in Visio interop will let me get properties information from a Shape.
Below is the code I am using and I am not getting any property using it. My ER diagram have just two entities a Parent and a Child table.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Visio;
namespace Visio_POC
{
public partial class Load_Visio : Form
{
static string strProperties = "";
public Load_Visio()
{
InitializeComponent();
string strFileName = "\\Visio_POC\\POC_Visio.vsd";
Microsoft.Office.Interop.Visio.Application vsApp = new Microsoft.Office.Interop.Visio.Application();
Microsoft.Office.Interop.Visio.Document docVisio = vsApp.Documents.Add(strFileName);
Page pgVisio = docVisio.Pages[1];
Shapes shpVisio = pgVisio.Shapes;
int intCnt = shpVisio.Count;
string[] strShapeText = new string[intCnt];
printProperties(pgVisio.Shapes);
txtProperties.Text = strProperties;
}
public static void printProperties(Shapes shapes)
{
// Look at each shape in the collection.
foreach (Shape shape in shapes)
{
// Use this index to look at each row in the properties
// section.
short iRow = (short) VisRowIndices.visRowFirst;
// While there are stil rows to look at.
while (shape.get_CellsSRCExists(
(short) VisSectionIndices.visSectionProp,
iRow,
(short) VisCellIndices.visCustPropsValue,
(short) 0) != 0)
{
// Get the label and value of the current property.
string label = shape.get_CellsSRC(
(short) VisSectionIndices.visSectionProp,
iRow,
(short) VisCellIndices.visCustPropsLabel
).get_ResultStr(VisUnitCodes.visNoCast);
string value = shape.get_CellsSRC(
(short) VisSectionIndices.visSectionProp,
iRow,
(short) VisCellIndices.visCustPropsValue
).get_ResultStr(VisUnitCodes.visNoCast);
// Print the results.
//Console.WriteLine(string.Format(
// "Shape={0} Label={1} Value={2}",
// shape.Name, label, value));
strProperties = strProperties + shape.Name + " - " + label + " - " + value;
// Move to the next row in the properties section.
iRow++;
}
// Now look at child shapes in the collection.
if (shape.Master == null && shape.Shapes.Count > 0)
printProperties(shape.Shapes);
}
}
}
}
The database reverse engineering is a closed solution. There was a book "Database Modeling" by Terry Halpin which covered this. Alternatively you could peruse my article at http://blog.bvisual.net/2014/03/26/creating-a-schema-from-visio-external-data-record-sets/ for an idea of how you could do it yourself.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TranslateText("hi", "German");
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static string TranslateText(string input, string languagePair)
{
return TranslateText(input, languagePair, System.Text.Encoding.UTF7);
}
/// <summary>
/// Translate Text using Google Translate
/// </summary>
/// <param name="input">The string you want translated</param>
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
/// e.g. "en|da" language pair means to translate from English to Danish</param>
/// <param name="encoding">The encoding.</param>
/// <returns>Translated to String</returns>
public static string TranslateText(string input, string languagePair, Encoding encoding)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
string result = String.Empty;
using (WebClient webClient = new WebClient())
{
webClient.Encoding = encoding;
result = webClient.DownloadString(url);
}
Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
if (m.Success)
result = m.Value;
MessageBox.Show(result);
return result;
}
}
}
I added in the constructor the line:
TranslateText("hi", "German");
And in the bottom i added:
MessageBox.Show(result);
I wanted for the test to translate the word "hi" to German
But the result im getting and in the messagebox is a very long text wich is containing all the google website.
I tried to go manualy to the web site in the string url address and its working im getting to the google translate website.
I dont understand why it dosent work.
I want later to put instead "hi" some text from a text file.
I tried ot use breakpoint and found that this part the Success is all the time return false dont know why:
if (m.Success)
result = m.Value;
I think you are not getting the translated text or value in your html result from your code and also from Google.
Reason:
If you execute this through the browser, it is not translating to the language you expect, example:
http://www.google.com/translate_t?hl=en&ie=UTF8&text=hi&langpair=de
I used langpair=de or langpair=German and doesn't work, it shows me always "hi" as my initial text and not "hallo" (text in german).
Well, just to answer your question to get the text, do the following:
Add this method to your class:
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
Change the following in your "TranslateText" method:
//Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");
string text = getBetween(result, "<span id=result_box class=\"short_text\">", "</span>");
//if (m.Success)
// result = m.Value;
return text;
Now execute your code like this:
// this will return empty ("") if no text found.
// or any problem happens (like lose your internet connection)
string translatedText = TranslateText("hi", "German");
Console.Write(translatedText);
At this point, if you get the translated text from google, it will be retrieved in your app.
Recommendations:
Use a console application and no windows forms, it will be faster.
Warning:
"Google is not a free translating tool. What you do is terms violation".
Hope this helps :-)
Would be easier, and more robust to parse the html using something other than a regex. You can then search the parsed HTML tree for the result and extract it from there.
See What is the best way to parse html in C#?
I googled and found the solution at MSDN.
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
How to extend the lines to complex content which including some natural C# code lines.
eg. I want to write the information below to my test.cs file.
Why?
I am parsing a XML schema with C# Console Application. And i want to generate the Console Result to a .cs file during the compiler time.
using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
{
public class CCODEData
{
public int iCodeId;
public string sCode;
public CODEDType cType;
public int iOccures;
}
[Description("CodeType for XML schema.")]
public enum CODEDType
{
cString = 1,
cInt = 2,
cBoolean = 3,
}
thank you.
If your source code is hardcoded as in your sample, you could use a C# literal string:
string lines =
#"using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
..."
Anyway in such cases it is a better idea (more readable and maintainable) to have the whole text contents into a text file as an embedded resource in your assembly, then read it using GetManifestResourceStream.
(I'm assuming you're trying to build up the result programmatically - if you genuinely have hard-coded data, you could use Konamiman's approach; I agree that using an embedded resource file would be better than a huge verbatim string literal.)
In your case I would suggest not trying to build up the whole file into a single string. Instead, use WriteLine repeatedly:
using (TextWriter writer = File.CreateText("foo.cs"))
{
foreach (string usingDirective in usingDirectives)
{
writer.WriteLine("using {0};", usingDirective);
}
writer.WriteLine();
writer.WriteLine("namespace {0}", targetNamespace);
// etc
}
You may wish to write a helper type to allow simple indentation etc.
If these suggestions don't help, please give more details of your situation.
I know an answer has already been accepted but why not use an XSLT applied to the XML instead? this would mean that you could easily generate c#, vb.net, .net without having to recompile the app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileHandling
{
class Class1
{
static void Main()
{
Console.WriteLine("Enter data");
ConsoleKeyInfo k;
//Console.WriteLine(k.KeyChar + ", " + k.Key + ", " + k.Modifiers );
string str="";
char ch;
while (true)
{
k = Console.ReadKey();
if ((k.Modifiers == ConsoleModifiers.Control) && (k.KeyChar == 23))
{
Console.WriteLine("\b");
break;
}
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
str += "\n";
}
ch = Convert.ToChar(k.KeyChar);
str += ch.ToString();
}
Console.WriteLine(str);
Console.Read();
}
}
}