IIS 8 ASP.Net Error “configuration section cannot be used…”

iis8logoWhen working with IIS 8 (or even 7 or 7.5), you may have run across this little gem / error: “This configuration section cannot be used at this path”

HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Module / Handler IIS Web Core
Notification BeginRequest
Handler Not yet determined

You’ll want to open the applicationhost.config located in: C:\Windows\System32\inetsrv\config

And now find the lines like this:

<section name="handlers" overrideModeDefault="Deny" />
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />

And change the Deny to Allow, like this:

<section name="handlers" overrideModeDefault="Allow" />
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />

Save the file, and you should be good!

IIS 8 ASP.Net Error “configuration section cannot be used…”

Parsing Html content using Html Agility Pack, Cookies & Proxy

stockpriceIf you’ve ever needed to parse (screen scrape?) some remote html, you may have wanted to pull info from a page that only renders content to a browser. The below example shows how to grab some content from a web page (using a web request) but also incorporates using cookies and a proxy to help and the Html Agility Pack to parse the returned html (allowing you to get a specific element):

Imports System.Net
Imports System.Web

Public Class Form1

    Public cookies As New CookieContainer

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        'create a web request
        Dim wreq As HttpWebRequest = WebRequest.Create("http://www.reuters.com/finance/stocks/overview?symbol=AMZN.OQ")

        'set the agent to mimic a recent browser
        wreq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"

        'how you're getting the page
        wreq.Method = "get"

        'create a proxy
        Dim prox As IWebProxy = wreq.Proxy

        'set the proxy cred
        prox.Credentials = CredentialCache.DefaultCredentials

        'create the html doc & web
        Dim document As New HtmlAgilityPack.HtmlDocument
        Dim web As New HtmlAgilityPack.HtmlWeb

        'needs to use cookies
        web.UseCookies = True

        'set the cookie request
        wreq.CookieContainer = cookies

        'start a response
        Dim res As HttpWebResponse = wreq.GetResponse()

        'get a stream from the response
        document.Load(res.GetResponseStream, True)

        'get some data from the page. 
        'in the below example, i'm looling for a div with the class 'sectionQuoteDetail' and getting the content of the second span inside
        Dim strCurrentQuote = document.DocumentNode.SelectSingleNode("//div[@class='sectionQuoteDetail']//span[2]")

        MsgBox(strCurrentQuote.InnerText)

    End Sub

End Class

As a side note, the use of the proxy code above also solves the frequent HttpWebRequest WebException “The remote server returned an error: (407) Proxy Authentication Required” error.

Parsing Html content using Html Agility Pack, Cookies & Proxy

Downloading a remote file with vb.net / c# using WebClient

