Implementing simple CRUD with OpenRasta and Web Forms - asp.net

I've been asked to look into OpenRasta as an alternative to MVC ASP.NET at work, and as a starting point I'm trying to replicate the Movies tutorial from the MVC ASP.NET website.
I really like the ReST style of OpenRasta, and so far have got a simple database and a handler for GET based by ID, in the form of
ResourceSpace.Has.ResourcesOfType<Movie>()
.AtUri("/movie/{id}")
.HandledBy<MovieHandler>()
.RenderedByAspx("~/Views/MovieView.aspx");
I understand that use of POST and DELETE would allow me to create/update and delete items from my database, but unfortunately I'm stumped on how to do the views.
In the OpenRasta documentation it says:
When you use an aspx page as a view in OpenRasta, you essentially create a template to
generate content. As such, postbacks and events are not supported.
I might be being really dumb here, but would I be able to POST and DELETE from an ASP.NET page in the manner required by OpenRasta? I'm using a code-behind page, but that's not something I'm fixated upon.
I'm not that familiar with ASP.NET (haven't done any for ages), so I may be missing something obvious, but would really appreciate some pointers in the right direction.

What this means is that the postback model in asp.net webforms (aka the behavior by which the asp.net webforms infrastructure creates one massive form tag to post back asp.net specific data to a page continuously) is not supported, so any events you may be used to use on webforms controls will not work.
If you're used to MVC-styled interactions, you know how to use the form tag so you do as usual to create a new movie.
<form method="post">
<fieldset>
<input type="text" name="Name" />
<input type="submit" />
</fieldset>
The alternative is to do it in code using the webforms engine
<% using(scope(Xhtml.Form<Movie>().Post())) { %>
<%= Xhtml.TextBox<Movie>(_=>_.Name) %>
<% } >
And your handler code
public Movie Post(Movie movie) {
// create the movie instance in your db or whatever
return new OperationResult.SeeOther { RedirectLocation = movie.CreateUri() };
}
Code compiles in my head and may need a reality check before being put in a compiler.
Note that it's probably a good idea to move away from the webforms engine if you can, there are better alternatives (razor, spark, whatever you may decide to plug in).

Related

Reusing ASP.NET code in multiple pages

