Welcome to MSDN Blogs Sign in | Join | Help

How to check if a user belongs to a Security or Distribution group in ASP.Net

If you need to check at Runtime if your User belongs to a Security group. Here's how to do it -  

Assuming the IIS Application has Authentication set to "Windows Authentication". The Request object of HttpContext has the Logged in users Identity which contains Groups. Here is the code which validates if a user belongs to a particular Security group -

var account = new NTAccount(@"Domain\SecurityGroupName"); //The security group you want to check the user belongs to

var groups = HttpContext.Current.Request.LogonUserIdentity.Groups;//Get a collection of Groups the user belongs to

bool hasAccount = groups.Contains(account.Translate(typeof(SecurityIdentifier)));//do the test

ASP.Net AJAX 4.0 Client Templates in depth

The best way to know a Javascript library is to pry open the javascript file and look at the details. This release has a lot of powerful features which I will discuss here.

1.   Sys.Observer – Ajax 4.0 includes an implementation of Observer Pattern. In plain words you can use this pattern to have a publisher/subscriber scenario, wherein if any property on the publisher changes all the subscribers are notified. Dave Reed has a great article which goes in depth about this pattern. The other features mentioned below use this pattern a lot internally. Here is an example on how to use this object -

                 var product = { name: "Foo Choclate Bar", price: 1, inStock: true }


var
productsPublisher = Sys.Observer.observe(product); //The publisher which is being observed


Sys.Observer.addPropertyChanged(productsPublisher, productSubscriber); //Add a subscriber for any property change on the publisher


productsPublisher.setValue("inStock", false); //Change a property


function
productSubscriber(product, eventArgs) //Subscriber

{

    if (eventArgs.get_propertyName() == "inStock" && product.inStock == false) {

        alert("The product is out of stock");

    }

}

 

2.   Sys.Ui.Templates or Client Side Templates – I think of this feature as a Client side repeater version of the classic ASP.Net server side repeater. Using this feature you can bind data to a defined template and it iterates through the data and renders it using the contents defined inside the template. An example of a template is -

<div id="authorsTemplate" style="visibility:hidden;display:none;">
    <ul>
        <li>First Name: {{ FirstName }}</li>
        <li>Last Name: {{LastName}}</li>
        <li>Url: <a href="{{Url}}">{{Url}}</a></li>
    </ul>
</div>

1.   Data which needs to be binded to a template are enclosed within {{<data>}}, e.g. {{ FirstName }}. The above template will be repeated and displayed if you loop through your data and instantiate the templates. Notice the style is made to hide this template so it is not shown to the user on load.

2.   Create a div where the above template will be rendered.
<div id="targetdiv"></div>

3.   To register this template with Sys.Ui.Template you pass the template Id to the constructor -
var template = new Sys.UI.Template($get("authorsTemplate"));

4.   To create an instance for each data row in your collection you need to call the “instanceIn” method -

template.instantiateIn($get("targetdiv"), <jsondata>);

“targetDiv” is the place where you need this template to be rendered.

 

Here is the snapshot of the example -

<script>
    var bloggers = [{ FirstName: "Piyush", LastName: "Shah", Url: "http://blogs.msdn.com/shahpiyush" },
            { FirstName: "Jon", LastName: "Gallant", Url: "http://blogs.msdn.com/jongallant" },
            { FirstName: "Scott", LastName: "Guthrie", Url: "http://webblogs.asp.com/scottgu"}]


    function LoadTemplates() {
        var template = new Sys.UI.Template($get("authorsTemplate"));
        for (var i = 0; i < bloggers.length; i++) {
            template.instantiateIn($get("targetdiv"), bloggers[i]);
        }
    }
</script>

<body onload="LoadTemplates()">
<div id="authorsTemplate" style="visibility:hidden;display:none;">
    <ul>
        <li>First Name: {{ FirstName }}</li>
        <li>Last Name: {{LastName}}</li>
        <li>Url: <a href="{{Url}}">{{Url}}</a></li>
    </ul>
</div>
<div id="targetdiv"></div>
</body>

 

3.   Markup Extensions – Using this feature you can create expressions. The syntax for using it is -
{expressionName, defaultValue, parameterName1=parameterValue1, parameterName2=parameterValue2[, ...]}  
Here is an example of a number to currency conversion expression I wrote.

1)    First register the markup extension -

Sys.Application.registerMarkupExtension("formatCurrency",
  function(component, targetProperty, properties) {
      var value = '' + properties.value;
      var numArray = value.split('.');
      var decmal = numArray[0];
      var cents = numArray.length > 1 ? '.' + numArray[1] : '';
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(decmal)) {
          decmal = decmal.replace(rgx, '$1' + ',' + '$2');
      }
      return ("$" + decmal + cents);
  }
);

2)    You can now use the markup in your template like this - {formatCurrency "US", value={{number}}}

3)    Let’s update the above example of the data to be like this -

