Thursday, February 24, 2011

ASP.NET: FindControl() returns null for an existing control while this control is still accessible via member variable

Building an AJAX enabled ASP.NET application we encountered the effect mentioned in the title of this article.

There is a TabContainer with a TabPanel containing a TextBox.

<cc1:TabPanel runat="server" ID="TabPanel1" TabIndex="0" HeaderText="Person">
<
ContentTemplate>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
</
ContentTemplate>
</
cc1:TabPanel>


This TextBox is accessible via a member variable, which is automatically created by Visual Studio Designer:


this.TextBoxName.Text = "Enter name here...";


If you try to access the TextBox using FindControl() method of Page class, you will be alerted with following message:



image



The error message is: “Object reference not set to an instance of an object.”.



That means, the FindControl() method cannot find the control by specified ID an returns null.



Slightly surprised (the TextBox is still accessible via member variable) we looked towards Microsoft Knowledge Base and Forums and found following article: http://msdn.microsoft.com/en-us/library/y81z8326%28v=vs.90%29.aspx#Y2166



It says: “When a control is not inside a naming container, you can get a reference to it by using the control's ID. When a control is inside a naming container, you must call a method that searches the naming container for the control's ID. A control might also be inside a naming container that you do not have direct access to.



To access a control by its ID inside a naming container, you have to extend your Page by instance method FindControlRecursive() described in the referenced article as well:

… 
((TextBox)this.FindControlRecursive(this,"TextBoxName")).Text = "Enter name here..."
… 
private Control FindControlRecursive(Control rootControl, string controlID) 

if (rootControl.ID == controlID) return rootControl; 
    foreach (Control controlToSearch in rootControl.Controls) 
    {


    Control controlToReturn =


                FindControlRecursive(controlToSearch, controlID);


     if (controlToReturn != null) return controlToReturn;


    }


    return null
}



It works! Enjoy…

Wednesday, February 23, 2011

HOWTO: find descendant XElement in XDocument by its name recursively using LINQ with namespaces

If you want to use LINQ to locate XML nodes by their names and your XML contains namespace notations, be aware to specify namespaces looking for descendants.

XML Example:

<?xml version="1.0" encoding="utf-8"?>
<
MyDataStruct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <
DataRoot xmlns="http://mydata.org/2011/1">
    <
Dispatch xmlns="http://mydata.org/2011/1">
      <
Target>
        <
Organisation>
          <
Comment></Comment>
          <
ID></ID>
        </
Organisation>
        <
System>
          <
ID>100</ID>
          <
Comment></Comment>
        </
System>
      </
Target>
      <
Source>
        <
Organisation>
          <
Comment></Comment>
          <
ID></ID>
        </
Organisation>
        <
System>
          <
ID>101</ID>
          <
Comment></Comment>
        </
System>
      </
Source>
    </
Dispatch>
  </
DataRoot>
</
MyDataStruct>

LINQ based recursive search operations:

XDocument xDoc = XDocument.Load(xmlFileName);

XElement xe1 = xDoc.Descendants("{http://mydata.org/2011/1}Target").First(); // locate first “Target” node
   XElement xe1 = xDoc.Descendants("{http://mydata.org/2011/1}Source").First()
                                  .Descendants("{http://mydata.org/2011/1}ID").First(); // locate “ID” subnode of“Source” node

UPDATE: seen also here -

http://stackoverflow.com/questions/566167/query-an-xdocument-for-elements-by-name-at-any-depth

Enjoy!

Friday, February 11, 2011

Internet Explorer 9 RC to download

Internet Explorer 9 Release Candidate can be downloaded at http://www.beautyOfTheWeb.com or at http://windows.microsoft.com/en-US/internet-explorer/downloads/ie.

OS supported are: Windows Vista/Windows 7/Windows Server 2008/Windows Server 2008 R2. There are already many languages available.

Finally the old known display mode for XML is back! (see my article: Internet Explorer 9 Beta does not display XML files in tree view ).

image

The site http://www.beautyOfTheWeb.com offers interesting information about new features and development tools for IE9.

Additionally there are advertised some featured sites tuned/created for IE9. One of my famous sites is BeatKeep: http://www.beatkeep.net/ - online music editor for (hobby) musicians.

