How to work conditional razor template c# - c#

i was trying this code but getting error at run time. i want if IsUPS has true value then a new table row & table data will be added to table if IsUPS is false then table will have one table row and data? how to achieve this with razor template? please guide. thanks
string template = "<table><tr><td>This is my sample template,
Hello #Model.Name!</td></tr> #if (#Model.IsUPS) {<tr><td> it is ups</td></tr> }
</table>";
string result = Razor.Parse(template, new { Name = "World", IsUPS = true });

Assuming your "string result =" line works correctly;
There's quite a few things I would do differently here.
The error message (you should really have shared what the error is), related to your use of "#".
Try this:
#{
string template = #"<table><tr><td>This is my sample template, Hello" + this.Model.Name + #"!</td></tr>";
if (true)
{
template += #"<tr><td> it is ups</td></tr>";
}
template += #"</table>";
}
The "#{ }" block encapsulates the html in a razor block so the use of # for razor changes. Please note I have made the strings use #"" rather than "" so that if you want to split the html between lines you won't need to have string concatenation.

Firstly: I believe that an error produces a following statement:
#if (#Model.IsUPS)
it should rather be:
#if (Model.IsUPS)
after first # you should put server-side code, so another # is not neccessary when writing condition.
Secondly: Is the template pasted in one-line? If not, you need to use verbatim string:
string template = #"<table><tr><td>This is my sample template,
Hello #Model.Name!</td></tr> #if (Model.IsUPS) {<tr><td> it is ups</td></tr> }
</table>";
Thirdly: show us an error you get. Are you using RazorEngine library?
Fourth: after my fixes that code should work, checked myself.

Related

How to check if the string contains dynamic word that starts with first letter