var bloggers = [{FirstName: "Piyush", LastName: "Shah", Url: "http://blogs.msdn.com/shahpiyush", SpendingBudget:1.50},
            { FirstName: "Jon", LastName: "Gallant", Url: "http://blogs.msdn.com/jongallant", SpendingBudget: 1000.99 },
            { FirstName: "Scott", LastName: "Guthrie", Url: "http://webblogs.asp.com/scottgu", SpendingBudget: 1000000.00}]

4)    Update the template to be like this -

<div id="authorsTemplate" style="visibility:hidden;display:none;">
    <ul>
        <li>First Name: {{ FirstName }}</li>
        <li>Last Name: {{LastName}}</li>
        <li>Url: <a href="{{Url}}">{{Url}}</a></li>
        <li>{formatCurrency "US", value={{SpendingBudget}}}</li>
    </ul>
</
div>

  1. Declarative Instantiation – In simple terms this allows you to create controls or behaviors by putting a certain markup in the container instead of creating a full xhtml markup. Here is an example this syntax attaches a Dataview (which I will go over next) to a div without -

1.   Register the namespace in the body. This is similar to Registering a user control in ASP.Net
<body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView" sys:activate="*" >
Here we are first registering “Sys” with “sys” and “Sys.Ui.Dataview” with “dataview”.
sys:Activate attribute specifies which ID’s of elements to activate. A “*” means any Id with sys:attach (seen shortly) will be activated.

2.   To activate the dataview in any html element you need to do this -

<div sys:attach="dataview" dataview:datasource="<jsondata>">

...
</div>

Here we are first attaching the “dataview” to the div and since sys:activate=”*” which means that on load it will be activated. I am also setting the datasource property on the dataview.

 

  1. Sys.UI.DataView– This control allows you to Bind data (one way or read-only) to your client templates. It hides the complexity and extra markup I had showed in creating templates above. To show how easy it is to create client templates using Dataview check out the example –

<body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView" sys:activate="*">

<script>

    var bloggers = [{ FirstName: "Piyush", LastName: "Shah", Url: "http://blogs.msdn.com/shahpiyush" },

            { FirstName: "Jon", LastName: "Gallant", Url: "http://blogs.msdn.com/jongallant"},

            { FirstName: "Scott", LastName: "Guthrie", Url: "http://webblogs.asp.com/scottgu"}]       

</script>

<div id="authorsTemplate" sys:attach="dataview" dataview:data="{{bloggers}}">

    <ul>

        <li>First Name: {{ FirstName }}</li>

        <li>Last Name: {{LastName}}</li>

        <li>Url: <a href="{{Url}}">{{Url}}</a></li>

    </ul>
</
div>

</body>

 

In my future post I will be showing how to do a 2 way binding using Client Templates.

 

 

ASP.Net RssToolkit Version 2.0

I have been part of the team working on the latest version ASPNET RssToolkit, originally created by Dmitry Robsman. We enhanced this awesome Toolkit and have just released version 2.0 of the Toolkit. Please check out Codeplex to download this toolkit.

Here are some of the changes in this version –

  • Consume and publish Atom/Rdf/Opml feeds.
  • Strongly typed classes, close to Rss specification.
  • Feeds Aggregation using OPML. The outlines in OPML can have Rss/Atom/Rdf.
  • Rss Schema validation during aggregation.
  • Download Manager can be used to download any Url and return a Stream. It also has inbuilt caching mechanism. 
  • Added support for Extensions and Enclosures.
  • Added Visual Studio Testing Framework Unit Tests.
  • Rearranged Namespaces to closely match the features.

Here is how to use the RssToolkit. I have taken excerpts from ScottGu’s review on the original RssToolkit.

Consuming Feeds using RssToolkit -

A.      Using RssDataSource – This webcontrol gives you the ability to databind to an Rss/Atom/Rdf/Opml feed. It inherits from DataSourceControl to give itself the ability serve as a data source to data-bound controls. Here are the steps you can take to use RssDataSource in your page or user control –

1.       Add the RssDataSource and RssHyperLink to the Toolbox in Visual Studio.

Toolbox 

2.       In your Web form, drop the RssDataSource.

3.       Click the control and “Configure Data Source”

Configure RssDataSource 

4.       It ask you for the feed Url. The RssDataSourceConfigForm.cs is used in this case.

You can provide RSS/ATOM/RDF/OPML and RssDataSource will automatically identify the feed type and provide Databinding capability.

As you can see below, I’m actually providing an Atom feed URL to the RssDataSource.

RssDataSourceConfigForm 

5.       You can then bind a control like Gridview to this DataSource.

Configure Grid to use RssDataSource 

6.       I will “Edit Columns” on the GridView and have 2 columns, as shown –

Grid Columns for RssDataSource 

7.       You can also specify the number of items you want to be returned back. I will go in the code behind and change that to 5

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<%@ Register Assembly="RssToolkit" Namespace="RssToolkit.Web.WebControls" TagPrefix="cc1" %>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Consuming Google News using RssToolkit</title>

</head>