Just download IE9 RC, navigate to BeatKeep and enjoy!

Saturday, January 29, 2011

Outlook Hotmail Connector for Office 2010: error on send/receive emails 4102 (80004102A, 8de00002)

Using Microsoft Outlook 2010 (both 32 and 64 bit versions) for Office 2010 you may encounter following troubles:

  • Outlook stops to download emails
  • Outlook stops to send emails
  • Outlook breaks unexpectedly synchronizing email folders

As error code you may see 4102 (different error messages may be shown), 0x80004102A or 0x8de00002.

The long and academically correct way is to analyze the reason and repair it.

The quick and pragmatically easiest way is:

  • Remove Hotmail account from Outlook email accounts
  • Close Outlook
  • Go to your local Outlook data folder ( %USERPROFILE%\AppData\Local\Microsoft\Outlook – for example, c:\users\mike\appdata\local\microsoft\outlook)
  • Delete .ost files (ddo not worry, they will be re-created  later)
  • Start Outlook and add the Hotmail account to email accounts (let the connector automatically detect settings)
  • Switch to Hotmail folders and let Outlook download all the emails

Enjoy!

Wednesday, January 19, 2011

Error: Windows Movie Maker cannot be used with Remote Desktop Connection or Terminal Services

Imagine, you’d like to use Windows Movie maker as known within Windows XP – whatever you reason should be. With Windows 7 and Windows XP mode you get an individual single instance of Windows XP inside of your Windows 7.

Starting Windows (XP) Movie Maker you may get following error message:

 image

Go to the settings of your VM and disable integration features WHILE THE VM IS RUNNING:

image

Re-login if required and enjoy!

Monday, January 03, 2011

‘JSON’ is undefined error after you install DivX Software

After you installed DivX Software (standard free of charge DivX package4 including codec, player, evaluation version of converter etc.) your Internet Explorer may start to display following error message directly after browser start or while surfing:

x10sctmp

The error message:

Message: 'JSON' is undefined
Line: 418
Char: 6
Code: 0
URI: about:blank

Somehow DivX Internet Explorer add-ons caused this message: after we disabled them – everything started to work as before.

image

There are numerous articles in internet describing alternative ways – up to changing code of a web site and so on, but what code do you expect in about:blank ?

Enjoy!

Fail to open Internet Options using IE7 or IE8 on Windows Server 2008 or Vista

As it usually happens on a computer being used by multiple persons one day on of our development machines (Windows Server 2008 Standard EN) started to show very strange behavior:

  • Trying to open Internet Options Dialog there’s just nothing happens – if the IE8 was running with no UAC escalation.
  • Trying to open Internet Options Dialog from an instance of IE8 started with administrator privileges – following error message appears:

image

“This operation has been cancelled due to restrictions in effect on this computer. Please contact your system administrator.”

Well, the box is a member of domain, but nobody from admins played with additional restrictions…

Some internet search showed numerous advices starting from editing computer’s registry (here) over editing Group Policy (here) up to re-install the machine…

Nothing from above could help (except new setup, what was too much overhead).

We tried to uninstall Internet Explorer 8: it was also tricky – IE8 may be missing in the list of installed software (“Programs and Features” applet). Then you should look for it in the list of installed updates (same applet, “View installed updates” – the are listed grouped by product). Even here you may still miss the IE8 entry – in this case the uninstall operation for IE8 is described here: http://support.microsoft.com/kb/957700. Check out additional information about dedicated command line to clean up the system from IE8:

FORFILES /P %WINDIR%\servicing\Packages /M Microsoft-Windows-InternetExplorer-8*.mum /c "cmd /c echo Uninstalling package @fname && start /w pkgmgr /up:@fname /norestart"

So we uninstalled the IE8, but the IE7 (that replaced the IE8 on our box) still reported an error on each try to open Internet Options. This time the message looks like a DLL is missing: RASDLG.DLL.

Indeed, we detected, that one of numerous last system updates (from Microsoft as well as from 3rd party vendors) somehow deleted RASDLG.DLL: the only copy we still could find was in WinSxS directory – where all side-by-side versions of same named DLLs live.

All the recovery operations (including usage of sfc /scannow, repair from boot disk) won’t restore this DLL and just failed.

So we copied the only found version of this DLL into %WINDIR%/System32 folder and restarted IE7: it worked now!

