Tech blog

Solving problems

About
Contact

Archive for the ‘Projects’ Category

Create Linq to SQL classes from .sdf (Local database)

leave a comment

Linq allows to handle data easily. Linq to SQL tools are integrated in Visual Studio but is limited to can generate code only for  certain databases. To create ORM from .sdf database file read on…

What to do?
Copy next script to a file with .bat extension.

Change DATABASE_NAME, DATABASE_PASSWORD and NAMESPACE according to your needs.

@echo off
rem Input parameters
rem DATABASE_NAME should NOT contain spaces
set DATABASE_NAME=MyDatabase
set DATABASE_PASSWORD=mypass
set NAMESPACE=MyNamespace.Database

rem Set full path to SqlMetal.exe
rem For 64-bit Windows
set SQLMETAL="%ProgramW6432%\Microsoft SDKs\Windows\v6.0A\Bin\SqlMetal.exe"
rem For 32-bit Windows
if "%ProgramW6432%"=="" set SQLMETAL="%ProgramFiles%\Microsoft SDKs\Windows\v6.0A\Bin\SqlMetal.exe"

rem Other parameters
set DATABASE_PATH="%CD%\%DATABASE_NAME%.sdf"
set OUTPUT_CS_PATH="%CD%\%DATABASE_NAME%.cs"
set OUTPUT_DBML_PATH="%CD%\%DATABASE_NAME%.dbml"
set CONNECTION_STRING="Data Source=\"%DATABASE_PATH%\"; Password=\"%DATABASE_PASSWORD%\";"

rem Check and run sqlmetal
if not exist %SQLMETAL% goto error-missing-sqlmetal
%SQLMETAL% /conn:%CONNECTION_STRING% /dbml:%OUTPUT_DBML_PATH% /namespace:%NAMESPACE% /context:%DATABASE_NAME%DataContext /pluralize
%SQLMETAL% /conn:%CONNECTION_STRING% /code:%OUTPUT_CS_PATH% /namespace:%NAMESPACE% /context:%DATABASE_NAME%DataContext /pluralize
goto end

:error-missing-sqlmetal
echo Error: cannot find sqlmetal.exe
echo Search location: %SQLMETAL%
goto end

:end

Example

If the database is stored in C:\db\Website.sdf then copy script into C:\db\make.bat. Change DATABASE_NAME to Website and run the script. Script should generate C:\db\Website.cs and C:\db\Website.dbml files. Include the generated .cs file into your project.

Using the generated code

class Program
{
  static void Main()
  {
    //Suppose that Website.sdf has Page table with CreationDate column of type DateTime
    WebsiteDataContext db = new WebsiteDataContext(@"C:\db\Website.sdf");
    var list = from p in db.Pages
                 where p.CreationDate > DateTime.Today
                 selet p;

    //Show number of pages that match Linq query
    Console.WriteLine(list.Count() + " pages created today.");
  }
}
VN:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

March 30th, 2010 at 7:53 pm

Posted in Projects

Tagged with , , , , , , ,

Auto-incement assembly build version in Visual Studio 2008

leave a comment

When building a project with Visual Studio an output assembly with embedded version is generated. Version indicates how an application is advancing in development.

Developer can change output assembly version for each project by opening project’s properties (right click, Properties), clicking Assembly Information… button and editing text in fields (see marked area on the image below).

VS2008 window for changing assembly version

VS2008 window for changing assembly version

Alternative is to open Properties/AssemblyInfo.cs or .vb and change AssemblyVersion value in a text editor.

Version can be automatically incremented on each build. To enable counter open Properties/AssemblyInfo.cs and set:

//Change AssemblyVersion's value from 1.0.0.0 to 1.0.* and comment AssemblyFileVersion
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]

Auto-increment symbol (‘*’) cannot be set in GUI (like screenshot above) but only in code.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

January 18th, 2010 at 5:12 pm

Saving Changes is Not Permitted?

leave a comment

We tried to add new ntext nullable column in MS SQL table.  We were quite surprised to get the following error message:

image

Saving changes is not permitted.  The changes you have made require the following tables to be dropped and re-created.  You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

It wouldn’t let us add an “Allow Nulls” column?  That just seemed absurd.