<body>

    <form id="form1" runat="server">

    Google News (Atom Format)

    <div>

        <cc1:rssdatasource id="RssDataSource1" runat="server" maxitems="5" url="http://news.google.com/?output=atom"></cc1:rssdatasource>

    </div>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="RssDataSource1">

            <Columns>

                <asp:HyperLinkField DataNavigateUrlFields="link" DataTextField="link" HeaderText="Link"/>

                <asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />

            </Columns>

        </asp:GridView>

    </form>

</body>

</html>

 

8.       Compile and View the page in browser –

RssDataSource Output 

B.      Consume using RssDocument.cs – RssDocument.cs class can be used from your code if you want to consume/publish or manipulate feeds. It provides various overloads for Loading a feed –

RssDocument Class 

·         Load - takes 3 overloads System.Uri, Xml string and XmlReader. You can provide Rss/Atom/Rdf/Opml type of formats for these 3 overloads and it will automatically identify the base feed type and construct the class.

·         SelectItems – this method returns IEnumerable which gives the ability to iterate over the collection. It is also used internally to provide data binding capability to RssDataSource.

·         ToXml – this method which returns an Xml as a string, provides the capability of publishing the feed into Rss/Atom/Rdf/Opml formats. The input parameter (DocumentType enum) suggests the format of Xml returned by this method.

·         ToDataSet – this method returns the feed as a DataSet.

Here is how to use the RssDocument –

void Page_Load(object sender, EventArgs e)

 {

    RssToolkit.Rss.RssDocument rss = RssToolkit.Rss.RssDocument.Load(new System.Uri("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml"));

    Image1.ImageUrl = rss.Channel.Image.Url;

    GridView1.DataSource = rss.SelectItems();

    GridView1.DataBind();

 }

C.      Consume using Custom Generated Class and RssDl.exe – Let’s say you want to consume a feed which has some extensions that is not specified in the Rss specification such as Media Rss by Yahoo.
An example of Media Rss tags are -
<media:player url="http://youtube.com/?v=dMH0bHeiRNg" />
<media:thumbnail url="http://sjc-static6.sjc.youtube.com/vi/dMH0bHeiRNg/2.jpg" width="120" height="90" />
<media:title>Evolution of Dance</media:title>
<media:category label="Tags">Dancing comedy</media:category>
<media:credit>judsonlaipply</media:credit>


You can still get strong typing for these extensions by generating a custom class using the RssDl.exe

 

Usage – RssDl.exe “URL” “ClassName.cs”

E.g.

RssDl.exe “http://youtube.com/rss/global/top_favorites.rss” “YouTube.cs”

RssDl.exe “http://news.google.com/?output=rss” “GoogleNews.vb”

  As shown below I created a custom class for YouTube’s Top favorites feed, which has Media Rss tags.

RssDl 

                If you open the newly created class “YouTube.cs” you will see the extensions as Strongly typed properties inside the class.

    [XmlElement("player", Namespace="http://search.yahoo.com/mrss/")]

    public YoutubePlayer Player {

        get {

            return _player;

        }

        set {

            _player = value;

        }

    }

   

    [XmlElement("thumbnail", Namespace="http://search.yahoo.com/mrss/")]

    public YoutubeThumbnail Thumbnail {

        get {

            return _thumbnail;

        }

        set {

            _thumbnail = value;

        }

    }

   

    [XmlElement("category", Namespace="http://search.yahoo.com/mrss/")]

    public YoutubeCategory Category {

        get {

            return _category;

        }

        set {

            _category = value;

        }

    }

   

    [XmlElement("credit", Namespace="http://search.yahoo.com/mrss/")]

    public string Credit {

        get {

            return _credit;

        }

        set {

            _credit = value;

        }

    }

 

 

You will have to embed this class in your application or put in App_Code folder of your website. You can then use the class just like RssDocument.cs.

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Youtube Media Rss</title>

 

    <script language="c#" runat="server">

        void Page_Load(object sender, EventArgs e)

        {

            YoutubeRss rss = YoutubeRss.Load();

            DataList1.DataSource = rss.Channel.Items;

            DataList1.DataBind();

        }

    </script>

 

</head>

<body>

    <form id="form1" runat="server">

        You Tube Top Favories(Media Rss)

        <asp:DataList ID="DataList1" runat="server" RepeatColumns="3" GridLines="both">

            <ItemTemplate>

                <asp:Image ID="Image1" runat="Server" ImageUrl='<%# Eval("Thumbnail.Url")  %>' /><br />

                        <asp:HyperLink ID="HyperLink1" NavigateUrl='<%# Eval("Player.Url") %>' Text='Link' runat="server" />

            </ItemTemplate>

        </asp:DataList>

    </form>

</body>

</html>

 

Here is what the page looks like -

Consuming Media Rss using RssToolkit 

Aggregation

RssToolkit provides Aggregation using Outline Processor Markup Language (OPML). Check out the OPML specification here. OPML is used for creating a list of feeds known as Outlines to be shared or aggregated. Here is what an OPML format looks like –

