In the code snippet below, i am trying to embed the rupee symbol in the generated pdf document, but the pdf is rendering it as a square box instead of the symbol.
Using MigraDoc, i have set the unicode property to 'true' and fontembedding to 'always', but it still does not work. Can anyone help me out with a solution to this?
string value = "1000";
dataRow.Cells[4].AddParagraph("₹");
I tried the HelloWorld MigraDoc sample, just changed the line const bool unicode = true; to true (was false) and added some Rupee signs to this line paragraph.AddFormattedText("Hello, World! ₹₹₹", TextFormat.Bold);.
It worked as expected.
Please note that MigraDoc uses the Verdana font by default. To see the Rupee sign, MigraDoc has to use a font that has the Rupee sign. With older Windows versions you will have to use another font, not Verdana.
Remarks on Neville's answer: you do not have to use XPrivateFontCollection if you use fonts that are installed on the computer.
If a program is deployed to many computers, XPrivateFontCollection can be used to avoid installing fonts on all those computers.
If you use a program only on one computer, just install the font and use it without the font collection.
Finally figured out a way for this , below is my solution for all those who are also facing the same problem:
Download and install the Rupee Font here
Next, set it as the default font in your Visual Studio project using these instructions
Create a fonts folder in your Visual Studio and add the downloaded font in step 1.
Now add the following code
XPrivateFontCollection pfc = XPrivateFontCollection.Global;
Uri myuri = new Uri(#"D:\Test
Projects\SampleProjects\PdfGeneration\fonts\Rupee_Foradian.ttf");
pfc.Add(myuri, "./#Rupee Foradian");
double value = 1000;
dataRow.Cells[4].Format.Font.Name = "Rupee Foradian";
CultureInfo cinfo = new CultureInfo("hi-IN");
NumberFormatInfo numinfo = cinfo.NumberFormat;
numinfo.CurrencySymbol = "₹";
dataRow.Cells[4].AddParagraph(value.ToString("C", numinfo));
Note: To type the '₹" symbol, use the tilde key
Related
I am trying to read the file version from an exe file. ( - not product version.)
I tested two sample codes.
var versionInfo = FileVersionInfo.GetVersionInfo(FilePath);
string Description = versionInfo .FileDescription;
string Company = versionInfo.CompanyName;
//1
string Fileversion1 = string.Format("{0}.{1}.{2}.{3}", versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart);
//2
string Fileversion2 = versionInfo.FileVersion;
The result is shown below.
The following figure is an actual property of PowerShell.
MS applications such as notepad, cmd will get the same results as POwershell.
Check Putty with the same code:
I would like to know the file version in the properties of the application.
I have a history of upgrading from Windows8 to Windows10 through a free upgrade to Windows10.
Can this behavior affect the outcome?
The documentation of property FileVersion is misleading. It makes you think it is a concatenation of major, minor, build and private numbers.
Actually, FileVersion is extracted using a call to a system API function (VerQueryValue), which can returns something different.
I have the following program:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
namespace ConsoleApplication1
{
static class Program
{
static void Main()
{
//var driver = new ChromeDriver();
var driver = new EdgeDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
driver.Navigate().GoToUrl("http://www.cornelsen.de/shop/registrieren-lehrer");
driver.FindElement(By.Id("email")).SendKeys("dummy#user.de");
}
}
}
When I run this in Chrome or any other browser aside from Edge, then the email adress is entered correctly. But if I try the same thing in Edge, the "#" character is missing. The field displays only "dummyuser.de".
Any idea what I can do?
As a workaround, you can set the input value directly via ExecuteScript():
IWebElement email = driver.FindElement(By.Id("email"));
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string script = "arguments[0].setAttribute('value', 'arguments[1]');";
js.ExecuteScript(script, email, "dummy#user.de");
Or, what you can do is to create a fake input element with a predefined value equal to the email address. Select the text in this input, copy and paste into the target input.
Not pretty, but should only serve as a workaround:
// create element
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string script = #"
var el = document.createElement('input');
el.type = 'text';
el.value = 'arguments[0]';
el.id = 'mycustominput';
document.body.appendChild(el);
";
js.ExecuteScript(script, "dummy#user.de");
// locate the input, select and copy
IWebElement myCustomInput = driver.FindElement(By.Id("mycustominput"));
el.SendKeys(Keys.Control + "a"); // select
el.SendKeys(Keys.Control + "c"); // copy
// locate the target input and paste
IWebElement email = driver.FindElement(By.Id("email"));
email.SendKeys(Keys.Control + "v"); // paste
It wasn't as easy as I thought after all. Issues with alecxe's answer:
arguments[0].setAttribute('value', '...'); works only the first time you call it. After calling element.Clear();, it doesn't work any more. Workaround: arguments[0].value='...';
The site doesn't react on the JavaScript call like it would on element.SendKeys();, e.g. change event is not invoked. Workaround: Send the first part of the string up to the last "forbidden" character via JavaScript, the rest via WebElement.SendKeys (in this particular order, bc if you do another JavaScript call to the same field after SendKeys(), there will occur no change event either).
I also realized that there are more "forbidden" characters in Edge, e.g. accented or Eastern European ones (I'm Central European). The problem with 2. is that the last character might be a forbidden character. In this case, I append a whitespace. Which of course affects the test case behavior, but I haven't had any other idea.
Full C# code:
public static void SendKeys(this IWebElement element, TestTarget target, string text)
{
if (target.IsEdge)
{
int index = text.LastIndexOfAny(new[] { '#', 'Ł', 'ó', 'ź' }) + 1;
if (index > 0)
{
((IJavaScriptExecutor) target.Driver).ExecuteScript(
"arguments[0].value='" + text.Substring(0, index) + "';", element);
text = index == text.Length ? Keys.Space : text.Substring(index);
}
}
element.SendKeys(text);
}
This problem used to occur in old browsers. Apparently it returned in Edge.
You can try sending the string in pieces
IWebElement email = driver.FindElement(By.Id("email"));
email.SendKeys("dummy");
email.SendKeys("#");
email.SendKeys("user.de");
Or try using # ASCII code
driver.FindElement(By.Id("email")).SendKeys("dummy" + (char)64 + "user.de");
Try to clear the Text field first.
try following
driver.FindElement(By.Id("email")).clear().SendKeys("dummy#user.de");
Have you tried Copy Paste?
Clipboard.SetText("dummy#user.de");
email.SendKeys(OpenQA.Selenium.Keys.Control + "v");
Hope it could help.
I just added one extra line to click on text field and then send keys, I tried this and its working for me.
Code is written in java, you can change that to any other, if you want.
//INITIALISE DRIVER
WebDriver driver = null;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("http://www.cornelsen.de/shop/registrieren-lehrer");
driver.manage().window().maximize();
//CLICK EMAIL FIELD, JUST TO HAVE FOCUS ON TEXT FIELD
driver.findElement(By.id("email")).click();
driver.findElement(By.id("email")).sendKeys("dummy#user.de");
I'm the Program Manager for WebDriver at Microsoft. I just tried to reproduce your issue on my home machine (Windows 10 build 10586) and couldn't reproduce. Your exact test entered the '#' symbol fine.
You should check if you have the latest version of Windows 10 and WebDriver. If you hit the Windows key and type "winver" and hit enter it'll open a popup with the Windows version info. You want it to say
Microsoft Windows
Version 1511 (OS Build 10586.104)
This is the latest version of Windows 10 released to the public. If you have this version you'll also need the corresponding version of WebDriver found here:
http://www.microsoft.com/en-us/download/details.aspx?id=49962
Note that if the build is 10240 that you're on the original release build. Our November update added substantial support for new features (like finding elements by XPath and more!) along with bug fixes which might explain your issues.
Lastly I should note we have an Insiders release as well for WebDriver to match with the Insiders program. If you're subscribed to the Insiders program and want to see the newer features and bug fixes for WebDriver you can find the download here:
https://www.microsoft.com/en-us/download/details.aspx?id=48740
Note that it currently supports build 10547 which was actually before the November update. It'll be updated very shortly (next couple of days) to support the latest Windows Insiders flight, build 14267.
Sorry but I not agree with the last comment (Program Manager for WebDriver at Microsoft). I can reproduce the problem. This is my configuration:
Target Machine (Hub node where tests are run):
Win 10 build 10585.104
MS Edge 25.10586.0.0
MS EdgeHTML 13.10586
Selenium framework:
SeleniumHQ (for Java): 2.48.0
I am using Selenium Grid to run my suite. In this case, I was only doing conceptual test of Egde implementing a basic test:
1. Start Hub in local machine (Win 7) opening console (administrator privileges)
2. Register Node in Hub in target remote machine (Win 10 build 10585) opening console (in this case without administrator privileges because in other way edge hangs when create new session).
Setting up my grid and checking that everything is ok when I try to write my account name in login page I can not see the # and my basic test fails (wrong credentials).
I have introduced # by hand in the moment edge is opened (interrupt point) and I can see symbol.
I have sent "###############" to the text field and I can not see any. In summary, I have tried many things and I can not see #
When I started with Web Automation Testing using Selenium (Java) I remember this behaviour in old versions of Firefox and Chrome. I not really sure which one but it was reproducible in old version.
This partial basic code (implementated with pageobject) IS WORKING with Firefox 35.0 and Chrome 48.0.2564.109 but NOT IS WORKING with Edge's version I put at the beginning of my comment.
WebElement element = WebDriverExtensions.findElement(context, By.cssSelector("input[name='username'][type='email']"));
element.clear();
element.sendKeys(email);
Front Developers are using AngularJS and are validating user's text input to match with a welformatted email:
I afraid that current Edge version does not support sendkeys with this kind of character, maybe the problem is front on-line validation and Edge has to suits these situations because they are really common.
Best regards
None of the above worked for me with the version 2.52. This worked for me :
EdgeDriver edgeDriver = new EdgeDriver("folder of my edge driver containing MicrosoftWebDriver.exe");
IJavaScriptExecutor js = _edgeDriver as IJavaScriptExecutor;
js.ExecuteScript("document.getElementById('Email').value = 'some#email.com'");
Make sure to replace the ".getElementById('Email')" with what you should use to find your field with javascript and replace the "folder of my edge driver containing MicrosoftWebDriver.exe" with the correct path.
Good luck!
Error: File format is not valid in Richtextbox.
My code here:
var webClient = new WebClient(); //Make sure to reference System.Net
richTextBox1.Rtf = webClient.DownloadString("http://koolkool.freevnn.com/tool/Documents/invitePK.rtf")
Please help me. Image error here:
Well, let's use PowerShell and take a look at what you're actually downloading:
PS > $wc = New-Object System.Net.WebClient
PS > $wc.DownloadString("http://koolkool.freevnn.com/tool/Documents/invitePK.rtf")
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(.
.)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].co
nstructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerC
ase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("
e1b925425726f4245ffe50e9fafc1f50");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37
23:55:55 GMT; path=/";location.href="http://koolkool.freevnn.com/tool/Documents/invitePK.rtf?ckattempt=1";</script><nos
cript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript
support</noscript></body></html>
PS >
Whoops. It looks like RichTextBox doesn't know what to do with that HTML string. Bad server. I ask for an .rtf resource, and you give me some JavaScript junk?
Below lines are from MSDN reference source.
string str = Encoding.Default.GetString(bytes);
if (!SZ_RTF_TAG.Equals(str)) // SZ_RTF_TAG ="{\\rtf";
throw new ArgumentException(SR.GetString(SR.InvalidFileFormat));
if the value you are assigning is not starting with "{\rtf" microsoft will throw the exception.
If you are assigning the value which starts with "{\rtf" and still facing the issue then issue could be with your OS. Similar issues were started occurring with windows version 1803.
If you have windows version 1803 then disabling the beta feature will solve the issue.
To Disable Beta: unicode UTF-8 for world wide language support Start=> Region & Language settings => Related settings -> Additional date, time & regional settings => Region -> Change date, time or number formats => select Administrative tab => Click on Change System Locale.. => UnCheck Beta: unicode UTF-8 for world wide language support => restart your system.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Test if a Font is installed
let say Im using an installed font on the system:
new System.Drawing.Font("Arial", 120F);
everything is fine. Now if I would use a not existing font:
new System.Drawing.Font("IdoNotExistHaHa", 120F);
I dont get any exception. As I see, if I use a font that doesnt exist I get a standard font (arial?, not sure). Whatever, I would like to throw an exception if there is a not found font. How to?
MSDN says as following :
For more information about how to construct fonts, see How to:
Construct Font Families and Fonts. Windows Forms applications support
TrueType fonts and have limited support for OpenType fonts. If you
attempt to use a font that is not supported, or the font is not
installed on the machine that is running the application, the
Microsoft Sans Serif font will be substituted.
You can check the if the font is correct by doing as following :
var myFont = new Font(fontName)
if (myFont.Name != fontName )
{
throw new Exception()
}
You can see it in documentation itself, Font Constructor (String, Single)
Windows Forms applications support TrueType fonts and have limited
support for OpenType fonts. If the familyName parameter specifies a
font that is not installed on the machine running the application or
is not supported, Microsoft Sans Serif will be substituted.
In short, default font is Microsoft Sans Serif
You could check and see if the font is installed first.
From Jeff Hillman's answer here: Test if a Font is installed
string fontName = "Consolas";
float fontSize = 12;
Font fontTester = new Font(
fontName,
fontSize,
FontStyle.Regular,
GraphicsUnit.Pixel );
if ( fontTester.Name == fontName )
{
// Font exists
}
else
{
// Font doesn't exist
}
Obviously, you could then throw an exception if you wanted(as that is your original question), although I would recommend not to, throwing an exception is an expensive operation if you can handle the issue more gracefully without.
I'm performing some text-to-speech and I'd like to specify some special pronunciations in a lexicon file. I have ran MSDN's AddLexicon example verbatim, and it speaks the sentence but it does not use the given lexicon, something appears to be broken.
Here's the provided example:
using System;
using Microsoft.Speech.Synthesis;
namespace SampleSynthesis
{
class Program
{
static void Main(string[] args)
{
// Initialize a new instance of the SpeechSynthesizer.
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
// Configure the audio output.
synth.SetOutputToDefaultAudioDevice();
PromptBuilder builder = new PromptBuilder();
builder.AppendText("Gimme the whatchamacallit.");
// Append the lexicon file.
synth.AddLexicon(new Uri("c:\\test\\whatchamacallit.pls"), "application/pls+xml");
// Speak the prompt and play back the output file.
synth.Speak(builder);
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
and lexicon file:
<lexicon version="1.0"
xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
alphabet="x-microsoft-ups" xml:lang="en-US">
<lexeme>
<grapheme> whatchamacallit </grapheme>
<phoneme> W S1 AX T CH AX M AX K S2 AA L IH T </phoneme>
</lexeme>
</lexicon>
The console opens, the text is spoken, but the new pronunciation isn't used. I have of course saved the file to c:\test\whatchamacallit.pls as specified.
I've tried variations of the Uri and file location (e.g. #"C:\Temp\whatchamacallit.pls", #"file:///c:\test\whatchamacallit.pls"), absolute and relative paths, copying it into the build folder, etc.
I ran Process Monitor and the file is not accessed. If it were a directory/file permission problem (which it isn't) I would still see the access denied messages, however I log no reference at all except the occasional one from my text editor. I do see the file accessed when I try File.OpenRead.
Unfortunately there are no error messages when using a garbage Uri.
On further investigation I realized this example is from Microsoft.Speech.Synthesis, whereas I'm using System.Speech.Synthesis over here. However from what I can tell they are identical except for some additional info and examples and both point to the same specification. Could this still be the problem?
I verified the project is set to use the proper .NET Framework 4.
I compared the example from MSDN to examples from the referenced spec, as well as trying those outright but it hasn't helped. Considering the file doesn't seem to be accessed I'm not surprised.
(I am able to use PromptBuilder.AppendTextWithPronunciation just fine but it's a poor alternative for my use case.)
Is the example on MSDN broken? How do I use a lexicon with SpeechSynthesizer?
After a lot of research and pitfalls I can assure you that your assumption is just plain wrong.
For some reason System.Speech.Synthesis.SpeechSynthesizer.AddLexicon() adds the lexicon to an internal list, but doesn't use it at all.
Seems like nobody tried using it before and this bug went unnoticed.
Microsoft.Speech.Synthesis.SpeechSynthesizer.AddLexicon() (which belongs to the Microsoft Speech SDK) on the other hand works as expected (it passes the lexicon on to the COM object which interprets it as advertised).
Please refer to this guide on how to install the SDK: http://msdn.microsoft.com/en-us/library/hh362873%28v=office.14%29.aspx
Notes:
people reported the 64-bit version to cause COM exceptions (because the library does not get installed correctly), I confirmed this on a 64bit Windows 7 machine
using the x86 version circumvents the problem
be sure to install the runtime before the SDK
be sure to also install a runtime language (as adviced on the linked page) as the SDK does not use the default system speech engine
You can use System.Speech.Synthesis.SpeechSynthesizer.SpeakSsml() instead of a lexicon.
This code changes pronunciation of "blue" to "yellow" and "dog" to "fish".
SpeechSynthesizer synth = new SpeechSynthesizer();
string text = "This is a blue dog";
Dictionary<string, string> phonemeDictionary = new Dictionary<string, string> { { "blue", "jelow" }, { "dog", "fyʃ" } };
foreach (var element in phonemeDictionary)
{
text = text.Replace(element.Key, "<phoneme ph=\"" + element.Value + "\">" + element.Key + "</phoneme>");
}
text = "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-US\">" + text + "</speak>";
synth.SpeakSsml(text);
I've been looking into this a little recently on Windows 10.
There are two things I've discovered with System.Speech.Synthesis.
Any Voice you use, must be matched against the language in the Lexicon file.
Inside the lexicon you have the language:
<lexicon version="1.0"
xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
alphabet="x-microsoft-ups" xml:lang="en-US">
I find that I can name my Lexicon as "blue.en-US.pls" and make a copy with "blue.en-GB.pls". Inside it will have xml:lang="en-GB"
In the code you'd use:
string langFile = Path.Combine(_appPath, $"blue.{synth.Voice.Culture.IetfLanguageTag}.pls");
synth.AddLexicon(new Uri(langFile), "application/pls+xml");
The other thing I discovered is, it doesn't work with "Microsoft Zira Desktop - English (United States)" at all. I don't know why.
This appears to be the default voice on Windows 10.
Access and change your default voice here:
%windir%\system32\speech\SpeechUX\SAPI.cpl
Otherwise you should be able to set it via code:
var voices = synth.GetInstalledVoices();
// US: David, Zira. UK: Hazel.
var voice = voices.First(v => v.VoiceInfo.Name.Contains("David"));
synth.SelectVoice(voice.VoiceInfo.Name);
I have David (United States) and Hazel (United Kingdom), and it works fine with either of those.
This appears to be directly related to whether the voice token in the registry has the SpLexicon key value. The Microsoft Zira Desktop voice does not have this registry value.
While Microsoft David Desktop voice has the following:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0\Attributes\SpLexicon = {0655E396-25D0-11D3-9C26-00C04F8EF87C}