Posts tagged ‘.NET’

System.AccessViolationException: Attempted to read or write protected memory ?

A common error always pop up when you run your .NET Application just like the following :

Error Details:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The reasons and resolutions:

These are different solutions due to different case, Here I collect some of them which I have found:

0: First of all, telerik company has a solution for their products, maybe it is fit for your case:

so far we have found the following reasons for the exception:

    * configuration/installation problems of the framework, VS.NET and/or SourceSafe/SourceGear (usually the SourceSafe/SourceGear installation is corrupted). Restarting of VS, IIS or the machine does not help;
    * running 32-bit code which tries to call 64-bit one and vice versa (this appears on 64bit machines, i.e. 64-bit CPU, Windows or .NET 2.0 version).

SOLUTIONS
This error message is still being investigated and other solutions may exist. In case you are able to fix the problem in some other way than the described below, please let us know, so that we can update the article.

   1. Try creating a new project – you should be able to use the Telerik controls in that project.
   2. If you are still using the beta version of VS2005, update to the latest official version and try again.
   3. A webserver with multiple worker processes may cause this inconsistency. The problem should disappear once the number of worker processes is set to 1.
   4. Ensure that the VS.NET addin works in SourceSafe/SourceGear works. You can do that by checking files in and out of your repository (try checking out a page before dropping a control and see if it works). Try uninstalling all copies of VSS that you may have on your machine and install the latest version only.
   5. If you use the 64bit version of .Net2, then review this Microsoft support article on switching from .NET1.x 32bit to .NET2 64bit: http://support.microsoft.com/default.aspx?scid=kb;en-us;894435, more importantly the ASP.NET 2.0, 32-bit version section and setting the 64bit Web Service to Prohibited.
   6. Simply copy and paste the controls’ DLLs and XML files into the bin directory.
   7. If none of the above works, you may consider reinstalling the machine.

1: (for Oracle Exception) This happens sometime due to corrupt data in memory. To resolve it Please restart the application or restart the system.

2:  I found the reason: I had installed a program called “Netlimiter” on the test server (used for testing the app with limmited bandwidth). It was en error in a nsl dll from that program that caused my problem. After uninstalling the program it worked fine.

However, I do not know why I only got the error with .Net 2.0 and not with 1.1.

/Nicolai

3:
Issue Description:
– Getting following pop-up error when trying to drag and drop Microsoft Controls in Visual Studio 2005 design view

Resolution:

– There was something wrong with the registration of VS packages. We reset those and it resolved the issue.
– We ran the following command from the
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE>devenv.exe /ResetSkipPkgs

– We opened the existing project in Visual Studio 2005 and now we did not get the above error while dragging and dropping Microsoft and non-Microsoft Controls.

– Tried closing and opening up the project again and still no issues.

(will continue to find more if possible)

Open Visual Studio 2008 project file in Visual Studio 2005 ?

We know the Microsoft Visual Studio IDE Higher version can open the project which created in lower version by convert wizard steps. For example, whey you try to open a VS 2005 project in VS 2008, you will see a convert wizard windows firstly, it helps you convert old project to new project which can be opened in VS 2008.

But, Is it possible to open a Visual Studio 2008 project in Visual Studio 2005 ?

The answer is : Yes.

Of course we can not do it in the Visual Studio IDE directly. We need to do some works by manual.

Firstly, we need to know the higher version project doesn’t use higher version of VS studio’s features. Then it is possible to open the higher version of project in lower version of VS studio.

The solution is that we just need to change some information related Visual Studio Version such as version number.

For example:

1: .sln

    Microsoft Visual Studio Solution File, Format Version 10.00
    # Visual Studio 2008
    Project(”{F184B08F-C81C-45F6-A57F-5ABD9991F28F}”) = “ProjectConverter”,
    “ProjectConverter.vbproj”, “{B637ACFD-0AFC-4FBB-A8C0-602B5ABA62F0}”
    EndProject
    Project(”{54435603-DBB4-11D2-8724-00A0C9A8B90C}”) = “Setup”, “Setup\Setup.vdproj”,
    “{09667F41-0E35-4D40-A0A9-E71BA6740D93}”
    EndProject
    Global

    ….

    EndGlobal

