Search Results

Search found 54019 results on 2161 pages for 'asp net weblogs'.

Page 12/2161 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Membership in ASP.Net applications - part 3

    - by nikolaosk
    This is the third post in a series of posts regarding ASP.Net built in membership functionality,providers,controls. You can read the first one post one here . You can read the second post here . In this post I would like to investigate how to use the Membership class methods to achieve the same functionality we have with the login web server controls.The login web server controls live inside the .aspx pages and access the underlying abstract membership classes to perform the desired functionality...(read more)

    Read the article

  • ASP.NET 4.0- Menu control enhancement.

    - by Jalpesh P. Vadgama
    Till asp.net 3.5 asp.net menu control was rendered through table. And we all know that it is very hard to have CSS applied to table. For a professional look of our website a CSS is must required thing. But in asp.net 4.0 Menu control is table less it will loaded with UL and LI tags which is easier to manage through CSS. Another problem with table is it will create a large html which will increase your asp.net page KB and decrease your performance. While with UL and LI Tags its very easy very short. So You page KB Size will also be down. Let’s take a simple example. Let’s Create a menu control in asp.net with four menu item like following. <asp:Menu ID="myCustomMenu" runat="server" > <Items> <asp:MenuItem Text="Menu1" Value="Menu1"></asp:MenuItem> <asp:MenuItem Text="Menu2" Value="Menu2"></asp:MenuItem> <asp:MenuItem Text="Menu3" Value="Menu3"></asp:MenuItem> <asp:MenuItem Text="Menu4" Value="Menu4"></asp:MenuItem> </Items></asp:Menu> It will render menu in browser like following. Now If we render this menu control with tables then HTML as you can see via view page source like following.   Now If in asp.net 4.0 It will be loaded with UL and LI tags and if you now see page source then it will look like following. Which will have must lesser HTML then it was earlier like following. So isn’t that great performance enhancement?.. It’s very cool. If you still like old way doing with tables then in asp.net 4.0 there is property called ‘RenderingMode’ is given. So you can set RenderingMode=Table then it will load menu control with table otherwise it will load menu control with UL and LI Tags. That’s it..Stay tuned for more..Happy programming.. Technorati Tags: Menu,Asp.NET 4.0

    Read the article

  • Class-Level Model Validation with EF Code First and ASP.NET MVC 3

    - by ScottGu
    Earlier this week the data team released the CTP5 build of the new Entity Framework Code-First library.  In my blog post a few days ago I talked about a few of the improvements introduced with the new CTP5 build.  Automatic support for enforcing DataAnnotation validation attributes on models was one of the improvements I discussed.  It provides a pretty easy way to enable property-level validation logic within your model layer. You can apply validation attributes like [Required], [Range], and [RegularExpression] – all of which are built-into .NET 4 – to your model classes in order to enforce that the model properties are valid before they are persisted to a database.  You can also create your own custom validation attributes (like this cool [CreditCard] validator) and have them be automatically enforced by EF Code First as well.  This provides a really easy way to validate property values on your models.  I showed some code samples of this in action in my previous post. Class-Level Model Validation using IValidatableObject DataAnnotation attributes provides an easy way to validate individual property values on your model classes.  Several people have asked - “Does EF Code First also support a way to implement class-level validation methods on model objects, for validation rules than need to span multiple property values?”  It does – and one easy way you can enable this is by implementing the IValidatableObject interface on your model classes. IValidatableObject.Validate() Method Below is an example of using the IValidatableObject interface (which is built-into .NET 4 within the System.ComponentModel.DataAnnotations namespace) to implement two custom validation rules on a Product model class.  The two rules ensure that: New units can’t be ordered if the Product is in a discontinued state New units can’t be ordered if there are already more than 100 units in stock We will enforce these business rules by implementing the IValidatableObject interface on our Product class, and by implementing its Validate() method like so: The IValidatableObject.Validate() method can apply validation rules that span across multiple properties, and can yield back multiple validation errors. Each ValidationResult returned can supply both an error message as well as an optional list of property names that caused the violation (which is useful when displaying error messages within UI). Automatic Validation Enforcement EF Code-First (starting with CTP5) now automatically invokes the Validate() method when a model object that implements the IValidatableObject interface is saved.  You do not need to write any code to cause this to happen – this support is now enabled by default. This new support means that the below code – which violates one of our above business rules – will automatically throw an exception (and abort the transaction) when we call the “SaveChanges()” method on our Northwind DbContext: In addition to reactively handling validation exceptions, EF Code First also allows you to proactively check for validation errors.  Starting with CTP5, you can call the “GetValidationErrors()” method on the DbContext base class to retrieve a list of validation errors within the model objects you are working with.  GetValidationErrors() will return a list of all validation errors – regardless of whether they are generated via DataAnnotation attributes or by an IValidatableObject.Validate() implementation.  Below is an example of proactively using the GetValidationErrors() method to check (and handle) errors before trying to call SaveChanges(): ASP.NET MVC 3 and IValidatableObject ASP.NET MVC 2 included support for automatically honoring and enforcing DataAnnotation attributes on model objects that are used with ASP.NET MVC’s model binding infrastructure.  ASP.NET MVC 3 goes further and also honors the IValidatableObject interface.  This combined support for model validation makes it easy to display appropriate error messages within forms when validation errors occur.  To see this in action, let’s consider a simple Create form that allows users to create a new Product: We can implement the above Create functionality using a ProductsController class that has two “Create” action methods like below: The first Create() method implements a version of the /Products/Create URL that handles HTTP-GET requests - and displays the HTML form to fill-out.  The second Create() method implements a version of the /Products/Create URL that handles HTTP-POST requests - and which takes the posted form data, ensures that is is valid, and if it is valid saves it in the database.  If there are validation issues it redisplays the form with the posted values.  The razor view template of our “Create” view (which renders the form) looks like below: One of the nice things about the above Controller + View implementation is that we did not write any validation logic within it.  The validation logic and business rules are instead implemented entirely within our model layer, and the ProductsController simply checks whether it is valid (by calling the ModelState.IsValid helper method) to determine whether to try and save the changes or redisplay the form with errors. The Html.ValidationMessageFor() helper method calls within our view simply display the error messages our Product model’s DataAnnotations and IValidatableObject.Validate() method returned.  We can see the above scenario in action by filling out invalid data within the form and attempting to submit it: Notice above how when we hit the “Create” button we got an error message.  This was because we ticked the “Discontinued” checkbox while also entering a value for the UnitsOnOrder (and so violated one of our business rules).  You might ask – how did ASP.NET MVC know to highlight and display the error message next to the UnitsOnOrder textbox?  It did this because ASP.NET MVC 3 now honors the IValidatableObject interface when performing model binding, and will retrieve the error messages from validation failures with it. The business rule within our Product model class indicated that the “UnitsOnOrder” property should be highlighted when the business rule we hit was violated: Our Html.ValidationMessageFor() helper method knew to display the business rule error message (next to the UnitsOnOrder edit box) because of the above property name hint we supplied: Keeping things DRY ASP.NET MVC and EF Code First enables you to keep your validation and business rules in one place (within your model layer), and avoid having it creep into your Controllers and Views.  Keeping the validation logic in the model layer helps ensure that you do not duplicate validation/business logic as you add more Controllers and Views to your application.  It allows you to quickly change your business rules/validation logic in one single place (within your model layer) – and have all controllers/views across your application immediately reflect it.  This help keep your application code clean and easily maintainable, and makes it much easier to evolve and update your application in the future. Summary EF Code First (starting with CTP5) now has built-in support for both DataAnnotations and the IValidatableObject interface.  This allows you to easily add validation and business rules to your models, and have EF automatically ensure that they are enforced anytime someone tries to persist changes of them to a database.  ASP.NET MVC 3 also now supports both DataAnnotations and IValidatableObject as well, which makes it even easier to use them with your EF Code First model layer – and then have the controllers/views within your web layer automatically honor and support them as well.  This makes it easy to build clean and highly maintainable applications. You don’t have to use DataAnnotations or IValidatableObject to perform your validation/business logic.  You can always roll your own custom validation architecture and/or use other more advanced validation frameworks/patterns if you want.  But for a lot of applications this built-in support will probably be sufficient – and provide a highly productive way to build solutions. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • jQuery Templates with ASP.NET MVC

    - by hajan
    In my three previous blogs, I’ve shown how to use Templates in your ASPX website. Introduction to jQuery TemplatesjQuery Templates - tmpl(), template() and tmplItem()jQuery Templates - {Supported Tags}Now, I will show one real-world example which you may use it in your daily work of developing applications with ASP.NET MVC and jQuery. In the following example I will use Pubs database so that I will retrieve values from the authors table. To access the data, I’m using Entity Framework. Let’s pass throughout each step of the scenario: 1. Create new ASP.NET MVC Web application 2. Add new View inside Home folder but do not select a master page, and add Controller for your View 3. BODY code in the HTML <body>     <div>         <h1>Pubs Authors</h1>         <div id="authorsList"></div>     </div> </body> As you can see  in the body we have only one H1 tag and a div with id authorsList where we will append the data from database.   4. Now, I’ve created Pubs model which is connected to the Pub database and I’ve selected only the authors table in my EDMX model. You can use your own database. 5. Next, lets create one method of JsonResult type which will get the data from database and serialize it into JSON string. public JsonResult GetAuthors() {     pubsEntities pubs = new pubsEntities();     var authors = pubs.authors.ToList();     return Json(authors, JsonRequestBehavior.AllowGet); } So, I’m creating object instance of pubsEntities and get all authors in authors list. Then returning the authors list by serializing it to JSON using Json method. The JsonRequestBehaviour.AllowGet parameter is used to make the GET requests from the client become allowed. By default in ASP.NET MVC 2 the GET is not allowed because of security issue with JSON hijacking.   6. Next, lets create jQuery AJAX function which will call the GetAuthors method. We will use $.getJSON jQuery method. <script language="javascript" type="text/javascript">     $(function () {         $.getJSON("GetAuthors", "", function (data) {             $("#authorsTemplate").tmpl(data).appendTo("#authorsList");         });     }); </script>   Once the web page is downloaded, the method will be called. The first parameter of $.getJSON() is url string in our case the method name. The second parameter (which in the example is empty string) is the key value pairs that will be send to the server, and the third function is the callback function or the result which is going to be returned from the server. Inside the callback function we have code that renders data with template which has id #authorsTemplate and appends it to element which has #authorsList ID.   7. The jQuery Template <script id="authorsTemplate" type="text/html">     <div id="author">         ${au_lname} ${au_fname}         <div id="address">${address}, ${city}</div>         <div id="contractType">                     {{if contract}}             <font color="green">Has contract with the publishing house</font>         {{else}}             <font color="red">Without contract</font>         {{/if}}         <br />         <em> ${printMessage(state)} </em>         <br />                     </div>     </div> </script> As you can see, I have tags containing fields (au_lname, au_fname… etc.) that corresponds to the table in the EDMX model which is the same as in the database. One more thing to note here is that I have printMessage(state) function which is called inside ${ expression/function/field } tag. The printMessage function <script language="javascript" type="text/javascript">     function printMessage(s) {         if (s=="CA") return "The author is from California";         else return "The author is not from California";     } </script> So, if state is “CA” print “The author is from California” else “The author is not from California”   HERE IS THE COMPLETE ASPX CODE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>Database Example :: jQuery Templates</title>     <style type="text/css">         body           {             font-family:Verdana,Arial,Courier New, Sans-Serif;             color:Black;             padding:2px, 2px, 2px, 2px;             background-color:#FF9640;         }         #author         {             display:block;             float:left;             text-decoration:none;             border:1px solid black;             background-color:White;             padding:20px 20px 20px 20px;             margin-top:2px;             margin-right:2px;             font-family:Verdana;             font-size:12px;             width:200px;             height:70px;}         #address           {             font-style:italic;             color:Blue;             font-size:12px;             font-family:Verdana;         }         .author_hover {background-color:Yellow;}     </style>     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>     <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>     <script language="javascript" type="text/javascript">         function printMessage(s) {             if (s=="CA") return "The author is from California";             else return "The author is not from California";         }     </script>     <script id="authorsTemplate" type="text/html">         <div id="author">             ${au_lname} ${au_fname}             <div id="address">${address}, ${city}</div>             <div id="contractType">                         {{if contract}}                 <font color="green">Has contract with the publishing house</font>             {{else}}                 <font color="red">Without contract</font>             {{/if}}             <br />             <em> ${printMessage(state)} </em>             <br />                         </div>         </div>     </script>     <script language="javascript" type="text/javascript">         $(function () {             $.getJSON("GetAuthors", "", function (data) {                 $("#authorsTemplate").tmpl(data).appendTo("#authorsList");             });         });     </script> </head>     <body>     <div id="title">Pubs Authors</div>     <div id="authorsList"></div> </body> </html> So, in the complete example you also have the CSS style I’m using to stylize the output of my page. Here is print screen of the end result displayed on the web page: You can download the complete source code including examples shown in my previous blog posts about jQuery templates and PPT presentation from my last session I had in the local .NET UG meeting in the following DOWNLOAD LINK. Do let me know your feedback. Regards, Hajan

    Read the article

  • Include weather information in ASP.Net site from weather.com services

    - by sreejukg
    In this article, I am going to demonstrate how you can use the XMLOAP services (referred as XOAP from here onwards) provided by weather.com to display the weather information in your website. The XOAP services are available to be used for free of charge, provided you are comply with requirements from weather.com. I am writing this article from a technical point of view. If you are planning to use weather.com XOAP services in your application, please refer to the terms and conditions from weather.com website. In order to start using the XOAP services, you need to sign up the XOAP datafeed. The signing process is simple, you simply browse the url http://www.weather.com/services/xmloap.html. The URL looks similar to the following. Click on the sign up button, you will reach the registration page. Here you need to specify the site name you need to use this feed for. The form looks similar to the following. Once you fill all the mandatory information, click on save and continue button. That’s it. The registration is over. You will receive an email that contains your partner id, license key and SDK. The SDK available in a zipped format, contains the terms of use and documentation about the services available. Other than this the SDK includes the logos and icons required to display the weather information. As per the SDK, currently there are 2 types of information available through XOAP. These services are Current Conditions for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Hourly Five-Day Forecast (today + 4 additional forecast days in consecutive order beginning with tomorrow) for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Three Times Daily The SDK provides detailed information about the fields included in response of each service. Additionally there is a refresh rate that you need to comply with. As per the SDK, the refresh rate means the following “Refresh Rate” shall mean the maximum frequency with which you may call the XML Feed for a given LocID requesting a data set for that LocID. During the time period in between refresh periods the data must be cached by you either in the memory on your servers or in Your Desktop Application. About the Services Weather.com will provide you with access to the XML Feed over the Internet through the hostname xoap.weather.com. The weather data from the XML feed must be requested for a specific location. So you need a location ID (LOC ID). The XML feed work with 2 types of location IDs. First one is with City Identifiers and second one is using 5 Digit US postal codes. If you do not know your location ID, don’t worry, there is a location id search service available for you to retrieve the location id from city name. Since I am a resident in the Kingdom of Bahrain, I am going to retrieve the weather information for Manama(the capital of Bahrain) . In order to get the location ID for Manama, type the following URL in your address bar. http://xoap.weather.com/search/search?where=manama I got the following XML output. <?xml version="1.0" encoding="UTF-8"?> <!-- This document is intended only for use by authorized licensees of The –> <!-- Weather Channel. Unauthorized use is prohibited. Copyright 1995-2011, –> <!-- The Weather Channel Interactive, Inc. All Rights Reserved. –> <search ver="3.0">       <loc id="BAXX0001" type="1">Al Manama, Bahrain</loc> </search> You can try this with any city name, if the city is available, it will return the location id, and otherwise, it will return nothing. In order to get the weather information, from XOAP,  you need to pass certain parameters to the XOAP service. A brief about the parameters are as follows. Please refer SDK for more details. Parameter name Possible Value cc Optional, if you include this, the current condition will be returned. Value can be anything, as it will be ignored e.g. cc=* dayf If you want the forecast for 5 days, specify dayf=5 This is optional iink Value should be XOAP par Your partner id. You can find this in your registration email from weather.com prod Value should be XOAP key The license key assigned to you. This will be available in the registration email unit s or m (standard or matric or you can think of Celsius/Fahrenheit) this is optional field, if not specified the unit will be standard(s) The URL host for the XOAP service is http://xoap.weather.com. So for my purpose, I need the following request to be made to access the XOAP services. http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=*********&key=************** (The ***** to be replaced with the corresponding alternatives) The response XML have a root element “weather”. Under the root element, it has the following sections <head> - the meta data information about the weather results returned. <loc> - the location data block that provides, the information about the location for which the wheather data is retrieved. <lnks> - the 4 promotional links you need to place along with the weather display. Additional to these 4 links, there should be another link with weather channel logo to the home page of weather.com. <cc> - the current condition data. This element will be there only if you specify the cc element in the request. <dayf> - the forcast data as you specified. This element will be there only if you specify the dayf in the request. In this walkthrough, I am going to capture the weather information for Manama (Location ID: BAXX0001). You need 2 applications to display weather information in your website. A Console application that retrieves data from the XMLOAP and store in the SQL Server database (or any data store as you prefer).This application will be scheduled to execute in every 25 minutes using windows task scheduler, so that we can comply with the refresh rate. A web application that display data from the SQL Server database Retrieve the Weather from XOAP I have created a console application named, Weather Service. I created a SQL server database, with the following columns. I named the table as tblweather. You are free to choose any name. Column name Description lastUpdated Datetime, this is the last time when the weather data is updated. This is the time of the service running TemparatureDateTime The date and time returned by XML feed Temparature The temperature returned by the XML feed. TemparatureUnit The unit of the temperature returned by the XML feed iconId The id of the icon to be used. Currently 48 icons from 0 to 47 are available. WeatherDescription The Weather Description Phrase returned by the feed. Link1url The url to the first promo link Link1Text The text for the first promo link Link2url The url to the second promo link Link2Text The text for the second promo link Link3url The url to the third promo link Link3Text The text for the third promo link Link4url The url to the fourth promo link Link4Text The text for the fourth promo link Every time when the service runs, the application will update the database columns from the XOAP data feed. When the application starts, It is going to get the data as XML from the url. This demonstration uses LINQ to extract the necessary data from the fetched XML. The following are the code segment for extracting data from the weather XML using LINQ. // first, create an instance of the XDocument class with the XOAP URL. replace **** with the corresponding values. XDocument weather = XDocument.Load("http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=***********&key=c*********"); // construct a query using LINQ var feedResult = from item in weather.Descendants() select new { unit = item.Element("head").Element("ut").Value, temp = item.Element("cc").Element("tmp").Value, tempDate = item.Element("cc").Element("lsup").Value, iconId = item.Element("cc").Element("icon").Value, description = item.Element("cc").Element("t").Value, links = from link in item.Elements("lnks").Elements("link") select new { url = link.Element("l").Value, text = link.Element("t").Value } }; // Load the root node to a variable, you may use foreach construct instead. var item1 = feedResult.First(); *If you want to learn more about LINQ and XML, read this nice blog from Scott GU. http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx Now you have all the required values in item1. For e.g. if you want to get the temperature, use item1.temp; Now I just need to execute an SQL query against the database. See the connection part. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { string strSql = @"update tblweather set lastupdated=getdate(), temparatureDateTime = @temparatureDateTime, temparature=@temparature, temparatureUnit=@temparatureUnit, iconId = @iconId, description=@description, link1url=@link1url, link1text=@link1text, link2url=@link2url, link2text=@link2text,link3url=@link3url, link3text=@link3text,link4url=@link4url, link4text=@link4text"; SqlCommand comm = new SqlCommand(strSql, conn); comm.Parameters.AddWithValue("temparatureDateTime", item1.tempDate); comm.Parameters.AddWithValue("temparature", item1.temp); comm.Parameters.AddWithValue("temparatureUnit", item1.unit); comm.Parameters.AddWithValue("description", item1.description); comm.Parameters.AddWithValue("iconId", item1.iconId); var lstLinks = item1.links; comm.Parameters.AddWithValue("link1url", lstLinks.ElementAt(0).url); comm.Parameters.AddWithValue("link1text", lstLinks.ElementAt(0).text); comm.Parameters.AddWithValue("link2url", lstLinks.ElementAt(1).url); comm.Parameters.AddWithValue("link2text", lstLinks.ElementAt(1).text); comm.Parameters.AddWithValue("link3url", lstLinks.ElementAt(2).url); comm.Parameters.AddWithValue("link3text", lstLinks.ElementAt(2).text); comm.Parameters.AddWithValue("link4url", lstLinks.ElementAt(3).url); comm.Parameters.AddWithValue("link4text", lstLinks.ElementAt(3).text); conn.Open(); comm.ExecuteNonQuery(); conn.Close(); Console.WriteLine("database updated"); } Now click ctrl + f5 to run the service. I got the following output Check your database and make sure, the data is updated with the latest information from the service. (Make sure you inserted one row in the database by entering some values before executing the service. Otherwise you need to modify your application code to count the rows and conditionally perform insert/update query) Display the Weather information in ASP.Net page Now you got all the data in the database. You just need to create a web application and display the data from the database. I created a new ASP.Net web application with a default.aspx page. In order to comply with the terms of weather.com, You need to use Weather.com logo along with the weather display. You can find the necessary logos to use under the folder “logos” in the SDK. Additionally copy any of the icon set from the folder “icons” to your web application. I used the 93x93 icon set. You are free to use any other sizes available. The design view of the page in VS2010 looks similar to the following. The page contains a heading, an image control (for displaying the weather icon), 2 label controls (for displaying temperature and weather description), 4 hyperlinks (for displaying the 4 promo links returned by the XOAP service) and weather.com logo with hyperlink to the weather.com home page. I am going to write code that will update the values of these controls from the values stored in the database by the service application as mentioned in the previous step. Go to the code behind file for the webpage, enter the following code under Page_Load event handler. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { SqlCommand comm = new SqlCommand("select top 1 * from tblweather", conn); conn.Open(); SqlDataReader reader = comm.ExecuteReader(); if (reader.Read()) { lblTemparature.Text = reader["temparature"].ToString() + "&deg;" + reader["temparatureUnit"].ToString(); lblWeatherDescription.Text = reader["description"].ToString(); imgWeather.ImageUrl = "icons/" + reader["iconId"].ToString() + ".png"; lnk1.Text = reader["link1text"].ToString(); lnk1.NavigateUrl = reader["link1url"].ToString(); lnk2.Text = reader["link2text"].ToString(); lnk2.NavigateUrl = reader["link2url"].ToString(); lnk3.Text = reader["link3text"].ToString(); lnk3.NavigateUrl = reader["link3url"].ToString(); lnk4.Text = reader["link4text"].ToString(); lnk4.NavigateUrl = reader["link4url"].ToString(); } conn.Close(); } Press ctrl + f5 to run the page. You will see the following output. That’s it. You need to configure the console application to run every 25 minutes so that the database is updated. Also you can fetch the forecast information and store those in the database, and then retrieve it later in your web page. Since the data resides in your database, you have the full control over your display. You need to make sure your website comply with weather.com license requirements. If you want to get the source code of this walkthrough through the application, post your email address below. Hope you enjoy the reading.

    Read the article

  • NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 2

    - by shiju
     In my last post, I have given an introduction to MongoDB and NoRM using an ASP.NET MVC demo app. I have updated the demo ASP.NET MVC app and a created a new drop at codeplex. You can download the demo at http://mongomvc.codeplex.com/In my last post, we have discussed to doing basic CRUD operations against a simple domain entity. In this post, let’s discuss on domain entity with deep object graph.The below is our domain entities  public class Category {       [MongoIdentifier]     public ObjectId Id { get; set; }       [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public List<Expense> Expenses { get; set; }       public Category()     {         Expenses = new List<Expense>();     } }    public class Expense {     [MongoIdentifier]     public ObjectId Id { get; set; }     public Category Category { get; set; }     public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }   }   We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category.The MongoSession class  internal class MongoSession : IDisposable {     private readonly MongoQueryProvider provider;       public MongoSession()     {         this.provider = new MongoQueryProvider("Expense");     }       public IQueryable<Category> Categories     {         get { return new MongoQuery<Category>(this.provider); }     }     public IQueryable<Expense> Expenses     {         get { return new MongoQuery<Expense>(this.provider); }     }     public MongoQueryProvider Provider     {         get { return this.provider; }     }       public void Add<T>(T item) where T : class, new()     {         this.provider.DB.GetCollection<T>().Insert(item);     }       public void Dispose()     {         this.provider.Server.Dispose();     }     public void Delete<T>(T item) where T : class, new()     {         this.provider.DB.GetCollection<T>().Delete(item);     }       public void Drop<T>()     {         this.provider.DB.DropCollection(typeof(T).Name);     }       public void Save<T>(T item) where T : class,new()     {         this.provider.DB.GetCollection<T>().Save(item);                }     }     ASP.NET MVC view model  for Expense transaction  public class ExpenseViewModel {     public ObjectId Id { get; set; }       public ObjectId CategoryId { get; set; }       [Required(ErrorMessage = "Transaction Required")]            public string Transaction { get; set; }       [Required(ErrorMessage = "Date Required")]            public DateTime Date { get; set; }       [Required(ErrorMessage = "Amount Required")]        public double Amount { get; set; }       public IEnumerable<SelectListItem> Category { get; set; } }  Let's create action method for Insert and Update a expense transaction   [HttpPost] public ActionResult Save(ExpenseViewModel expenseViewModel) {     try     {         if (!ModelState.IsValid)         {             using (var session = new MongoSession())             {                 var categories = session.Categories.AsEnumerable<Category>();                 expenseViewModel.Category = categories.ToSelectListItems(expenseViewModel.CategoryId);                }             return View("Save", expenseViewModel);         }           var expense=new Expense();         ModelCopier.CopyModel(expenseViewModel, expense);           using (var session = new MongoSession())         {             ObjectId Id = expenseViewModel.CategoryId;             var category = session.Categories                 .Where(c => c.Id ==Id  )                 .FirstOrDefault();             expense.Category = category;             session.Save(expense);         }         return RedirectToAction("Index");     }     catch     {         return View();     } } Query with Expenses  using (var session = new MongoSession()) {     var expenses = session.Expenses.         Where(exp => exp.Date >= StartDate && exp.Date <= EndDate)         .AsEnumerable<Expense>(); }  We are doing a LINQ query expression with a Date filter. We can easily work with MongoDB using NoRM driver and can managing object graph of domain entities are pretty cool. Download the Source - You can download the source code form http://mongomvc.codeplex.com

    Read the article

  • Functions inside page using Razor View Engine – ASP.NET MVC

    - by hajan
    As we already know, Razor is probably the best view engine for ASP.NET MVC so far. It keeps your code fluid and very expressive. Besides the other functionalities Razor has, it also supports writing local functions. If you want to write a function, you can’t just open new @{ } razor block and write it there… it won’t work. Instead, you should specify @functions { } so that inside the brackets you will write your own C#/VB.NET functions/methods. Lets see an example: 1. I have the following loop that prints data using Razor <ul> @{     int N = 10;     for (int i = 1; i<=N; i++)     {         <li>Number @i</li>     }     } </ul> This code will print the numbers from 1 to 10: Number 1 Number 2 Number 3 Number 4 Number 5 Number 6 Number 7 Number 8 Number 9 Number 10 So, now lets write a function that will check if current number is even, if yes… add Even before Number word. Function in Razor @functions{     public bool isEven(int number)     {         return number % 2 == 0 ? true : false;     } } The modified code which creates unordered list is: <ul> @{     int N = 10;     for (int i = 1; i<=N; i++)     {         if (isEven(@i)) {             <li>Even number @i</li>         }         else {             <li>Number @i</li>         }                 }             } </ul> As you can see, in the modified code we use the isEven(@i) function to check if the current number is even or not… The result is: Number 1 Even number 2 Number 3 Even number 4 Number 5 Even number 6 Number 7 Even number 8 Number 9 Even number 10 So, the main point of this blog was to show how you can define your own functions inside page using Razor View Engine. Of course you can define multiple functions inside the same @functions { } defined razor statement. The complete code: @{     Layout = null; } <!DOCTYPE html> <html> <head>     <title>ASP.NET MVC - Razor View Engine :: Functions</title> </head> <body>     <div>         <ul>         @{             int N = 10;             for (int i = 1; i<=N; i++)             {                 if (isEven(@i)) {                     <li>Even number @i</li>                 }                 else {                     <li>Number @i</li>                 }                         }                     }         </ul>         @functions{             public bool isEven(int number)             {                 return number % 2 == 0 ? true : false;             }         }     </div> </body> </html> Hope you like it. Regards, Hajan

    Read the article

  • Guarding against CSRF Attacks in ASP.NET MVC2

    - by srkirkland
    Alongside XSS (Cross Site Scripting) and SQL Injection, Cross-site Request Forgery (CSRF) attacks represent the three most common and dangerous vulnerabilities to common web applications today. CSRF attacks are probably the least well known but they are relatively easy to exploit and extremely and increasingly dangerous. For more information on CSRF attacks, see these posts by Phil Haack and Steve Sanderson. The recognized solution for preventing CSRF attacks is to put a user-specific token as a hidden field inside your forms, then check that the right value was submitted. It's best to use a random value which you’ve stored in the visitor’s Session collection or into a Cookie (so an attacker can't guess the value). ASP.NET MVC to the rescue ASP.NET MVC provides an HTMLHelper called AntiForgeryToken(). When you call <%= Html.AntiForgeryToken() %> in a form on your page you will get a hidden input and a Cookie with a random string assigned. Next, on your target Action you need to include [ValidateAntiForgeryToken], which handles the verification that the correct token was supplied. Good, but we can do better Using the AntiForgeryToken is actually quite an elegant solution, but adding [ValidateAntiForgeryToken] on all of your POST methods is not very DRY, and worse can be easily forgotten. Let's see if we can make this easier on the program but moving from an "Opt-In" model of protection to an "Opt-Out" model. Using AntiForgeryToken by default In order to mandate the use of the AntiForgeryToken, we're going to create an ActionFilterAttribute which will do the anti-forgery validation on every POST request. First, we need to create a way to Opt-Out of this behavior, so let's create a quick action filter called BypassAntiForgeryToken: [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] public class BypassAntiForgeryTokenAttribute : ActionFilterAttribute { } Now we are ready to implement the main action filter which will force anti forgery validation on all post actions within any class it is defined on: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class UseAntiForgeryTokenOnPostByDefault : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (ShouldValidateAntiForgeryTokenManually(filterContext)) { var authorizationContext = new AuthorizationContext(filterContext.Controller.ControllerContext);   //Use the authorization of the anti forgery token, //which can't be inhereted from because it is sealed new ValidateAntiForgeryTokenAttribute().OnAuthorization(authorizationContext); }   base.OnActionExecuting(filterContext); }   /// <summary> /// We should validate the anti forgery token manually if the following criteria are met: /// 1. The http method must be POST /// 2. There is not an existing [ValidateAntiForgeryToken] attribute on the action /// 3. There is no [BypassAntiForgeryToken] attribute on the action /// </summary> private static bool ShouldValidateAntiForgeryTokenManually(ActionExecutingContext filterContext) { var httpMethod = filterContext.HttpContext.Request.HttpMethod;   //1. The http method must be POST if (httpMethod != "POST") return false;   // 2. There is not an existing anti forgery token attribute on the action var antiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), false);   if (antiForgeryAttributes.Length > 0) return false;   // 3. There is no [BypassAntiForgeryToken] attribute on the action var ignoreAntiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(BypassAntiForgeryTokenAttribute), false);   if (ignoreAntiForgeryAttributes.Length > 0) return false;   return true; } } The code above is pretty straight forward -- first we check to make sure this is a POST request, then we make sure there aren't any overriding *AntiForgeryTokenAttributes on the action being executed. If we have a candidate then we call the ValidateAntiForgeryTokenAttribute class directly and execute OnAuthorization() on the current authorization context. Now on our base controller, you could use this new attribute to start protecting your site from CSRF vulnerabilities. [UseAntiForgeryTokenOnPostByDefault] public class ApplicationController : System.Web.Mvc.Controller { }   //Then for all of your controllers public class HomeController : ApplicationController {} What we accomplished If your base controller has the new default anti-forgery token attribute on it, when you don't use <%= Html.AntiForgeryToken() %> in a form (or of course when an attacker doesn't supply one), the POST action will throw the descriptive error message "A required anti-forgery token was not supplied or was invalid". Attack foiled! In summary, I think having an anti-CSRF policy by default is an effective way to protect your websites, and it turns out it is pretty easy to accomplish as well. Enjoy!

    Read the article

  • Create Resume problem

    - by ar31an
    hello mates, i am working on a project of online resume management system and i am encountering an exception while creating resume. [b] Exception: Data type mismatch in criteria expression. [/b] here is my code for Create Resume-1.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class _Default : System.Web.UI.Page { string sql, sql2, sql3, sql4, sql5, sql6, sql7, sql8, sql9, sql10, sql11, sql12; string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Deliverable4.accdb"; protected OleDbConnection rMSConnection; protected OleDbCommand rMSCommand; protected OleDbDataAdapter rMSDataAdapter; protected DataSet dataSet; protected DataTable dataTable; protected DataRow dataRow; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string contact1 = TextBox1.Text; string contact2 = TextBox2.Text; string cellphone = TextBox3.Text; string address = TextBox4.Text; string city = TextBox5.Text; string addqualification = TextBox18.Text; //string SecondLastDegreeGrade = TextBox17.Text; //string SecondLastDegreeInstitute = TextBox16.Text; //string SecondLastDegreeNameOther = TextBox15.Text; string LastDegreeNameOther = TextBox11.Text; string LastDegreeInstitute = TextBox12.Text; string LastDegreeGrade = TextBox13.Text; string tentativeFromDate = (DropDownList4.SelectedValue + " " + DropDownList7.SelectedValue + " " + DropDownList8.SelectedValue); try { sql6 = "select CountryID from COUNTRY"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql6, rMSConnection); dataSet = new DataSet("cID"); rMSDataAdapter.Fill(dataSet, "COUNTRY"); dataTable = dataSet.Tables["COUNTRY"]; int cId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql4 = "select PersonalDetailID from PERSONALDETAIL"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql4, rMSConnection); dataSet = new DataSet("PDID"); rMSDataAdapter.Fill(dataSet, "PERSONALDETAIL"); dataTable = dataSet.Tables["PERSONALDETAIL"]; int PDId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql5 = "update PERSONALDETAIL set Phone1 ='" + contact1 + "' , Phone2 = '" + contact2 + "', CellPhone = '" + cellphone + "', Address = '" + address + "', City = '" + city + "', CountryID = '" + cId + "' where PersonalDetailID = '" + PDId + "'"; rMSConnection = new OleDbConnection(conString); rMSConnection.Open(); rMSCommand = new OleDbCommand(sql5, rMSConnection); rMSCommand.ExecuteNonQuery(); rMSConnection.Close(); sql3 = "select DesignationID from DESIGNATION"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql3, rMSConnection); dataSet = new DataSet("DesID"); rMSDataAdapter.Fill(dataSet, "DESIGNATION"); dataTable = dataSet.Tables["DESIGNATION"]; int desId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql2 = "select DepartmentID from DEPARTMENT"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql2, rMSConnection); dataSet = new DataSet("DID"); rMSDataAdapter.Fill(dataSet, "DEPARTMENT"); dataTable = dataSet.Tables["DEPARTMENT"]; int dId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql7 = "select ResumeID from RESUME"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql7, rMSConnection); dataSet = new DataSet("rID"); rMSDataAdapter.Fill(dataSet, "RESUME"); dataTable = dataSet.Tables["RESUME"]; int rId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql = "update RESUME set PersonalDetailID ='" + PDId + "' , DesignationID = '" + desId + "', DepartmentID = '" + dId + "', TentativeFromDate = '" + tentativeFromDate + "', AdditionalQualification = '" + addqualification + "' where ResumeID = '" + rId + "'"; rMSConnection = new OleDbConnection(conString); rMSConnection.Open(); rMSCommand = new OleDbCommand(sql, rMSConnection); rMSCommand.ExecuteNonQuery(); rMSConnection.Close(); sql8 = "insert into INSTITUTE (InstituteName) values ('" + LastDegreeInstitute + "')"; rMSConnection = new OleDbConnection(conString); rMSConnection.Open(); rMSCommand = new OleDbCommand(sql8, rMSConnection); rMSCommand.ExecuteNonQuery(); rMSConnection.Close(); sql9 = "insert into DEGREE (DegreeName) values ('" + LastDegreeNameOther + "')"; rMSConnection = new OleDbConnection(conString); rMSConnection.Open(); rMSCommand = new OleDbCommand(sql9, rMSConnection); rMSCommand.ExecuteNonQuery(); rMSConnection.Close(); sql11 = "select InstituteID from INSTITUTE"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql11, rMSConnection); dataSet = new DataSet("insID"); rMSDataAdapter.Fill(dataSet, "INSTITUTE"); dataTable = dataSet.Tables["INSTITUTE"]; int insId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql12 = "select DegreeID from DEGREE"; rMSConnection = new OleDbConnection(conString); rMSDataAdapter = new OleDbDataAdapter(sql12, rMSConnection); dataSet = new DataSet("degID"); rMSDataAdapter.Fill(dataSet, "DEGREE"); dataTable = dataSet.Tables["DEGREE"]; int degId = (int)dataTable.Rows[0][0]; rMSConnection.Close(); sql10 = "insert into QUALIFICATION (Grade, ResumeID, InstituteID, DegreeID) values ('" + LastDegreeGrade + "', '" + rId + "', '" + insId + "', '" + degId + "')"; rMSConnection = new OleDbConnection(conString); rMSConnection.Open(); rMSCommand = new OleDbCommand(sql10, rMSConnection); rMSCommand.ExecuteNonQuery(); rMSConnection.Close(); Response.Redirect("Applicant.aspx"); } catch (Exception exp) { rMSConnection.Close(); Label1.Text = "Exception: " + exp.Message; } } protected void Button2_Click(object sender, EventArgs e) { } } And for Create Resume-1.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Create Resume-1.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div><center> <strong><span style="font-size: 16pt"></span></strong>&nbsp;</center> <center> &nbsp;</center> <center style="background-color: silver"> &nbsp;</center> <center> <strong><span style="font-size: 16pt">Step 1</span></strong></center> <center style="background-color: silver"> &nbsp;</center> <center> &nbsp;</center> <center> &nbsp;</center> <center> <asp:Label ID="PhoneNo1" runat="server" Text="Contact No 1*"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox1"></asp:RequiredFieldValidator><br /> <asp:Label ID="PhoneNo2" runat="server" Text="Contact No 2"></asp:Label> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /> <asp:Label ID="CellNo" runat="server" Text="Cell Phone No"></asp:Label> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br /> <asp:Label ID="Address" runat="server" Text="Street Address*"></asp:Label> <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox4"></asp:RequiredFieldValidator><br /> <asp:Label ID="City" runat="server" Text="City*"></asp:Label> <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox5"></asp:RequiredFieldValidator><br /> <asp:Label ID="Country" runat="server" Text="Country of Origin*"></asp:Label> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="CountryName" DataValueField="CountryID"> </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString7 %>" DeleteCommand="DELETE FROM [COUNTRY] WHERE (([CountryID] = ?) OR ([CountryID] IS NULL AND ? IS NULL))" InsertCommand="INSERT INTO [COUNTRY] ([CountryID], [CountryName]) VALUES (?, ?)" ProviderName="<%$ ConnectionStrings:ConnectionString7.ProviderName %>" SelectCommand="SELECT * FROM [COUNTRY]" UpdateCommand="UPDATE [COUNTRY] SET [CountryName] = ? WHERE (([CountryID] = ?) OR ([CountryID] IS NULL AND ? IS NULL))"> <DeleteParameters> <asp:Parameter Name="CountryID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="CountryName" Type="String" /> <asp:Parameter Name="CountryID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="CountryID" Type="Int32" /> <asp:Parameter Name="CountryName" Type="String" /> </InsertParameters> </asp:SqlDataSource> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="DropDownList1"></asp:RequiredFieldValidator><br /> <asp:Label ID="DepartmentOfInterest" runat="server" Text="Department of Interest*"></asp:Label> <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="DepartmentName" DataValueField="DepartmentID"> </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString7 %>" DeleteCommand="DELETE FROM [DEPARTMENT] WHERE [DepartmentID] = ?" InsertCommand="INSERT INTO [DEPARTMENT] ([DepartmentID], [DepartmentName]) VALUES (?, ?)" ProviderName="<%$ ConnectionStrings:ConnectionString7.ProviderName %>" SelectCommand="SELECT * FROM [DEPARTMENT]" UpdateCommand="UPDATE [DEPARTMENT] SET [DepartmentName] = ? WHERE [DepartmentID] = ?"> <DeleteParameters> <asp:Parameter Name="DepartmentID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="DepartmentName" Type="String" /> <asp:Parameter Name="DepartmentID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="DepartmentID" Type="Int32" /> <asp:Parameter Name="DepartmentName" Type="String" /> </InsertParameters> </asp:SqlDataSource> <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="DropDownList2"></asp:RequiredFieldValidator><br /> <asp:Label ID="DesignationAppliedFor" runat="server" Text="Position Applied For*"></asp:Label> <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource3" DataTextField="DesignationName" DataValueField="DesignationID"> </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString7 %>" DeleteCommand="DELETE FROM [DESIGNATION] WHERE [DesignationID] = ?" InsertCommand="INSERT INTO [DESIGNATION] ([DesignationID], [DesignationName], [DesignationStatus]) VALUES (?, ?, ?)" ProviderName="<%$ ConnectionStrings:ConnectionString7.ProviderName %>" SelectCommand="SELECT * FROM [DESIGNATION]" UpdateCommand="UPDATE [DESIGNATION] SET [DesignationName] = ?, [DesignationStatus] = ? WHERE [DesignationID] = ?"> <DeleteParameters> <asp:Parameter Name="DesignationID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="DesignationName" Type="String" /> <asp:Parameter Name="DesignationStatus" Type="String" /> <asp:Parameter Name="DesignationID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="DesignationID" Type="Int32" /> <asp:Parameter Name="DesignationName" Type="String" /> <asp:Parameter Name="DesignationStatus" Type="String" /> </InsertParameters> </asp:SqlDataSource> <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="DropDownList3"></asp:RequiredFieldValidator><br /> <asp:Label ID="TentativeFromDate" runat="server" Text="Can Join From*"></asp:Label> <asp:DropDownList ID="DropDownList4" runat="server"> <asp:ListItem>1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem>4</asp:ListItem> <asp:ListItem>5</asp:ListItem> <asp:ListItem>6</asp:ListItem> <asp:ListItem>7</asp:ListItem> <asp:ListItem>8</asp:ListItem> <asp:ListItem>9</asp:ListItem> <asp:ListItem>10</asp:ListItem> <asp:ListItem>11</asp:ListItem> <asp:ListItem>12</asp:ListItem> </asp:DropDownList>&nbsp;<asp:DropDownList ID="DropDownList7" runat="server"> <asp:ListItem>1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem>4</asp:ListItem> <asp:ListItem>5</asp:ListItem> <asp:ListItem>6</asp:ListItem> <asp:ListItem>7</asp:ListItem> <asp:ListItem>8</asp:ListItem> <asp:ListItem>9</asp:ListItem> <asp:ListItem>10</asp:ListItem> <asp:ListItem>11</asp:ListItem> <asp:ListItem>12</asp:ListItem> <asp:ListItem>13</asp:ListItem> <asp:ListItem>14</asp:ListItem> <asp:ListItem>15</asp:ListItem> <asp:ListItem>16</asp:ListItem> <asp:ListItem>17</asp:ListItem> <asp:ListItem>18</asp:ListItem> <asp:ListItem>19</asp:ListItem> <asp:ListItem>20</asp:ListItem> <asp:ListItem>21</asp:ListItem> <asp:ListItem>22</asp:ListItem> <asp:ListItem>23</asp:ListItem> <asp:ListItem>24</asp:ListItem> <asp:ListItem>25</asp:ListItem> <asp:ListItem>26</asp:ListItem> <asp:ListItem>27</asp:ListItem> <asp:ListItem>28</asp:ListItem> <asp:ListItem>29</asp:ListItem> <asp:ListItem>30</asp:ListItem> <asp:ListItem>31</asp:ListItem> </asp:DropDownList> <asp:DropDownList ID="DropDownList8" runat="server"> <asp:ListItem>2010</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="DropDownList4"></asp:RequiredFieldValidator></center> <center> <br /> <asp:Label ID="LastDegreeName" runat="server" Text="Last Degree*"></asp:Label> <asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="SqlDataSource5" DataTextField="DegreeName" DataValueField="DegreeID"> </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString7 %>" DeleteCommand="DELETE FROM [DEGREE] WHERE [DegreeID] = ?" InsertCommand="INSERT INTO [DEGREE] ([DegreeID], [DegreeName]) VALUES (?, ?)" ProviderName="<%$ ConnectionStrings:ConnectionString7.ProviderName %>" SelectCommand="SELECT * FROM [DEGREE]" UpdateCommand="UPDATE [DEGREE] SET [DegreeName] = ? WHERE [DegreeID] = ?"> <DeleteParameters> <asp:Parameter Name="DegreeID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="DegreeName" Type="String" /> <asp:Parameter Name="DegreeID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="DegreeID" Type="Int32" /> <asp:Parameter Name="DegreeName" Type="String" /> </InsertParameters> </asp:SqlDataSource> <asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="DropDownList5"></asp:RequiredFieldValidator><br /> <asp:Label ID="LastDegreeNameOther" runat="server" Text="Other"></asp:Label> <asp:TextBox ID="TextBox11" runat="server"></asp:TextBox><br /> <asp:Label ID="LastDegreeInstitute" runat="server" Text="Institute Name*"></asp:Label> <asp:TextBox ID="TextBox12" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox12"></asp:RequiredFieldValidator><br /> <asp:Label ID="LastDegreeGrade" runat="server" Text="Marks / Grade*"></asp:Label> <asp:TextBox ID="TextBox13" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox13"></asp:RequiredFieldValidator></center> <center> &nbsp;</center> <center> <br /> <asp:Label ID="SecondLastDegreeName" runat="server" Text="Second Last Degree*"></asp:Label> <asp:DropDownList ID="DropDownList6" runat="server" DataSourceID="SqlDataSource4" DataTextField="DegreeName" DataValueField="DegreeID"> </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString7 %>" DeleteCommand="DELETE FROM [DEGREE] WHERE [DegreeID] = ?" InsertCommand="INSERT INTO [DEGREE] ([DegreeID], [DegreeName]) VALUES (?, ?)" ProviderName="<%$ ConnectionStrings:ConnectionString7.ProviderName %>" SelectCommand="SELECT * FROM [DEGREE]" UpdateCommand="UPDATE [DEGREE] SET [DegreeName] = ? WHERE [DegreeID] = ?"> <DeleteParameters> <asp:Parameter Name="DegreeID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="DegreeName" Type="String" /> <asp:Parameter Name="DegreeID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="DegreeID" Type="Int32" /> <asp:Parameter Name="DegreeName" Type="String" /> </InsertParameters> </asp:SqlDataSource> <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="DropDownList6"></asp:RequiredFieldValidator><br /> <asp:Label ID="SecondLastDegreeNameOther" runat="server" Text="Other"></asp:Label> <asp:TextBox ID="TextBox15" runat="server"></asp:TextBox><br /> <asp:Label ID="SecondLastDegreeInstitute" runat="server" Text="Institute Name*"></asp:Label> <asp:TextBox ID="TextBox16" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox16"></asp:RequiredFieldValidator><br /> <asp:Label ID="SecondLastDegreeGrade" runat="server" Text="Marks / Grade*"></asp:Label> <asp:TextBox ID="TextBox17" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator13" runat="server" ErrorMessage="Items marked with '*' cannot be left blank." ControlToValidate="TextBox17"></asp:RequiredFieldValidator></center> <center> <br /> <asp:Label ID="AdditionalQualification" runat="server" Text="Additional Qualification"></asp:Label> <asp:TextBox ID="TextBox18" runat="server" TextMode="MultiLine"></asp:TextBox></center> <center> &nbsp;</center> <center> <asp:Button ID="Button1" runat="server" Text="Save and Exit" OnClick="Button1_Click" /> &nbsp;&nbsp; <asp:Button ID="Button2" runat="server" Text="Next" OnClick="Button2_Click" /></center> <center> &nbsp;</center> <center> <asp:Label ID="Label1" runat="server"></asp:Label>&nbsp;</center> <center> &nbsp;</center> <center style="background-color: silver"> &nbsp;</center> </div> </form> </body> </html>

    Read the article

  • How to Put Javascript into an ASP.NET MVC View

    - by Maxim Z.
    I'm really new to ASP.NET MVC, and I'm trying to integrate some Javascript into a website I'm making as a test of this technology. My question is this: how can I insert Javascript code into a View? Let's say that I start out with the default ASP.NET MVC template. In terms of Views, this creates a Master page, a "Home" View, and an "About" view. The "Home" View, called Index.aspx, looks like this: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h2><%= Html.Encode(ViewData["Message"]) %></h2> <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. </p> <p>Welcome to this testing site!</p> </asp:Content> Adding a <script> tag here didn't work. Where and how should I do it? P.S.: I have a feeling I'm missing something very basic... Thanks in advance!

    Read the article

  • Converting a generic list into JSON string and then handling it in java script

    - by Jalpesh P. Vadgama
    We all know that JSON (JavaScript Object Notification) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script. To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName public class UserInfo { public int UserId { get; set; } public string UserName { get; set; } } Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Experiment.WebService { /// <summary> /// Summary description for WsApplicationUser /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WsApplicationUser : System.Web.Services.WebService { [WebMethod] public string GetUserList() { List<UserInfo> userList = new List<UserInfo>(); for (int i = 1; i <= 5; i++) { UserInfo userInfo = new UserInfo(); userInfo.UserId = i; userInfo.UserName = string.Format("{0}{1}", "J", i.ToString()); userList.Add(userInfo); } System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return jSearializer.Serialize(userList); } } } Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side. Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following function GetUserList() { Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback); } After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function. function ReuqestCompleteCallback(result) { result = eval(result); var divResult = document.getElementById("divUserList"); CreateUserListTable(result); } function RequestFailedCallback(error) { var stackTrace = error.get_stackTrace(); var message = error.get_message(); var statusCode = error.get_statusCode(); var exceptionType = error.get_exceptionType(); var timedout = error.get_timedOut(); // Display the error. var divResult = document.getElementById("divUserList"); divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" + "Service Error: " + message + "<br/>" + "Status Code: " + statusCode + "<br/>" + "Exception Type: " + exceptionType + "<br/>" + "Timedout: " + timedout; } Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function. function CreateUserListTable(userList) { var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>'; for (var i = 0, len = userList.length; i < len; ++i) { tablestring=tablestring + "<tr>"; tablestring=tablestring + "<td>" + userList[i].UserId + "</td>"; tablestring=tablestring + "<td>" + userList[i].UserName + "</td>"; tablestring=tablestring + "</tr>"; } tablestring = tablestring + "</table>"; var divResult = document.getElementById("divUserList"); divResult.innerHTML = tablestring; } Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have. <form id="form1" runat="server"> <asp:ScriptManager ID="myScirptManger" runat="Server"> <Services> <asp:ServiceReference Path="~/WebService/WsApplicationUser.asmx" /> </Services> </asp:ScriptManager> <div id="divUserList"> </div> </form> Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following. window.onload=GetUserList(); That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected. That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming.. Technorati Tags: JSON,Javascript,ASP.NET,WebService

    Read the article

  • Weird .ASP pages from my non-ASP site generating 404s

    - by Amanda
    In Google Webmaster Tools, I have a huge list of "Not Found" crawl errors (404) with URLs that look like this: http://www.exclusivevillas.co.za/villa_view.asp?vSeq=82&activitySeq=3&page=3, seemingly originating from URLs very similar to that (eg http://www.exclusivevillas.co.za/villa_view.asp?vSeq=82&activitySeq=3&page=4. Thing is, the site is WordPress. Has been for almost a year now. Was plain html before that. I don't know where these ASP requests are coming from. And furthermore, the dates these supposed ASP pages requested these other ASP pages, resulting in 404s, are very recent. What's going on?

    Read the article

  • Membership in ASP.Net applications - part 4

    - by nikolaosk
    This is the fourth post in a series of posts regarding ASP.Net built in membership functionality,providers,controls. You can read the first one here . You can read the second post here . You can read the third post here . In this post I will show you how to add users programmatically to a role. In the third post we saw how to get users in a specific role.I will also show you how to delete a user and a role programmatically. 1) Launch Visual Studio 2005,2008/2010. Express editions will work fine....(read more)

    Read the article

  • Rendering ASP.NET MVC Views to String

    - by Rick Strahl
    It's not uncommon in my applications that I require longish text output that does not have to be rendered into the HTTP output stream. The most common scenario I have for 'template driven' non-Web text is for emails of all sorts. Logon confirmations and verifications, email confirmations for things like orders, status updates or scheduler notifications - all of which require merged text output both within and sometimes outside of Web applications. On other occasions I also need to capture the output from certain views for logging purposes. Rather than creating text output in code, it's much nicer to use the rendering mechanism that ASP.NET MVC already provides by way of it's ViewEngines - using Razor or WebForms views - to render output to a string. This is nice because it uses the same familiar rendering mechanism that I already use for my HTTP output and it also solves the problem of where to store the templates for rendering this content in nothing more than perhaps a separate view folder. The good news is that ASP.NET MVC's rendering engine is much more modular than the full ASP.NET runtime engine which was a real pain in the butt to coerce into rendering output to string. With MVC the rendering engine has been separated out from core ASP.NET runtime, so it's actually a lot easier to get View output into a string. Getting View Output from within an MVC Application If you need to generate string output from an MVC and pass some model data to it, the process to capture this output is fairly straight forward and involves only a handful of lines of code. The catch is that this particular approach requires that you have an active ControllerContext that can be passed to the view. This means that the following approach is limited to access from within Controller methods. Here's a class that wraps the process and provides both instance and static methods to handle the rendering:/// <summary> /// Class that renders MVC views to a string using the /// standard MVC View Engine to render the view. /// /// Note: This class can only be used within MVC /// applications that have an active ControllerContext. /// </summary> public class ViewRenderer { /// <summary> /// Required Controller Context /// </summary> protected ControllerContext Context { get; set; } public ViewRenderer(ControllerContext controllerContext) { Context = controllerContext; } /// <summary> /// Renders a full MVC view to a string. Will render with the full MVC /// View engine including running _ViewStart and merging into _Layout /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to render the view with</param> /// <returns>String of the rendered view or null on error</returns> public string RenderView(string viewPath, object model) { return RenderViewToStringInternal(viewPath, model, false); } /// <summary> /// Renders a partial MVC view to string. Use this method to render /// a partial view that doesn't merge with _Layout and doesn't fire /// _ViewStart. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to pass to the viewRenderer</param> /// <returns>String of the rendered view or null on error</returns> public string RenderPartialView(string viewPath, object model) { return RenderViewToStringInternal(viewPath, model, true); } public static string RenderView(string viewPath, object model, ControllerContext controllerContext) { ViewRenderer renderer = new ViewRenderer(controllerContext); return renderer.RenderView(viewPath, model); } public static string RenderPartialView(string viewPath, object model, ControllerContext controllerContext) { ViewRenderer renderer = new ViewRenderer(controllerContext); return renderer.RenderPartialView(viewPath, model); } protected string RenderViewToStringInternal(string viewPath, object model, bool partial = false) { // first find the ViewEngine for this view ViewEngineResult viewEngineResult = null; if (partial) viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath); else viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null); if (viewEngineResult == null) throw new FileNotFoundException(Properties.Resources.ViewCouldNotBeFound); // get the view and attach the model to view data var view = viewEngineResult.View; Context.Controller.ViewData.Model = model; string result = null; using (var sw = new StringWriter()) { var ctx = new ViewContext(Context, view, Context.Controller.ViewData, Context.Controller.TempData, sw); view.Render(ctx, sw); result = sw.ToString(); } return result; } } The key is the RenderViewToStringInternal method. The method first tries to find the view to render based on its path which can either be in the current controller's view path or the shared view path using its simple name (PasswordRecovery) or alternately by its full virtual path (~/Views/Templates/PasswordRecovery.cshtml). This code should work both for Razor and WebForms views although I've only tried it with Razor Views. Note that WebForms Views might actually be better for plain text as Razor adds all sorts of white space into its output when there are code blocks in the template. The Web Forms engine provides more accurate rendering for raw text scenarios. Once a view engine is found the view to render can be retrieved. Views in MVC render based on data that comes off the controller like the ViewData which contains the model along with the actual ViewData and ViewBag. From the View and some of the Context data a ViewContext is created which is then used to render the view with. The View picks up the Model and other data from the ViewContext internally and processes the View the same it would be processed if it were to send its output into the HTTP output stream. The difference is that we can override the ViewContext's output stream which we provide and capture into a StringWriter(). After rendering completes the result holds the output string. If an error occurs the error behavior is similar what you see with regular MVC errors - you get a full yellow screen of death including the view error information with the line of error highlighted. It's your responsibility to handle the error - or let it bubble up to your regular Controller Error filter if you have one. To use the simple class you only need a single line of code if you call the static methods. Here's an example of some Controller code that is used to send a user notification to a customer via email in one of my applications:[HttpPost] public ActionResult ContactSeller(ContactSellerViewModel model) { InitializeViewModel(model); var entryBus = new busEntry(); var entry = entryBus.LoadByDisplayId(model.EntryId); if ( string.IsNullOrEmpty(model.Email) ) entryBus.ValidationErrors.Add("Email address can't be empty.","Email"); if ( string.IsNullOrEmpty(model.Message)) entryBus.ValidationErrors.Add("Message can't be empty.","Message"); model.EntryId = entry.DisplayId; model.EntryTitle = entry.Title; if (entryBus.ValidationErrors.Count > 0) { ErrorDisplay.AddMessages(entryBus.ValidationErrors); ErrorDisplay.ShowError("Please correct the following:"); } else { string message = ViewRenderer.RenderView("~/views/template/ContactSellerEmail.cshtml",model, ControllerContext); string title = entry.Title + " (" + entry.DisplayId + ") - " + App.Configuration.ApplicationName; AppUtils.SendEmail(title, message, model.Email, entry.User.Email, false, false)) } return View(model); } Simple! The view in this case is just a plain MVC view and in this case it's a very simple plain text email message (edited for brevity here) that is created and sent off:@model ContactSellerViewModel @{ Layout = null; }re: @Model.EntryTitle @Model.ListingUrl @Model.Message ** SECURITY ADVISORY - AVOID SCAMS ** Avoid: wiring money, cross-border deals, work-at-home ** Beware: cashier checks, money orders, escrow, shipping ** More Info: @(App.Configuration.ApplicationBaseUrl)scams.html Obviously this is a very simple view (I edited out more from this page to keep it brief) -  but other template views are much more complex HTML documents or long messages that are occasionally updated and they are a perfect fit for Razor rendering. It even works with nested partial views and _layout pages. Partial Rendering Notice that I'm rendering a full View here. In the view I explicitly set the Layout=null to avoid pulling in _layout.cshtml for this view. This can also be controlled externally by calling the RenderPartial method instead: string message = ViewRenderer.RenderPartialView("~/views/template/ContactSellerEmail.cshtml",model, ControllerContext); with this line of code no layout page (or _viewstart) will be loaded, so the output generated is just what's in the view. I find myself using Partials most of the time when rendering templates, since the target of templates usually tend to be emails or other HTML fragment like output, so the RenderPartialView() method is definitely useful to me. Rendering without a ControllerContext The preceding class is great when you're need template rendering from within MVC controller actions or anywhere where you have access to the request Controller. But if you don't have a controller context handy - maybe inside a utility function that is static, a non-Web application, or an operation that runs asynchronously in ASP.NET - which makes using the above code impossible. I haven't found a way to manually create a Controller context to provide the ViewContext() what it needs from outside of the MVC infrastructure. However, there are ways to accomplish this,  but they are a bit more complex. It's possible to host the RazorEngine on your own, which side steps all of the MVC framework and HTTP and just deals with the raw rendering engine. I wrote about this process in Hosting the Razor Engine in Non-Web Applications a long while back. It's quite a process to create a custom Razor engine and runtime, but it allows for all sorts of flexibility. There's also a RazorEngine CodePlex project that does something similar. I've been meaning to check out the latter but haven't gotten around to it since I have my own code to do this. The trick to hosting the RazorEngine to have it behave properly inside of an ASP.NET application and properly cache content so templates aren't constantly rebuild and reparsed. Anyway, in the same app as above I have one scenario where no ControllerContext is available: I have a background scheduler running inside of the app that fires on timed intervals. This process could be external but because it's lightweight we decided to fire it right inside of the ASP.NET app on a separate thread. In my app the code that renders these templates does something like this:var model = new SearchNotificationViewModel() { Entries = entries, Notification = notification, User = user }; // TODO: Need logging for errors sending string razorError = null; var result = AppUtils.RenderRazorTemplate("~/views/template/SearchNotificationTemplate.cshtml", model, razorError); which references a couple of helper functions that set up my RazorFolderHostContainer class:public static string RenderRazorTemplate(string virtualPath, object model,string errorMessage = null) { var razor = AppUtils.CreateRazorHost(); var path = virtualPath.Replace("~/", "").Replace("~", "").Replace("/", "\\"); var merged = razor.RenderTemplateToString(path, model); if (merged == null) errorMessage = razor.ErrorMessage; return merged; } /// <summary> /// Creates a RazorStringHostContainer and starts it /// Call .Stop() when you're done with it. /// /// This is a static instance /// </summary> /// <param name="virtualPath"></param> /// <param name="binBasePath"></param> /// <param name="forceLoad"></param> /// <returns></returns> public static RazorFolderHostContainer CreateRazorHost(string binBasePath = null, bool forceLoad = false) { if (binBasePath == null) { if (HttpContext.Current != null) binBasePath = HttpContext.Current.Server.MapPath("~/"); else binBasePath = AppDomain.CurrentDomain.BaseDirectory; } if (_RazorHost == null || forceLoad) { if (!binBasePath.EndsWith("\\")) binBasePath += "\\"; //var razor = new RazorStringHostContainer(); var razor = new RazorFolderHostContainer(); razor.TemplatePath = binBasePath; binBasePath += "bin\\"; razor.BaseBinaryFolder = binBasePath; razor.UseAppDomain = false; razor.ReferencedAssemblies.Add(binBasePath + "ClassifiedsBusiness.dll"); razor.ReferencedAssemblies.Add(binBasePath + "ClassifiedsWeb.dll"); razor.ReferencedAssemblies.Add(binBasePath + "Westwind.Utilities.dll"); razor.ReferencedAssemblies.Add(binBasePath + "Westwind.Web.dll"); razor.ReferencedAssemblies.Add(binBasePath + "Westwind.Web.Mvc.dll"); razor.ReferencedAssemblies.Add("System.Web.dll"); razor.ReferencedNamespaces.Add("System.Web"); razor.ReferencedNamespaces.Add("ClassifiedsBusiness"); razor.ReferencedNamespaces.Add("ClassifiedsWeb"); razor.ReferencedNamespaces.Add("Westwind.Web"); razor.ReferencedNamespaces.Add("Westwind.Utilities"); _RazorHost = razor; _RazorHost.Start(); //_RazorHost.Engine.Configuration.CompileToMemory = false; } return _RazorHost; } The RazorFolderHostContainer essentially is a full runtime that mimics a folder structure like a typical Web app does including caching semantics and compiling code only if code changes on disk. It maps a folder hierarchy to views using the ~/ path syntax. The host is then configured to add assemblies and namespaces. Unfortunately the engine is not exactly like MVC's Razor - the expression expansion and code execution are the same, but some of the support methods like sections, helpers etc. are not all there so templates have to be a bit simpler. There are other folder hosts provided as well to directly execute templates from strings (using RazorStringHostContainer). The following is an example of an HTML email template @inherits RazorHosting.RazorTemplateFolderHost <ClassifiedsWeb.SearchNotificationViewModel> <html> <head> <title>Search Notifications</title> <style> body { margin: 5px;font-family: Verdana, Arial; font-size: 10pt;} h3 { color: SteelBlue; } .entry-item { border-bottom: 1px solid grey; padding: 8px; margin-bottom: 5px; } </style> </head> <body> Hello @Model.User.Name,<br /> <p>Below are your Search Results for the search phrase:</p> <h3>@Model.Notification.SearchPhrase</h3> <small>since @TimeUtils.ShortDateString(Model.Notification.LastSearch)</small> <hr /> You can see that the syntax is a little different. Instead of the familiar @model header the raw Razor  @inherits tag is used to specify the template base class (which you can extend). I took a quick look through the feature set of RazorEngine on CodePlex (now Github I guess) and the template implementation they use is closer to MVC's razor but there are other differences. In the end don't expect exact behavior like MVC templates if you use an external Razor rendering engine. This is not what I would consider an ideal solution, but it works well enough for this project. My biggest concern is the overhead of hosting a second razor engine in a Web app and the fact that here the differences in template rendering between 'real' MVC Razor views and another RazorEngine really are noticeable. You win some, you lose some It's extremely nice to see that if you have a ControllerContext handy (which probably addresses 99% of Web app scenarios) rendering a view to string using the native MVC Razor engine is pretty simple. Kudos on making that happen - as it solves a problem I see in just about every Web application I work on. But it is a bummer that a ControllerContext is required to make this simple code work. It'd be really sweet if there was a way to render views without being so closely coupled to the ASP.NET or MVC infrastructure that requires a ControllerContext. Alternately it'd be nice to have a way for an MVC based application to create a minimal ControllerContext from scratch - maybe somebody's been down that path. I tried for a few hours to come up with a way to make that work but gave up in the soup of nested contexts (MVC/Controller/View/Http). I suspect going down this path would be similar to hosting the ASP.NET runtime requiring a WorkerRequest. Brrr…. The sad part is that it seems to me that a View should really not require much 'context' of any kind to render output to string. Yes there are a few things that clearly are required like paths to the virtual and possibly the disk paths to the root of the app, but beyond that view rendering should not require much. But, no such luck. For now custom RazorHosting seems to be the only way to make Razor rendering go outside of the MVC context… Resources Full ViewRenderer.cs source code from Westwind.Web.Mvc library Hosting the Razor Engine for Non-Web Applications RazorEngine on GitHub© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET   ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Persisting model state in ASP.NET MVC using Serialize HTMLHelper

    - by shiju
    ASP.NET MVC 2 futures assembly provides a HTML helper method Serialize that can be use for persisting your model object. The Serialize  helper method will serialize the model object and will persist it in a hidden field in the HTML form. The Serialize  helper is very useful when situations like you are making multi-step wizard where a single model class is using for all steps in the wizard. For each step you want to retain the model object's whole state.The below is serializing our model object. The model object should be a Serializable class in order to work with Serialize helper method. <% using (Html.BeginForm("Register","User")) {%><%= Html.Serialize("User",Model) %> This will generate hidden field with name "user" and the value will the serialized format of our model object.In the controller action, you can place the DeserializeAttribute in the action method parameter. [HttpPost]               public ActionResult Register([DeserializeAttribute] User user, FormCollection userForm) {     TryUpdateModel(user, userForm.ToValueProvider());     //To Do } In the above action method you will get the same model object that you serialized in your view template. We are updating the User model object with the form field values.

    Read the article

  • Novo Suporte para Combinação e Minificação de Arquivos JavaScript e CSS (Série de posts sobre a ASP.NET 4.5)

    - by Leniel Macaferi
    Este é o sexto post de uma série de posts que estou escrevendo sobre a ASP.NET 4.5. Os próximos lançamentos do .NET e Visual Studio incluem vários novos e ótimos recursos e capacidades. Com a ASP.NET 4.5 você vai ver um monte de melhorias realmente emocionantes em formulários da Web ( Web Forms ) e MVC - assim como no núcleo da base de código da ASP.NET, no qual estas tecnologias são baseadas. O post de hoje cobre um pouco do trabalho que estamos realizando para adicionar suporte nativo para combinação e minificação de arquivos JavaScript e CSS dentro da ASP.NET - o que torna mais fácil melhorar o desempenho das aplicações. Este recurso pode ser utilizado por todas as aplicações ASP.NET, incluindo tanto a ASP.NET MVC quanto a ASP.NET Web Forms. Noções básicas sobre Combinação e Minificação Como mais e mais pessoas usando dispositivos móveis para navegar na web, está se tornando cada vez mais importante que os websites e aplicações que construímos tenham um bom desempenho neles. Todos nós já tentamos carregar sites em nossos smartphones - apenas para, eventualmente, desistirmos em meio à frustração porque os mesmos são carregados lentamente através da lenta rede celular. Se o seu site/aplicação carrega lentamente assim, você está provavelmente perdendo clientes em potencial por causa do mau desempenho/performance. Mesmo com máquinas desktop poderosas, o tempo de carregamento do seu site e o desempenho percebido podem contribuir enormemente para a percepção do cliente. A maioria dos websites hoje em dia são construídos com múltiplos arquivos de JavaScript e CSS para separar o código e para manter a base de código coesa. Embora esta seja uma boa prática do ponto de vista de codificação, muitas vezes isso leva a algumas consequências negativas no tocante ao desempenho geral do site. Vários arquivos de JavaScript e CSS requerem múltiplas solicitações HTTP provenientes do navegador - o que pode retardar o tempo de carregamento do site.  Exemplo Simples A seguir eu abri um site local no IE9 e gravei o tráfego da rede usando as ferramentas do desenvolvedor nativas do IE (IE Developer Tools) que podem ser acessadas com a tecla F12. Como mostrado abaixo, o site é composto por 5 arquivos CSS e 4 arquivos JavaScript, os quais o navegador tem que fazer o download. Cada arquivo é solicitado separadamente pelo navegador e retornado pelo servidor, e o processo pode levar uma quantidade significativa de tempo proporcional ao número de arquivos em questão. Combinação A ASP.NET está adicionando um recurso que facilita a "união" ou "combinação" de múltiplos arquivos CSS e JavaScript em menos solicitações HTTP. Isso faz com que o navegador solicite muito menos arquivos, o que por sua vez reduz o tempo que o mesmo leva para buscá-los. A seguir está uma versão atualizada do exemplo mostrado acima, que tira vantagem desta nova funcionalidade de combinação de arquivos (fazendo apenas um pedido para JavaScript e um pedido para CSS): O navegador agora tem que enviar menos solicitações ao servidor. O conteúdo dos arquivos individuais foram combinados/unidos na mesma resposta, mas o conteúdo dos arquivos permanece o mesmo - por isso o tamanho do arquivo geral é exatamente o mesmo de antes da combinação (somando o tamanho dos arquivos separados). Mas note como mesmo em uma máquina de desenvolvimento local (onde a latência da rede entre o navegador e o servidor é mínima), o ato de combinar os arquivos CSS e JavaScript ainda consegue reduzir o tempo de carregamento total da página em quase 20%. Em uma rede lenta a melhora de desempenho seria ainda maior. Minificação A próxima versão da ASP.NET também está adicionando uma nova funcionalidade que facilita reduzir ou "minificar" o tamanho do download do conteúdo. Este é um processo que remove espaços em branco, comentários e outros caracteres desnecessários dos arquivos CSS e JavaScript. O resultado é arquivos menores, que serão enviados e carregados no navegador muito mais rapidamente. O gráfico a seguir mostra o ganho de desempenho que estamos tendo quando os processos de combinação e minificação dos arquivos são usados ??em conjunto: Mesmo no meu computador de desenvolvimento local (onde a latência da rede é mínima), agora temos uma melhoria de desempenho de 40% a partir de onde originalmente começamos. Em redes lentas (e especialmente com clientes internacionais), os ganhos seriam ainda mais significativos. Usando Combinação e Minificação de Arquivos dentro da ASP.NET A próxima versão da ASP.NET torna realmente fácil tirar proveito da combinação e minificação de arquivos dentro de projetos, possibilitando ganhos de desempenho como os que foram mostrados nos cenários acima. A forma como ela faz isso, te permite evitar a execução de ferramentas personalizadas/customizadas, como parte do seu processo de construção da aplicação/website - ao invés disso, a ASP.NET adicionou suporte no tempo de execução/runtime para que você possa executar a combinação/minificação dos arquivos dinamicamente (cacheando os resultados para ter certeza de que a performance seja realmente satisfatória). Isto permite uma experiência de desenvolvimento realmente limpa e torna super fácil começar a tirar proveito destas novas funcionalidades. Vamos supor que temos um projeto simples com 4 arquivos JavaScript e 6 arquivos CSS: Combinando e Minificando os Arquivos CSS Digamos que você queira referenciar em uma página todas as folhas de estilo que estão dentro da pasta "Styles" mostrada acima. Hoje você tem que adicionar múltiplas referências para os arquivos CSS para obter todos eles - o que se traduziria em seis requisições HTTP separadas: O novo recurso de combinação/minificação agora permite que você combine e minifique todos os arquivos CSS da pasta Styles - simplesmente enviando uma solicitação de URL para a pasta (neste caso, "styles"), com um caminho adicional "/css" na URL. Por exemplo:    Isso fará com que a ASP.NET verifique o diretório, combine e minifique os arquivos CSS que estiverem dentro da pasta, e envie uma única resposta HTTP para o navegador com todo o conteúdo CSS. Você não precisa executar nenhuma ferramenta ou pré-processamento para obter esse comportamento. Isso te permite separar de maneira limpa seus estilos em arquivos CSS separados e condizentes com cada funcionalidade da aplicação mantendo uma experiência de desenvolvimento extremamente limpa - e mesmo assim você não terá um impacto negativo de desempenho no tempo de execução da aplicação. O designer do Visual Studio também vai honrar a lógica de combinação/minificação - assim você ainda terá uma experiência WYSWIYG no designer dentro VS. Combinando e Minificando os Arquivos JavaScript Como a abordagem CSS mostrada acima, se quiséssemos combinar e minificar todos os nossos arquivos de JavaScript em uma única resposta, poderíamos enviar um pedido de URL para a pasta (neste caso, "scripts"), com um caminho adicional "/js":   Isso fará com que a ASP.NET verifique o diretório, combine e minifique os arquivos com extensão .js dentro dele, e envie uma única resposta HTTP para o navegador com todo o conteúdo JavaScript. Mais uma vez - nenhuma ferramenta customizada ou etapas de construção foi necessária para obtermos esse comportamento. Este processo funciona em todos os navegadores. Ordenação dos Arquivos dentro de um Pacote Por padrão, quando os arquivos são combinados pela ASP.NET, eles são ordenados em ordem alfabética primeiramente, exatamente como eles são mostrados no Solution Explorer. Em seguida, eles são automaticamente reorganizados de modo que as bibliotecas conhecidas e suas extensões personalizadas, tais como jQuery, MooTools e Dojo sejam carregadas antes de qualquer outra coisa. Assim, a ordem padrão para a combinação dos arquivos da pasta Scripts, como a mostrada acima será: jquery-1.6.2.js jquery-ui.js jquery.tools.js a.js Por padrão, os arquivos CSS também são classificados em ordem alfabética e depois são reorganizados de forma que o arquivo reset.css e normalize.css (se eles estiverem presentes na pasta) venham sempre antes de qualquer outro arquivo. Assim, o padrão de classificação da combinação dos arquivos da pasta "Styles", como a mostrada acima será: reset.css content.css forms.css globals.css menu.css styles.css A ordenação/classificação é totalmente personalizável, e pode ser facilmente alterada para acomodar a maioria dos casos e qualquer padrão de nomenclatura que você prefira. O objetivo com a experiência pronta para uso, porém, é ter padrões inteligentes que você pode simplesmente usar e ter sucesso com os mesmos. Qualquer número de Diretórios/Subdiretórios é Suportado No exemplo acima, nós tivemos apenas uma única pasta "Scripts" e "Styles" em nossa aplicação. Isso funciona para alguns tipos de aplicação (por exemplo, aplicações com páginas simples). Muitas vezes, porém, você vai querer ter múltiplos pacotes/combinações de arquivos CSS/JS dentro de sua aplicação - por exemplo: um pacote "comum", que tem o núcleo dos arquivos JS e CSS que todas as páginas usam, e então arquivos específicos para páginas ou seções que não são utilizados globalmente. Você pode usar o suporte à combinação/minificação em qualquer número de diretórios ou subdiretórios em seu projeto - isto torna mais fácil estruturar seu código de forma a maximizar os benefícios da combinação/minificação dos arquivos. Cada diretório por padrão pode ser acessado como um pacote separado e endereçável através de uma URL.  Extensibilidade para Combinação/Minificação de Arquivos O suporte da ASP.NET para combinar e minificar é construído com extensibilidade em mente e cada parte do processo pode ser estendido ou substituído. Regras Personalizadas Além de permitir a abordagem de empacotamento - baseada em diretórios - que vem pronta para ser usada, a ASP.NET também suporta a capacidade de registrar pacotes/combinações personalizadas usando uma nova API de programação que estamos expondo.  O código a seguir demonstra como você pode registrar um "customscript" (script personalizável) usando código dentro da classe Global.asax de uma aplicação. A API permite que você adicione/remova/filtre os arquivos que farão parte do pacote de maneira muito granular:     O pacote personalizado acima pode ser referenciado em qualquer lugar dentro da aplicação usando a referência de <script> mostrada a seguir:     Processamento Personalizado Você também pode substituir os pacotes padrão CSS e JavaScript para suportar seu próprio processamento personalizado dos arquivos do pacote (por exemplo: regras personalizadas para minificação, suporte para Saas, LESS ou sintaxe CoffeeScript, etc). No exemplo mostrado a seguir, estamos indicando que queremos substituir as transformações nativas de minificação com classes MyJsTransform e MyCssTransform personalizadas. Elas são subclasses dos respectivos minificadores padrão para CSS e JavaScript, e podem adicionar funcionalidades extras:     O resultado final desta extensibilidade é que você pode se plugar dentro da lógica de combinação/minificação em um nível profundo e fazer algumas coisas muito legais com este recurso. Vídeo de 2 Minutos sobre Combinação e Minificacão de Arquivos em Ação Mads Kristensen tem um ótimo vídeo de 90 segundo (em Inglês) que demonstra a utilização do recurso de Combinação e Minificação de Arquivos. Você pode assistir o vídeo de 90 segundos aqui. Sumário O novo suporte para combinação e minificação de arquivos CSS e JavaScript dentro da próxima versão da ASP.NET tornará mais fácil a construção de aplicações web performáticas. Este recurso é realmente fácil de usar e não requer grandes mudanças no seu fluxo de trabalho de desenvolvimento existente. Ele também suporta uma rica API de extensibilidade que permite a você personalizar a lógica da maneira que você achar melhor. Você pode facilmente tirar vantagem deste novo suporte dentro de aplicações baseadas em ASP.NET MVC e ASP.NET Web Forms. Espero que ajude, Scott P.S. Além do blog, eu uso o Twitter para disponibilizar posts rápidos e para compartilhar links.Lidar com o meu Twitter é: @scottgu Texto traduzido do post original por Leniel Macaferi. google_ad_client = "pub-8849057428395760"; /* 728x90, created 2/15/09 */ google_ad_slot = "4706719075"; google_ad_width = 728; google_ad_height = 90;

    Read the article

  • Persisting model state in ASP.NET MVC using Serialize HTMLHelper

    - by shiju
    ASP.NET MVC 2 futures assembly provides a HTML helper method Serialize that can be use for persisting your model object. The Serialize  helper method will serialize the model object and will persist it in a hidden field in the HTML form. The Serialize  helper is very useful when situations like you are making multi-step wizard where a single model class is using for all steps in the wizard. For each step you want to retain the model object's whole state.The below is serializing our model object. The model object should be a Serializable class in order to work with Serialize helper method. <% using (Html.BeginForm("Register","User")) {%><%= Html.Serialize("User",Model) %> This will generate hidden field with name "user" and the value will the serialized format of our model object.In the controller action, you can place the DeserializeAttribute in the action method parameter. [HttpPost]               public ActionResult Register([DeserializeAttribute] User user, FormCollection userForm) {     TryUpdateModel(user, userForm.ToValueProvider());     //To Do } In the above action method you will get the same model object that you serialized in your view template. We are updating the User model object with the form field values.

    Read the article

  • Breaking Changes in Asp.Net 4

    - by joelvarty
    I upgraded an app to .net just for fun and a bunch of things broke. Turns out there are quite a few things that are officially broken between anything and .Net 4.0… http://www.asp.net/%28S%28ywiyuluxr3qb2dfva1z5lgeg%29%29/learn/whitepapers/aspnet4/breaking-changes/ more later – joel

    Read the article

  • Should I migrate to MVC3?

    - by eestein
    Hi everyone. I have a MVC2 project, my question is: should I migrate to MVC3? Why? I'd like the opinion of some who already migrated, or at least used MVC3 and MVC2. Already read http://weblogs.asp.net/scottgu/archive/2011/01/13/announcing-release-of-asp-net-mvc-3-iis-express-sql-ce-4-web-farm-framework-orchard-webmatrix.aspx and I already know about the described tool for migrating: http://blogs.msdn.com/b/marcinon/archive/2011/01/13/mvc-3-project-upgrade-tool.aspx What I'd really appreciate is your valuable insight. Best regards.

    Read the article

  • Returning Images from ASP.NET Web API

    - by bipinjoshi
    Sometimes you need to save and retrieve image data in SQL Server as a part of Web API functionality. A common approach is to save images as physical image files on the web server and then store the image URL in a SQL Server database. However, at times you need to store image data directly into a SQL Server database rather than the image URL. While dealing with the later scenario you need to read images from a database and then return this image data from your Web API. This article shows the steps involved in this process. http://www.bipinjoshi.net/articles/4b9922c3-0982-4e8f-812c-488ff4dbd507.aspx

    Read the article

  • A problem with the asp.net create user control

    - by Sir Psycho
    Hi, I've customised the asp.net login control and it seems to create new accounts fine, but if I duplicate the user id thats already registered or enter an email thats already used, the error messages arn't displaying. Its driving me crazy. The page just refreshes without showing an error. I've included the as instructed on the MSDN site but nothing. http://msdn.microsoft.com/en-us/library/ms178342.aspx <asp:CreateUserWizard ErrorMessageStyle-BorderColor="Azure" ID="CreateUserWizard1" runat="server" ContinueDestinationPageUrl="~/home.aspx"> <WizardSteps> <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server"> <ContentTemplate> <asp:Literal ID="ErrorMessage" runat="server"></asp:Literal> <div class="fieldLine"> <asp:Label ID="lblFirstName" runat="server" Text="First Name:" AssociatedControlID="tbxFirstName"></asp:Label> <asp:Label ID="lblLastName" runat="server" Text="Last Name:" AssociatedControlID="tbxLastName"></asp:Label> </div> <div class="fieldLine"> <asp:TextBox ID="tbxFirstName" runat="server"></asp:TextBox> <asp:TextBox ID="tbxLastName" runat="server"></asp:TextBox> </div> <asp:Label ID="lblEmail" runat="server" Text="Email:" AssociatedControlID="Email"></asp:Label> <asp:TextBox ID="Email" runat="server" CssClass="wideInput"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="aspValidator" Display="Dynamic" ControlToValidate="Email" ErrorMessage="Required"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Display="Dynamic" CssClass="aspValidator" ControlToValidate="Email" SetFocusOnError="true" ValidationExpression="^(?:[a-zA-Z0-9_'^&amp;/+-])+(?:\.(?:[a-zA-Z0-9_'^&amp;/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$" ErrorMessage="Email address not valid"></asp:RegularExpressionValidator> <asp:Label ID="lblEmailConfirm" runat="server" Text="Confirm Email Address:" AssociatedControlID="tbxEmailConfirm"></asp:Label> <asp:TextBox ID="tbxEmailConfirm" runat="server" CssClass="wideInput"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" CssClass="aspValidator" Display="Dynamic" ControlToValidate="tbxEmailConfirm" ErrorMessage="Required"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" Display="Dynamic" CssClass="aspValidator" ControlToValidate="tbxEmailConfirm" SetFocusOnError="true" ValidationExpression="^(?:[a-zA-Z0-9_'^&amp;/+-])+(?:\.(?:[a-zA-Z0-9_'^&amp;/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$" ErrorMessage="Email address not valid"></asp:RegularExpressionValidator> <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" SetFocusOnError="true" CssClass="aspValidator" ControlToCompare="Email" ControlToValidate="tbxEmailConfirm" ErrorMessage="Email address' do not match"></asp:CompareValidator> <asp:Label ID="lblUsername" runat="server" Text="Username:" AssociatedControlID="UserName"></asp:Label> <asp:TextBox ID="UserName" runat="server" MaxLength="12"></asp:TextBox><br /> <asp:CustomValidator ID="CustomValidatorUserName" runat="server" Display="Dynamic" SetFocusOnError="true" CssClass="aspValidator" ValidateEmptyText="true" ControlToValidate="UserName" ErrorMessage="Username can be between 6 and 12 characters." ClientValidationFunction="ValidateLength" OnServerValidate="ValidateUserName"></asp:CustomValidator> <div class="fieldLine"> <asp:Label ID="lblPassword" runat="server" Text="Password:" AssociatedControlID="Password"></asp:Label> <asp:Label ID="lblPasswordConfirm" runat="server" Text="Confirm Password:" AssociatedControlID="ConfirmPassword" CssClass="confirmPassword"></asp:Label> </div> <div class="fieldLine"> <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox> <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox><br /> <asp:CustomValidator ID="CustomValidatorPassword" runat="server" Display="Dynamic" SetFocusOnError="true" CssClass="aspValidator" ControlToValidate="Password" ValidateEmptyText="true" ErrorMessage="Password can be between 6 and 12 characters" ClientValidationFunction="ValidateLength" OnServerValidate="ValidatePassword"></asp:CustomValidator> <asp:CustomValidator ID="CustomValidatorConfirmPassword" runat="server" Display="Dynamic" SetFocusOnError="true" CssClass="aspValidator" ControlToValidate="ConfirmPassword" ValidateEmptyText="true" ErrorMessage="Password can be between 6 and 12 characters" ClientValidationFunction="ValidateLength" OnServerValidate="ValidatePassword"></asp:CustomValidator> <asp:CompareValidator ID="CompareValidator2" runat="server" Enabled="false" Display="Dynamic" SetFocusOnError="true" CssClass="aspValidator" ControlToCompare="Password" ControlToValidate="ConfirmPassword" ErrorMessage="Passwords do not match"></asp:CompareValidator> </div> <asp:Label ID="lblCaptch" runat="server" Text="Captcha:" AssociatedControlID="imgCaptcha"></asp:Label> <div class="borderBlue" style="width:200px;"> <asp:Image ID="imgCaptcha" runat="server" ImageUrl="~/JpegImage.aspx" /><br /> </div> <asp:TextBox ID="tbxCaptcha" runat="server" CssClass="captchaText"></asp:TextBox> <asp:RequiredFieldValidator ControlToValidate="tbxCaptcha" CssClass="aspValidator" ID="RequiredFieldValidator3" runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator> <asp:CustomValidator ID="CustomValidator1" ControlToValidate="tbxCaptcha" runat="server" OnServerValidate="ValidateCaptcha" ErrorMessage="Captcha incorrect"></asp:CustomValidator> </ContentTemplate> <CustomNavigationTemplate> <div style="float:left;"> <asp:Button ID="CreateUser" runat="server" Text="Register Now!" CausesValidation="true" CommandName="CreateUser" OnCommand="CreateUserClick" CssClass="registerButton" /> </div> </CustomNavigationTemplate> </asp:CreateUserWizardStep> <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"> <ContentTemplate> <table border="0" style="font-size: 100%; font-family: Verdana" id="TABLE1" > <tr> <td align="center" colspan="2" style="font-weight: bold; color: white; background-color: #5d7b9d; height: 18px;"> Complete</td> </tr> <tr> <td> Your account has been successfully created.<br /> </td> </tr> <tr> <td align="right" colspan="2"> <asp:Button ID="Button1" PostBackUrl="~/home.aspx" runat="server" Text="Button" /> </td> </tr> </table> </ContentTemplate> </asp:CompleteWizardStep> </WizardSteps> </asp:CreateUserWizard>

    Read the article

  • Azure, don't give me multiple VMs, give me one elastic VM

    - by FransBouma
    Yesterday, Microsoft revealed new major features for Windows Azure (see ScottGu's post). It all looks shiny and great, but after reading most of the material describing the new features, I still find the overall idea behind all of it flawed: why should I care on how much VMs my web app runs? Isn't that a problem to solve for the Windows Azure engineers / software? And what if I need the file system, why can't I simply get a virtual filesystem ? To illustrate my point, let's use a real example: a product website with a customer system/database and next to it a support site with accompanying database. Both are written in .NET, using ASP.NET and use a SQL Server database each. The product website offers files to download by customers, very simple. You have a couple of options to host these websites: Buy a server, place it in a rack at an ISP and run the sites on that server Use 'shared hosting' with an ISP, which means your sites' appdomains are running on the same machine, as well as the files stored, and the databases are hosted in the same server as the other shared databases. Hire a VM, install your OS of choice at an ISP, and host the sites on that VM, basically the same as the first option, except you don't have a physical server At some cloud-vendor, either host the sites 'shared' or in a VM. See above. With all of those options, scalability is a problem, even the cloud-based ones, though not due to the same reasons: The physical server solution has the obvious problem that if you need more power, you need to buy a bigger server or more servers which requires you to add replication and other overhead Shared hosting solutions are almost always capped on memory usage / traffic and database size: if your sites get too big, you have to move out of the shared hosting environment and start over with one of the other solutions The VM solution, be it a VM at an ISP or 'in the cloud' at e.g. Windows Azure or Amazon, in theory allows scaling out by simply instantiating more VMs, however that too introduces the same overhead problems as with the physical servers: suddenly more than 1 instance runs your sites. If a cloud vendor offers its services in the form of VMs, you won't gain much over having a VM at some ISP: the main problems you have to work around are still there: when you spin up more than one VM, your application must be completely stateless at any moment, including the DB sub system, because what's in memory in instance 1 might not be in memory in instance 2. This might sounds trivial but it's not. A lot of the websites out there started rather small: they were perfectly runnable on a single machine with normal memory and CPU power. After all, you don't need a big machine to run a website with even thousands of users a day. Moving these sites to a multi-VM environment will cause a problem: all the in-memory state they use, all the multi-page transitions they use while keeping state across the transition, they can't do that anymore like they did that on a single machine: state is something of the past, you have to store every byte of state in either a DB or in a viewstate or in a cookie somewhere so with the next request, all state information is available through the request, as nothing is kept in-memory. Our example uses a bunch of files in a file system. Using multiple VMs will require that these files move to a cloud storage system which is mounted in each VM so we don't have to store the files on each VM. This might require different file paths, but this change should be minor. What's perhaps less minor is the maintenance procedure in place on the new type of cloud storage used: instead of ftp-ing into a VM, you might have to update the files using different ways / tools. All in all this makes moving an existing website which was written for an environment that's based around a VM (namely .NET with its CLR) overly cumbersome and problematic: it forces you to refactor your website system to be able to be used 'in the cloud', which is caused by the limited way how e.g. Windows Azure offers its cloud services: in blocks of VMs. Offer a scalable, flexible VM which extends with my needs Instead, cloud vendors should offer simply one VM to me. On that VM I run the websites, store my DB and my files. As it's a virtual machine, how this machine is actually ran on physical hardware (e.g. partitioned), I don't care, as that's the problem for the cloud vendor to solve. If I need more resources, e.g. I have more traffic to my server, way more visitors per day, the VM stretches, like I bought a bigger box. This frees me from the problem which comes with multiple VMs: I don't have any refactoring to do at all: I can simply build my website as if it runs on my local hardware server, upload it to the VM offered by the cloud vendor, install it on the VM and I'm done. "But that might require changes to windows!" Yes, but Microsoft is Windows. Windows Azure is their service, they can make whatever change to what they offer to make it look like it's windows. Yet, they're stuck, like Amazon, in thinking in VMs, which forces developers to 'think ahead' and gamble whether they would need to migrate to a cloud with multiple VMs in the future or not. Which comes down to: gamble whether they should invest time in code / architecture which they might never need. (YAGNI anyone?) So the VM we're talking about, is that a low-level VM which runs a guest OS, or is that VM a different kind of VM? The flexible VM: .NET's CLR ? My example websites are ASP.NET based, which means they run inside a .NET appdomain, on the .NET CLR, which is a VM. The only physical OS resource the sites need is the file system, however this too is accessed through .NET. In short: all the websites see is what .NET allows the websites to see, the world as the websites know it is what .NET shows them and lets them access. How the .NET appdomain is run physically, that's the concern of .NET, not mine. This begs the question why Windows Azure doesn't offer virtual appdomains? Or better: .NET environments which look like one machine but could be physically multiple machines. In such an environment, no change has to be made to the websites to migrate them from a local machine or own server to the cloud to get proper scaling: the .NET VM will simply scale with the need: more memory needed, more CPU power needed, it stretches. What it offers to the application running inside the appdomain is simply increasing, but not fragmented: all resources are available to the application: this means that the problem of how to scale is back to where it should be: with the cloud vendor. "Yeah, great, but what about the databases?" The .NET application communicates with the database server through a .NET ADO.NET provider. Where the database is located is not a problem of the appdomain: the ADO.NET provider has to solve that. I.o.w.: we can host the databases in an environment which offers itself as a single resource and is accessible through one connection string without replication overhead on the outside, and use that environment inside the .NET VM as if it was a single DB. But what about memory replication and other problems? This environment isn't simple, at least not for the cloud vendor. But it is simple for the customer who wants to run his sites in that cloud: no work needed. No refactoring needed of existing code. Upload it, run it. Perhaps I'm dreaming and what I described above isn't possible. Yet, I think if cloud vendors don't move into that direction, what they're offering isn't interesting: it doesn't solve a problem at all, it simply offers a way to instantiate more VMs with the guest OS of choice at the cost of me needing to refactor my website code so it can run in the straight jacket form factor dictated by the cloud vendor. Let's not kid ourselves here: most of us developers will never build a website which needs a truck load of VMs to run it: almost all websites created by developers can run on just a few VMs at most. Yet, the most expensive change is right at the start: moving from one to two VMs. As soon as you have refactored your website code to run across multiple VMs, adding another one is just as easy as clicking a mouse button. But that first step, that's the problem here and as it's right there at the beginning of scaling the website, it's particularly strange that cloud vendors refuse to solve that problem and leave it to the developers to solve that. Which makes migrating 'to the cloud' particularly expensive.

    Read the article

  • Using SocialCounter.NET with ASP.NET MVC

    - by DigiMortal
    I found small library called SocialCounter.NET that is able to display some data from popular social sites. Although it is possible to use widgets offered by social networks there are also scenarios when you don’t want or can’t use these JavaScript based widgets. In this posting I will show you how to use SocialCounter.NET. Start with downloading SocialCounter.NET. You can also use NuGet package manager to download SocialCounter.NET. Using SocialCounter.NET is very easy as you can see from this example view: @using SocialCounter.NET; @{      ViewBag.Title = "Home Page"; } <h2>Social</h2> <p>     Twitter followers: @Counter.GetTwitterFollowersCount("gpeipman")<br />     Facebook friends: @Counter.GetFacebookFriendsCount("gpeipman")<br />     Facebook likes: @Counter.GetFacebookLikes("http://www.eindhovenmetalmeeting.nl/")<br />     Delicious saves count: @Counter.GetDeliciousSaveCount("http://youreffectiveleadership.com/")<br /> </p> And the result is shown on image on right. You can use SocialCounter.NET by example on user profile pages and on your content pages where you want to show how many people have saved current page as bookmark. SocialCounter.NET supports also LinkedIn, RSS-feeds and Google Plus accounts. In future – I hope – they will add support for more social networks to their library.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >