Quotes in Asp.NET MVC View - asp.net

In View,
#{
Layout = "~/Views/Shared/site.cshtml";
ViewBag.Title = "Organizations";
var organizations = "";
foreach (var org in Model)
{
organizations += "'" + org.Name + "':'" + org.Id + "',";
}
organizations = organizations.Substring(0, organizations.Length - 1);
}
Result operation: organizations = "'Passport':'14f0eac0-43eb-4c5f-b9fe-a09d2848db80','Bank':'ad1d77d8-7eb1-4a4c-9173-b0f2f7269644'";
Output the data in section JS code.
But when viewing the source code of the page in the browser, not getting what wanted.
What's the problem? How to make a normal quotes?
JS: "data": "#organizations"
Result in view webpage returned "data": "'Passport':'14f0eac0-43eb-4c5f-b9fe-a09d2848db80','Bank':'ad1d77d8-7eb1-4a4c-9173-b0f2f7269644'"

OK cool Q,try this source:
#{
var model = Model.ToArray().Select(org => string.Format("'{0}':'{1}'", org.Name, org.Id));
var data = string.Join(",", model);
}
#Html.Raw(data)

What if you change
"data": "#organizations"
to
"data": "#Html.Raw(organizations)"

#Html.Raw(content)
And check this one out: http://jeffreypalermo.com/blog/what-is-the-difference-in-lt-variable-gt-and-lt-variable-gt-in-asp-net-mvc/

In your code example here, the culprit is the
#organizations
that generates the quotes. You could instead use:
#Html.Raw(organizations)
Okay, that's great, but by creating JSON, you are doing work the framework could be doing for you. You probably want a model that the framework can serialize for you. This way you don't even need any code in your view header at all.
#Html.Raw(JsonConvert.SerializeObject(Model.ToDictionary(m => m.Name, m => m.Id))))
Above, note that I'm using Json.NET, which you probably want to NuGET into your project because Microsoft is moving to it. No point in figuring out how to use the old JSON serializer to do this. Also note that unless you are using the model for other purposes, you might choose to do the dictionary conversion outside the view, reducing the code-work in the view.
Next, if you are embedding JSON in the view, you might want to consider one of two other options. If the amount of data will be small, consider using the join method proposed by eli (here), but instead encoding it in HTML 5 "data-" elements and loading it using JavaScript. That way you keep javascript out of your view. It's just one more step of confusing when debugging javascript, looking for variables that are initialized by dynamically-generated HTML.
Better yet, create a reusable HTML helper method to transform your model into data attributes: How to use dashes in HTML-5 data-* attributes in ASP.NET MVC
Finally, if there are MANY JSON elements, consider sending the data separately. Render it with a simple Json() method in your controller, and get it with a simple jQuery $.json() in your client-side code. See here for an example
Good luck!

Related

Replace single quotes

I am using Google Forms to get data and them importing it into Google Fusion Tables. The problem is if someone type an '. The script I am using is here. Could I edit it to replace or remove all apostrophes before syncing? If it is possible I would prefer to do it inside of the Google Spreadsheet using some formula. I think I could also use another script just to do this but I am not really sure how to do that.
I am using the form to gather applications for dogs so people of all ages will be using it. I really wish I could just say don't use apostrophes but people will not always see that.
Thanks for any help!
Sure here is an easy way with JS:
Working Fiddle: https://jsbin.com/hosagu/3/edit?js,console
var str = "don't";
var test = "f's'a'g'd'a's'd'g'";
console.log(str.replace(/\'/g, "")); // "dont"
console.log(test.replace(/\'/g, "")); //"fsagdasdg"
As a 'Script' or function:
function REMOVEAPOSTROPHE (string) {
return str.replace(/\'/g, "");
}

Meteor how to save templates in mongo

I want to give my users the possibility to create document templates (contracts, emails, etc.)
The best option I figured out would be to store these document templates in mongo (maybe I'm wrong...)
I've been searching for a couple of hours now but I can't figure out how to render these document template with their data context.
Example:
Template stored in Mongo: "Dear {{firstname}}"
data context: {firstname: "Tom"}
On Tom's website, He should read: "Dear Tom"
How can I do this?
EDIT
After some researches, I discovered a package called spacebars-compiler that brings the option to compile to the client:
meteor add spacebars-compiler
I then tried something like this:
Template.doctypesList.rendered = ->
content = "<div>" + this.data.content + "</div>"
template = Spacebars.compile content
rendered = UI.dynamic(template,{name:"nicolas"})
UI.insert(rendered, $(this).closest(".widget-body"))
but it doesn't work.
the template gets compiled but then, I don't know how to interpret it with its data context and to send it back to the web page.
EDIT 2
I'm getting closer thanks to Tom.
This is what I did:
Template.doctypesList.rendered = ->
content = this.data.content
console.log content
templateName = "template_#{this.data._id}"
Template.__define__(templateName, () -> content)
rendered = UI.renderWithData(eval("Template.#{templateName}"),{name:"nicolas"})
UI.insert(rendered, $("#content_" + this.data._id).get(0))
This works excepted the fact that the name is not injected into the template. UI.renderWithData renders the template but without the data context...
The thing your are missing is the call to (undocumented!) Template.__define__ which requires the template name (pick something unique and clever) as the first argument and the render function which you get from your space bars compiler. When it is done you can use {{> UI.dynamic}} as #Slava suggested.
There is also another way to do it, by using UI.Component API, but I guess it's pretty unstable at the moment, so maybe I will skip this, at least for now.
Use UI.dynamic: https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/
It is fairly new and didn't make its way to docs for some reason.
There are few ways to achieve what you want, but I would do it like this:
You're probably already using underscore.js, if not Meteor has core package for it.
You could use underscore templates (http://underscorejs.org/#template) like this:
var templateString = 'Dear <%= firstname %>'
and later compile it using
_.template(templateString, {firstname: "Tom"})
to get Dear Tom.
Of course you can store templateString in MongoDB in the meantime.
You can set delimiters to whatever you want, <%= %> is just the default.
Compiled template is essentially htmljs notation Meteor uses (or so I suppose) and it uses Template.template_name.lookup to render correct data. Check in console if Template.template_name.lookup("data_helper")() returns the correct data.
I recently had to solve this exact (or similar) problem of compiling templates client side. You need to make sure the order of things is like this:
Compiled template is present on client
Template data is present (verify with Template.template_name.lookup("data_name")() )
Render the template on page now
To compile the template, as #apendua have suggested, use (this is how I use it and it works for me)
Template.__define__(name, eval(Spacebars.compile(
newHtml, {
isTemplate: true,
sourceName: 'Template "' + name + '"'
}
)));
After this you need to make sure the data you want to render in template is available before you actually render the template on page. This is what I use for rendering template on page:
UI.DomRange.insert(UI.render(Template.template_name).dom, document.body);
Although my use case for rendering templates client side is somewhat different (my task was to live update the changed template overriding meteor's hot code push), but this worked best among different methods of rendering the template.
You can check my very early stage package which does this here: https://github.com/channikhabra/meteor-live-update/blob/master/js/live-update.js
I am fairly new to real-world programming so my code might be ugly, but may be it'll give you some pointers to solve your problem. (If you find me doing something stupid in there, or see something which is better done some other way, please feel free to drop a comment. That's the only way I get feedback for improvement as I am new and essentially code alone sitting in my dark corner).

EF 4.3 Code First Migrations - Uncompress __MigrationHistory Model

How can I uncompress/read the compressed models stored in the EF 4.3 Code First Migrations __MigrationHistory table?
I found a hint in this comment, that I can uncompress it using zip/gzip, but I don't know how exactly I should do this.
The problem is that I have changed something in my ef model classes, but when I call "add-migration" an empty migration ist generated. I think that is because the changes of my model classes are already assigned to an existing migration :(
(this may be a good starting point - won't work in your case)
I think you may find this useful - you 'just' need to work it out in the opposite direction, I think (I'm just hinting here as to what might be the direction, you'll have to check it out, test yourself)...
http://brice-lambson.blogspot.com/2012/05/using-entity-framework-code-first-with.html
It uses the following code...
private byte[] GetModel(TContext context)
{
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(
memoryStream,
CompressionMode.Compress))
using (var xmlWriter = XmlWriter.Create(
gzipStream,
new XmlWriterSettings { Indent = true }))
{
EdmxWriter.WriteEdmx(context, xmlWriter);
}
return memoryStream.ToArray();
}
}
to serialize the model.
However, as I understand (if I understand it properly) you need it in the other direction...
Quick search didn't show the equivalent reader - you can download the latest EF6 code - or also find EF5 one (I'll link in later if needed).
Reader:
Actually this may be closer to what you want:
http://edmxdom.codeplex.com/
(I haven't tried it out but was linked from MS)
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/1546548f-9f90-4cc2-b1b2-28cf7e9d1cb5/
And check the response about using MetadataWorkspace
If you need more info on the MetadataWorkspace I'll post some posts I made on that subject. You can get most info out - you'll need to sort 'reverse' what EdmxWriter is doing.
Essentially, you're looking for entity framework Edmx reader.
EdmxDOM:
I just checked it out fast - and it seems to be doing the Edmx format management you need.
It's a 'VB' project - but you can work through that
There is what seems to be a 'reader' (again, not sure, just went through this, as I know about the writer - but never worked w/ this part, direction)...
Public Sub LoadFile(ByVal fileName As String)
In the Edmx.vb

How to get the itemxml of a selected item in Tridion

I would like to get and display the itemxml of the selected item from the Tridion CME.
I was able to get the Itemxml from my VM server when i give the tcm id in the browser.
However, i would like to get the same information from Tridion GUI Extension.
I am able to get the selected item tcm id. Is there any way to get the itemxml using coreservice?
or is there any other way to get this?
At the moment there's no way you can get Item XML through core service. Item XML you have seen was provided to you by TCM Protocol handler that might not be there in future versions. If you want to show item XML in CME - take a look at this extention by Yoaw:
http://sdltridionworld.com/articles/sdltridion2011/tutorials/GUIextensionIn8steps.aspx
Also, keep in mind that not all properties of an item might be exposed in Xml, sometimes you have more info in Data object
Take a look at the PowerTools, it has an ItemXML viewer (written by Robert Curlette) for all items in SDL Tridion
http://code.google.com/p/tridion-2011-power-tools/wiki/ItemXML
The XML is loaded on a tab using JavaScript as follows:
ItemXmlTab.ItemXmlTab.prototype.updateView = function ItemXmlTab$updateView()
{
if (this.isSelected())
{
var xslPath = $ptUtils.expandPath("/PowerTools/Client/ItemXml/ItemXmlTab.xslt", true);
$xml.loadXsltProcessor(xslPath, function (value)
{
var xmlSource = $display.getItem().getXml();
// Filter out all spacing characters
xmlSource = xmlSource.replace(/\t|\n|\r/g, "");
var html = $xml.xsltTransform(value, $xml.getNewXmlDocument(xmlSource), null);
$dom.setOuterHTML($("#itemXml"), html);
});
}
};
You can view the source code of the extension at http://code.google.com/p/tridion-2011-power-tools/source/browse/#svn%2Ftrunk%2FPowerTools.Editor%2FPowerTools%2FClient%2FItemXml%253Fstate%253Dclosed
You can get the item XML via CoreService, but this will get you the Tridion R6 (2011) Xml format, which is not the same you would see before.
Sample code available here.
I tend to have a page "GetItemXml.aspx" on my Tcm servers that I then call with a Uri as a parameter, and then this page would return the Item Xml.
Article written by Yoav Niran (Url in the post of user978511) is perfect for your requirement.
if you are still facing any issue and in hurry to get it working just perform below steps -
1- Download the extension.
2- Apply the steps 7 and 8 of this article to configure this extension.

.NET frameworks for formatting e-mail messages?

Are there any open source/free frameworks available that take some of the pain out of building HTML e-mails in C#?
I maintain a number of standalone ASP.NET web forms whose main function is to send an e-mail. Most of these are in plain text format right now, because doing a nice HTML presentation is just too tedious.
I'd also be interested in other approaches to tackling this same problem.
EDIT: To be clear, I'm interested in taking plain text form input (name, address, phone number) and dropping it into an HTML e-mail template. That way the receipient would see a nicely formatted message instead of the primitive text output we're currently giving them.
EDIT 2: As I'm thinking more about this and about the answers the question has generated so far, I'm getting a clearer picture of what I'm looking for. Ideally I'd like a new class that would allow me to go:
HtmlMessage body = new HtmlMessage();
body.Header(imageLink);
body.Title("Some Text That Will Display as a Header");
body.Rows.Add("First Name", FirstName.Text);
The HtmlMessage class builds out a table, drops the images in place and adds new rows for each field that I add. It doesn't seem like it would be that hard to write, so if there's nothing out there, maybe I'll go that route
Andrew Davey created Postal which lets you do templated emails using any of the ASP.NET MVC view engines. Here's a video where he talks about how to use it.
His examples:
public class HomeController : Controller {
public ActionResult Index() {
dynamic email = new Email("Example");
email.To = "webninja#example.com";
email.FunnyLink = DB.GetRandomLolcatLink();
email.Send();
return View();
}
}
And the template using Razor:
To: #ViewBag.To From: lolcats#website.com Subject: Important Message
Hello, You wanted important web links right? Check out this:
#ViewBag.FunnyLink
<3
The C# port of StringTemplate worked well for me. I highly recommend it. The template file can have a number of named tokens like this:
...
<b>
Your information to login is as follows:<br />
Username: $username$<br />
Password: $password$<br />
</b>
...
...and you can load this template and populate it like this:
notificationTemplate.SetAttribute("username", Username);
notificationTemplate.SetAttribute("password", Password);
At the end, you get the ToString() of the template and assign it to the MailMessage.Body property.
I recently implemented what you're describing using MarkDownSharp. It was pretty much painless.
It's the same framework (minus a few tweaks) that StackOverflow uses to take plain-text-formatted posts and make them look like nice HTML.
Another option would be to use something like TinyMCE to give your users a WYWIWYG HTML editor. This would give them more power over the look and feel of their emails, but it might just overcomplicate things.
Bear in mind that there are also some security issues with user-generated HTML. Regardless of which strategy you use, you need to make sure you sanitize the user's input so they can't include scary things like script tags in their input.
Edit
Sorry, I didn't realize you were looking for an email templating solution. The simplest solution I've come up with is to enable text "macros" in user-generated content emails. So, for example, the user could input:
Dear {RecipientFirstName},
Thank you for your interest in {ClientCompanyName}. The position you applied for has the following minimum requirements:
- B.S. or greater in Computer Science or related field
- ...
And then we'd do some simple parsing to break this down to:
Dear {0},
Thank you for your interest in {1}. The position you applied for has the following minimum requirements:
- B.S. or greater in Computer Science or related field
- ...
... and ...
0 = "RecipientFirstName"
1 = "ClientCompanyName"
...
We store these two components in our database, and whenever we're ready to create a new instance from this template, we evaluate the values of the given property names, and use a standard format string call to generate the actual content.
string.Format(s, macroCodes.Select(c => EvaluateMacroCode(c, obj)).ToArray());
Then I use MarkdownSharp, along with some HTML sanitizing methods, to produce a nicely-formatted HTML email message:
Dear John,
Thank you for your interest in Microsoft. The position you applied for has the following minimum requirements:
B.S. or greater in Computer Science or related field
...
I'd be curious to know if there's something better out there, but I haven't found anything yet.

Resources