I am trying to find out in the string if the word that changes but starts with letter 'F' (C#). The result output from service call is as below:
Exception_Remote_Call--VNQ DN ERROR CODE found ERROR CODE= F0123,
ERROR DESCRIPTION= NOT AVAILABLE
In the above string, F0123 word changes according to the different ERROR CODE. I tried as below but it works for F0123 and does not work if the output is F0111. I would like to find if it starts with 'F'.
var isStartsWithF = s.Contains("F0123");
I would really appreciate for the help. Thank you in advance!
This is a job for regular expressions. To make things clearer and easier to spot for future maintainers, I might include the ERROR CODE = as part of the expression:
var data = "Exception_Remote_Call--VNQ DN ERROR CODE found ERROR CODE = F0123, ERROR DESCRIPTION= NOT AVAILABLE";
var exp = new Regex(#"ERROR CODE\s?= (F\d{4,5})");
var result = exp.Match(data).Groups[1].Value;
See it work here:
https://dotnetfiddle.net/nOXOCt

IStringLocalizer based resx localization with "\n" not working

After trudging around the net (and GitHub source and issues), I did find this SO post that describes essentially the same problem, and a "solution" for it (SHIFT+ENTER, which equates to "\r\n", in the Resx editor). This seems hackish and far less than ideal (I see it leading to inconsistent line terminations.)
However, while digging through the source to try and reproduce it or see if there was a known issue, I cloned the ms repo here.
git clone -b master https://github.com/aspnet/Localization.git
Master is important (dev wouldn't compile.) It does the upgrade for the project files (I am using VS2017, v15.2) without issue. Change "samples\LocalizationSample" to be the startup project.
I add a using System.Text to the top of Startup.cs and then by adding the following at original line 66...
const string HELLO = "Hello";
var name = "John Doe";
var sb = new StringBuilder($"{name}\n");
// Similiar to what I am currently using that is not working.
// However, tmplt gets the expected value here in this cloned repo!
// Yet, after the AppendFormat call below, it is back to escaped "\n" ("\\n")
var tmplt = SR[HELLO]; // A
// In my code that started this rabbit hole, tmplt gets the
// following via my injected _localizer/resx.
//var tmplt = "{0}:\\n Score: {1}\\n Pct: {2}\\n\\n"; // B
// Comment out above tmplt lines, and uncomment this and it works as expected
// This is the string that I have in my resx
//var tmplt = "{0}:\n Score: {1}\n Pct: {2}\n\n"; // C
string subj = "Subject";
int score = 100;
int? pct = 100;
sb.AppendFormat(
tmplt, // A = "\n"!, B = "\\n" (expected), C = "\n" (known good)
subj,
score,
pct.Value
);
// A = "\\n" :-(
// B = "\\n"
// C = "\n"
var msg = sb.ToString();
var just_a_place_to_set_a_breakpoint = true;
I then duplicate the Startup.es-ES.resx file as Startup.en-US.resx, then change the value for the single key in my new resx to match my string shown in "C" above (// C)
I can now set a breakpoint at just_a_place_to_set_a_breakpoint and fire up the project.
It is able to correctly get the value out without the extra escape character before the newline from this project's localization data! I haven't figured out why that much works in this cloned/modified repo, but not in my original private repo.
However, once it gets to the ToString call, it is back to the unwanted escaped newline ("\n") in both scenarios A and B! :-(
How is it that the tmplt variable contains the correct
representation in this hacked cloned repo when it pulls the
localization string out, but not in mine?
How is it that, regardless, by the time the StringBuilder.ToString is
called, unless I supply a hardcoded string in the source directly, the
"\n" characters ended up escaped ("\n") when it may not have been
present in the string to be formatted?
Any help greatly appreciated, my eyeballs are about to fall out (and I fear this is something easy/documented and Google just failed to turn it up.)
UPDATE: I found the branch that I presume should match the version of the Microsoft.Extensions.Localization my original project is using, v1.1.2... but it fails to build.

Code mirror get uncomment code only

I have implemented the latest code mirror in our asp.net application. the editor allows to type javascript which has commented code and un commented code.
I want to know whether all the code written in the editor is commented or not.
Can anyone please advice.
You can fetch the document text, than pass it through a regex, filtering out all the comments:
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
lineNumbers: true
});
var out = document.getElementById('out');
out.textContent = editor.getValue()
.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:[\s;]+\/\/(?:.*)$)/gm, '');
Demo

replace linebreak with \r\n when sending back to database

Newbie here again.
I have a form in c# that retrieves by calling a Web Service information from a database. One field it gets is just "notes" regarding this client.
The form i have allows multiple lines in the Notes field, but when i save it (send it via webservice to the database back) it doesn't recognize line breaks. How can i tell it to replace line breaks with the /r/n/ (is that right?) code, so when it retrieves it next time from the database it will know how to display it in the notes field?
This is the code i am using now which doesn't work.
if (MasterRecord.Customer.Notes.Trim().Length < 1)
{
string s = "";
foreach (object o in txtNotes.Text)
{
s += o.ToString() + ("\r\n");
}
}
Just do:
var stringToInsert = txtNotes.Text.Replace("\n", "\r\n");
When you are saving multiline text in sql server then replace carriage return with your Custom NewLine specifier for example : %NL%
txtNote.Text.Replace(Environment.NewLine, "%NL%");
and when you retrieving from database field then follow the reveres approach:
MasterRecord.Customer.Notes.Replace("%NL%", Environment.NewLine);
if you access this on .net platform then all ok.. i am not confirm about the the another platforms which acess this webserivce..
it works but it is trick to process data through application it saves %NL% in the field value.

how can I use js/coffee to screen scrape an asp page?

I've got a website that I'd like to pull data from and it's really stuck in the stone ages. There's no web service, no API and it's very much an ASP/Session/table-based-layout page. Pretty fugly.
I'd like to just screen scrape it and use js (coffeescript) to automate that. I wonder if this is possible. I could do this with C# and linqpad but then I'm stuck parsing the tables (and sub-tables and sub-sub-tables) with regex. Plus if I do it with js or coffeescript I'll get much more comfortable with those languages and I'll be able to use jQuery for pulling elements out of the DOM.
I see two possibilities here:
use C# and find a library that will do things like Jquery but in C# code
use coffeescript (js) and use jquery to find the elements that I'm looking for in the page
I'd also like to automate the page a bit (get next set of results). This is strictly for personal use -- I'm not pulling results of someone's search to use in my business. I just want to make a crappy search engine do what I want.
I wrote a class that allows you to supply a bunch of urls and a code block to scrape pages inside a chrome extension. You can find the github repo here: https://github.com/jkarmel/Executor. It could use some more testing and I need to work on the documentation, but it looks like it might be what you are looking for.
Here is how you would use it to get the all the links from a few different pages:
/*
* background.js by Jeremy Karmel.
*/
URLS = ['http://www.apple.com/',
'http://www.google.com/',
'http://www.facebook.com/',
'http://www.stanford.edu'];
//Function will be provided to exector to collect information
var getLinks = function() {
var links = [];
var numLinks = $('a');
$links.each(function(i, val) {links.push(val.href)});
var request = {data: links, url: window.location.href};
chrome.extension.sendRequest(request);
}
var main = function() {
var specForUsersTopics = {
urls : URLS,
code : getLinks,
callback : function(results) {
for (var url in results) {
console.log(url + ' has ' + results[url].length + ' links.');
var links = results[url];
for (var i = 0; i < links.length; i++)
console.log(' ' + links[i]);
}
console.log('all done!!!!');
}
};
var exec = Executor(specForUsersTopics);
exec.start();
}
main();
So basically the code to collect the links would be supplied to the executor instance and then you would do whatever you wanted with the results in the callback. It can deal with longish lists of url (~1000) and it will work on more than one at a time (default == 5). It doesn't handle errors in the code block very well right now, so be sure to test the code you are supplying.
I'm liking Curtain A) "use C# and find a library..."
"HTML Agility Pack" might be just what you're looking for:
http://htmlagilitypack.codeplex.com/
You can do it easily with Node.js, jsdom, and jQuery. See this tutorial (in JavaScript).

Categories