Search Results

Search found 52729 results on 2110 pages for 'net'.

Page 15/2110 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Asp.net session on browser close

    - by budugu
    Note: Cross posted from Vijay Kodali's Blog. Permalink How to capture logoff time when user closes browser? Or How to end user session when browser closed? These are some of the frequently asked questions in asp.net forums. In this post I'll show you how to do this when you're building an ASP.NET web application. Before we start, one fact: There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP. The Web server is out of the picture as soon as it finishes sending the page content to the client. After that, all you can rely on is a client side script. Unfortunately, there is no reliable client side event for browser close. Solution: The first thing you need to do is create the web service. I've added web service and named it AsynchronousSave.asmx.    Make this web service accessible from Script, by setting class qualified with the ScriptServiceAttribute attribute...  Add a method (SaveLogOffTime) marked with [WebMethod] attribute. This method simply accepts UserId as a string variable and writes that value and logoff time to text file. But you can pass as many variables as required. You can then use this information for many purposes. To end user session, you can just call Session.Abandon() in the above web method. To enable web service to be called from page’s client side code, add script manager to page. Here i am adding to SessionTest.aspx page When the user closes the browser, onbeforeunload event fires on the client side. Our final step is adding a java script function to that event, which makes web service calls. The code is simple but effective My Code HTML:( SessionTest.aspx ) C#:( SessionTest.aspx.cs ) That’s’ it. Run the application and after browser close, open the text file to see the log off time. The above code works well in IE 7/8. If you have any questions, leave a comment.

    Read the article

  • A simple DotNetNuke article module with C# and VB.NET Source

    - by Chris Hammond
    For the DotNetNuke Connections conference last month I provided an advanced DotNetNuke module development course as a pre-conference training session. That training covered details on how to implement some of the newer features in the DotNetNuke platform within custom modules, mainly ContentItem integration and Taxonomy features. For the course I created a very basic Article module for DotNetNuke, ultimately naming it DNNSimpleArticle. For the course I created both a C# and a VB.NET version of the...(read more)

    Read the article

  • 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

  • Setting up Visual Studio 2010 to step into Microsoft .NET Source Code

    - by rajbk
    Using the Microsoft Symbol Server to obtain symbol debugging information is now much easier in VS 2010. Microsoft gives you access to their internet symbol server that contains symbol files for most of the .NET framework including the recently announced availability of MVC 2 Symbols.  SETUP In VS 2010 RTM, go to Tools –> Options –> Debugging –> General. Check “Enable .NET Framework source stepping” We get the following dialog box   This automatically disables “Enable My Code”   Go to Debugging –> Symbols and Check “Microsoft Symbol Servers”. You can selectively exclude modules if you want to.   You will get a warning dialog like so: Hitting OK will start the download process   The setup is complete. You are now ready to start debugging! DEBUGGING Add a break point to your application and run the application in debug mode (F5 shortcut for me). Go to your call stack when you hit the break point. Right click on a frame that is grayed out. Select “Load Symbols from” “Microsoft Symbol Servers”. VS will begin a one time download of that assembly. This assembly will be cached locally so you don’t have to wait for the download the next time you debug the app.   We get a one time license agreement dialog box You might see an error like the one below regarding different encoding (hopefully will be fixed).    Assemblies for which the symbols have been loaded are no longer grayed out. Double clicking on any entry in the call stack should now directly take you to the source code for that assembly. AFAIK, not all symbols are available on the MS symbol server. In cases like that you will see a tab like the one below and be given the option to “Show Disassembly”. Enjoy! Newsreel Announcer: Humiliated, Muntz vows a return to Paradise Falls and promises to capture the beast alive! Charles Muntz: [speaking to a large audience outside in the newsreel] I promise to capture the beast alive, and I will not come back until I do!

    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

  • ASP.NET developers build rich management system using the VWG extension

    - by Visual WebGui
    When The Center for Organ Recovery & Education (CORE) decided they needed a web application to allow easy access to the expenses management system they initially went to ASP.NET web forms combined with CSS. The outcome, however, was not satisfying enough as it appeared bland and lacked in richness. So in order to enrich the UI and give the web application some glitz, Visual WebGui was selected. Visual WebGui provided the needed richness and the familiar Windows look and feel also made the transition...(read more)

    Read the article

  • ASP.NET Meta Keywords and Description

    - by Ben Griswold
    Some of the ASP.NET 4 improvements around SEO are neat.  The ASP.NET 4 Page.MetaKeywords and Page.MetaDescription properties, for example, are a welcomed change.  There’s nothing earth-shattering going on here – you can now set these meta tags via your Master page’s code behind rather than relying on updates to your markup alone.  It isn’t difficult to manage meta keywords and descriptions without these ASP.NET 4 properties but I still appreciate the attention SEO is getting.  It’s nice to get gentle reminder via new coding features that some of the more subtle aspects of one’s application deserve thought and attention too.  For the record, this is how I currently manage my meta: <meta name="keywords"     content="<%= Html.Encode(ConfigurationManager.AppSettings["Meta.Keywords"]) %>" /> <meta name="description"     content="<%= Html.Encode(ConfigurationManager.AppSettings["Meta.Description"]) %>" /> All Master pages assume the same keywords and description values as defined by the application settings.  Nothing fancy. Nothing dynamic. But it’s manageable.  It works, but I’m looking forward to the new way in ASP.NET 4.

    Read the article

  • jQuery + Perl CGI to vb.net transition

    - by user1257458
    I've been developing oracle database-heavy "web applications" forever by building my html by hand, adding some jquery to handle ajax requests (html inserts for forms processing etc), and always did my server side stuff in perl cgi. I really love how easy it is to read some form input, execute some select statements through dbi (SO EASY), and generate HTML to be inserted by the jquery request. That's a web application to me. However, my new boss builds everything in visual studio 2010, vb.net, usually webforms. So, for work reasons, I now need to start developing in vb.net so it can be collectively maintained, and I'm just seeking advice on where to start learning/how to approach this. I know I could at least learn ASP.net and VB.net, and create a webform, have it read parameters, return HTML, etc. which would allow me to use my previously written HTML and client-side scripts (jQuery). Although- since we're moving heavily to mobile applications I really need to reduce client-side processing load. Is there any advantage to my boss' method? Thanks a ton.

    Read the article

  • A basic T4 template for generating Model Metadata in ASP.NET MVC2

    - by rajbk
    I have been learning about T4 templates recently by looking at the awesome ADO.NET POCO entity generator. By using the POCO entity generator template as a base, I created a T4 template which generates metadata classes for a given Entity Data Model. This speeds coding by reducing the amount of typing required when creating view specific model and its metadata. To use this template, Download the template provided at the bottom. Set two values in the template file. The first one should point to the EDM you wish to generate metadata for. The second is used to suffix the namespace and classes that get generated. string inputFile = @"Northwind.edmx"; string suffix = "AutoMetadata"; Add the template to your MVC 2 Visual Studio 2010 project. Once you add it, a number of classes will get added to your project based on the number of entities you have.    One of these classes is shown below. Note that the DisplayName, Required and StringLength attributes have been added by the t4 template. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------   using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations;   namespace NorthwindSales.ModelsAutoMetadata { public partial class CustomerAutoMetadata { [DisplayName("Customer ID")] [Required] [StringLength(5)] public string CustomerID { get; set; } [DisplayName("Company Name")] [Required] [StringLength(40)] public string CompanyName { get; set; } [DisplayName("Contact Name")] [StringLength(30)] public string ContactName { get; set; } [DisplayName("Contact Title")] [StringLength(30)] public string ContactTitle { get; set; } [DisplayName("Address")] [StringLength(60)] public string Address { get; set; } [DisplayName("City")] [StringLength(15)] public string City { get; set; } [DisplayName("Region")] [StringLength(15)] public string Region { get; set; } [DisplayName("Postal Code")] [StringLength(10)] public string PostalCode { get; set; } [DisplayName("Country")] [StringLength(15)] public string Country { get; set; } [DisplayName("Phone")] [StringLength(24)] public string Phone { get; set; } [DisplayName("Fax")] [StringLength(24)] public string Fax { get; set; } } } The gen’d class can be used from your project by creating a partial class with the entity name and setting the MetadataType attribute.namespace MyProject.Models{ [MetadataType(typeof(CustomerAutoMetadata))] public partial class Customer { }} You can also copy the code in the metadata class generated and create your own ViewModel class. Note that the template is super basic  and does not take into account complex properties. I have tested it with the Northwind database. This is a work in progress. Feel free to modify the template to suite your requirements. Standard disclaimer follows: Use At Your Own Risk, Works on my machine running VS 2010 RTM/ASP.NET MVC 2 AutoMetaData.zip Mr. Incredible: Of course I have a secret identity. I don't know a single superhero who doesn't. Who wants the pressure of being super all the time?

    Read the article

  • ASP.NET MVC for the php/asp noob

    - by dotjosh
    I was talking to a friend today, who's foremost a php developer, about his thoughts on Umbraco and he said "Well they're apparently working feverishly on the new version of Umbraco, which will be MVC... which i still don't know what that means, but I know you like it." I ended up giving him a ground up explanation of ASP.NET MVC, so I'm posting this so he can link this to his friends and for anyone else who finds it useful.  The whole goal was to be as simple as possible, not being focused on proper syntax. Model-View-Controller (or MVC) is just a pattern that is used for handling UI interaction with your backend.  In a typical web app, you can imagine the *M*odel as your database model, the *V*iew as your HTML page, and the *C*ontroller as the class inbetween.  MVC handles your web request different than your typical php/asp app.In your php/asp app, your url maps directly to a php/asp file that contains html, mixed with database access code and redirects.In an MVC app, your url route is mapped to a method on a class (the controller).  The body of this method can do some database access and THEN decide which *V*iew (html/aspx page) should be displayed;  putting the controller in charge and not the view... a clear seperation of concerns that provides better reusibility and generally promotes cleaner code. Mysite.com, a quick example:Let's say you hit the following url in your application: http://www.mysite.com/Product/ShowItem?Id=4 To avoid tedious configuration, MVC uses a lot of conventions by default. For instance, the above url in your app would automatically make MVC search for a .net class with the name "Product" and a method named "ShowItem" based on the pattern of the url.  So if you name things properly, your method would automatically be called when you entered the above url.  Additionally, it would automatically map/hydrate the "int id" parameter that was in your querystring, matched by name.Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        return View();    }} From this point you can write the code in the body of this method to do some database access and then pass a "bag" (also known as the ViewData) of data to your chosen *V*iew (html page) to use for display.  The view(html) ONLY needs to be worried about displaying the flattened data that it's been given in the best way it can;  this allows the view to be reused throughout your application as *just* a view, and not be coupled to HOW the data for that view get's loaded.. Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        var database = new Database();        var item = database.GetItem(id);        ViewData["TheItem"] = item;        return View();    }} Again by convention, since the class' method name is "ShowItem", it'll search for a view named "ShowItem.aspx" by default, and pass the ViewData bag to it to use. ShowItem.aspx<html>     <body>      <%        var item =(Item)ViewData["TheItem"]       %>       <h1><%= item.FullProductName %></h1>     </body></html> BUT WAIT! WHY DOES MICROSOFT HAVE TO DO THINGS SO DIFFERENTLY!?They aren't... here are some other frameworks you may have heard of that use the same pattern in a their own way: Ruby On Rails Grails Spring MVC Struts Django    

    Read the article

  • Watching Green Day and discovering Sitecore, priceless.

    - by jonel
    I’m feeling inspired and I’d like to share a technique we’ve implemented in Sitecore to address a URL mapping from our legacy site that we wanted to carry over to the new beautiful Littelfuse.com. The challenge is to carry over all of our series URLs that have been published in our datasheets, we currently have a lot of series and having to create a manual mapping for those could be really tedious. It has the format of http://www.littelfuse.com/series/series-name.html, for instance, http://www.littelfuse.com/series/flnr.html. It would have been easier if we have our information architecture defined like this but that would have been too easy. I took a solution that is 2-fold. First, I need to create a URL rewrite rule using the IIS URL Rewrite Module 2.0. Secondly, we need to implement a handler that will take care of the actual lookup of the actual series. It will be amazing after we’ve gone over the details. Let’s start with the URL rewrite. Create a new blank rule, you can name it with anything you wish. The key part here to talk about is the Pattern and the Action groups. The Pattern is nothing but regex. Basically, I’m telling it to match the regex I have defined. In the Action group, I am telling it what to do, in this case, rewrite to the redirect.aspx webform. In this implementation, I will be using Rewrite instead of redirect so the URL sticks in the browser. If you opt to use Redirect, then the URL bar will display the new URL our webform will redirect to. Let me explain one small thing, the (\w+) in my Pattern group’s regex, will actually translate to {R:1} in my Action’s group. This is where the magic begins. Now let’s see what our Redirect.aspx contains. Remember our {R:1} above which becomes the query string variable s? This are basic .Net code. The only thing that you will probably ask is the LFSearch class. It’s our own implementation of addressing finding items by using a field search, we supply the fieldname, the value of the field, the template name of the item we are after, and the value of true or false if we want to do an exact search, or not. If eureka, then redirect to that item’s Path (Url). If not, tell the user tough luck, here’s the 404 page as a consolation. Amazing, ain’t it?

    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

  • Asynchronous Streaming in ASP.NET WebApi

    - by andresv
     Hi everyone, if you use the cool MVC4 WebApi you might encounter yourself in a common situation where you need to return a rather large amount of data (most probably from a database) and you want to accomplish two things: Use streaming so the client fetch the data as needed, and that directly correlates to more fetching in the server side (from our database, for example) without consuming large amounts of memory. Leverage the new MVC4 WebApi and .NET 4.5 async/await asynchronous execution model to free ASP.NET Threadpool threads (if possible).  So, #1 and #2 are not directly related to each other and we could implement our code fulfilling one or the other, or both. The main point about #1 is that we want our method to immediately return to the caller a stream, and that client side stream be represented by a server side stream that gets written (and its related database fetch) only when needed. In this case we would need some form of "state machine" that keeps running in the server and "knows" what is the next thing to fetch into the output stream when the client ask for more content. This technique is generally called a "continuation" and is nothing new in .NET, in fact using an IEnumerable<> interface and the "yield return" keyword does exactly that, so our first impulse might be to write our WebApi method more or less like this:           public IEnumerable<Metadata> Get([FromUri] int accountId)         {             // Execute the command and get a reader             using (var reader = GetMetadataListReader(accountId))             {                 // Read rows asynchronously, put data into buffer and write asynchronously                 while (reader.Read())                 {                     yield return MapRecord(reader);                 }             }         }   While the above method works, unfortunately it doesn't accomplish our objective of returning immediately to the caller, and that's because the MVC WebApi infrastructure doesn't yet recognize our intentions and when it finds an IEnumerable return value, enumerates it before returning to the client its values. To prove my point, I can code a test method that calls this method, for example:        [TestMethod]         public void StreamedDownload()         {             var baseUrl = @"http://localhost:57771/api/metadata/1";             var client = new HttpClient();             var sw = Stopwatch.StartNew();             var stream = client.GetStreamAsync(baseUrl).Result;             sw.Stop();             Debug.WriteLine("Elapsed time Call: {0}ms", sw.ElapsedMilliseconds); } So, I would expect the line "var stream = client.GetStreamAsync(baseUrl).Result" returns immediately without server-side fetching of all data in the database reader, and this didn't happened. To make the behavior more evident, you could insert a wait time (like Thread.Sleep(1000);) inside the "while" loop, and you will see that the client call (GetStreamAsync) is not going to return control after n seconds (being n == number of reader records being fetched).Ok, we know this doesn't work, and the question would be: is there a way to do it?Fortunately, YES!  and is not very difficult although a little more convoluted than our simple IEnumerable return value. Maybe in the future this scenario will be automatically detected and supported in MVC/WebApi.The solution to our needs is to use a very handy class named PushStreamContent and then our method signature needs to change to accommodate this, returning an HttpResponseMessage instead of our previously used IEnumerable<>. The final code will be something like this: public HttpResponseMessage Get([FromUri] int accountId)         {             HttpResponseMessage response = Request.CreateResponse();             // Create push content with a delegate that will get called when it is time to write out              // the response.             response.Content = new PushStreamContent(                 async (outputStream, httpContent, transportContext) =>                 {                     try                     {                         // Execute the command and get a reader                         using (var reader = GetMetadataListReader(accountId))                         {                             // Read rows asynchronously, put data into buffer and write asynchronously                             while (await reader.ReadAsync())                             {                                 var rec = MapRecord(reader);                                 var str = await JsonConvert.SerializeObjectAsync(rec);                                 var buffer = UTF8Encoding.UTF8.GetBytes(str);                                 // Write out data to output stream                                 await outputStream.WriteAsync(buffer, 0, buffer.Length);                             }                         }                     }                     catch(HttpException ex)                     {                         if (ex.ErrorCode == -2147023667) // The remote host closed the connection.                          {                             return;                         }                     }                     finally                     {                         // Close output stream as we are done                         outputStream.Close();                     }                 });             return response;         } As an extra bonus, all involved classes used already support async/await asynchronous execution model, so taking advantage of that was very easy. Please note that the PushStreamContent class receives in its constructor a lambda (specifically an Action) and we decorated our anonymous method with the async keyword (not a very well known technique but quite handy) so we can await over the I/O intensive calls we execute like reading from the database reader, serializing our entity and finally writing to the output stream.  Well, if we execute the test again we will immediately notice that the a line returns immediately and then the rest of the server code is executed only when the client reads through the obtained stream, therefore we get low memory usage and far greater scalability for our beloved application serving big chunks of data.Enjoy!Andrés.        

    Read the article

  • the size of apt-get update lists is too big

    - by dumb906
    I ran a clean install to Ubuntu 12.04 and so far everything has been working well. I especially commend the Ubuntu team for this release. I only noticed that the size of repository update is now about ~13MB. Normally, it is about this size for the first time you run apt-get update after a clean install and then ~ 23kb - 1300kb for subsequent updates. The output from apt-get update is the same I get for previous versions of Ubuntu (its pretty normal). Its a bit too long but look at an example output I got from running apt-get update. Ign http://archive.canonical.com precise InRelease Ign http://dl.google.com stable InRelease Ign http://dl.google.com stable InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Hit http://download.virtualbox.org precise InRelease Ign http://security.ubuntu.com precise-security InRelease Ign http://linux.dropbox.com precise InRelease Ign http://extras.ubuntu.com precise InRelease Ign http://download.skype.com stable InRelease Hit http://archive.canonical.com precise Release.gpg Get:1 http://dl.google.com stable Release.gpg [198 B] Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net oneiric InRelease Ign http://ppa.launchpad.net precise InRelease Get:2 http://security.ubuntu.com precise-security Release.gpg [198 B] Get:3 http://extras.ubuntu.com precise Release.gpg [72 B] Hit http://download.virtualbox.org precise/contrib i386 Packages Ign http://download.skype.com stable Release.gpg Hit http://linux.dropbox.com precise Release.gpg Ign http://us.archive.ubuntu.com precise InRelease Ign http://us.archive.ubuntu.com precise-updates InRelease Ign http://us.archive.ubuntu.com precise-backports InRelease Hit http://archive.canonical.com precise Release Get:4 http://dl.google.com stable Release.gpg [198 B] Ign http://ppa.launchpad.net oneiric InRelease Ign http://ppa.launchpad.net oneiric InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Ign http://ppa.launchpad.net precise InRelease Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Get:5 http://security.ubuntu.com precise-security Release [49.6 kB] Hit http://extras.ubuntu.com precise Release Ign http://download.skype.com stable Release Ign http://download.virtualbox.org precise/contrib TranslationIndex Get:6 http://us.archive.ubuntu.com precise Release.gpg [198 B] Hit http://archive.canonical.com precise/partner i386 Packages Hit http://linux.dropbox.com precise Release Get:7 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Hit http://extras.ubuntu.com precise/main Sources Get:8 http://ppa.launchpad.net precise Release.gpg [316 B] Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Get:9 http://us.archive.ubuntu.com precise-updates Release.gpg [198 B] Ign http://archive.canonical.com precise/partner TranslationIndex Ign http://download.skype.com stable/non-free i386 Packages/DiffIndex Get:10 http://dl.google.com stable Release [1,347 B] Hit http://linux.dropbox.com precise/main i386 Packages Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net oneiric Release.gpg Hit http://extras.ubuntu.com precise/main i386 Packages Ign http://extras.ubuntu.com precise/main TranslationIndex Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net oneiric Release.gpg Hit http://ppa.launchpad.net oneiric Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release.gpg Get:11 http://us.archive.ubuntu.com precise-backports Release.gpg [198 B] Ign http://download.skype.com stable/non-free TranslationIndex Get:12 http://dl.google.com stable Release [1,347 B] Hit http://ppa.launchpad.net precise Release.gpg Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Ign http://linux.dropbox.com precise/main TranslationIndex Hit http://ppa.launchpad.net precise Release Ign http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Get:13 http://ppa.launchpad.net precise Release [11.9 kB] Get:14 http://us.archive.ubuntu.com precise Release [49.6 kB] Hit http://download.skype.com stable/non-free i386 Packages Get:15 http://dl.google.com stable/main i386 Packages [1,268 B] Ign http://dl.google.com stable/main TranslationIndex Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net oneiric Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net oneiric Release Get:16 http://security.ubuntu.com precise-security/main Sources [7,089 B] Hit http://ppa.launchpad.net oneiric Release Get:17 http://dl.google.com stable/main i386 Packages [769 B] Ign http://dl.google.com stable/main TranslationIndex Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise Release Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Get:18 http://security.ubuntu.com precise-security/restricted Sources [14 B] Get:19 http://security.ubuntu.com precise-security/universe Sources [3,653 B] Get:20 http://security.ubuntu.com precise-security/multiverse Sources [696 B] Get:21 http://security.ubuntu.com precise-security/main i386 Packages [32.9 kB] Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Get:22 http://us.archive.ubuntu.com precise-updates Release [49.6 kB] Ign http://ppa.launchpad.net precise/main Sources/DiffIndex Ign http://ppa.launchpad.net precise/main i386 Packages/DiffIndex Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Get:23 http://security.ubuntu.com precise-security/restricted i386 Packages [14 B] Get:24 http://security.ubuntu.com precise-security/universe i386 Packages [8,594 B] Get:25 http://security.ubuntu.com precise-security/multiverse i386 Packages [1,393 B] Hit http://security.ubuntu.com precise-security/main TranslationIndex Hit http://security.ubuntu.com precise-security/multiverse TranslationIndex Hit http://security.ubuntu.com precise-security/restricted TranslationIndex Hit http://security.ubuntu.com precise-security/universe TranslationIndex Ign http://ppa.launchpad.net precise/main TranslationIndex Get:26 http://us.archive.ubuntu.com precise-backports Release [49.6 kB] Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Get:27 http://ppa.launchpad.net precise/main i386 Packages [1,276 B] Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Get:28 http://us.archive.ubuntu.com precise/main Sources [934 kB] Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main i386 Packages Hit http://security.ubuntu.com precise-security/main Translation-en Hit http://security.ubuntu.com precise-security/multiverse Translation-en Hit http://security.ubuntu.com precise-security/restricted Translation-en Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net oneiric/main Sources Hit http://ppa.launchpad.net oneiric/main i386 Packages Ign http://ppa.launchpad.net oneiric/main TranslationIndex Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net oneiric/main Sources Hit http://security.ubuntu.com precise-security/universe Translation-en Ign http://archive.canonical.com precise/partner Translation-en_US Hit http://ppa.launchpad.net oneiric/main i386 Packages Ign http://ppa.launchpad.net oneiric/main TranslationIndex Hit http://ppa.launchpad.net oneiric/main Sources Hit http://ppa.launchpad.net oneiric/main i386 Packages Ign http://ppa.launchpad.net oneiric/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Ign http://extras.ubuntu.com precise/main Translation-en_US Ign http://download.virtualbox.org precise/contrib Translation-en_US Ign http://archive.canonical.com precise/partner Translation-en Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Ign http://extras.ubuntu.com precise/main Translation-en Ign http://download.virtualbox.org precise/contrib Translation-en Hit http://ppa.launchpad.net precise/main Sources Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://ppa.launchpad.net precise/main TranslationIndex Hit http://ppa.launchpad.net precise/main Sources Ign http://linux.dropbox.com precise/main Translation-en_US Hit http://ppa.launchpad.net precise/main i386 Packages Ign http://download.skype.com stable/non-free Translation-en_US Ign http://linux.dropbox.com precise/main Translation-en Ign http://download.skype.com stable/non-free Translation-en Ign http://dl.google.com stable/main Translation-en_US Ign http://dl.google.com stable/main Translation-en Ign http://dl.google.com stable/main Translation-en_US Get:29 http://us.archive.ubuntu.com precise/restricted Sources [5,470 B] Get:30 http://us.archive.ubuntu.com precise/universe Sources [5,019 kB] Ign http://dl.google.com stable/main Translation-en Get:31 http://us.archive.ubuntu.com precise/multiverse Sources [155 kB] Get:32 http://us.archive.ubuntu.com precise/main i386 Packages [1,274 kB] Get:33 http://us.archive.ubuntu.com precise/restricted i386 Packages [8,431 B] Get:34 http://us.archive.ubuntu.com precise/universe i386 Packages [4,796 kB] Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net oneiric/main Translation-en_US Ign http://ppa.launchpad.net oneiric/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net oneiric/main Translation-en_US Ign http://ppa.launchpad.net oneiric/main Translation-en Ign http://ppa.launchpad.net oneiric/main Translation-en_US Ign http://ppa.launchpad.net oneiric/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Ign http://ppa.launchpad.net precise/main Translation-en_US Ign http://ppa.launchpad.net precise/main Translation-en Get:35 http://us.archive.ubuntu.com precise/multiverse i386 Packages [121 kB] Hit http://us.archive.ubuntu.com precise/main TranslationIndex Hit http://us.archive.ubuntu.com precise/multiverse TranslationIndex Hit http://us.archive.ubuntu.com precise/restricted TranslationIndex Hit http://us.archive.ubuntu.com precise/universe TranslationIndex Get:36 http://us.archive.ubuntu.com precise-updates/main Sources [31.2 kB] Get:37 http://us.archive.ubuntu.com precise-updates/restricted Sources [765 B] Get:38 http://us.archive.ubuntu.com precise-updates/universe Sources [10.1 kB] Get:39 http://us.archive.ubuntu.com precise-updates/multiverse Sources [696 B] Get:40 http://us.archive.ubuntu.com precise-updates/main i386 Packages [96.5 kB] Get:41 http://us.archive.ubuntu.com precise-updates/restricted i386 Packages [770 B] Get:42 http://us.archive.ubuntu.com precise-updates/universe i386 Packages [27.7 kB] Get:43 http://us.archive.ubuntu.com precise-updates/multiverse i386 Packages [1,393 B] Hit http://us.archive.ubuntu.com precise-updates/main TranslationIndex Hit http://us.archive.ubuntu.com precise-updates/multiverse TranslationIndex Hit http://us.archive.ubuntu.com precise-updates/restricted TranslationIndex Hit http://us.archive.ubuntu.com precise-updates/universe TranslationIndex Get:44 http://us.archive.ubuntu.com precise-backports/main Sources [700 B] Get:45 http://us.archive.ubuntu.com precise-backports/restricted Sources [14 B] Get:46 http://us.archive.ubuntu.com precise-backports/universe Sources [1,680 B] Get:47 http://us.archive.ubuntu.com precise-backports/multiverse Sources [14 B] Get:48 http://us.archive.ubuntu.com precise-backports/main i386 Packages [559 B] Get:49 http://us.archive.ubuntu.com precise-backports/restricted i386 Packages [14 B] Get:50 http://us.archive.ubuntu.com precise-backports/universe i386 Packages [1,391 B] Get:51 http://us.archive.ubuntu.com precise-backports/multiverse i386 Packages [14 B] Hit http://us.archive.ubuntu.com precise-backports/main TranslationIndex Hit http://us.archive.ubuntu.com precise-backports/multiverse TranslationIndex Hit http://us.archive.ubuntu.com precise-backports/restricted TranslationIndex Hit http://us.archive.ubuntu.com precise-backports/universe TranslationIndex Hit http://us.archive.ubuntu.com precise/main Translation-en Hit http://us.archive.ubuntu.com precise/multiverse Translation-en Hit http://us.archive.ubuntu.com precise/restricted Translation-en Hit http://us.archive.ubuntu.com precise/universe Translation-en Hit http://us.archive.ubuntu.com precise-updates/main Translation-en Hit http://us.archive.ubuntu.com precise-updates/multiverse Translation-en Hit http://us.archive.ubuntu.com precise-updates/restricted Translation-en Hit http://us.archive.ubuntu.com precise-updates/universe Translation-en Hit http://us.archive.ubuntu.com precise-backports/main Translation-en Hit http://us.archive.ubuntu.com precise-backports/multiverse Translation-en Hit http://us.archive.ubuntu.com precise-backports/restricted Translation-en Hit http://us.archive.ubuntu.com precise-backports/universe Translation-en Fetched 12.8 MB in 1min 33s (137 kB/s) Is this a new feature in 12.04? Or, if it is unintended, is there a way I can fix this? Thanks.

    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

  • Creating an ASP.NET report using Visual Studio 2010 - Part 3

    - by rajbk
    We continue building our report in this three part series. Creating an ASP.NET report using Visual Studio 2010 - Part 1 Creating an ASP.NET report using Visual Studio 2010 - Part 2 Adding the ReportViewer control and filter drop downs. Open the source code for index.aspx and add a ScriptManager control. This control is required for the ReportViewer control. Add a DropDownList for the categories and suppliers. Add the ReportViewer control. The markup after these steps is shown below. <div> <asp:ScriptManager ID="smScriptManager" runat="server"> </asp:ScriptManager> <div id="searchFilter"> Filter by: Category : <asp:DropDownList ID="ddlCategories" runat="server" /> and Supplier : <asp:DropDownList ID="ddlSuppliers" runat="server" /> </div> <rsweb:ReportViewer ID="rvProducts" runat="server"> </rsweb:ReportViewer> </div> The design view for index.aspx is shown below. The dropdowns will display the categories and suppliers in the database. Changing the selection in the drop downs will cause the report to be filtered by the selections in the dropdowns. You will see how to do this in the next steps.   Attaching the RDLC to the ReportViewer control by clicking on the top right of the control, going to Report Viewer tasks and selecting Products.rdlc.   Resize the ReportViewer control by dragging at the bottom right corner. I set mine to 800px x 500px. You can also set this value in source view. Defining the data sources. We will now define the Data Source used to populate the report. Go back to the “ReportViewer Tasks” and select “Choose Data Sources” Select a “New data source..” Select “Object” and name your Data Source ID “odsProducts”   In the next screen, choose “ProductRepository” as your business object. Choose “GetProductsProjected” in the next screen.   The method requires a SupplierID and CategoryID. We will set these so that our data source gets the values from the drop down lists we defined earlier. Set the parameter source to be of type “Control” and set the ControlIDs to be ddlSuppliers and ddlCategories respectively. Your screen will look like this: We are now going to define the data source for our drop downs. Select the ddlCategory drop down and pick “Choose Data Source”. Pick “Object” and give it an id “odsCategories”   In the next screen, choose “ProductRepository” Select the GetCategories() method in the next screen.   Select “CategoryName” and “CategoryID” in the next screen. We are done defining the data source for the Category drop down. Perform the same steps for the Suppliers drop down.   Select each dropdown and set the AppendDataBoundItems to true and AutoPostback to true.     The AppendDataBoundItems is needed because we are going to insert an “All“ list item with a value of empty. Go to each drop down and add this list item markup as shown below> Finally, double click on each drop down in the designer and add the following code in the code behind. This along with the “Autopostback= true” attribute refreshes the report anytime a drop down is changed. protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e) { rvProducts.LocalReport.Refresh(); }   protected void ddlSuppliers_SelectedIndexChanged(object sender, EventArgs e) { rvProducts.LocalReport.Refresh(); } Compile your report and run the page. You should see the report rendered. Note that the tool bar in the ReportViewer control gives you a couple of options including the ability to export the data to Excel, PDF or word.   Conclusion Through this three part series, we did the following: Created a data layer for use by our RDLC. Created an RDLC using the report wizard and define a dataset for the report. Used the report design surface to design our report including adding a chart. Used the ReportViewer control to attach the RDLC. Connected our ReportWiewer to a data source and take parameter values from the drop downlists. Used AutoPostBack to refresh the reports when the dropdown selection was changed. RDLCs allow you to create interactive reports including drill downs and grouping. For even more advanced reports you can use Microsoft® SQL Server™ Reporting Services with RDLs. With RDLs, the report is rendered on the report server instead of the web server. Another nice thing about RDLs is that you can define a parameter list for the report and it gets rendered automatically for you. RDLCs and RDLs both have their advantages and its best to compare them and choose the right one for your requirements. Download VS2010 RTM Sample project NorthwindReports.zip   Alfred Borden: Are you watching closely?

    Read the article

  • ASP.NET MVC 3: Razor’s @: and <text> syntax

    - by ScottGu
    This is another in a series of posts I’m doing that cover some of the new ASP.NET MVC 3 features: New @model keyword in Razor (Oct 19th) Layouts with Razor (Oct 22nd) Server-Side Comments with Razor (Nov 12th) Razor’s @: and <text> syntax (today) In today’s post I’m going to discuss two useful syntactical features of the new Razor view-engine – the @: and <text> syntax support. Fluid Coding with Razor ASP.NET MVC 3 ships with a new view-engine option called “Razor” (in addition to the existing .aspx view engine).  You can learn more about Razor, why we are introducing it, and the syntax it supports from my Introducing Razor blog post.  Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type. For example, the Razor snippet below can be used to iterate a list of products: When run, it generates output like:   One of the techniques that Razor uses to implicitly identify when a code block ends is to look for tag/element content to denote the beginning of a content region.  For example, in the code snippet above Razor automatically treated the inner <li></li> block within our foreach loop as an HTML content block because it saw the opening <li> tag sequence and knew that it couldn’t be valid C#.  This particular technique – using tags to identify content blocks within code – is one of the key ingredients that makes Razor so clean and productive with scenarios involving HTML creation. Using @: to explicitly indicate the start of content Not all content container blocks start with a tag element tag, though, and there are scenarios where the Razor parser can’t implicitly detect a content block. Razor addresses this by enabling you to explicitly indicate the beginning of a line of content by using the @: character sequence within a code block.  The @: sequence indicates that the line of content that follows should be treated as a content block: As a more practical example, the below snippet demonstrates how we could output a “(Out of Stock!)” message next to our product name if the product is out of stock: Because I am not wrapping the (Out of Stock!) message in an HTML tag element, Razor can’t implicitly determine that the content within the @if block is the start of a content block.  We are using the @: character sequence to explicitly indicate that this line within our code block should be treated as content. Using Code Nuggets within @: content blocks In addition to outputting static content, you can also have code nuggets embedded within a content block that is initiated using a @: character sequence.  For example, we have two @: sequences in the code snippet below: Notice how within the second @: sequence we are emitting the number of units left within the content block (e.g. - “(Only 3 left!”). We are doing this by embedding a @p.UnitsInStock code nugget within the line of content. Multiple Lines of Content Razor makes it easy to have multiple lines of content wrapped in an HTML element.  For example, below the inner content of our @if container is wrapped in an HTML <p> element – which will cause Razor to treat it as content: For scenarios where the multiple lines of content are not wrapped by an outer HTML element, you can use multiple @: sequences: Alternatively, Razor also allows you to use a <text> element to explicitly identify content: The <text> tag is an element that is treated specially by Razor. It causes Razor to interpret the inner contents of the <text> block as content, and to not render the containing <text> tag element (meaning only the inner contents of the <text> element will be rendered – the tag itself will not).  This makes it convenient when you want to render multi-line content blocks that are not wrapped by an HTML element.  The <text> element can also optionally be used to denote single-lines of content, if you prefer it to the more concise @: sequence: The above code will render the same output as the @: version we looked at earlier.  Razor will automatically omit the <text> wrapping element from the output and just render the content within it.  Summary Razor enables a clean and concise templating syntax that enables a very fluid coding workflow.  Razor’s smart detection of <tag> elements to identify the beginning of content regions is one of the reasons that the Razor approach works so well with HTML generation scenarios, and it enables you to avoid having to explicitly mark the beginning/ending of content regions in about 95% of if/else and foreach scenarios. Razor’s @: and <text> syntax can then be used for scenarios where you want to avoid using an HTML element within a code container block, and need to more explicitly denote a content region. 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

  • ASP.NET Membership Provider Setup

    - by Ben Griswold
    In this screencast, Noah and I show you how to quickly get started with the ASP.NET Membership Provider.  We’ll take you through basic features and setup and walk you through membership table creation with the ASP.NET SQL Server Wizard. I’ve written about the ASP.NET Membership Provider and setup before.  If you missed the post, this introductory video may be for you.     This is one of our first screencasts.  If you have feedback, I’d love to hear it.

    Read the article

  • User is trying to leave! Set at-least confirm alert on browser(tab) close event!!

    - by kaushalparik27
    This is something that might be annoying or irritating for end user. Obviously, It's impossible to prevent end user from closing the/any browser. Just think of this if it becomes possible!!!. That will be a horrible web world where everytime you will be attacked by sites and they will not allow to close your browser until you confirm your shopping cart and do the payment. LOL:) You need to open the task manager and might have to kill the running browser exe processes.Anyways; Jokes apart, but I have one situation where I need to alert/confirm from the user in any anyway when they try to close the browser or change the url. Think of this: You are creating a single page intranet asp.net application where your employee can enter/select their TDS/Investment Declarations and you wish to at-least ALERT/CONFIRM them if they are attempting to:[1] Close the Browser[2] Close the Browser Tab[3] Attempt to go some other site by Changing the urlwithout completing/freezing their declaration.So, Finally requirement is clear. I need to alert/confirm the user what he is going to do on above bulleted events. I am going to use window.onbeforeunload event to set the javascript confirm alert box to appear.    <script language="JavaScript" type="text/javascript">        window.onbeforeunload = confirmExit;        function confirmExit() {            return "You are about to exit the system before freezing your declaration! If you leave now and never return to freeze your declaration; then they will not go into effect and you may lose tax deduction, Are you sure you want to leave now?";        }    </script>See! you are halfway done!. So, every time browser unloads the page, above confirm alert causes to appear on front of user like below:By saying here "every time browser unloads the page"; I mean to say that whenever page loads or postback happens the browser onbeforeunload event will be executed. So, event a button submit or a link submit which causes page to postback would tend to execute the browser onbeforeunload event to fire!So, now the hurdle is how can we prevent the alert "Not to show when page is being postback" via any button/link submit? Answer is JQuery :)Idea is, you just need to set the script reference src to jQuery library and Set the window.onbeforeunload event to null when any input/link causes a page to postback.Below will be the complete code:<head runat="server">    <title></title>    <script src="jquery.min.js" type="text/javascript"></script>    <script language="JavaScript" type="text/javascript">        window.onbeforeunload = confirmExit;        function confirmExit() {            return "You are about to exit the system before freezing your declaration! If you leave now and never return to freeze your declaration; then they will not go into effect and you may lose tax deduction, Are you sure you want to leave now?";        }        $(function() {            $("a").click(function() {                window.onbeforeunload = null;            });            $("input").click(function() {                window.onbeforeunload = null;            });        });    </script></head><body>    <form id="form1" runat="server">    <div></div>    </form></body></html>So, By this post I have tried to set the confirm alert if user try to close the browser/tab or try leave the site by changing the url. I have attached a working example with this post here. I hope someone might find it helpful.

    Read the article

  • Union,Except and Intersect operator in Linq

    - by Jalpesh P. Vadgama
    While developing a windows service using Linq-To-SQL i was in need of something that will intersect the two list and return a list with the result. After searching on net i have found three great use full operators in Linq Union,Except and Intersect. Here are explanation of each operator. Union Operator: Union operator will combine elements of both entity and return result as third new entities. Except Operator: Except operator will remove elements of first entities which elements are there in second entities and will return as third new entities. Intersect Operator: As name suggest it will return common elements of both entities and return result as new entities. Let’s take a simple console application as  a example where i have used two string array and applied the three operator one by one and print the result using Console.Writeline. Here is the code for that. C#, using GeSHi 1.0.8.6 using System; using System.Collections.Generic; using System.Linq; using System.Text;     namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             string[] a = { "a", "b", "c", "d" };             string[] b = { "d","e","f","g"};               var UnResult = a.Union(b);             Console.WriteLine("Union Result");               foreach (string s in UnResult)             {                 Console.WriteLine(s);                          }               var ExResult = a.Except(b);             Console.WriteLine("Except Result");             foreach (string s in ExResult)             {                 Console.WriteLine(s);             }               var InResult = a.Intersect(b);             Console.WriteLine("Intersect Result");             foreach (string s in InResult)             {                 Console.WriteLine(s);             }             Console.ReadLine();                        }          } }   Parsed in 0.022 seconds at 45.54 KB/s Here is the output of console application as Expected. Hope this will help you.. Technorati Tags: Linq,Except,InterSect,Union,C#

    Read the article

  • How to access HTML elements from server side code in an asp.net website

    - by nikolaosk
    In this post I will demonstrate with a hands on example how HTML elements in an .aspx page can be processed exactly like standard ASP.Net server controls. Basically how to make them accessible from server side code. 1) Launch Visual Studio 2010/2008/2005. (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose VB as the development language. 2) Add a new item in your site, a web form. Leave the default name. 3) Let's say that we want to change the background...(read more)

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >