Ok, I'm still new to Asp.Net and MVC3. I'm becoming more familiar with things but still experimenting after finishing my first web application (a simple web form submission into a database). Now I am working on smaller projects such as converting some old ColdFusion web forms that submit e-mails. I've easily accomplished this in MVC3 but all of our web pages are in a separate content management system where our central HTML template is. I've already asked a question about this here and didn't get anywhere.
What we have is the majority of our web pages get exported from the CMS as straight HTML files, and only the ones that need database access or a programming language are exported as ColdFusion. It's very easy to "include" ColdFusion code to use inside of the template in our CMS. I would love to be able to use this HTML template in my mvc3 project but I've found no way to perform an "include" or link to an external file. I'm not sure how this would work anyway, so I settled on just copy/pasting the template to mvc3 and figuring out a way I can share this template (now a "layout") between all of the small projects I'll be working on. If the template changes I do not want to have to update every single little mvc3 web application. I learned about using "Areas" but it seems you can't just publish a single area to a folder on the web server, the whole project has to be deployed.
All I really need is a way for small mvc3 projects to use one template and these small mvc3 projects to be scattered all over our web server. Would this best be done in one large project that publishes to multiple different folders, or as many small projects that can share a common layout? Is either of these two possible?
After attempting and experimenting with all of this, I'm beginning to think MVC is not going to work with what I want. It seems better suited for intranet applications or entire web sites, not this little "here and there" applications like what I want. Should I learn Web Forms instead? I know I can "include" a aspx file inside our CMS much like I do with ColdFusion.
Do your templates have to be "exported" from the CMS? Or, can you have a template that "lives" on a static CMS URL? This is what we do for apps that need db access / can't be easily done within the CMS, but need to share the same look and feel.
What you can do is have your plain old HTML file live at a URL, for example, https://cms.domain.tld/templates/designxyz.html. That file will serve up a basic layout, except where your custom app content goes, you simply have the string "content goes here".
Then, from the MVC app, you can call this URL to get the HTML content as a string. Once you have the string, you can split it in 2 before and after the "content goes here" string. Then, in your layout.cshtml file, you can do something like this:
#{
const string contentPlaceholder = "content goes here";
var allHtml = GetHtmlTemplateFromLiveServer();
var index = allHtml.IndexOf(contentPlaceholder);
var topHtml = allHtml.Substring(0, index);
var botHtml = allHtml.Substring(index + contentPlaceHolder.Length);
}
#topHtml
#RenderBody()
#botHtml
If something like this works, you can then abstract all of this away into a HTML Helper, then reuse that helper in other projects (NuGet would be good for this).
_Layout.cshtml
#{
var options = new CmsTemplateRenderOptions
{
Url = "https://cms.domain.tld/templates/designxyz.html",
Cache = new TimeSpan(1, 0, 0);
};
}
#Html.RenderCmsTemplate(CmsTemplateRenderRegion.Top, options)
#RenderBody()
#Html.RenderCmsTemplate(CmsTemplateRenderRegion.Bottom, options)
Then, to update the layout for all of your apps, you would just publish changes to the https://cms.domain.tld/templates/designxyz.html URL.
Related
I want to alter the default code genaration of MVC CRUD ASP . NET.
Visual Studio.It generates pages of "Edit.cshtml/Insert.cshtml/Delete.cshtml"
I want to translate "Edit" to "Alterar" - "Insert" to "Inserir", and I would like that the razor file to be called "Alterar.cshtml" instead of "Edit.cshtml"
How can I do that?
Is it possible?
Yes, you can.
Based on this excellent blogpost by Scott Hanselman I changed the default template in a few steps. The difference between Scott's approach and mine is that he apparently made it in a way that keeps the global default but gives him a separate generator for each project. Since I didn't get it working immediately, I opted to instead just change the global template.
Go to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 4\CodeTemplates\AddController (some parts of the URI may vary in your situation
Optionally: grant yourselves write privileges on Controller.tt
Open Controller.tt in an editor of your choice and change what you want to change. Note that these are T4 templates so you have a wide variety of tools to your disposition if you want to do more advanced stuff.
Create a new ASP.NET MVC project
Go to the "Controllers" folder and add a new controller (not an api controller)
You don't have to change anything to get a differently named view: the view, including the file in which it is stored, is generated based on the name of the action method that creates it. If you generate the view from Alterar then the popup window will present you with the name "Alterar" for the file.
I am trying to write a windows services that will generate email based on HTML templates. I want my HTML templates to be included in my project as resources. Do i have read these these template files as using filestreams or are there built in C# functions to read these files as resources.
Is there better way to use HTML files as templates for generating emails in asp .net
Thanks
SCS
You just need to create resource file (.resx), then fill it in key/value manner like key = "email_template", value = "your html template". And after you will have the class with the field called email_template, and it will provide you your html template without any additional coding.
UPD
O, also you could save your template like asp.net user control (*.ascx) and then render it to string with technique described in this article
The same variant possible in MVC world. It could be done this way
For one project, we've to generate static .html pages, which are gonna to be published on the same server to serve to millions of visitors.
We've to automate the creation of those files from a c# code, which takes data from a SQL Server database.
The project is already developed using C# asp.net MVC3, and we need to store the dynamically generated pages in .html on the same url to be served to visitors.
I was wondering how to use asp.net MVC3/Razor to generate those .html pages?
I don't want/need to use web caching, for a lot of reasons(load(millions of pages loaded every day), these static pages will be cached on CDN network to further serve super fast without original server going into picture, number of pages are really too many (caching will only help me if I've the same pages a lot of time, but I will have more than million pages visited very frequently, so I will have to generate them often.)
So I really search something to generate HTML pages.
Any idea how to do this...
To start with, make sure your routes all produce urls that can be duplicated as static html files. So that your calls to Html.ActionLink will produce urls you can use.
Generate your whole site as if you are using it directly, and then let it be cached externally.
You could use something like wget on Linux to grab the whole html tree of the site, and put those up along with the content files; css, images, javascript, etc.
Then redownload the site when there are changes.
In my company we've done something similar. We have a separate program that goes trhough a list of urls, sends a http-request against them. Saves the result and copies it out to the web servers. This way we only have one web server with asp-code on it internally on the network and the servers on the internet has static copies of the dynamic pages. And we get some great performance out of it.
In order for you to get the list of urls you would probably have to create a special view/controller that queries the database for the keys that can be used to query the info you want. So if you have for example a site that shows hamburgers, your list view that creates the urls might query your burger-table and create a bunch of /myburger?name=Wopper type urls. Then your batch-program reads those urls and as described before, does a http-request and saves the result etc.
If you want to generate html based on the mvc views and models, you could use the Razor.
I have used it to generate email templates, where we have used the Razor to inject the model into a view. You could generate the html from the views and write them into static html files if that fits your purpose.
Refer Razor Engine from NuGet, And you could use it like
var html = Razor.Parse(templateView, model);
If you want more customization on it, May be this tutorial could help you.
http://www.west-wind.com/weblog/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String
I always use my own email generating method instead of MvcMailer.
First, you should generate a string from your view or partial, then add/remove some html tags, such as <html> etc, if you need... Next write this string into a file, save it as a .html file to your path.
public static string HTMLToString(ControllerContext context, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
var viewData = new ViewDataDictionary(model);
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
In the app I am working on, I want to allow the user to upload static HTML pages to replace the default "user profile" MVC View page. Is this possible? That is, the user uploaded html pages will totally run out of MVC, and it can include its own CSS links, etc.
Ideas? Suggestions?
Obviously the .net MVC framework handles static content already for images / css / js etc. It would just be a matter of extending that (routing?) to pass .html files through straight to IIS. That coupled with a dash of rewriting to make prettier urls should do the trick.
However, I would be very, very wary of allowing User Generated Content in the form of raw HTML uploads as you're leaving a very very wide door open. At best, you're going to wind up with people's pages full of spam/porn/adverts. At the worst, you'll be providing a gateway for people to upload cross-site scripting hacks and potentially uploading malicious content to damage your site. The could easily take an existing form on your site, hardcode a load of junk into it, and exectute it from their homepage and break a whole heap of things.
At the very least you should be parsing the uploaded content to reduce it down to just a block of content, and then wrapping that in your own etc. I would personally be much more inclined to just provide users with a nice WYSIWYG editor to edit a single block of content - any editor worth it's salt should provide you with sanitisation as to what elements it includes / excludes. Then store this content fragment in your database / on disc and have the request for a homepage go through a standard MVC controller route and load up that content.
Edit - for you request for examples
You should be able to add an Ignore rule to your routing - there will probably already be examples of these already - crack open your Global.asax file - you will want to put in a call to the routes.IgnoreRoute method :
routes.IgnoreRoute("UserPages/{*path}");
Should let IIS handle all requests for yourwebsite.com/UserPages/aUser/homepage.html - you can also play about a bit more with the wild card fragments / constraints for prettier solutions
I suggest you to make your custom ViewEngine that will allow to use static html markup with custom tags in it, that will be replaced by user info.
So, your view engine may accept something like that:
<html>
<body>
<b><user:FirstName /></b>
<b><user:LastName /></b>
</body>
</html>
and produce
<html>
<body>
<b>First Name</b>
<b>Last Name</b>
</body>
</html>
This custom markup you can store in database, for example.
You can take a look at custom ViewEngine implementations at MVC Contrib project.
We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's.
The way we're doing it now is with code I found here that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system.
Does anyone know of any way to do this?
I seem to have found the solution for my problemby using the Server.Ecxcute method.
I found an article that demonstared the use of it:
TextWriter textWriter = new StringWriter();
Server.Execute("myOtherPage.aspx", textWriter);
Then I do a few maniulatons on the textWriter, and insert it into an html file. Et voila! It works!
Calling the Render method is still pretty simple. Just create an instance of your page, create a stub WebContext along with the WebRequest object, and call the Render method of the page. You are then free to do whatever you want with the results.
Alternatively, write a little curl or wget script to download and store whichever pages you want to make static.
You could use wget (a command line tool) to recursively query each page and save them to html files. It would update all necessary links in the resulting html to reference .html files instead of .aspx. This way, you can code all your site as if you were using server-generated pages (easier to test), and then convert it to static pages.
If you need static HTML for performance reasons only, my preference would be to use ASP.Net output caching.
I recommend you do this a very simple way and don't do it in code. It will allow your CMS code to do what the CMS code should do and will keep it as simple as possible.
Use a product such as HTTrack. It calls itself a "website copier". It crawls a site and creates html output. It is fast and free. You can just have it run at whatever frequency you think is best.
It decouples your HTML output needs from your CMS design and implementation. It reduces complexity and gives you some flexibility in how you output the HTML without introducing failure points in your CMS code.
#ckarras: I would rather not use an external tool, because I want the HTML pages to be created programmatically and not manually.
#jttraino: I don't have a time interval in which the site needs to be outputted- the uotput has to occur when a user creates a new site.
#Frank Krueger: I don't really understand how to create an instance of my page using WebContext and WebRequest.
I searched for "wget" in searchdotnet, and got to a post about a .net class called WebClient. It seems to do what I want if I use the DownloadString() method - gets a string from a specific url. The problem is that because our CMS needs to be logged in to, when the method tries to reach the page it's thrown to the login page, and therefore returns the login.aspx HTML...
Any thoughts as to how I can continue from here?