2: .vbproj, .csproj, .vcproj

ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    Debug
AnyCPU
9.0.21022    2.0
{B637ACFD-0AFC-4FBB-A8C0-602B5ABA62F0}    WinExe

    ProjectConverter.My.MyApplication    ProjectConverter    ProjectConverter    512

    WindowsForms    v2.0    On    Binary

    ...

The above examples copied from This Article in Chinese.

Also, there is another More Professional Article and there are much more detail information (Visual Studio 2005/2008 Interoperability).

How to add a Uninstall option in Visual Studio Setup project without writing code

Using Visual Studio 2005/2008, you don’t need to write any code to add a uninstall option for a Setup project (Yes I know some people can write code to do it)

1) In the Setup Project –> File System windows –> Right Click “File System on Target machine” –> add a Special Folder, select System Folder;

2) Into this system folder Add a file. Browse for msiexec.exe from local System32 folder and add it. Override default properties of this file as follows:

Condition:=Not Installed (make sure you put ‘Not Installed’ exactly like that, same case and everything),
Permanent:=True,
System:=True,
Transitive:=True,
Vital:=False.

3) Create a new shortcut under the ‘Users Program Menu’, Set Target to the System Folder which you created in the step 1. and point it’s at the msiexec.exe. Rename the shortcut to ‘Uninstall Your Application’. Set the Arguments property to /x{space}[ProductCode].

5) Build the project, ignore warning about the fact that msiexec should be excluded, DONT exclude it or the setup project wont build.

The ‘Not Installed’ condition and Permananet:=True ensure that the msiexec.exe is only placed into the system folder as part of the install IF it doesn’t aready exist, and it is not removed on an uninstall – therefore it;s pretty safe to ignore that warning and just go for it.

(Based on the description from SlapHead)

Create SQL Server Database using C#

Here is a sample from codeproject :

private void CreateDatabase(DatabaseParam DBParam)
{
    System.Data.SqlClient.SqlConnection tmpConn;
    string sqlCreateDBQuery;
    tmpConn = new SqlConnection();
    tmpConn.ConnectionString = "SERVER = " + DBParam.ServerName +
                         "; DATABASE = master; User ID = sa; Pwd = sa";
    sqlCreateDBQuery = " CREATE DATABASE "
                       + DBParam.DatabaseName
                       + " ON PRIMARY "
                       + " (NAME = " + DBParam.DataFileName +", "
                       + " FILENAME = '" + DBParam.DataPathName +"', "
                       + " SIZE = 2MB,"
                       + " FILEGROWTH =" + DBParam.DataFileGrowth +") "
                       + " LOG ON (NAME =" + DBParam.LogFileName +", "
                       + " FILENAME = '" + DBParam.LogPathName + "', "
                       + " SIZE = 1MB, "
                       + " FILEGROWTH =" + DBParam.LogFileGrowth +") ";
     SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
     try
     {
         tmpConn.Open();
         MessageBox.Show(sqlCreateDBQuery);
         myCommand.ExecuteNonQuery();
         MessageBox.Show("Database has been created successfully!",
                           "Create Database", MessageBoxButtons.OK,
                                       MessageBoxIcon.Information);
      }
     catch (System.Exception ex)
     {
         MessageBox.Show(ex.ToString(), "Create Database",
                                     MessageBoxButtons.OK,
                              MessageBoxIcon.Information);
     }
     finally
     {
         tmpConn.Close();
     }
     return;
}

There are many others. Another sample from Microsoft :

using System;
using System.Data.SqlClient;