Then we updated the system with IE8 again, restart the box – and it still works! We still do not know, which step deleted this library and what shadow effects we will encounter using this version (6.0.6001.18000 instead of reported 6.0.6001.18005 as required by SFC).

So, once you see this strange error message by opening Internet Options – look into System32 folder: maybe you are missing this DLL…

Enjoy!

Tuesday, December 21, 2010

SQL Server Reporting Services report export failed: “Internet Explorer cannot download …ed.ReportViewerWebControl.axd from <server>”

Using SSRS (Microsoft © SQL Server Reporting Services) you may encounter following problem: once you select export of the currently displayed report in one of comfort formats -

image

your Internet Explorer pops-up following error:

image

The reason is: you are using SSL/TLS to connect to SSRS and “Do not save encrypted pages to disk” setting of Internet Explorer is activated:

image

Uncheck the box and retry.

Enjoy!

Friday, December 17, 2010

ASP.NET SQL based state management: mirroring state management database

Using Microsoft SQL Server for ASP.NET state management you may like to use SQL database mirroring to increase Web application availability while using NLB Web cluster. Basically, ASP.NET supports three ways for application state management:

  • in-process: unsuitable for NLB based architectures, since state data are managed in-process on one Web frontend node and are unavailable for any other nodes in failure case
  • using ASP.NET own state management service: this proprietary service of ASP.NET requires dedicated installation and management, using TCP-based connection from each Web frontend node
  • using SQL database: this case covers management of the state data in a dedicated SQL database available for any node from ASP.NET NLB cluster (configuration assumed)

Once the state management database is going down, all the session data becomes unavailable and may impact availability of the ASP.NET application. To avoid it, there are different approaches: among them usage of mirrored databases as one of the features came with SQL 2005 and higher.

The important things to know while you configure your ASP.NET application to get state managed using SQL mirrored database:

  1. Configure SQL database mirroring properly, refer to manual here (Microsoft)
  2. Pay attention and configure your connection string ON EACH NLB node properly:
    • add allowCustomSqlDatabase=”true” attribute to the sessionState element parameters, do not ask, just add;
    • add “initial catalog=ASPState” section to the sqlConnectionString – even if you use the standard database named ASPState (as installed by default using aspnet_regsql utility), you need this connection string extension;
    • add “failover partner=<name or IP address of the SQL mirror>”;
    • check “data source=<name or IP address of the master SQL server>” for validity;
  3. Since some of state data is encrypted, you have to take care about the encryption process: all the Web frontend nodes must be able to encrypt/decrypt state management data same way – otherwise the encrypted data becomes unusable. For this goal ensure, that all the nodes have same <machineKey …/> setting in web.config of the application. Refer to Microsoft article, how to configure and generate this setting (quick start – use IIS manager)
    image

If you paid enough attention to the conditions listed above, your application should just work in NLB with mirrored SQL state management database behind. Enjoy!

Saturday, November 27, 2010

Microsoft Codename Atlanta – monitoring SQL installation - welcome!

Yes, Microsoft does offer a new cloud service to monitor and guard your SQL Server installation. Local installation, I mean, not the SQL Server Azure.

Here the details : https://beta.microsoftatlanta.com/ – Registration (Live) is required.

clip_image002

After registration you will be provided with a link to download a certificate (will be installed locally) and a software modules. Store the certificate locally (you will need it later) and the software setup as well.

The software setup provides you with three setup variants: setup agent (collects information about local SQL installation), gateway (sends data collected by agents to the cloud) or both.

clip_image002[4]

For single box or evaluation purposes you’d choose to setup both agent and gateway.

While gateway installs you’ll be prompted for the issued certificate (s. above):

clip_image002[6]

Complete the setup and wait a couple of minutes, then go to the https://beta.microsoftatlanta.com/ and sign in – you’ll be redirected to the page where all the diagnostics information is shown:

image

Click on error or warning in the provided list – and enjoy the explanation of the cause and cure below the list:

clip_image002[8]

As you see, there’s also a link to appreciated download – if applicable.

The usage of Atlanta in the beta phase is for free, but requires registration.

Friday, November 19, 2010

Microsoft SQL Server product management says “Good Bye” to Itanium

image