Is there a way to reuse a piece of ASP.NET code (that tag-based code, not the code-behind) in many different pages? For example I have a <div> with some contents in it that appears in 5 different pages of my site. I'm looking for a technique through which I could save this <div> in a separate web-content file so to speak, with maybe a different extension like MyDiv.ASPC and could then do a server-side tag anywhere in a webpage like:
<asp:Import href="~/MyDiv.aspc" />
and ASP.NET would inject the entire content of this file at that point where this tag appears.
I thought of creating a user control for this, but I'm not sure if a user control always injects precisely what is written in its body, or could there sometimes be unwanted tags generated by user control itself.
Or are there existing better ways of doing this?
Edit
About Master Pages, they are far away from what I'm looking for. They are actually good for a common basic layout of your website. My idea is quite opposite of that. My pages do not have a common layout; it is just that they have one common <div>. It is more closely fulfilled by a UserControl.
For UCs, my fear is that they generate more than what is written in their body, whereas what I'm after is a simple text injection. To put it technically, what I'm looking for is basically a preprocessor step (kind of #include thing in C++) rather than a compiler step, if you see what I mean.
You need to use ASP.NET User Controls, as these are specifically created to be the solution to the problem you are describing. For more information, see MS Documentation.
From their documentation...
In addition to using Web server controls in your ASP.NET Web pages,
you can create your own custom, reusable controls using the same
techniques you use for creating ASP.NET Web pages. These controls are
called user controls.
A user control is a kind of composite control that works much like an
ASP.NET Web page—you can add existing Web server controls and markup
to a user control, and define properties and methods for the control.
You can then embed them in ASP.NET Web pages, where they act as a
unit.
An empty userControl would do just that - nothing. A user Control just adds it's contents to the page, or usercontrol hosting it. It adds nothing extra.
UserControls give you a nice easy page fragment type approach to reusing content. They work great within a project & most people use them for just that.
If you wanted to make something more reusable across projects, you could write server control. It's more involved, but much more reusable. Google should be able to find you many tutorials on how to do this.
Ran a short test. User Controls do not enter extra tags as long as you don't place any Runat="Server" tags in it, so this would indeed be a solution I guess.
You can also read output from a cache object where you would read your files.
So
<%= Static.ContentXyz %>
would mean:
public static class Static
{
public static string ContentXyz
{
get
{
string s;
if (!this.cacheDictionary.TryGetValue("ContentXyz", out s))
{
s = File.ReadAllText(Server.MapPath("ContentXyz.html"));
this.cacheDictionary("ContentXyz", s);
}
return s;
}
}
}

Is there a CMS that will integrate alongside existing tools (maybe as a control inside a page) in asp.net?

I'm looking for a lightweight solution that will let me spread out the responsibility for content amongst various departments. This sounds a lot like a CMS. However, initial impressions suggest that when implementing a CMS you usually then have to integrate your existing tools to work inside that CMS. That doesn't sound terribly appealing.
What would be ideal, would be a CMS solution that could operate alongside existing architecture without the existing tools needing to make changes in order to continue doing what they've always done. Something like a control I can drop into a page and give a unique id, and that control will pull the appropriate content from the DB (one example only, other ways to accomplish the same goal are fine). Can probably put something like this together myself, but that seems very likely to be reinventing the wheel.
Are there any asp.net CMS solutions that can integrate in that fashion?
Extra points for:
Compatible with MS SQL
Ability to use existing asp.net users/roles to determine access to edit content
Works with both web forms and MVC
Ability to work with regular css, rather than needing to convert it in some fashion
Edit - Integrated HTML editor looks likely to solve the problem. N2 CMS also claimed to integrate alongside existing asp.net solutions, but I'm not sure what that entails. Are there things that I miss out on by going with an html editor? If I can put more power into the users hands, that'd be good as long as it was still able to operate alongside stuff rather than being something that everything else has to integrate into.
IF all you need is a very lightweight ability for users to control content on some ares of your site you can use an HTML editor control integrated into your environment just as suggested for free.
FCKEditor
TinyMCE
ExtJs
MarkdownSharp (Stack Overflow uses this one, modified...)
check out Ektron CMS400, it has server controls that you can add to existing pages.
Ektron is an .NET CMS that can plug it into an existing architecture. It is uses MS SQL Server and the latest version (v8.5) works with both web forms and MVC.
Its API (called the Framework API) is a .NET API used to perform CRUD operations on Content objects (GetItem(), GetList(), Add(), Update(), Delete()). For example, regarding your use case, it has methods that allow you to get content by its ID, get lists of content items by defining filters, and so on. You render Content using standard ASP.NET databinding, then style using CSS.
Here's a snippet for retrieving a Content object, then rendering using a standard ASP.NET ListView Server Control:
ContentManager contentManager = new ContentManager();
ContentData contentData = contentManager.GetItem(30);
ListView1.DataSource = new List<ContentData> { contentData };
ListView1.DataBind();
And then in your ASPX Template, you would render it using a ListView Server Control like this:
<form id="form1" runat="server">
<div>
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<h1><%# Eval("Title") %></h1>
<p><%# Eval("Html") %></p>
<p><%# Eval("DateCreated") %></p>
</ItemTemplate>
</asp:ListView>
</div>
</form>
The most recent release (v8.5) focused on providing a tight developer API, and has gotten a lot of positive feedback from developers. You can see some of that feedback here: http://ektron.tumblr.com/
To get a better understanding of what the developer experience is like using the latest version of Ektron, I'd recommend starting by watching these technical webinars: https://www.ektron.com/BlogPost.aspx?id=12884902084

asp.net mvc using div or any such text control

I have been trying to use div element in the view in controller but i can't find the control.
This is what I've done in the view:
<div id="z" style="display:none">
<p id="af">Please enter your CustomerID.You cannot try to enter Products for a different Customer </p>
</div>
controller side:
The intellisense does not show me div id. and Findcontrol seems to be useless. So, I need to make the div element viewable. Can you please help me?
I think you have major misunderstandings about how ASP.NET MVC works. There are no server controls. There is no ViewState, PostBacks and code behind contrary to what you might have the habit of using in classic WebForms. In ASP.NET MVC you write a Controller action which will receive the user request, manipulate the Model and pass a view model to the View for rendering.
I would recommend you checking out the following site and familiarize yourself with the basic notions by going through the tutorials: http://asp.net/mvc

jquery.clone() and ASP.NET Forms

So I have a page where I would like to be able to add multiple, dynamic users to a record in a database. Here's the rough start page:
<div id="records">
<div id="userRecord">
Name: <asp:TextBox runat="server" ID="objNameTextBox"></asp:TextBox> <br />
Phone Number: <asp:TextBox runat="server" ID="objPhoneNumberTextBox"></asp:TextBox> <br />
</div>
</div>
And the jquery:
$(function () {
$(".button").button().click(function (event) { addnew(); event.preventDefault(); });
})
function addnew() {
$('#userRecord').clone().appendTo('#records');
}
So my question is what do I use within ASP.NET to be able to poll all of the data in the form and add a unique record for each #userRecord div within the #records div? Yes - I should change the userRecord to a class - I will deal with that. This is just simple testing here.
Should I look in JSON for this type of function? I'm not familiar with it but could figure it out if that is indeed my best option. Thanks for the guidance!
You cannot duplicate ASP.NET web forms controls with Javascript, because the runtime keeps tracks of the controls in your HTML, if you try to duplicate them with Javascript, you duplicate the HTML and they may look the same, but ASP.NET won't know anything about them.
You could do it using an UpdatePanel, and triggering a post back in it with your button and create the controls in your backend programmatically and appending them to said panel, that would mimic what you are trying to do.
Another way would be creating HTML inputs and submitting the things to a web service, or a web method and do the actual insertions to the database there, but normal ASP.NET methods won't work on said inputs, as they are not controls as far as ASP.NET is concerned.
If you're trying to add new records during postback of the ASP.NET page, then ... good luck. I'm not sure you CAN add new 'items' to a list client-side. ASP.NET WebForms uses the view state (which is really just a big blob of information embedded directly in the HTML of the page that's returned to the user) to maintain the state of the page and I don't think you can easily (I'm sure it's theoretically possible) update the view state client-side (regardless of whether you're using jQuery or even JavaScript).
Maybe my own situation is similar enough. If I have a page with a list of items and I wish to allow the user to add new items, I'd add the appropriate input fields, as you've done, and add a special button for which I'd bind a JavaScript function (via jQuery) that makes an AJAX request to a web-service (another item in your Visual Studio project) and passes data back-and-forth using JSON (much simpler than using the default XML). That way the entire page doesn't need to be posted to the web server for the user to make changes to the backend data and you don't need to (somehow) parse the page data itself to determine what items need to be added to the database.

What is the recommended approach for Bulk Insert/Update in ASP.NET Gridview?

What best practice or strategy would you use to enable bulk insert/update in an asp.net gridview control with paging enabled?
Say for e.g. you have about 10000 records and this data gets populated when the page loads and this happens in chunks of say 100 records per webservice request.
To enable editing on these rows what approach would you follow.
Just to give an example say the object model for the fictitious scenario is given below.
List customers; // list of customers
customers = ServiceFacade.GetAllCustomers(pageSize, currentPage);
Assume the above service calls brings back 50 records based on the pageSize displaying 10 records per page.
This will be bound to the gridView as below.
gridCustomers.DataSource = customers;
gridCustomers.DataBind();
Some points I would think of is outlined below and requires experts inputs...
Disable viewstate for gridview (as this will slow down the performance of the page).
Use session object to persist the change (OR what would you recommend. Is two way binding really helpful here, I don't know as I haven't tried it.)
Your ideas/suggestions are greatly appreciated. I understand I could be flamed for this, but I think the good old DataSet may be useful here (as it has all the essential information which enables tracking changes etc).
Take a look at this article on Code Project.
UPDATE:
I found a better implementation of the same kind of control here.
Have you considered not using the ASP.Net GridView in favor of a purely client side grid control (i.e. a JQuery plugin control)? What I would suggest you consider is to perhaps use client side JSON or an XML data island as the data source, to store all the changes the user is making and then once they hit the main submit button send this payload to the server and handle all the database updates in a single batch or round trip.
The downside to this is that it is going to probably be quite a bit more work that just a ASP.Net GridView. Also you'll have to build in/incorporate an optimistic concurrency data model. Once it's all done you'll have a really fast and slick interface since most of the actions will occur client side without all the post backs. I built something like this several years back and it turned out great.
Sorry I cannot provide more, but below is a very rough skeleton of how it would work. I hope this helps.
<html>
<head>
<SCRIPT LANGUAGE="javascript">
var xmlDomItems;
function initialize()
{
xmlDomItems = document.all("itemsXML").XMLDocument;
docProds.async = false;
}
function ModifyXMLDOM()
{
// just work with the xmlDomItems variable just like you would with an .Net XMLDocument Object.
}
function SumbitChangePayload()
{
// submit xmlDomItems.OuterXML to some AJAX or web service endpoint in an async manner.
}
</SCRIPT>
</head>
<body onload="initialize()">
<XML id="itemsXML">
<Items>
<%
// Server side code to render XML inner contents here...
%>
</Items>
</XML>
<form>
<!-- build your UI here -->
<input type="button" onclick="SumbitChangePayload()" value="Submit" />
</form>
</body>
</html>

Resources