Can you believe it’s 2013 already? Me either. Anyhow, just wanted to provide a simple solution for a very popularly asked question: “how can I download a remote file?.” Well, below is a basic method using the WebClient class. It’s pretty cut and dry, just pass a remote file (ie: http://www.chrisbitting.com/image.jpg) and a local file (c:\temp\file.jpg) and it downloads. If you’re interested how to do this with cookies enabled for authentication, let me know!

vb.net

Private Sub dloadhttpFile(fileToDownload As String, localFile As String)
        'Examples:
        'fileToDownload = http://www.chrisbitting.com/image.jpg
        'localFile = c:\files\someimage.jpg

        Try
            'create an instance of WebClient - the heart of downloading a file
            Dim fileReader As New WebClient()

            'check if the file already exists locally
            If Not (System.IO.File.Exists(localFile)) Then
                fileReader.DownloadFile(fileToDownload, localFile)
            End If
        Catch ex As HttpListenerException
            Console.WriteLine(("Error Downloading: " & fileToDownload & " - ") + ex.Message)
        Catch ex As Exception
            Console.WriteLine(("Error Downloading: " & fileToDownload & " - ") + ex.Message)
        End Try
    End Sub

c#

   private void dloadhttpFile(string fileToDownload, string localFile)
        {
             //Examples:
             //fileToDownload = http://www.chrisbitting.com/image.jpg
             //localFile = c:\files\someimage.jpg

            try
            {
                //create an instance of WebClient - the heart of downloading a file
                WebClient fileReader = new WebClient();

                //check if the file already exists locally
                if (!(System.IO.File.Exists(localFile)))
                {
                    fileReader.DownloadFile(fileToDownload, localFile);
                }
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine("Error Downloading: " + fileToDownload + " - " + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Downloading: " + fileToDownload + " - " + ex.Message);
            }
        }
Downloading a remote file with vb.net / c# using WebClient

Accessing Visual Studio 2010’s built in web server remotely

So as you’re developing / debugging a Visual Studio 2010 web app, you may want to access the local web server from a remote machine. Visual Studio will be accessible locally using an address like: http://localhost:5524, but if you try from another machine on your network using the ip address ie: http://192.168.4.2:5524, you won’t be able to reach the solution.

The easiest way to get this working:
1. Download SPI Port Forward.
2. Install SPI Port Forward.
3. The config is a little backwards in my opinion, so after running SPI Port Forward, enter the remote port you want to use in the  “Local Port” text box (ie: 8080), and in the “Remote Host” enter “localhost” (usually) and in the “Remote Port” enter your local Visual Studio debugging port (in my example, 5524.
4. Click Activate

SPI Port Forward Setup

You should now be able to access your Visual Studio web app (provided it’s open and running) using http://(your machine ip)/(the port you choose above) ie: http://192.168.4.2:8080

Happy Testing!

Note: If you have any additional local or network firewalls, they may interfere with the setup and you’ll have additional steps…
Accessing Visual Studio 2010’s built in web server remotely

.Net’s System.ServiceModel.Syndication / RSS Feeds!

If you’re looking to work with RSS feeds, I suggest you checkout the .net ServiceModel.Syndication. Below is a quick example in .net 4 / VB:

 

Imports System.ServiceModel.Syndication

'In case you're using a proxy:
Dim wReq As HttpWebRequest
wReq = WebRequest.Create("http://yourRSSfeedURL")
wReq.Proxy = WebProxy.GetDefaultProxy
wReq.Proxy.Credentials = CredentialCache.DefaultCredentials
Dim xReader As XmlReader = XmlReader.Create(wReq.GetResponse.GetResponseStream)
'Create the feed from the xml loaded
Dim sFeed As SyndicationFeed = SyndicationFeed.Load(xReader)
'Loop through the results
For Each sItem As SyndicationItem In sFeed.Items
  Debug.WriteLine(sItem.Title.Text) 'Many other SyndicationItem properties available!
Next

I have compared this to other libraries and this by far is the cleanest / easiest way to pull in RSS Feeds. What are your thoughts?

.Net’s System.ServiceModel.Syndication / RSS Feeds!

The Classic: Cannot refer to an instance member of a class from within a shared method…

I am sure you’ve gotten this before:

Cannot refer to an instance member of a class from within a shared method

Well, instead of all the reasons why, I will just tell you one simple solution:

Pretend you’re doing this:

Public Shared Function getSomething() As Integer
   For Each tControl As Control In FlowLayoutPanel1.Controls    Next

End Function

It will ERROR.

Now Add the form name:

Public Shared Function getSomething() As Integer
   For Each tControl As Control In sampleForm.FlowLayoutPanel1.Controls   Next

End Function

And run again!

The Classic: Cannot refer to an instance member of a class from within a shared method…

Importing IIS Logs into a SQL Database / Table

1. Download the Log Parser tool from Microsoft here. I know, it’s old but works great.

2. Dump your IIS log files somewhere (ie: c:\temp\logs).

3. Run this in cmd:

C:\Program Files (x86)\Log Parser 2.2>logparser “SELECT * INTO iisLogs FROM c:\temp\logs\*.log ” -i:iisw3c -o:SQL -server:localhost -database:webLogs -username:sa -password:yourpass -createTable: ON

if you’re on 32bit, run Log Parser will be in this folder:

C:\Program Files\Log Parser 2.2>logparser “SELECT * INTO iisLogs FROM c:\temp\logs\*.log ” -i:iisw3c -o:SQL -server:localhost -database:webLogs -username:sa -password:yourpass -createTable: ON

Now you have a table w/ tons of data!

Update:

In an updated article, I discuss increasing import performance the transactionRowCount option.

Importing IIS Logs into a SQL Database / Table

Creating & Playing Playlist – VB.Net Windows Media Player Control

'create playlist
 Dim newPlayList As WMPLib.IWMPPlaylist = wmpControl.playlistCollection.newPlaylist("soundsToPlay")
 newPlayList.appendItem(wmpControl.newMedia("C:\Sample1.mp3"))
 newPlayList.appendItem(wmpControl.newMedia("C:\Sample2.mp3"))
'play the list
 wmpControl.Visible = False
 wmpControl.currentPlaylist = newPlayList
 wmpControl.stretchToFit = True
 wmpControl.Ctlcontrols.play()
Creating & Playing Playlist – VB.Net Windows Media Player Control