Apparently, this is now the default behavior for any of the following changes to a table:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

In order to prevent this default behavior, you simply need to uncheck a box in the table designer options using the Tools -> Options menu item

image

Expand the Designers section to display the Table and Database Designers options.

image

To change this behavior, just uncheck the “Prevent saving changes that require table re-creation” checkbox.

Original article was published at http://codeslammer.wordpress.com/2008/10/19/saving-changes-is-not-permitted/

VN:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

December 21st, 2009 at 4:44 pm

IF WRN: Assembly binding logging is turned OFF or It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level

leave a comment

We had some problems with subdirectories under our root website.

We wanted to add different examples under our website root (organized into folders) like this:

  • www.our-website.com/example1
  • www.our-website.com/example2

And we always got these errors.

At root of our website www.our-website.com we didn’t have any web.config and we didn’t want any. Every subfolder has its own web.config and it didn’t worked under IIS7

Solution:

Click on each folder under IIS and then right mouse click Convert To Application and it worked.

VN:F [1.9.3_1094]
Rating: 3.0/5 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Could Not Load Type in ASP.NET MVC

leave a comment

If you got this message you have missing web.config in Views directory.

You have this file in your development project – click on it in Visual Studio and set to Copy Local, so it will be copied when you click Publish.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

November 30th, 2009 at 5:39 pm

Visual Studio 2008 and Windows Service project and setup

leave a comment

Problem is that Visual Studio 2008 does not have Windows Service project and you can not add it and create a setup for this project.

To override this use manual approach:

1. Create your service class manually:

using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace WindowsService
{
    class WindowsService : ServiceBase
    {
        ///
        /// Public Constructor for WindowsService.
        /// - Put all of your Initialization code here.
        ///
        public WindowsService()
        {
            this.ServiceName = "My Windows Service";
            this.EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific

            //  type of event. Set to true if you need it, false otherwise.

            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;
        }

        ///
        /// The Main Thread: This is where your Service is Run.
        ///
        static void Main()
        {
            ServiceBase.Run(new WindowsService());
        }

        ///
        /// Dispose of objects that need it here.
        ///
        ///
Whether
        ///    or not disposing is going on.
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        ///
        /// OnStart(): Put startup code here
        ///  - Start threads, get inital data, etc.
        ///
        ///

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
        }

        ///
        /// OnStop(): Put your stop code here
        /// - Stop threads, set final data, etc.
        ///
        protected override void OnStop()
        {
            base.OnStop();
        }

        ///
        /// OnPause: Put your pause code here
        /// - Pause working threads, etc.
        ///
        protected override void OnPause()
        {
            base.OnPause();
        }

        ///
        /// OnContinue(): Put your continue code here
        /// - Un-pause working threads, etc.
        ///
        protected override void OnContinue()
        {
            base.OnContinue();
        }

        ///
        /// OnShutdown(): Called when the System is shutting down
        /// - Put code here when you need special handling
        ///   of code that deals with a system shutdown, such
        ///   as saving special data before shutdown.
        ///
        protected override void OnShutdown()
        {
            base.OnShutdown();
        }

        ///
        /// OnCustomCommand(): If you need to send a command to your
        ///   service without the need for Remoting or Sockets, use
        ///   this method to do custom methods.
        ///
        ///
Arbitrary Integer between 128 & 256
        protected override void OnCustomCommand(int command)
        {
            //  A custom command can be sent to a service by using this method:
            //#  int command = 128; //Some Arbitrary number between 128 & 256
            //#  ServiceController sc = new ServiceController("NameOfService");
            //#  sc.ExecuteCommand(command);

            base.OnCustomCommand(command);
        }

        ///
        /// OnPowerEvent(): Useful for detecting power status changes,
        ///   such as going into Suspend mode or Low Battery for laptops.
        ///
        ///
The Power Broadcast Status
        /// (BatteryLow, Suspend, etc.)
        protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
        {
            return base.OnPowerEvent(powerStatus);
        }

        ///
        /// OnSessionChange(): To handle a change event
        ///   from a Terminal Server session.
        ///   Useful if you need to determine
        ///   when a user logs in remotely or logs off,
        ///   or when someone logs into the console.
        ///
        ///
The Session Change
        /// Event that occured.
        protected override void OnSessionChange(
                  SessionChangeDescription changeDescription)
        {
            base.OnSessionChange(changeDescription);
        }
    }
}

