Tech blog

Solving problems

About
Contact

Archive for the ‘c#’ tag

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)

Saving high quality JPG in C# or ASP.NET

leave a comment

Just use this piece of code or read at this MSDN article:

private void VaryQualityLevel()
{
	// Get a bitmap.
	Bitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg");
	ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

	// Create an Encoder object based on the GUID
	// for the Quality parameter category.
	System.Drawing.Imaging.Encoder myEncoder =
	System.Drawing.Imaging.Encoder.Quality;

	// Create an EncoderParameters object.
	// An EncoderParameters object has an array of EncoderParameter
	// objects. In this case, there is only one
	// EncoderParameter object in the array.
	EncoderParameters myEncoderParameters = new EncoderParameters(1);

	EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
	myEncoderParameters.Param[0] = myEncoderParameter;
	bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters);

	myEncoderParameter = new EncoderParameter(myEncoder, 100L);
	myEncoderParameters.Param[0] = myEncoderParameter;
	bmp1.Save(@"c:\TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters);

	// Save the bitmap as a JPG file with zero quality level compression.
	myEncoderParameter = new EncoderParameter(myEncoder, 0L);
	myEncoderParameters.Param[0] = myEncoderParameter;
	bmp1.Save(@"c:\TestPhotoQualityZero.jpg", jgpEncoder, myEncoderParameters);

}

...

private ImageCodecInfo GetEncoder(ImageFormat format)
{
	ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

	foreach (ImageCodecInfo codec in codecs)
	{
	if (codec.FormatID == format.Guid)
	{
	return codec;
	}
	}
	return null;
}
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 13th, 2009 at 4:17 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

C# sizeof – Gets a size of a custom class programatically

leave a comment

In .NET, sizeof() works only for basic variable types, like int, double, etc. If you try to use sizeof() for a managed class then compiler reports error:

Cannot take the address of, get the size of, or declare a pointer to a managed type

Alternative to sizeof() would be System.Runtime.InteropServices.Marshal.SizeOf() but this one works with unmanaged types (not a native .NET class).

So far, a decent solution would be to serialize object into binary stream and get the stream size. Source code:

public static long SizeOf(object obj)
{
long size = 0;

try
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
BinaryFormatter objFormatter = new BinaryFormatter();
objFormatter.Serialize(stream, obj);
size = stream.Length;
}
catch (Exception ex)
{
}

return size;
}

A non-programatic alternative is to use .NET profiler to retrieve object size.

Reference: http://social.msdn.microsoft.com/forums/en-US/clr/thread/b871dee4-6eb5-4dca-be79-b9589a79f5e9/

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 5th, 2009 at 2:06 pm

Hosting ASP.NET MVC on IIS7 and “Could Not Load Type” error

one comment

  1. If you want to host ASP.NET MVC on IIS7 don’t forget to copy also MVC DLLs to bin directory when publishing.
    • If you have ASP.NET 3.5 SP1 installed on server copy only System.Web.Mvc
    • If you don’t have ASP.NET 3.5 SP1 installed on server copy
      System.Web.Mvc
      System.Web.Routing
      System.Web.Abstractions
  2. You need to copy also web.config that is under directory where your Views are – it is not included in your project by default so it will not be published. Copy this manually or include this web.config in your project and then 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

September 14th, 2009 at 4:15 pm