<?xml version="1.0" encoding="iso-8859-1"?>

<opml version="1.1">

  <head>

    <title>List of Feeds News Feeds</title>

    <dateCreated>Tue, 11 Nov 2003 19:47:24 GMT</dateCreated>

    <dateModified>Tue, 11 Nov 2003 19:47:28 GMT</dateModified>

    <ownerName>Webmaster</ownerName>

    <ownerEmail>owner@msdn.com</ownerEmail>

    <expansionState></expansionState>

    <vertScrollState>3</vertScrollState>

    <windowTop>93</windowTop>

    <windowLeft>127</windowLeft>

    <windowBottom>585</windowBottom>

    <windowRight>710</windowRight>

  </head>

  <body>

    outline text='BBC News’ description='Updated every minute of every day - FOR PERSONAL USE ONLY' htmlUrl='http://news.bbc.co.uk/go/click/rss/0.91/public/-/1/hi/default.stm' language='unknown' title='BBC News' type='rss' version='RSS' xmlUrl='http://news.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss091.xml'/>

    <outline text='CNET News.com' description='Tech news and business reports by CNET News.com. Focused on information technology, core topics include computers, hardware, software, networking, and Internet media.' htmlUrl='http://news.com.com/' language='unknown' title='CNET News.com' type='rss' version='RSS2' xmlUrl='http://news.com.com/2547-1_3-0-5.xml'/>

  </body>

</opml>

 

As seen above the Outline has the information of the feeds to be aggregated, XmlUrl provides the Url of the Feed.

To aggregate Feeds using RssToolkit you need to provide the location of the OPML file or proved the OPML Xml. You can use the Load method in the RssDocument.cs Class for Aggregation. As shown before the Load of RssDocument has 3 overloads –

public static RssDocument Load(string xml);
public static RssDocument Load(Uri url);
public static RssDocument Load(XmlReader reader);

 

Example -

RssDocument rssAggregatedFeed = RssDocument.Load (new System.Uri("http://static2.podcatch.com/blogs/gems/opml/mySubscriptions.opml"));

Publishing your Feeds

 

RssHyperLink – This WebControl can be used for publishing your Feed. You can point this tool to the feed location and it automatically generates link tag -

<link rel="alternate" type="application/rss+xml" title="Rss" href="~/RssHyperLink.ashx" />

 

This tag enables Feed Autodiscovery in browsers. It enables the Rss Autodiscovery in IE and FireFox. To publish the feeds using RssToolkit, you can use one of the mechanisms below –

 

A.       Using ASP.Net Buildprovider mechanism – RssToolkit uses ASP.Net BuildProvider class to automatically detect certain files created or modified in the filesystem. It automatically generates code and compiles the code for any files with extension *.rss or *.rssdl. RssToolkit then uses RssDocument.cs class and De-serializes the feed. It also builds an HttpHandler, which you can then inherit from to publish your feed.

In the samples provided. The App_Code folder has Sample5.Rss

<?xml version="1.0" encoding="utf-8"?>

<rss version="2.0">

    <channel>

        <title>Sample Channel</title>

        <link>~/RssHyperlinkFromCustomClass.aspx</link>

        <description>Channel For Scenario5 in ASP.NET RSS Toolkit samples.</description>

        <ttl>10</ttl>

        <name></name>

        <user></user>

        <pubDate>Tue, 10 Apr 2007 23:01:10 GMT</pubDate>

        <lastBuildDate>Tue, 10 Apr 2007 23:01:10 GMT</lastBuildDate>

        <webMaster>webmaster@email.com</webMaster>

        <item>

            <title></title>

            <description></description>

            <link></link>

        </item>

        <item>

            <title></title>

            <description></description>

            <link></link>

        </item>

    </channel>

</rss>

When the file is created or modified RssToolkit automatically generates code and compiles it based on the schema of this file. It pre-fixes all the files with “Sample5”. So like RssDocument there will be Sample5Rss, RssChannel will have Sample5Channel and so on. It also creates a default HttpHanlder called Sample5HtppHandlerBase which inherits from RssHttpHandlerBase. You can create a custom *.ashx HttpHandler which inherits from Sample5HttpHandlerBase and you can publish the Sample5.rss

<%@ WebHandler Language="C#" Class="RssHyperLinkFromCustomClass" %>

 

using System;

using System.Collections.Generic;

using System.Web;

using RssToolkit.Rss;

 

public class RssHyperLinkFromCustomClass: Sample5HttpHandlerBase

{

    protected override void PopulateRss(string rssName, string userName)