String str;
    SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

    str = "CREATE DATABASE MyDatabase ON PRIMARY " +
        "(NAME = MyDatabase_Data, " +
        "FILENAME = 'C:\\MyDatabaseData.mdf', " +
        "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
        "LOG ON (NAME = MyDatabase_Log, " +
        "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
        "SIZE = 1MB, " +
        "MAXSIZE = 5MB, " +
        "FILEGROWTH = 10%)";

    SqlCommand myCommand = new SqlCommand(str, myConn);
    try
    {
        myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception ex)
    {
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    finally
    {
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
    }

If you want to create a database that is similar to the SQL Server Model database, and you want the database in the default location, then change the str variable in the code, as in the following sample code:

str = "CREATE DATABASE MyDatabase"

Also, the 3rd sample is using Microsoft “SQLDMO.dll”:

(you can find the SQLDMO.dll in C:\Program Files\Microsoft SQL Server\80\Tools\Binn or download it from http://www.driverskit.com/dll/sqldmo.dll/3449.html
to add refference to a project , From project menu select “add refference” -> select the browse tab and select the dll file from the location and add to the project
)

public bool CreateDb(string serverName, string Uid, string Pwd, string dbName)
        {
            bool result = true;
            SQLDMO.SQLServer gSQLServerDMO = new SQLDMO.SQLServer();
            SQLDMO.Database nDatabase = new SQLDMO.Database();
            SQLDMO.DBFile nDBFileData = new SQLDMO.DBFile();
            SQLDMO.LogFile nLogFile = new SQLDMO.LogFile();

         
            try
            {
                gSQLServerDMO.LoginSecure = true;
                gSQLServerDMO.Connect(serverName, Uid, Pwd);

                nDatabase.Name = dbName;

                nDBFileData.Name = dbName;

                nDBFileData.PhysicalName = gSQLServerDMO.Registry.SQLDataRoot + "\\DATA\\" + dbName + "_Data.mdf";
              
                nDBFileData.PrimaryFile = true;

                nDBFileData.Size = 2;

                nDBFileData.FileGrowthType = SQLDMO.SQLDMO_GROWTH_TYPE.SQLDMOGrowth_MB;

                nDBFileData.FileGrowth = 1;

                //Add the DBFile object

                nDatabase.FileGroups.Item("PRIMARY").DBFiles.Add(nDBFileData);
               //

                nLogFile.Name = dbName + "Log";

                nLogFile.PhysicalName = gSQLServerDMO.Registry.SQLDataRoot + "\\DATA\\" + dbName + "_Log.ldf";
               
                nLogFile.Size = 2;

                nDatabase.TransactionLog.LogFiles.Add(nLogFile);

                gSQLServerDMO.Databases.Add(nDatabase);

                MessageBox.Show("Database Created Sucessfully);

                gSQLServerDMO.DisConnect();

            }

            catch (Exception SQLDBException)
            {

                MessageBox.Show(SQLDBException.Message);

                result = false;

            }

            finally
            {

            }
            return (result);
        }

              
Above 3rd sample from here

List enum item names using C#

Assume you have define an enum like :

public enum LanguageCollection : int
{
    English = 0,
    简体中文,
    Español,
    Tuurkish,
    Français
}

Is it possible to populate all enum item to a dropdownlist control without hard code each enum name ? The answer is Yes.

Here is sample code :

this.menuCBLanguage.Items.Clear();
for (int i = 0; i < Enum.GetNames(typeof(LanguageCollection)).Length; i++)
{
     this.menuCBLanguage.Items.Add(Enum.GetName(typeof(LanguageCollection), i));
}

Should I add the Visual Studio .suo and .user files to source control ?

.suo and .user file are two types of hidden user files in Visual Studio project.

.suo file which is a binary file. .user file is the project user file which is a text file.

You don’t need to add these 2 files to your source control (SCM) since they contain per-user settings and SUO (Solution User Options) records all of the options that you might associate with your solution so that each time you open it, it includes customizations that you have made.

What is .suo file in Visual Studio project ?

Copied explanation from Microsoft official site:

Solution Files (.sln and .suo)

Visual Studio uses two file types (.sln and .suo) to store settings specific to solutions. These files, known collectively as solution files, provide Solution Explorer with the information it needs to display a graphical interface for managing your files. They allow you to concentrate on your projects and final goals rather than on the environment itself each time you return to your development tasks.

.sln:   Visual Studio Solution

Organizes projects, project items and solution items into the solution by providing the environment with references to their locations on disk.

.suo  Solution User Options

Records all of the options that you might associate with your solution so that each time you open it, it includes customizations that you have made.

Content from here