CodeCopy

November 27, 2009

Get Highres Thumbnail

Filed under: c# — mazzoo @ 00:11

public Image GetThumbnail(FileInfo from, Size size)
      {
          try
          {
              Image image = Bitmap.FromFile(from.ToString());

              int width = size.Width;
              int height = size.Height;

              if (image.Width > image.Height)
                  height = width * image.Height / image.Width;
              else
                  width = height * image.Width / image.Height;

              if (width > size.Width)
              {
                  width = size.Width;
                  height = width * image.Height / image.Width;
              }
              if (height > size.Height)
              {
                  height = size.Height;
                  width = height * image.Width / image.Height;
              }

              Image returnImage = new Bitmap(size.Width, size.Height);

              Graphics graphics = Graphics.FromImage(returnImage);
              graphics.SmoothingMode = SmoothingMode.HighQuality;
              graphics.CompositingQuality = CompositingQuality.HighQuality;
              graphics.InterpolationMode = InterpolationMode.High;

              graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, returnImage.Width, returnImage.Height);

              graphics.DrawImage(image, new Rectangle((size.Width – width) / 2, (size.Height – height) / 2, width, height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

              return returnImage;
          }
          catch (Exception exception)
          {
          }

          return null;
      }

 

 

To save it, just use image.save(…); with the result

November 5, 2009

How to remove objects from generic List by property value

Filed under: c# — sterndorff @ 23:59
Tags: , ,

Having two generic lists of type List<MyClass>, how do I remove from List1 all the instances of List2, matching a property?

This is the setup. I have a class:

public class MyClass
{
    public int MyValue { get; set; }
    public int MyOtherValue { get; set; }
}

And two lists:

List<MyClass> list1 = new List<MyClass>();
list1.Add(new MyClass() { MyValue = 1, MyOtherValue = 10 });
list1.Add(new MyClass() { MyValue = 2, MyOtherValue = 20 });
list1.Add(new MyClass() { MyValue = 3, MyOtherValue = 30 });
list1.Add(new MyClass() { MyValue = 4, MyOtherValue = 40 });

List<MyClass> list2 = new List<MyClass>();
list2.Add(new MyClass() { MyValue = 2, MyOtherValue = 50 });
list2.Add(new MyClass() { MyValue = 3, MyOtherValue = 60 });

I want to remove all list2 instances from list1 matching on MyValue property.

(more…)

October 20, 2009

.NET 4.0 Argument Overloading Galore

Filed under: c# — mazzoo @ 21:45

Tired of maintaining millions of manically malicious misplaced Method overloads ?

Then you must go 4.0 !

To make a simple constructor overload with and without parameters like:

public Constructor() : this( null ) { .. }

public Constructor(string str ) { .. }

Simply write:

public Constructor( string str = null ) {.. }

Much easier to read and maintain, brilliant :)

 

When calling constructors you historically have had to choose the less of two evils. Either call:

new Class( unknowParameter1, i, valueFromNowhere );

Which ensured that all wanted parameters where specified, but is impossible to read. Or the more readable, but less secure:

new Class(){ Name = unknownParameter, Age = i, FavoriteColor = valueFromNowhere };

Now you can have both:

new Class(Name: unknownParameter, Age: i, FavoriteColor: valueFromNowhere };

Again brilliant !

October 14, 2009

3 Groovy Shortcuts in VS

Filed under: c# — mazzoo @ 11:55

Add Using statements in Visual Studio

Instead of guessing which using statement to use, just Write the class you want, and hit Control + .(DOT). Then a menu will appear with the possible usings. When selected, the statement is automatically added to the file. 

Jump to definition

To jump to a definition ( of a class, method, attribute or what ever ) just hit F12. To go the other way, hit Shift + F12. ( This will result in a list of options )

Go to solution explorer

To move focus to the solution explorer use Ctrl + W + S.

October 13, 2009

WCF selfhosting helper

Filed under: c#, wpf — sterndorff @ 16:28
Tags: ,

A simple wrapper for hosting wcf services that works with both service references and web references.

WcfServiceHelper.Instance.StartService<MyService, IMyService>(new ServerConf());

More can be done in terms of configuration and a StopService method is missing. That is left for the reader (or untill I need it in my app).

(more…)

Selfhosting WCF on win2008

Filed under: c#, wcf — sterndorff @ 13:41
Tags: ,

If you host a WCF service as a non-administrator user on Windows 2008 (and Vista) you may get this error even if you are member of the admin groups:

HTTP could not register URL http://+:8000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details)

Solution: Log in as administrator and fire:

