Roman Pelepei gives smart answers on questions about C# .Net, ASP .Net, WPF and Silverlight programming with examples and source code.
среда, 30 сентября 2009 г.
Ajax style File Upload
воскресенье, 27 сентября 2009 г.
Html Encoding Code Blocks With ASP.NET 4
One great new feature being introduced in ASP.NET 4 is a new code block (often called a Code Nugget by members of the Visual Web Developer team) syntax which provides a convenient means to HTML encode output in an ASPX page or view.
<%: CodeExpression %>
I often tell people it’s <%=
but with the =
seen from the front.
Let’s look at an example of how this might be used in an ASP.NET MVC view. Suppose you have a form which allows the user to submit their first and last name. After submitting the form, the same view is used to display the submitted values.
First Name: <%: Model.FirstName %> Last Name: <%: Model.FirstName %> <form method="post"> <%: Html.TextBox("FirstName") %> <%: Html.TextBox("LastName") %> form>
By using the the new syntax, Model.FirstName
and Model.LastName
are properly HTML encoded which helps in mitigating Cross Site Scripting (XSS) attacks.
Expressing Intent with the new IHtmlString
interface
If you’re paying close attention, you might be asking yourself “Html.TextBox
is supposed to return HTML that is already sanitized. Wouldn’t using this syntax with Html.TextBox
cause double encoding?”
ASP.NET 4 also introduces a new interface, IHtmlString along with
a default implementation, HtmlString
. Any method that returns a value that implements the IHtmlString
interface will not get encoded by this new syntax.
In ASP.NET MVC 2, all helpers which return HTML now take advantage of this new interface which means that when you’re writing a view, you can simply use this new syntax all the time and it will just work. By adopting this habit, you’ve effectively changed the act of HTML encoding from an opt-in model to an opt-out model.
The Goals
There were four primary goals we wanted to satisfy with the new syntax.
Obvious at a glance. When you look at a page or a view, it should be immediately obvious which code blocks are HTML encoded and which are not. You shouldn’t have to refer back to flags in
web.config
or thepage
directive (which could turn encoding on or off) to figure out whether the code is actually being encoded. Also, it’s not uncommon to review code changes via check-in emails which only show a DIFF. This is one reason we didn’t reuse existing syntax.Not only that, code review becomes a bit easier with this new syntax. For example, it would be easy to do a global search for
<%=
in a code base and review those lines with more scrutiny (though we hope there won’t be any to review). Also, when you receive a check-in email which shows a DIFF, you have most of the context you need to review that code.Evokes a similar meaning to <%=. We could have used something entirely new, but we didn’t have the time to drastically change the syntax. We also wanted something that had a similar feel to
<%=
which evokes the sense that it’s related to output. Yeah, it’s a bit touchy feely and arbitrary, but I think it helps people feel immediately familiar with the syntax.Replaces the old syntax and allows developers to show their intent. One issue with the current implementation of output code blocks is there’s no way for developers to indicate that a method is returning already sanitized HTML. Having this in place helps enable our goal of completely replacing the old syntax with this new syntax in practice.
This also means we need to work hard to make sure all new samples, books, blog posts, etc. eventually use the new syntax when targeting ASP.NET 4.
Hopefully, the next generation of ASP.NET developers will experience this as being the default output code block syntax and
<%=
will just be a bad memory for us old-timers like punch cards, manual memory allocations, andDo While Not rs.EOF
.Make it easy to migrate from ASP.NET 3.5. We strongly considered just changing the existing
<%=
syntax to encode by default. We eventually decided against this for several reasons, some of which are listed in the above goals. Doing so would make it tricky and painful to upgrade an existing application from earlier versions of ASP.NET.Also, we didn’t want to impose an additional burden for those who already do practice good encoding. For those who don’t already practice good encoding, this additional burden might prevent them from porting their app and thus they wouldn’t get the benefit anyways.
When Can I Use This?
This is a new feature of ASP.NET 4. If you’re developing on ASP.NET 3.5, you will have to continue to use the existing <%=
syntax and remember to encode the output yourself.
In ASP.NET 4 Beta 2, you will have the ability to try this out yourself with ASP.NET MVC 2 Preview 2. If you’re running on ASP.NET 3.5, you’ll have to use the old syntax.
What about ASP.NET MVC 2?
As mentioned, ASP.NET MVC 2 supports this new syntax in its helper when running on ASP.NET 4.
In order to make this possible, we are making a breaking change such that the relevant helper methods (ones that return HTML as a string) will return a type that implements IHtmlString
.
In a follow-up blog post, I’ll write about the specifics of that change. It was an interesting challenge given that IHtmlString
is new to ASP.NET 4, but ASP.NET MVC 2 is actually compiled against ASP.NET 3.5 SP1. :)
пятница, 18 сентября 2009 г.
Does C# have templates like C++?
четверг, 17 сентября 2009 г.
Announcing the Microsoft AJAX CDN
понедельник, 14 сентября 2009 г.
The C# Programming Language Version 4.0
Visual Studio 2010 and the .NET Framework 4.0 will soon be in beta 2 and there are some excellent new features that we can all get excited about with this new release. Along with Visual Studio 2010 and the .NET Framework 4.0 we will see version 4.0 of the C# programming language. In this blog post I thought I'd look back over where we have been with the C# programming language and look to where Anders Hejlsberg and the C# team are taking us next.
http://software.intel.com/en-us/blogs/2009/03/30/the-c-programming-language-version-40/
New Features in C# 4.0
Samples and documents describing C# 4.0 language and IDE features.
Visual Studio 2010 Beta1 Samples are now live!
Samples and documents for C# 4.0 can be found on the Downloads page. The CSharpDynamic samples include several projects showing how to use Dynamic with Office, IronPython and other technologies. There is also a covariance and contravariance example, and an example show how to use the new IDynamicObject interface to create native C# objects that can be called dynamically.
The document New Features in C# 4.0 is a high level description of the additions to the C# language, and the samples are designed to show off the new language features, particularly around the dynamic scenario.
Please see the walkthroughs that ship with Visual Studio 2010 Beta1 for additional information about these samples. The code in these samples is preliminary, and may not run correctly. We recommend installing the samples on the root drive of your system, for instance, place them in c:\beta1_samples. These samples may be modified by the C# team at any time, so you might want to check back occasionally for updates.
Please submit bugs through connect, or provide comments in the discussion section of this site.
It is important to remember that the code shown here is preliminary, and is designed to run on a beta version of Visual Studio 10.0. This code may not work correctly, and the syntax shown in this code may change before VS 2010 is released.
The Office example ought to run smoothly if you have a copy of the most recent version of Microsoft Office installed. It may also work with older verisions of Office. The Python example will work if you download IronPython 2.0 . It may also work with more recent versions of IronPython. You will need to replace the IronPython, IronPython.Modules and the Microsoft.Scripting assemblies found in the references section. Right click on the References node in the Solution Explorer and choose Add Reference. Browse to the directory where you installed IronPython and add the missing Assemblies. By default, IronPython is installed in the Program Files directory. Please come back here later for additional information about the Silverlight example.
Thank you for your interest in Microsoft products.
Windows 7 Code Pack V. 1.0 Released
The Windows® API Code Pack for Microsoft® .NET Framework provides support for various features of Windows 7 and previous releases of that operating system. The Code Pack has reached version 1.0 and has been published on Code Gallery:
Here are some of the features you can from managed code using the Code Pack:
- Windows 7 Taskbar Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars.
- Windows 7 Libraries, Known Folders, non-file system containers.
- Windows Shell Search API support, a hierarchy of Shell Namespace entities, and Drag and Drop functionality for Shell Objects.
- Explorer Browser Control.
- Shell property system.
- Windows Vista and Windows 7 Common File Dialogs, including custom controls.
- Windows Vista and Windows 7 Task Dialogs.
- Direct3D 11.0, Direct3D 10.1/10.0, DXGI 1.0/1.1, Direct2D 1.0, DirectWrite, Windows Imaging Component (WIC) APIs. (DirectWrite and WIC have partial support)
- Sensor Platform APIs
- Extended Linguistic Services APIs
- Power Management APIs
- Application Restart and Recovery APIs
- Network List Manager APIs
- Command Link control and System defined Shell icons.
Using URL Rewrite Module
The Microsoft URL Rewrite Module for IIS 7.0 provides flexible rules-based rewrite engine that can be used to perform broad spectrum of URL manipulation tasks, including, but not limited to:
- Enabling user friendly and search engine friendly URL with dynamic web applications;
- Rewriting URL’s based on HTTP headers and server variables;
- Web site content handling;
- Controlling access to web site content based on URL segments or request metadata.
воскресенье, 13 сентября 2009 г.
Reading Meta Tags of Any Page Programatically without loading in browser
In this article I will show you how to read meta tags programatically using C# and Asp.Net. How this article is different from other articles available on internet is that all the samples available on internet talks about reading and writing tags from page itself but In this article our approach will be do dynamically download the contents of a page and read meta tags from it.
First thing first we need to download the content of page without loading it into browser. For this we will be using WebRequest class. Below Code creates a request to "http://www.microsoft.com/en/us/default.aspx" using default credentials
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.microsoft.com/en/us/default.aspx");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
Now we are set to get response from the client. To receive response we are going to use WebResponse class as
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Once we have response we want to load this into Html DOM. As you should know that Html uses DOM model to load documents. So in next few lines we will get response in form of string and use that string to load IHTMLDocument2 class.
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
//reads the html into an html document to enable parsing
IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { responseFromServer });
doc.close();
Now that we have entire Page loaded in memory in form of HtmlDocument we are going to iterate it and retrieve Meta tags from it.
//loops through each element in the document to check if it qualifies for the attributes to be set
foreach (IHTMLElement el in (IHTMLElementCollection)doc.all)
{
// check to see if all the desired attributes were found with the correct values
bool qualify = true;
if (el.tagName == "META")
{
HTMLMetaElement meta = (HTMLMetaElement)el;
Response.Write("Content " + meta.content + "
");
}
}
Of course you can do lot of more things with above code. But we will take that up in some other articles. For your reference I am pasting te complete code below. For the sample to work please add a reference to mshtml by
Steps:-
1.) In the solution explorer, highlight the project to which you want to add the parsing functionality
2.) In the menu, click on Project -> Add reference
3.) In the dialog box that is shown, under the .Net tab - choose the Microsoft.mshtml assembly
4.) Click the select button and click on the OK button
Now we can reference this assembly
Don't forget to add namespace
using mshtml;
Response.Write("Button2_Click");
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.microsoft.com/en/us/default.aspx");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
//reads the html into an html document to enable parsing
IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { responseFromServer });
doc.close();
//loops through each element in the document to check if it qualifies for the attributes to be set
foreach (IHTMLElement el in (IHTMLElementCollection)doc.all)
{
// check to see if all the desired attributes were found with the correct values
bool qualify = true;
if (el.tagName == "META")
{
HTMLMetaElement meta = (HTMLMetaElement)el;
Response.Write("Content " + meta.content + "
");
}
}
вторник, 8 сентября 2009 г.
Microsoft FTP service for IIS 7.0
Microsoft has released a brand-new FTP service that is available as a separate download for Windows Server® 2008 that provides a a robust, secure solution for FTP in a Windows environment. This new FTP service was written specifically for Windows Server 2008 and enables Web authors to publish content more easily and securely than before, and offers both Web administrators and hosters better integration, management, authentication and logging features. It should be noted that there are two FTP services available for IIS 7.0:
- The new Microsoft FTP service for IIS 7.0 is provided as a download from the Web for Windows Server 2008.
- The other FTP service ships on the Windows Vista™ and Windows Server 2008 DVD. (This FTP service is essentially the same FTP service from IIS 6.0.)
There are two separate downloadable packages for the new FTP server; you will need to download the appropriate package for your version of Windows Server 2008:
- 32-bit Installation Package:
- 64-bit Installation Package:
For more information about installing the new FTP service, see the the following walkthrough:
SOLVED!!! CS0016: Could not write to output file ...
Just right click following folders
1. C:\Windows\Temp
2. C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
and go to Security tab, click Edit and click Add and try adding "Network Service" and "YourComputerName\IIS_IUSERS", from the Permission checkbox, click Full Control. Click Apply and OK.
Restart your IIS and try running your web application. Hopefully it should run.
суббота, 5 сентября 2009 г.
Hosting ASP.NET sites on IIS 7.0
IIS 7.0 provides the ASP.NET Integration by default, It supports both the new and old integration modes that can be used side by side on the same server. On IIS 7.0 you can run multiple ASP.NET version applications using integration and classic modes .
You can run the both old and new ASP.NET application on IIS 7.0 in two modes
- Integration mode
- Classic mode
You can perform the migration IIS 7.0 using the APPCMD.EXE command tool.
%windir%\system32\inetsrv\APPCMD.EXE migrate config <Application Path>
You must run the above command as an administrator by navigating
Programs—>Accessories–>Command Prompt icon
Where application path in the command line is virtual path of your application.
When migration is complete your application can run in both Integration and Classic modes.
If you still want to run your applications under classic integration mode you can do the following configuration.
Changing ASP.NET Application Modes in IIS 7.0
In order to change the integration mode for an application, do the following
- Create an application pool that is configured to use the desired mode. By default all new application pools run in Integration mode. However there is a application pool named “Classic .NET AppPool” that runs in the classic ASP.NET mode. You can use this application pool for applications that should run under classic mode.
open internet information manager [IIS manager] and set the classic mode or integration mode for new application pools as follows
While creating the new application it prompt the above dialogue and there you can choose .NET Framework version and ASP.NET mode for the application pool.
2. You can map the newly created application pool to your applications as follows
Select the site and say Add Application pool then you will get the above dialogue there you can type the alias name for your site and then can select the physical path for the application.
Allowing Multiple ASP.NET Versions to run under IIS 7.0 as follows
Select the ISAPI and CGI Restrictions from features pane after selecting the web site level. Either you can Allow or Deny the particular to run under your web server.
This post explained the basic steps required for running ASP.NET applications under IIS 7.0. To learn more about Hosting the ASP.NET applications under Integration Mode see http://learn.iis.net/page.aspx/244/how-to-take-advantage-of-the-iis7-integrated-pipeline/.
четверг, 3 сентября 2009 г.
Custom Numeric Format Strings in C#
Custom numeric format specifiers are supported by all of the numeric types in the .NET Framework class library. These include the BigInteger, Byte, Decimal, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, and UInt64 types.
Standard Numeric Format Strings in C#
Оператор as в C#
ASP.NET 4.0 WebForms Routing
Those who have been working in ASP.NET MVC are already aware of the ASP.NET Routing feature introduced with .NET 3.5 SP1.But I have seen many who has developed a perception that ASP.NET Routing is something that can be used with only ASP.NET MVC.This is not the case.ASP.NET Routing comes under a separate namespace (System.Web.Routing) and assembly (System.Web.Routing.dll).This can be used with WebForms applications as well.But this required some custom coding to develop your RouteHandler as shown in the post below:
http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx
In ASP.NET 4.0, added capabilities are provided to make routing fully complete in order to work with WebForms.This is what I will be discussing in this post today.I will use simple webpage with 2 hyperlinks to demonstrate this feature.
Step1: Add a reference to System.Web.Routing.dll to the ASP.NET Web Application project.
Step2: Add the UrlRoutingModule in the web.config as shown below.This HttpModule intercepts the incoming request and routes the control to appropriate handler.
- <httpModules>
- <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add name="RoutingModule" type="System.Web.Routing.UrlRoutingModule"/>
- httpModules>
Step3:We have to define the Routes and populate the RouteTable.RouteTable class exposes a static property Routes which is a collection of Route objects.This RouteTable is referenced by the ASP.NET Routing Engine to resolve the route values from the URL.The RouteTable needs to be populated at theApplication_Start event of Global.asax.cs as shown below:
- protected void Application_Start(object sender, EventArgs e)
- {
- RegisterRoutes();
- }
- private void RegisterRoutes()
- {
- RouteTable.Routes.Add("Products",new Route("{product}",new PageRouteHandler("~/Default.aspx")));
- }
Here Routes.Add method expects two parameters:
- A string identifying the name of the Route.In this case I have given “Products”
- An instance of the RouteBase class.This is the base class and I have passed an instance of the Route class which is an implementation of RouteBase.
- Route class takes url pattern and an instance of IRouteHandleras argument.Here I have passed an instance ofPageRouteHandler which is an implementation of IRouteHandlerinterface specifically designed to handle of ASP.NET Webforms.
- PageRouteHandler takes the relative path of the WebForm as input.
- Route class takes url pattern and an instance of IRouteHandleras argument.Here I have passed an instance ofPageRouteHandler which is an implementation of IRouteHandlerinterface specifically designed to handle of ASP.NET Webforms.
As a demo I have used a simple page with two hyperlinks as shown below:
- <form id="form1" runat="server">
- <div>
- <h2> Routing Demoh2>
- <ul>
- <li>
- <asp:HyperLink runat="server" NavigateUrl="/Books" Text="Books">asp:HyperLink>
- li>
- <li>
- <asp:HyperLink runat="server" NavigateUrl="/CDDVD" Text="CD and DVD">asp:HyperLink>
- li>
- ul>
- div>
- form>
In the Page_Load event I have retrieved the value passed as Route in the url as shown below:
- protected void Page_Load(object sender, EventArgs e)
- {
- string product = RouteData.Values["product"] as string;
- if (product != null)
- {
- Response.Write("Product::" + product);
- }
- }
RouteData is a new property that is exposed by the Page class and contains the route names and values.
This is a very rudimentary working sample.In the next post we will take a more detailed look into what PageRouteHandler class is doing.