    {

        Rss.Channel = new Sample5Channel();

       

        Rss.Channel.Items = new List<Sample5Item>();

        if (!string.IsNullOrEmpty(rssName))

        {

            Rss.Channel.Title += " '" + rssName + "'";

        }

 

        if (!string.IsNullOrEmpty(userName))

        {

            Rss.Channel.Title += " (generated for " + userName + ")";

        }

 

        Rss.Channel.Link = "~/scenario6.aspx";

        Rss.Channel.Description = "Channel For Scenario6 in ASP.NET RSS Toolkit samples.";

        Rss.Channel.Ttl = "10";

        Rss.Channel.User = userName;

 

 

        Sample5Item item = new Sample5Item();

        item.Title = "CodeGeneratedClass";

        item.Description = "Consuming RSS feed programmatically using strongly typed classes";

        item.Link = "~/CodeGeneratedClass.aspx";

        Rss.Channel.Items.Add(item);

 

        item = new Sample5Item();

        item.Title = "ObjectDataSource";

        item.Description = "Consuming RSS feed using ObjectDataSource";

        item.Link = "~/ObjectDataSource.aspx";

        Rss.Channel.Items.Add(item);

    }   

}

You can use RssHyperLink to point to this Custom HttpHandler –

<cc1:RssHyperLink ID="Rsshyperlink4" runat="server" IncludeUserName="True" NavigateUrl="~/RssHyperLinkFromCustomClass.ashx">RSS</cc1:RssHyperLink>

When clicked on the link the output shown will be –

RssHandler output 

B.      Using RssDocument class – RssDocument.cs has a method ToXml(), which can be used to serialize and publish the RssDocument class.

public string ToXml(DocumentType outputType);

 

It takes DocumentType enum which has the following values –

public enum DocumentType
{
    Unknown,
    Rss,
    Opml,
    Atom,
    Rdf

}

 

So to publish your feed as an ATOM from RssDocument, you can do the following inside an ASP.Net Module or an HttpHandler –

string inputXml = rssDocument.ToXml(DocumentType.Atom); // Publish as Atom

XmlDocument document = new XmlDocument();
document.LoadXml(inputXml);

            context.Response.ContentType = "text/xml";

// save XML into response

            document.Save(HttpContent.Current.Response.OutputStream);

 

In the samples provided with the Toolkit you can see 2 samples which publish your feed into various formats. The output is as shown

output type as atom

As seen in the above sample, the output feed is picked up from the querystring “outputtype”. You can provide “rss”, “rdf”, “atom” and “opml” for the respective feeds.

Strongly typed classes –

The toolkit provides strong typing to the Rss Classes.

e.g.

void Page_Load(object sender, EventArgs e)

 {

    RssToolkit.Rss.RssDocument rss = RssToolkit.Rss.RssDocument.Load(new System.Uri("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml"));

    Image1.ImageUrl = rss.Channel.Image.Url;

    GridView1.DataSource = rss.SelectItems();

    GridView1.DataBind();

 }

 

Caching of Feeds –

DownloadManager.cs class is used to get information of the feed. The feed is cached locally to the disk. The location and time of the caching is configurable. You can use the keys in the web.config to change the values –

<appSettings>

        <add key="defaultRssTtl" value="10"/>

        <add key="rssTempDir" value="c:\temp"/>

</appSettings>

 

You can download the ASP.Net RSSToolkit here.

You can Discuss or Post issues on Codeplex.

 Special Thanks to Dmitry Robsman, Marc Brooks and Jon Gallant.

Translate your text using Google Api's

Here is how you can translate a Text using Google's "Unofficial" API's.

The URL for Google Translate is - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}

  • "text" is your input string which needs to be translated.
  • langpair is the language pairs involved in the tranlsation. E.g. "ar|en" means translate from Arabic to English.

The result when you browse to the URL is a HTML page. You will have to do screen scraping to get your translated text.

Below is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.

/// <summary>

/// Translate Text using Google Translate API's

/// Google URL - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}

/// </summary>

/// <param name="input">Input string</param>

/// <param name="languagePair">2 letter Language Pair, delimited by "|".

/// E.g. "ar|en" language pair means to translate from Arabic to English</param>

/// <returns>Translated to String</returns>

public string TranslateText(

    string input,

    string languagePair)

{

    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

    WebClient webClient = new WebClient();

    webClient.Encoding = System.Text.Encoding.UTF8;

    string result = webClient.DownloadString(url);

    result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);

    result = result.Substring(0, result.IndexOf("</div"));

    return result;

}

More details about this Unofficial Google Translation API can be found Here

Posted by shahpiyush | 48 Comments
Filed under: , ,

VS 2005 not loading project on IIS 7 and Vista

If you get this error when loading a Web Application project on Visual Studio 2005 running on Vista and IIS 7 -

"Unable to read the project file 'xxx.csproj'. The Web Application Project xxx is configured to use IIS. To access local IIS Web sites, you must install all of the following components:

Internet Information Services.

IIS 6 Metabase and IIS 6 Configuration Compatibility

ASP.Net

In addition, you must run Visual Studio in the context of an administrator account........"

 

IIS 7 error on VS 2005 and Vista

