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?…