Yes, the announce, the Microsoft SQL Server 2008 R2 is the last version with Itanium support is true. The announced SQL Server successor version (Codename “Denali”) does not support Itanium anymore.

Change your IA64 machines (if you have any) to x64 boxes and enjoy SQL Server “Denali” as CTP1.

Tuesday, November 16, 2010

Internet Explorer 9 Beta does not display XML files in tree view

The lifestory of XML files support in Internet Explorer passed many phases: pure text view in IE5 and IE6, animated tree view in IE7 with expanding and collapsing nodes, security warning for blocked content in IE8.

The newest version of IE – IE9 – does not display XML files in a tree view anymore. It displays the sequence of text values of all the XML document nodes – but neither nodes tags nor nodes hierarchy information.

Assume an XML file sample.xml:

<?xml version="1.0" encoding="utf-8"?>
<InternetBrowsers>
  <InternetBrowser>
    <Product>Internet Explorer</Product>
    <Version>7</Version>
    <Manufacturer>Microsoft</Manufacturer>
  </InternetBrowser>
  <InternetBrowser>
    <Product>Internet Explorer</Product>
    <Version>8</Version>
    <Manufacturer>Microsoft</Manufacturer>
  </InternetBrowser>
  <InternetBrowser>
    <Product>Internet Explorer</Product>
    <Version>9</Version>
    <Manufacturer>Microsoft</Manufacturer>
  </InternetBrowser>
</InternetBrowsers>

This file is shown in IE9 as follows:
image

The problem is, on most Windows based systems the Internet Explorer is the only program to view XML files (except Notepad as Editor – but not as comfortable quick viewer).

Looking forward to get tree view XML viewing back in final version of IE9 to enjoy it again…

Saturday, November 06, 2010

Write Windows Phone 7 game – for beginners (Part II)

Let’s start with game design. Our decision was a light version of blackjack game. “Light” means here: we implement only a subset of the real blackjack game. (Anyway you can improve the game logic using the sample source code later to narrow the “real” game).

First, we design the gambling table as the only frontend of the game:

Untitled

  • dealer: the picture of the dealer (computer)
  • player: the picture of player (human)
  • cardstock: the picture of the playing cards stock used to hit cards by the player if “touched”
  • stand: the picture used as “stand” button if “touched”
  • dealer cards: the sequence of cards hit by dealer
  • player cards: the sequence of cards hit by player
  • score dealer: the current score of the dealer
  • score player: the current score of the player

So far so good, we reach the first part of quick start into WP7 game programming: display information.

Display information in Windows Phone 7 games

The display functionality is encapsulated in the method Draw():

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Green); // we paint the table green

    // TODO: Add your drawing code here

    base.Draw(gameTime);
}

The method is described here: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.draw.aspx
”Called when the game determines it is time to draw a frame. Override this method with game-specific rendering code.”

We will display data using the class SpriteBatch described here:

An instance variable of the class SpriteBatch:

SpriteBatch spriteBatch;

will do the display job for us.

SpríteBatch instance does display the data in three steps:

  • Begin() initiates begin of sprite operations ( = display actions)
  • the instance of SpriteBatch performs the display actions
  • End() finishes the sprite operations

So referring to the UI model designed above, the Draw() function looks like follows:

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.DarkGreen);

    // begin the display actions
    spriteBatch.Begin();

    // draw dealer's picture
    drawDealer();
    // draw player's picture
    drawPlayer();
    // draw card stock
    drawStock();
    // draw player's cards
    drawPlayerCards();
    // draw dealer's cards
    drawDealerCards();
    // draw game controls
    drawControls();
    // draw game score
    drawScore();
    // draw game result
    drawResult();

    // end display actions
    spriteBatch.End();

    base.Draw(gameTime);
}

There are two basic display operations implemented in this game: display a picture (called texture in terms of WP7 game) and display a string of text.

Display pictures

The most popular task to display information in a game is to display a picture. The pictures in WP7 games are called textures. The textures can be displayed by spriteBatch, but have to be loaded before from game content.

The loading of textures used in the game is realized usually in LoadContent() method:
 http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.loadcontent.aspx

This method is called when game resources need to be (re)loaded – even if DeviceReset() is called.

Loading of pictures looks like follows:

textureCardBack = Content.Load<Texture2D>("cardBack");

where cardBack is the name of the graphic resource saved as a picture (PNG, BMP etc.) file in game content project:

image

During the Draw() method call the previously loaded texture can be dispalyed by spriteBatch as follows:

spriteBatch.Draw(textureCardBack, stockPosition, Color.White);

The Draw() method of SpriteBatch used here takes three parameters:

  • texture (picture) to be displayed
  • screen position to display the picture
  • color to tint the picture (we use Color.White to avoid tinting)

Adding pícture to game content

To add a picture to the game use “Add” –> “New Item…” command from the context menu in the game content project:

image

Then select “Bitmap file” and edit it.

Alternatively use “Add” –> “Existing item…” to add an existing graphic file

Display text

SpriteBatch() can also display text messages. We use this functionality to display scores:

spriteBatch.DrawString(scoreFont, scoreDealer.ToString(), DealerScorePosition, color);

The method DrawString() used here takes four parameters:

  • font to be used (this font must be loaded before the call – usually in the LoadContent() method similar to loading textures)
  • text to display (in the sample above – dealer’s score as string)
  • screen position to display the text
  • text display color

Adding font to game content

To add a font to the game use “Add Item…” command from the context menu in the game content project as described above (adding picture to game).

Then select “Sprite Font” - a new font description file will be added to game content:

image

The spritefont file is a XML based font description file:

<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Segoe UI Mono</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>36</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Bold</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    -->
    <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#126;</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>


Edit the font parameters regarding text display requirements.

Play sound

Another way to provide user with information is playing sounds. A sound to play must be loaded from the game content the same way as we do for textures or fonts:

cardDownSound = Content.Load<SoundEffect>("cardDown");

where cardDown is the name of the sound file (usually WAV encoded) enclosed in game content:

image

To play the sound at the drawing time or in other game situations just use Play() method:

cardDownSound.Play();

…more to come…

Friday, November 05, 2010

Windows Live Writer 2011, Word 2010 and blog entry formatting


 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


 

namespace HelloWorld

{


class
Program

{


static
void Main(string[] args)

{

}

}

}


 

This is the reason to create blog entries with Word 2010: the color formatting is kept on copy/paste from Visual Studio. Windows Live Writer doesn't keep the colors.

This is a good news. Here are two bad news:

  1. Word doesn't keep other formatting parameters (newlines, tabs etc.) – see above.
  2. Word doesn't support blog entry embedded pictures.

What to use? Decide yourself…

Thursday, October 28, 2010

Write Windows Phone 7 game – for beginners (Part I)

Over the weekend there was a rainy weather, so I lighted up the fireplace in the living room, turned on the TV and occupied the couch with my laptop to check, what news we’ve got with Windows Phone 7 development tools.

Just to learn the WP7 programming news I started with a light version of blackjack game for WP7 – even I haven’t one yet, just using emulator. It was surprisingly easy and I had fun. So there is the description how I did it:

After developer tools succeeded just start Microsoft Visual Studio 2010 and create a new Windows Phone Game project:
image

Let’s call the project BJLight for Blackjack Light. We will learn the WP7 game programming building a light version of the old known card game – Blackjack.

Visual Studio 2010 creates new solution with all the required projects and files for a new WP7 game:

image

First rename Game1.cs to BJGame.cs as the only game contained in the project: just edit it in Solution Explorer.

You will be asked:

image

Confirm with “Yes”: you will see the file name changed in Solution Explorer:

image

… and source code will be updated as well:

image

Open “BJLite” project properties to set some common and initial configuration parameters of the game:

image

  • Ensure the “Game startup type” is “(Not set)” – this will enforce the only Game derived class to be launched on game start: in our project this is BJLite class. Note: if there are many Game derived classes in the project, you can specify, what class should be launched on game start.
  • The thumbnail of the game appears on WP7 display as the control to launch game. Let us fill this thumbnail with appropriate image to identify our game:

image

The do the same with Game.ico:

image

The project should be signed – this is a good programming style.

image

Select “New” key file and enter as follows:

image

A new key file will be created and added to project:

image

After initial project configuration is set, let us start with game design.

One of the key methods of the BJLite class instance is Draw(). This method is called each time the game requires the display to be redrawn:

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

   // TODO: Add your drawing code here

    base.Draw(gameTime);
}