Do the following -

  • Run VS.Net 2005 as Administrator - On the VS.Net 2005 shortcut, right click, Properties-Compatability and check the Run as administrator box is checked.
  • Check if ASP.NET is installed: Go to Control Panel - Programs and Features - Turn Windows features on or off - Internet Information Services -World Wide Web Services - Application Development Features - Check ASP.Net option. 
  • Make sure the IIS 6 compatibility is installed: Go to Control Panel - Programs and Features - Turn Windows features on or off - Internet Information Services - Web Management Tools - IIS 6 Management Compatibility - Check all of them.
  • Posted by shahpiyush | 15 Comments
    Filed under: ,

    101 LINQ query samples

    If you are starting into writing LINQ queries or you are stuck in writing a query here is a link which I'm sure will help you -

    http://msdn2.microsoft.com/en-us/vcsharp/aa336746.aspx

    Posted by shahpiyush | 0 Comments
    Filed under: ,

    Convert any feed to ATOM

    Judging by ATOM's rising popularity, see Atom compared to RSS, and its public endorsement by Google. Atom may be the future of Feed Syndication.

    Here is a quick way, courtesy of Google, to convert any Feed type to Atom. Google provides a nice REST interface to convert your feed into ATOM. Just do a Get to http://www.google.com/reader/atom/feed/{url-to-convert}

    e.g. To Convert MSDN RSS 2.0 feed (http://msdn.microsoft.com/rss.xml) do a GET on http://www.google.com/reader/atom/feed/http://msdn.microsoft.com/rss.xml. If you do View Source, you will see that it's converted to ATOM.

    Posted by shahpiyush | 4 Comments
    Filed under: , ,

    Creating Widgets using Javascript Simple Syndication - JSS

    Web syndication is a way to make content of your website or application available for others to use.  Rss/Atom/Rdf are specifications, which websites use for this purpose. However to consume such formats in your website, you need to know a little programming as these feeds are in Xml and they have a certain specification. Let’s say you want to show top 10 latest news items from Google news in the bottom right corner of your website. You will need to write code to read the feed off the Google website, parse the Xml and then format it into Html.

    This is fine if you have the ability, but with Web 2.0, widgets, badges, AJAX, etc.  Simplicity, refactoring, ease of use is what consumers are looking for. People want readymade plug and play components, which they can just plug into their website and it works, instead of diving into programming, rummaging through specifications, poking around with formatting, etc.

    JSS can help in that regards. JSS is not a syndication specification, its an easy way to use the available syndication formats. All the consumer needs to do for using your syndication is to embed some lines of readymade Javascript code you provide them, which they can plug into their website to automatically display your content.

    Below is a sample of what the consumer would need to put in the website –

    <script language="javascript" type="text/javascript" src="Jss.ashx?url=http://news.google.com/?output=rss&count=10&showtitle=1&style=bullets"></script>

    By embedding the above line of code in your website it will render something like below

    Jss 

    The options I have in the above URL are –

    ·         Feed Url – The url which contains the Feed the consumer would like to display.

    ·         Count – number of items to display

    ·         ShowTitle – Whether to show the title of the feed.

    ·         Table Parameters – You can specify the columns you would like to see, if style is table.

    ·         Style – It takes 4 styles

    o   Bullets

    Jss Bullets

    o   Dropdown

    Jss Dropdown 

    o   Table – You can specify the columns in the tableparameters querystring 

    Jss Table

    o   Definition lists

    Jss Definition List

    A code implementation of JSS provided below.

    MSDN Video Vista Sidebar Gadget

    I created a Vista Gadget with the help of my Lead Jon Gallant. This gadget helps you find Videos on MSDN. You can select from existing categories or you can search for videos. It shows the Video links at the bottom. When you hover over the video links it shows a tooltip with a thumbnail and a title of the video.

    You can download and try it here - http://gallery.live.com/liveItemDetail.aspx?li=f33020fe-65af-4abc-9d29-6c9b643e9cb3&l=1

    Try some searches like - "Scott Guthrie", "AJAX", "Silverlight"

    You can even look at my (or any other Gadget) source code, once you have downloaded it, open the folder for the Gadget under "C:\Users\[username]\AppData\Local\Microsoft\Windows Sidebar\Gadgets"

    If you have any feedback please leave a comment.

    Here is a screenshot of what the Gadget looks like. 

    MSDN Video Gadget

     

    UPDATE 05/02/2007 - As per comments below, modified the Gadget to open the Video in Media player in the "Flyout" window. Also added auto refresh on the content every 5 minutes.

    Posted by shahpiyush | 10 Comments
    Filed under: , , , ,

    Convert Rss to JSON - Serialize to JSON by using XmlSerialization and JavaScriptSerializer

    JSON (Javascript Object Notation) – is a light weight data interchange format.  It essentially is composed of key-value pairs.  For Example –

     XML

    <rss version="2.0">

      <channel>

        <item>

          <link>http://test.com</link>

          <title>Page Title</title>

        </item>

      </channel>

    </rss>

    JSON  -

    {
       "Version":"2.0",
       "Channel": {
             "Items": [{
                   "Link":"http://test.com",
                   "Title":"Page Title"
              }]
           }
    }

    The beauty of JSON is it integrates easily with Javascript. Just use eval() function of JavaScript to parse. So to initialize the above JSON this should do the trick –

    var rss = eval(‘({ "Version":"2.0", "Channel": { "Items": [{Link":"http://test.com",Title":"Page Title" }]}}’);

    Javascript does provide some level of Object orientation. So you could access the properties from the above object like –

    var itemtitle = rss.Channel.Items[0].Title;
    var rssVersion = rss.Version;

    RSS (Really Simple Syndication) – is used to syndicate your content. Unless you were hibernating for the past 5 years, I’m sure you know what Rss is. :)


    So let’s get to the meat of this article. How to Convert an Rss Feed to JSON?

    First I will use XmlSerialization to Serialize/Deserialize Rss. The System.Xml.Serialization namespace is  used for this purpose. You will need to decorate all your properties with XmlSerialization attributes. E.g. –

    [XmlElement("description")]

    public string Description

    {

    get

          {

                return _description;

          }

     

          set

          {

                _description = value;

          }

    }

    In this example (code provided below) I have created classes closely matching Rss specification (http://blogs.law.harvard.edu/tech/rss)

    To Serialize you can use the Serialize() method of XmlSerializer class

    private string Serialize()

    {

    string xml = string.Empty;

     

          using (StringWriter output = new StringWriter(new StringBuilder(), System.Globalization.CultureInfo.InvariantCulture))

          {

                XmlSerializer xmlSerializer = new XmlSerializer(typeof(RssDocument));

                xmlSerializer.Serialize(output, this);

                xml = output.ToString();

          }

     

          return xml;

    }

    To Deserialize you can use the Deserialize ) method of XmlSerializer class

    private static T DeserializeFromXmlUsingStringReader<T>(string xml)

    {

    if (string.IsNullOrEmpty(xml))

          {

                throw new ArgumentException("xml");

          }

     

          XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

          using (StringReader strngReader = new StringReader(xml))

          {

                return (T)xmlSerializer.Deserialize(strngReader);

          }

    }

    This should create a Strongly typed representation of Rss.

    To convert this Strongly typed Rss classes to Json format is actually very easy.  ASP.Net AJAX provides JavaScriptSerializer class in System.Web.Script.Serialization.JavascriptSerializer.


    Of particular importance to this example in this table is Serialize(object) method.

    public string ToJson()

    {

    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

          return js.Serialize(this); //this is an instance of the strongly typed Rss Class

    }

    What’s cool is this technique can be used on any objects which uses XmlSerialization.

    I have code example in the attachment below with example on how to Convert Rss to Json by pointing to a Url or loading from Xml string.

    Note : To run the example you need to have ASP.Net 2.0 and Ajax Extensions. You can download it from here

     

    Posted by shahpiyush | 8 Comments
    Attachment(s): RssToJson.zip

    Compressing ViewState of your Application

    .Net framework has an entire namespace for compression - System.IO.Compression. GZipStream is the class used for Compression and Decompression.

    .Net Framework 2.0, exposes a new class called PageStatePersister. This class is used to override and customize how you can Load and Persist the ViewState. This is a huge bonus for people who want to persist the ViewState out of the client side Html and move it to server side Cache or Database.

    So this example will create a new class "ViewStateCompressor" which inherits from PageStatePersister. There are 2 methods of PageStatePersister you will need to override Load() and Save(). This class will Compress the ViewState on Save(), so the ViewState sent to the Client side is small and it will Decompress on Load().

            /// <summary>

            /// Overridden by derived classes to serialize persisted state information when a <see cref="T:System.Web.UI.Page"></see> object is unloaded from memory.

            /// </summary>

            public override void Save()

            {

                using (StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))

                {

                    StateFormatter.Serialize(writer, new Pair(base.ViewState, base.ControlState));

                    byte[] bytes = Convert.FromBase64String(writer.ToString());

                    using (MemoryStream output = new MemoryStream())

                    {

                        using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true))

                        {

                            gzip.Write(bytes, 0, bytes.Length);

                        }

     

                        base.Page.ClientScript.RegisterHiddenField(Constants.ViewStateFieldName, Convert.ToBase64String(output.ToArray()));

                    }

                }

            }

            /// <summary>

            /// Overridden by derived classes to deserialize and load persisted state information when a <see cref="T:System.Web.UI.Page"></see> object initializes its control hierarchy.

            /// </summary>

            public override void Load()

            {

                byte[] bytes = Convert.FromBase64String(base.Page.Request.Form[Constants.ViewStateFieldName]);

                using (MemoryStream input = new MemoryStream())

                {

                    input.Write(bytes, 0, bytes.Length);

                    input.Position = 0;

                    using (GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true))

                    {

                        using (MemoryStream output = new MemoryStream())

                        {

                            byte[] buff = new byte[64];

                            int read = -1;

                            read = gzip.Read(buff, 0, buff.Length);

                            while (read > 0)

                            {

                                output.Write(buff, 0, read);

                                read = gzip.Read(buff, 0, buff.Length);

                            }

     

                            Pair p = ((Pair)(StateFormatter.Deserialize(Convert.ToBase64String(output.ToArray()))));

     

                            base.ViewState = p.First;

                            base.ControlState = p.Second;

                        }

                    }

                }

            }

     

    I created a BasePage which inherits from System.Web.UI.Page and all the pages in the application will inherit from this BasePage. In the BasePage, you will need to override the PageStatePersistor and return our ViewStateCompressor class

     

    public class BasePage : System.Web.UI.Page

    {

    private ViewStateCompressor _viewStateCompressor;

     

          public BasePage() : base()

          {

                _viewStateCompressor = new ViewStateCompressor(this);

          }

     

          protected override PageStatePersister PageStatePersister

          {

          get

          {

          return _viewStateCompressor;

          }

          }

    }

     

    Inherit the BasePage in your pages and you should get ViewState Compression. My test has shown the ViewState typically reduces by 30-40%. Try the code provided below.

     

    Posted by shahpiyush | 0 Comments
    Filed under: ,

    Attachment(s): ViewStateCompression.zip

    Sharing Master Pages amongst Applications by Embedding it in a Dll

    If you need to share Master Pages across applications and you don't want to create a ton of virtual directories, below is a way to do that. You can embed the Master Page as a Resource in your Dll and use VirtualPathProvider mechanism to call the Resource.

    VirtualPathProvider is a new functionality provided in .Net Framework 2.0, this functionality allows you to retrieve pages/resources from a virtual file system. This means that you can create web application to serve pages from a Database, Zip file, etc.

    You will need to inherit and provide functionality for these 3 classes –

    1.       VirtualPathProvider class provides a set of methods to implement the Virtual File System. It has methods which you will need to override like –

    a.       FileExists – indicates whether a file exists in the virtual file system

    b.      GetFile –This method gets the file from the virtual file system.

    c.       DirectoryExists -  indicates whether a directory exists in the virtual file system.

    d.      GetDirectory – This method gets a virtual directory from the virtual file system.

    2.       VirtualFile class represents a file object in a virtual file or resource space. You will need to override Open() method.

    3.       VirtualDirectory  class Represents a directory object in a virtual file. I am not including this functionality in this example, as its not used.

     

    First, I will create the Master page (and its code behind) and embed it as a Resource

     Set build action to Embedded Resource

    Next I will create the VirtualPathProvider, by inheriting from System.Web.Hosting.VirtualPathProvider. You need to override FileExists and GetFile methods

     

    public override bool FileExists(string virtualPath)

    {

       if (IsPathVirtual(virtualPath))

       {

          MasterPageVirtualFile file = (MasterPageVirtualFile)GetFile(virtualPath);

          return (file == null) ? false : true;

       }

       else

       {

          return Previous.FileExists(virtualPath);

       }

    }

     

    public override VirtualFile GetFile(string virtualPath)

    {

       if (IsPathVirtual(virtualPath))

       {

          return new MasterPageVirtualFile(virtualPath);

       }

       else

       {

       return Previous.GetFile(virtualPath);

       }

    }

    Both the methods call IsPathVirtual method to check if the file requested is a Virtual file.

     

    private static bool IsPathVirtual(string virtualPath)

    {

    String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);

    return checkPath.StartsWith(VirtualMasterPagePath,   StringComparison.InvariantCultureIgnoreCase);

    }

     

    Next I will create the VirtualFile and implement Open()

     

    public MasterPageVirtualFile(string virtualPath): base(virtualPath)

    {

    this.virPath = virtualPath;

    }

     

    public override Stream Open()

    {

    return ReadResource(virPath);

    }

     

    private static Stream ReadResource(string embeddedFileName)

    {

    string resourceFileName = VirtualPathUtility.GetFileName(embeddedFileName);

          Assembly assembly = Assembly.GetExecutingAssembly();

    return assembly.GetManifestResourceStream(

    Constants.MasterPageKeys.VirtualPathProviderResourceLocation + "." + resourceFileName);

    }

    Now I will use this VirtualPathProvider in the Web Application.
    First you need to Register the VirtualPathProvider with the Application. You can do that in the Application_Start of Global.asax.


    void
    Application_Start(object sender, EventArgs e)

    {

        MasterPageVirtualPathProvider vpp = new MasterPageVirtualPathProvider();

        HostingEnvironment.RegisterVirtualPathProvider(vpp);

    }

    Next, you will need to register the Master page in the PreInit event of the page.

    protected override void OnPreInit(EventArgs e)

    {

       MasterPageFile = MasterPageVirtualPathProvider.MasterPageFileLocation;

       base.OnPreInit(e);

    }

    The advantages are plentiful with this approach –

    1.       You can distribute Master pages inside Dll’s.

    2.       You can share Master pages amongst different applications.

    3.       You can extend this approach for Themes, Pages, etc.

    Having said the advantages you need to note that this approach has these shortcomings –

    1.       No designer support.

    2.       You cannot bind the Master page inside the ASPX in the <%@Page%> directive.

     

     

     
    Page view tracker