Editing html templates - c#

I am going to create a function in my application that is going to send som status mails to several receivers in a list.
Earlier i used plane text format on the email, but now i want to send the mail based on som html templates. I need tips reguarding a good way to insert data into these templates before sending them.
eks
%CpuStatus%
%HardriveStatus%
and so on. I have the solution for everything except a way to fill anchors like that with data. This is a WinForm application so i dont have access to the ASP functionality

Maybe this sort of thing would be the simplest?
// This would most likely be loaded from a file or database.
string emailBody = "CPU Status: %CpuStatus%\nHard Drive Status: %HardriveStatus%";
string cpuStatus = MyService.GetCpuStatus();
emailBody.Replace("%CpuStatus%", cpuStatus);

If you really wanted to make a big project out of it, you can use a webbrowser control, load it with your html file and then use the WebBrowser's Document property to get an HtmlDocument object. You can then loop through it's children (recursively) to find the tags you want to change.
Personally, I would do the .Replace method suggested previously.

Related

Capture signature using HTML5 and save it as image to database

I am just starting to learn Jquery and working on asp.net webform app that will be used on a touchscreen device, and I need to capture user signature, basically user will sign and after hit save, I want their signature to be saved as an image to SQL server database so I can retrieve and display it later on a webpage.
I found this question: Capture Signature using HTML5 and iPad
and the jQuery plugin works great, exactly as I want.
Here the demo: http://szimek.github.io/signature_pad
Here the plug-in: https://github.com/szimek/signature_pad
So on the demo I see after hit "save" you will go to a new tab that display an image of your signed signature, and I noticed that the url is something like
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApIAAAE+CAYAAAA+vvBuAAAgAElEQVR4Xu3df8i37V0X8I/l0GY5BzZdiWslKhnNUaBR62lBP0htjuiHfz0uROgPmQsH/hE8jiKKjLl/IoLa9k+NMOYyhCRamyM0WI9bUBst5kzbUNfjxBlmaLy389jO+3q......
What does this url mean?
what type of variable will be used to store this in database table (nvarchar, binary...)
3 (MAIN QUESTION). How do I get those data text in code behind C# button click event to store them to a string variable for other purposes. Can someone provide a simple example so i can go from there?
if I am missing something please let me know, as I am looking at the .html file and those .js files in the demo project of that plugin, I am lost.
That URL is in BASE64 format. You can use that long string of characters in the SRC attribute of an image tag and it will be displayed.
To get better performance, the recommended way of storing photos is to store the image on the disk (using some kind of server side language) and then save the name of the file in a database as a CHAR or TEXT.
Not quite sure. I've never used the library before.
That is a Base64 encoded image.
data: says that data is following instead of a URL
image/png; specifies the content "mimetype" the data should be served as
base64, indicates the encoding type of the data
As base64 only uses ASCII characters, a varchar(MAX) would be suitable for storage. No need for nvarchar. I normally store the base64 encoding only (the last part after the comma), and keep the mime-type (e.g. image/png) in a separate field.
There are many options in C#. If you store the base64 part separately, you simplify the code a bit.
Turn it into an image server-side using byte[] imageBytes = System.Convert.FromBase64String(base64data) and creating an image from the byte array and type.
Inject the image into a webpage <img src="#Html.Raw("data:"+ mimetype + "base64," + base64data)"/>
Notes:
As #anthony mentions, your would typically store images as files (or in Blob storage nowadays) and only record the filename/URI. This depends on quantity size & usage.
We have found it convenient, for certain projects requiring extra security, for base64 images to be stored as encoded & encrypted strings in a database.
From comments: To save to, place the string value into a hidden input and update its value. It will then get posted back like any other string. Our own signature plugin just hides the original <input type="text"> it is attached to and puts the value there.
In addition to TrueBlueAussie's answer:
The simplest way to get your string in CodeBehind is:
Declare a HiddenField using ASP and assign a Static ID to it. (Static ID is important since ASP normally assigns automatically generated IDs to each control, and this can get difficult to predict).
Shape your JavaScript function in a way that SignaturePad writes the output base64 image string into this HiddenField. You can for example, use a button "Verify" that calls the Export function of the SignaturePad.
After the string is written into the HiddenField, read it back on CodeBehind. For this, you can use an additional button, for example something like "Save".
There are of course other options which are much more secure/versatile/appropriate, but this might be a good starting point for you.

How to effictively send custom email with MvcMailer?