Since we design a card game, let us emulate a casino gambling table and repaint it green:

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Green);

   // TODO: Add your drawing code here

    base.Draw(gameTime);
}

Start the solution with F5: the WP7 emulator appears and shows the newly created game screen - gambling table:

image

Click on the “Back” button and see the game thumbnail:

image

Clicking on the thumbnail you start the game.

The WP7 emulator controls allow rotate the emulator to get appropriate screen orientation:

image

We will design the game for landscape orientation.

(more to come)

Wednesday, October 27, 2010

Free books from Microsoft Press

Information from Microsoft Press web site:

After the release of Moving to Microsoft Visual Studio 2010 in September, here’s an updated list of some of our free eBooks:

Download books and enjoy!

Tuesday, October 26, 2010

Problem with SQL 2008 based ASP.NET 2.0 state management (Update 2)

…and one more: configuration of ASPState succeeded using

aspnet_regsql –ssadd –sstype p –E –S .

(s. also Problems with SQL based ASP.NET state management ).

The Web Appication still reports an error:

Unable to use SQL Server because ASP.NET version 2.0 Session State is not installed on the SQL server. Please install ASP.NET Session State SQL Server version 2.0 or above.
at System.Web.SessionState.SqlSessionStateStore.SqlPartitionInfo.GetServerSupportOptions(SqlConnection sqlConnection)
at System.Web.SessionState.SqlSessionStateStore.SqlPartitionInfo.InitSqlInfo(SqlConnection sqlConnection)
at System.Web.SessionState.SqlSessionStateStore.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo)
at System.Web.SessionState.SqlSessionStateStore.GetConnection(String id, Boolean& usePooling)
at System.Web.SessionState.SqlSessionStateStore.DoGet(HttpContext context, String id, Boolean getExclusive, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)
at System.Web.SessionState.SqlSessionStateStore.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)
at System.Web.SessionState.SessionStateModule.GetSessionStateItem()
at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

The database (usually named ASPState) may be installed on the used SQL Server instance, the Web Application pool account may have granted connect, dataread and datawrite privileges, but the error comes over and over again.

Thereason is mostly, the Web Application pool account is missing some execution permissions on the  ASPState objects like store procedures.
image

You can either

  • grant to the Web Application pool account execute permission to each store procedure listed above
    or
  • alternatively grant to this account db_owner role (it includes execution permissions to mentioned stored procedures).

Enjoy!

Problem with SQL 2008 based ASP.NET 2.0 state management (Update 1)

Here is another popular problems while configuring SQL Server 2008 R2 for ASP.NET 2.0 state management (s. also Part1 at http://winmike.blogspot.com/2010/10/problems-with-sql-based-aspnet-state.html).

Web Application throws exception on start:

Error    Unable to connect to SQL Server session database.
   at System.Web.SessionState.SqlSessionStateStore.ThrowSqlConnectionException(SqlConnection conn, Exception e)
   at System.Web.SessionState.SqlSessionStateStore.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo)
   at System.Web.SessionState.SqlSessionStateStore.GetConnection(String id, Boolean& usePooling)
   at System.Web.SessionState.SqlSessionStateStore.DoGet(HttpContext context, String id, Boolean getExclusive, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)
   at System.Web.SessionState.SqlSessionStateStore.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)
   at System.Web.SessionState.SessionStateModule.GetSessionStateItem()
   at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Web.SessionState.SqlSessionStateStore.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo)

The problem is, your Web Application cannot connect to the SQL Server instance running the session state database (usually named ASPState).

There are many possible reasons, why the connection won’t be established.