2. Add installer class:

using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace WindowsService
{
    [RunInstaller(true)]
    public class WindowsServiceInstaller : Installer
    {
        ///
        /// Public Constructor for WindowsServiceInstaller.
        /// - Put all of your Initialization code here.
        ///
        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller =
                               new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //# Service Account Information
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceProcessInstaller.Username = null;
            serviceProcessInstaller.Password = null;

            //# Service Information
            serviceInstaller.DisplayName = "My New C# Windows Service";
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            //# This must be identical to the WindowsService.ServiceBase name
            //# set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "My Windows Service";

            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}

3. Use Framework 2.0 instalutil.exe to create Installation:

Install.bat

@ECHO OFF

REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%

echo Installing WindowsService...
echo ---------------------------------------------------
InstallUtil /i WindowsService.exe
echo ---------------------------------------------------
echo Done.

Uninstall.bat

@ECHO OFF

REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%

echo Installing WindowsService...
echo ---------------------------------------------------
InstallUtil /u WindowsService.exe
echo ---------------------------------------------------
echo Done.
VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

October 21st, 2009 at 2:19 pm

ArrayOfXElement not recognized by Silverlight 2.0

one comment

Last weekend I was working on a Silverlight 2.0 game that loads and saves scores to an external database. Database is accessed via web service which has two methods: GetScore and SaveScore. GetScore returns DataSet and SaveScore returns nothing.

Web service proxy is generated as usual – right click on the project node in VS2008, “Add Service Reference…”, enter url, proxy class is generated and the methods are accessible in the code. But when I tried to build the project an error occured: “The type or namespace name ‘ArrayOfXElement’ does not exist in the namespace” which means that ArrayOfXElement is unrecognized class for the compiler. Searching on the Google reveals that this happens when service method returns DataSet, so ArrayOfXElement is actually DataSet and DataSets are not supported in Silverlight 2.0.

A quick solution is to replace all ‘ArrayOfXElement’ words with ‘object’. Project would build that way but the data would have no meaning.

Another solution is to change the web service return type but this is not always editable by the client side developer.

Finally, workaround idea is to get DataSet schema and convert it to a class. How to do this?
1. Create a dummy WPF project.
2. Add web service reference to the WPF project. Return type is DataSet instead of ArrayOfXElement.
3. Write some code to call a web service methods that returns DataSet then extract xsd schema and save it to the disk. Build and run. Sample:
GameServiceClient client = new GameServiceClient();
DataSet ds = client.GetScore(1, “abc”, “”, DateTime.Now);
ds.WriteXmlSchema(@”C:\Temp\Score.xsd”);
4. So you have the xsd file. Now find ‘xsd.exe’ which is located in the same directory as ‘svcutil.exe’ (e.g. C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin). Run it with arguments:
xsd C:\Temp\Score.xsd /c
5. xsd tool generates Score.cs file which contains tables as classes and columns as properties. Include the generated file in the Silverlight project.
6. Replace all ‘ArrayOfXElement’ words with ‘NewDataSet’ or other class name, depends on the retrieved DataSet name and generated code.

Note that this is just an idea. So far the sample project builds fine but there is a problem with cross-domain security. Another story.

Url to the web service in this example:
http://www.silverlightclub.com/apps/GameService.asmx

References:
http://silverlight.net/forums/t/60518.aspx
http://blogs.msdn.com/suwatch/archive/2009/01/21/wcf-silverlight-exception-and-serialization.aspx

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)

Written by Avivo

March 21st, 2009 at 8:26 pm

Project for European parlament

leave a comment

After we created the best scenario for interactive Flash game for competition in knowledge about European Union, we got this interesting project from European parlament.

We developed the game, organized precontest and contest among Slovenian high school grades and best 5 grades got a main prize – free touristic trip to Strasbourgh.

We will publish the results on Monday – 9th February 2009.

Url to our game is: www.evrosola.si

Here are some screenshots of our game:

VN:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by Avivo

February 7th, 2009 at 3:49 pm