netsh http add urlacl url=http://+:8000/ user=DOMAIN\UserName

October 7, 2009

Rotate Zune HD screen to landscape

Filed under: c# — mazzoo @ 22:25
Tags: ,

When developing applications for the Zune HD, you might need to be able to rotate your display to landscape mode. To achieve this easily just make a Pre and Post Draw action ( BeginDraw and EndDraw ), where you manipulate the Viewport. This way you can develop the entire program in horizotal and then rotate it afterwards.

public class LandscapeZuneGame : Game
{
   private RenderTarget2D renderTarget;
   private SpriteBatch spriteBatch;

   public LandscapeZuneGame()
   {
      new GraphicsDeviceManager(this)
      {
         PreferredBackBufferWidth = 480,
         PreferredBackBufferHeight = 272
      };

      IsMouseVisible = true;
   }

   protected override void LoadContent()
   {
      renderTarget = new RenderTarget2D(GraphicsDevice, 480, 272, 1, SurfaceFormat.Color);
      spriteBatch = new SpriteBatch(GraphicsDevice);
      base.LoadContent();
   }

   // override BeginDraw so we can set the render target and Viewport before
   // any game drawing occurs.
   protected override bool BeginDraw()
   {
      if (base.BeginDraw())
      {
         GraphicsDevice.SetRenderTarget(0, renderTarget);
         GraphicsDevice.Viewport = new Viewport
         {
            X = 0,
            Y = 0,
            Width = 480,
            Height = 272,
            MinDepth = GraphicsDevice.Viewport.MinDepth,
            MaxDepth = GraphicsDevice.Viewport.MaxDepth
         };
         return true;
      }
      return false;
   }

   // override EndDraw to handle unsetting the render target, resetting the Viewport,
   // and drawing the render target's contents to the screen
   protected override void EndDraw()
   {
      GraphicsDevice.SetRenderTarget(0, null);
      GraphicsDevice.Viewport = new Viewport
      {
         X = 0,
         Y = 0,
         Width = 272,
         Height = 480,
         MinDepth = GraphicsDevice.Viewport.MinDepth,
         MaxDepth = GraphicsDevice.Viewport.MaxDepth
      };

      GraphicsDevice.Clear(Color.Black);
      spriteBatch.Begin();
      spriteBatch.Draw(
         renderTarget.GetTexture(),
         new Vector2(136f, 240f),
         null,
         Color.White,
         MathHelper.PiOver2,
         new Vector2(240f, 136f),
         1f,
         SpriteEffects.None,
         0);

      spriteBatch.End();
      base.EndDraw();
   }
}

Thanks to Nick Gravelyn for the great and easy solution

October 6, 2009

WPF Databinding Enum with nice descriptions

Filed under: c#, wpf — sterndorff @ 17:28
Tags: , , ,

I have an Enum that I want to databind to a wpf drop down box. But I want to represent the enum with some nice descriptions instead of Enum.ToString().

1) The enum with the nice descriptions: MyEnum.cs

    public enum MyEnum
    {
        [Description("Default value")] // Default value if enum is nullable and used in databinding
        DefaultValue,
        [Description("Value1 description")]
        Value1,
        [Description("Value2 description")]
        Value2
    }

(more…)

October 4, 2009

Method with a variable number of parameters

Filed under: c# — mazzoo @ 21:44
Tags: ,

When you need to create a method that handles an undefined number of parameters, one way to define it is by using an Array or list. Like this:

private void Method( string[] arguments )
{
    //...
}

This, however, have a semantic inconvenience when called:

Method( new string[] {  “a”, “b”, “c” };

To overcome this, use params before the string[] identifier, like this

private void Method( params string[] arguments )
{
    //...
}

Now you can call the Method a bit cleaner, making your code more readable:

Method(“a”, ”b”, ”c”);

October 1, 2009

mssql creating index on view

Filed under: SQL — sterndorff @ 09:50
Tags: , ,

You have a fulltext index on a view. If you edit one of the tables that is in the view, Sql Server Manager will drop the index. When recreating the view you might get the error:

Cannot create index on view ‘vw_TestView’ because the view is not schema bound. (Microsoft SQL Server, Error: 1939)

Solution: You have to drop the view and recreate with schemabound

CREATE VIEW [dbo].[T_IC_USERS_1] WITH SCHEMABINDING
AS
SELECT U.APP_ID,U.CREATED_BY,U.CREATED_TIME,U.LOWERED_USER_NAME
  FROM   dbo.T_IC_USERS AS U
  WHERE  (IS_DELETED = '0')
GO
Next Page »

Blog at WordPress.com.