Here (http://blogs.msdn.com/b/sql_protocols/archive/2007/03/31/named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server.aspx) is a very good compilation of most frequent causes for failed connection to the SQL Server.

If you use Windows Server 2008 R2 running SQL Server 2008 R2 you may need to configure Windows Firewall exceptions on the SQL Server 2008 box to enable network connections. The MSDN KB 968872 Script:

@echo =========  SQL Server Ports  ===================
@echo Enabling SQLServer default instance port 1433
netsh firewall set portopening TCP 1433 "SQLServer"
@echo Enabling Dedicated Admin Connection port 1434
netsh firewall set portopening TCP 1434 "SQL Admin Connection"
@echo Enabling conventional SQL Server Service Broker port 4022 
netsh firewall set portopening TCP 4022 "SQL Service Broker"
@echo Enabling Transact-SQL Debugger/RPC port 135
netsh firewall set portopening TCP 135 "SQL Debugger/RPC"
@echo =========  Analysis Services Ports  ==============
@echo Enabling SSAS Default Instance port 2383
netsh firewall set portopening TCP 2383 "Analysis Services"
@echo Enabling SQL Server Browser Service port 2382
netsh firewall set portopening TCP 2382 "SQL Browser"
@echo =========  Misc Applications  ==============
@echo Enabling HTTP port 80
netsh firewall set portopening TCP 80 "HTTP"
@echo Enabling SSL port 443
netsh firewall set portopening TCP 443 "SSL"
@echo Enabling port for SQL Server Browser Service's 'Browse' Button
netsh firewall set portopening UDP 1434 "SQL Browser"
@echo Allowing multicast broadcast response on UDP (Browser Service Enumerations OK)netsh firewall set multicastbroadcastresponse ENABLE

Save the script in a .bat file and run in console, STARTED WITH ADMINISTRATION PRIVILEGES EVELATED, then enjoy.

Monday, October 25, 2010

Who wakes up my computer?

I suspend my computer running Windows 7 Ultimate each time I finish my work, but in morning see it running again. Somebody touched mouse or pressed the keyboard? No.

How to detect, who wakes up the computer and how to prevent it?

First, let us see, which event was responsible for changing computer’s power state. there are two ways:

- run
powercfg –lastwake
from console window
image

or

- check in System event log for event from Power-Troubleshooter:
image

In my case the mcupdate_scheduled task was the reason to wake up.

Checked in the scheduled task library (to find in Windows 7 in Computer management)

image

Yes, it is! The Media Center updater wakes up the computer to perform an update.

To turn it out, open task properties, go to “Conditions” tab, clear the checkbox “Wake the computer to run this task”, confirm with “OK” and enjoy:

image

Sunday, October 24, 2010

Redirect G DATA antivirus update, log and quarantine folders and save disk space on the system volume

The freshly installed G DATA antivirus management server takes care about internet based update of virus signatures and program files for client and server.

By default the update folders are residing in the “Documents and Settings”/”All Users” path usually on the system disk. The G DATA management server downloads and keeps numerous (I cannot say how much, but definitely over 5-6) pre-downloaded versions of modules. This way you may face the problem of free disk space: the downloads on my server are in sum over 2 GB!

Fortunately, there’s a setting you can change manually to redirect update (and some other destination folders) to another disk to keep system disk free of the waste.

  1. stop the service “G DATA ManagementServer”.
  2. go to %Programs%\G DATA\G DATA AntiVirus ManagementServer folder.
  3. edit gdmms.exe.config file, UpdateDistributionFolder entry:
    (example)
  4. <setting name="UpdateDistributionFolder" serializeAs="String">
        <value>D:\Software\GData\AntiVirus ManagementServer\Updates</value>
    </setting>
  5. if required, edit also the entries LogFileFolder and QuarantineFolder:
    (example)
    <setting name="LogFileFolder" serializeAs="String">
        <value>D:\Software\GData\AntiVirus ManagementServer\Log</value>
    </setting>
    <setting name="QuarantineFolder" serializeAs="String">
        <value>D:\Software\GData\AntiVirus ManagementServer\Quarantine</value>
    </setting>
  6. save gdmms.exe.config.
  7. edit IUpdateCfg.xml file, entry BasePath:
    (example)
    <BasePath>D:\Software\GData\AntiVirus ManagementServer\Updates</BasePath>
  8. start “G DATA ManagementServer”.
  9. try internet update and check for destination folders.
  10. …enjoy!

Saturday, October 23, 2010

Restart missing G DATA antivirus client

If the G DATA antivirus client is running, you will see an icon in Windows task bar:

image

Sometimes the manually initiated update process gets hung and must be terminated. At this time the antivirus client process is killed, and the icon disappears. There are two ways to get the icon appearing again:

  • Restart computer (for servers somehow problematic way)
    or
  • Restart G DATA antivirus client autromatically:
  1. open console window (on Windows Server 2008, 2008 R"2 and Windows 7 “run as administrator” option may be required).
  2. switch to %ProgramFiles%\G DATA\AVKClient.
  3. start AVKCl.exe as follows:
    AVKCl.exe /GUI
  4. the icon should appear immediately and provide you with usual control options for G DATA antivirus client.

enjoy!

Wednesday, October 20, 2010

Windows Phone 7 for developers

image

The tools are free for download here, the introductions are here. Go and enjoy!

Tuesday, October 19, 2010

Install recent Adobe software updates

Install Adobe vulnerability patches from here and enjoy!

Tuesday, October 05, 2010

Problems with SQL based ASP.NET state management

If you plan to use SQL based ASP.NET 2.0 state management with Windows Server 2008 and SQL Server 2008 R2, you may encounter following problem: the ASP.NET application won’t start. The error message in Event Log sound like:

The SELECT permission was denied on the object 'ASPStateTempApplications', database 'tempdb', schema 'dbo'.

The INSERT permission was denied on the object 'ASPStateTempApplications', database 'tempdb', schema 'dbo'.

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)

   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)

   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)

   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)

   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)

   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)

   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)

   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

   at System.Web.SessionState.SqlSessionStateStore.SqlPartitionInfo.InitSqlInfo(SqlConnection sqlConnection)

   at System.Web.SessionState.SqlSessionStateStore.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo)

   at System.Web.SessionState.SqlSessionStateStore.GetConnection(String id, Boolean& usePooling)

   at System.Web.SessionState.SqlSessionStateStore.DoGet(HttpContext context, String id, Boolean getExclusive, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)

   at System.Web.SessionState.SqlSessionStateStore.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)

   at System.Web.SessionState.SessionStateModule.GetSessionStateItem()

   at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)

   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