I need to send like 100 000 mails, so I need my process to be efficient.
We are using MvcMailer because the enables us to use Razor as the template engine.
My problem : the resulting email is in 2 part:
A common part for everyone
A custom part for each recipients
Because there is a custom part I have to create a new mail for everyone. But MvcMailer is running the view engine for every mail, so the common part is rendered 100 000, and that is not acceptable.
My only idea so far :
use the EmailBody method for rendering the common part at the very beginning of my process (in this common part there'll be something like "{USER-CONTENT}")
string commonContent = mailer.EmailBody("Common");
Populate my mail body with only the user content and do
myMail.Body = commonContent.Replace("{USER-CONTENT}",myMail.Body)
But it's still a dirty solution : creating my own template language inside Razor.
Do you have a better idea ?

Recommended practice to store a mail template

My application sends notification mails to users so I created a html template for each type of notification. I set something like fields in the template as {n} in order to use something like this when I'm sending the message:
string bodyTemplate = GetBodyTemplate(); //gets the html template with {n} in it
message.Body = String.Format(bodyTemplate, fieldZeroValue, fieldOneValue);
For example, the template can have a piece of this:
<td style="vertical-align:middle;padding:0.5em 0.5em 0.5em 0.5em;">
Go to page
</td>
In this example I would use:
message.Body = String.Format(bodyTemplate, IdValue.ToString());
Here is my question: Where should I store those very long string with the html templates?
I don't want to connect to the the database to get them and storing them in string constants looks awful.
Please tell me what is the recomended practice to store those strings.
I create text files and store the templates in the project. If there aren't too many, you could build them into your assembly and get them out of the Resources. If there are a lot, I would point to a directory that contains the files and use a string reader to pick out a filename.
I heard a pearl of wisdom the other day over an argument of using #regions or not. The "pro #regions" guy said, "But I want to hide ugly code" and the "anti #regions" guy said "if it's so ugly, you shouldn't have written it."
It made me laugh to see that you were getting a code smell from ugly constants.
What is the aversion to putting it in the db? is it the cost of having to get it frequently? If that's so, then perhaps cache it and re-pull from the db at a reasonable interval. That way you can maintain the flexibility of being able to add or change templates without having to hit the db every time.
If constants would genuenly work and you're bawlking that they're ugly, then hide them with a #region :)

How to translate website in another language?(ASP .NET , c#)

I have developed a large business portal. I just realized I need my website in another language. I have researched the solutions available like
Used third party control on my website. (Does fit in my design. Not useful regarding SEO point of view. Dont want to show third party brand names.)
Create Resource files for each language.( A lot of work required to restructure pages to use text from resource files. What about the data entered by the user like Business Description. )
Are there any Other options available.
I was thinking of a solution like a when a page is created on server side then I could translate it before sending back to client. Is there any way I can do that?(to translate everything including data added from databases or through a code. And without effecting design. )
If you really need to translate your application, it's going to take a lot of hard, tedious work. There is no magic bullet.
The first thing you need to do is convert your plain text in your markup to asp:Localize controls. By using the Localize control, you can leave your existing <span> tags in place and just replace the text inside of them. There's really no way around this. Visual Studio's search and replace supports regular expression matching that may help you with this, or you can use Resharper (see below).
The first approach would be to download the open source shopping application nopCommerce and see how they handle their localization. They store their strings in a database and have a UI for editing languages. A similar approach may work well for you.
Alternatively, if you want to use Resource Files, there are two tools that I would recommend using in addition to Visual Studio: Resharper 5 (Localization Features screencast) and Zeta Resource Editor. These are the steps I would take to accomplish it using this method:
Use the "Generate Local Resource" tool in visual studio for each page
Use Resharper's "Move HTML to resource" on the text in your markup to make them into Localize controls.
Use Resharper to search out any localizable strings in your code behind and move them to the resource file as well.
Use the Globalization Rules of Code Analysis / FXCop to help find any additional problems you might face formatting numbers, dates, etc.
Once all text is in the resx files, use Zeta Resource Editor to load up all of your resx files, add new languages, and export for translation (or auto translate if you're brave enough).
I've used this approach on a site translated into 8 languages (and growing) with dozens of pages (and growing). However, this is not a user-editable site; the pages are solely controlled by the programmers.
a large switch case? use a dictionary/hashtable (seperate instance for each a language), it is much, much more effective and fast.
To Convert The Page To Arabic Language Or Other Language .
Go to :
1-page design
2-Tools
3-Generate Local Resource
4-obtain "App_LocalResources" include "filename.aspx.resx"
5-copy the file and change the name to "filename.aspx.ar.resx" to convert the page to arabic language or other .
hope to helpful :)
I found a good solution, see in http://www.nopcommerce.com/p/1784/nopcommerce-translator.aspx
this project is open source and source repository is here: https://github.com/Marjani/NopCommerce-Translator
good luck
Without installing any 3rd party tool, APIs, or dll objects, I am able to utilize the App_LocalResources. Although I still use Google Translate for the words and sentences to be translated and copy and paste it to the file as you can see in one of the screenshots below (or you can have a person translator and type manually to add). In your Project folder (using MS Visual Studio as editor), add an App_LocalResources folder and create the English and other language (resx file). In my case, it's Spanish (es-ES) translation. See screenshot below.
Next, on your aspx, add the meta tags (meta:resourcekey) that will match in the App_LocalResources. One for English and another to the Spanish file. See screenshots below:
Spanish: (filename.aspx.es-ES.resx)
English: (filename.aspx.resx)
.
Then create a link on your masterpage file with a querystring that will switch the page translation and will be available on all pages:
<%--ENGLISH/SPANISH VERSION BUTTON--%>
<asp:HyperLink ID="eng_ver" runat="server" Text="English" Font-Underline="false"></asp:HyperLink> |
<asp:HyperLink ID="spa_ver" runat="server" Text="Español" Font-Underline="false"></asp:HyperLink>
<%--ENGLISH/SPANISH VERSION BUTTON--%>
.
On your masterpage code behind, create a dynamic link to the Hyperlink tags:
////LOCALIZATION
string thispage = Request.Url.AbsolutePath;
eng_ver.NavigateUrl = thispage;
spa_ver.NavigateUrl = thispage + "?ver=es-ES";
////LOCALIZATION
.
Now, on your page files' code behind, you can set a session variable to make all links or redirections to stick to the desired translation by always adding a querystring to urls.
On PageLoad:
///'LOCALIZATION
//dynamic querystring; add this to urls ---> ?" + Session["add2url"]
{
if (Session["version"] != null)
{
Session["add2url"] = "?ver=" + Session["version"]; //SPANISH version
}
else
{
Session["add2url"] = ""; // ENGLISH as default
}
}
///'LOCALIZATION
.
On Click Events sample:
protected void btnBack_Click(object sender, EventArgs e)
{
Session["FileName.aspx"] = null;
Response.Redirect("FileName.aspx" + Session["add2url"]);
}
I hope my descriptions were easy enough.
If you don't want to code more and if its feasible with google translator then You can try with Google Translator API. you can check below code.
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script>
function googleTranslateElementInit() {
$.when(
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en',
layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element')
).done(function(){
var select = document.getElementsByClassName('goog-te-combo')[0];
select.selectedIndex = 1;
select.addEventListener('click', function () {
select.dispatchEvent(new Event('change'));
});
select.click();
});
}
$(window).on('load', function() {
var select = document.getElementsByClassName('goog-te-combo')[0];
select.click();
var selected = document.getElementsByClassName('goog-te-gadget')[0];
selected.hidden = true;
});
</script>
Also, Find below code for <body> tag
<div id="google_translate_element"></div>
It will certainly be more work to create resource files for each language - but this is the option I would opt for, as it gives you the opportunity to be more accurate. If you do it this way you can have the text translated, manually, by someone that speaks the language (there are many companies out there that offer this kind of service).
Automatic translation systems are often good for giving a general impression of what something in another language means, but I would never use them when trying to portray a professional image, as often what they output just doesn't make sense. Nothing screams 'unprofessional!' like text that just doesn't make sense because it's been automatically translated.
I would take the resource file route over the translation option because the meaning of words in a language can be very contextual and even one mistake could undermine your site's credibility.
As you suggest Visual Studio can generate the meta resource file keys for most controls containing text but may leave you having to do the rest manually but I don't see an easier, more reliable solution.
I don't think localisation is an easy-to-automate thing anyway as text held in the database often results in schema changes to allow for multiple languages, and web HTML often need restructuring to deal with truncated or wrapped label and button text because, for example, you've translated into German or something.
Other considerations:
Culture settings - financial delimitors, date formats.
Right-to-left - some languages like arabic are written right to left meaning that the pages require rethinking as to control positioning like images etc.
Good luck whatever you go with.
I ended up doing it the hard way:
I wrote an extension method on the string class called TranslateInto
On the Page's PreRender method I grab all controls recursively based on their type (the types that would have text)
Foreach through them and text.TranslateInto(SupportedLanguages.CurrentLanguage)
In my TranslateInto method I have a ridiculously large switch statement with every string displayed to the user and its associated translation.
Its not very pretty, but it worked.
We work with a Translation CAT tool (Computer Assisted Translation) called MemoQ that allows us to translate the text while leaving all the tags and coding in place. This is very helpful when the order of words change when you translate from one language to another.
It is also very useful because it allows us to work with translators from around the world, without the need for them to have any technical expertise. It also allows us to have the translation proof read by a second translator.
We use this translation environment to translate html, xml, InDesign, Word, etc.
I think you should try Google Translate.
http://translate.google.com/translate_tools
Very easy and very very effective.
HTH

Creating a simple 'spider'

I have researched on spidering and think that it is a little too complex for quite a simple app I am trying to make. Some data on a web page is not available to view in the source as it is just being displayed by the browser.
If I wanted to get a value from a specific web page that I was to display in a WebBrowser control, is there any method to read values off of the contents of this browser?
If not, does anyone have any suggestions on how they might approach this?
You’re not looking for spidering, you’re looking for screen scraping.
I'd have to agree with Bombe, it sounds more like you want HTML Screen Scraping. It requires lots of parsing, and if the page your scraping ever changes, your app will break, however here's a small example of how to do it:
WebClient webClient = new WebClient();
const string strUrl = "http://www.yahoo.com/";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string html = objUTF8.GetString(reqHTML);
Now the html variable has the entire HTML in it, and you can start parsing away.
Because the browser simply renders the underlying content, the most flexible approach would be to parse the underlying content (html/css/js/whatever) yourself.
I would create a parsing engine that looks for the things your spider application needs.
This could be a basic string searching algorithm which looks for href="" for example and reads the values in order to produce new requests and continue spidering. Your engine could be written to only look for things it is interested in and extended in that way for more functionality.

Categories

Resources