The reason is:

- you configured usage of temporary database for ASP.NET state data management (for example, specifying 
–sstype t
or omitting this option while launching aspnet_regsql command for ASP.NET SQL state management)

-  the user account configured for Application Pool of your ASP.NET Web Application has no permission on ASPState database and (!) no SELECT/INSERT/DELETE/UPDATE permissions on 'ASPStateTempApplications' and 'ASPStateTempSessions' tables of tempdb database.

The very first attempt is to provide your Application Pool user with required permissions – and it works! It really works – until you restart the machine. At this moment the temporary database tempdb is re-created and all the permissions you configured for the Application Pool user are gone.

This behavior is known and described in technet article

http://technet.microsoft.com/en-us/library/dd392259(WS.10).aspx

Unfortunately, none of offered in this article solutions did work for me.

My solution looks like follows:

  • remove ASP.NET SQL state management: for example, use command
    aspnet_regsql –ssremove –E  -S .
    confirm command with “y” if asked

    Note:
    -E is essential for integrated security connection usage
    -S informs what SQL server and SQL instance to use, “.” (dot) specifies default local instance of SQL Server
  • add ASP.NET SQL state management: for example, use command
    aspnet_regsql –ssadd –sstype p –E  -S .
    confirm command with “y” if asked
  • open SSMS and ensure the ASPState database is created
    image
  • add Application Pool user to User logins of ASPState database, associate him with db_datareader and db_datawriter roles
  • open “Properties” dialog for ASPState database, select “Permissions” Tab and provide Application Pool user with SELECT/INSERT/DELETE/UPDATE permissions for the ASPState database.
    aspstate

Start your Web Application: if all the application state management settings are configured properly (check the connection string), everything should work immediately. Even after machine gets restarted.

Enjoy!

Friday, October 01, 2010

Microsoft SQL Server 2008 Samples

The SDK samples for Microsoft SQL Server 2008 © Developer Edition are no longer shipped in the box. If you install Client Tools SDK feature from installation disk, you get a folder Samples with only HTML file there saying:

 

There are many code samples and sample databases available for Microsoft SQL Server. These samples are no longer shipped in the box. Instead, you can browse through and download the samples in several different projects on CodePlex.com. There is a portal samples project which directs you to all the other SQL Server sample projects on CodePlex: http://SqlServerSamples.CodePlex.com/.

 

So navigate to codeplex and download samples from there. Enjoy (if you can).

Interesting, what to do if you have no internet access actually?…

Thursday, September 30, 2010