Tech blog

Solving problems

About
Contact

Archive for the ‘Programming Techniques’ Category

Random sorting using LINQ

leave a comment

Random Sort

Consider the below Person class:

public class Person
{
    public int Id
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }
}

This is how you can randomly sort the List object:

List list = new List();

list.Add(new Person { Id = 1, Name = "Davolio Nancy" });
list.Add(new Person { Id = 2, Name = "Fuller Andrew" });
list.Add(new Person { Id = 3, Name = "Leverling Janet" });
list.Add(new Person { Id = 4, Name = "Peacock Margaret" });
list.Add(new Person { Id = 5, Name = "Buchanan Steven" });
list.Add(new Person { Id = 6, Name = "Suyama Michael" });
list.Add(new Person { Id = 7, Name = "King Robert" });
list.Add(new Person { Id = 8, Name = "Callahan Laura" });
list.Add(new Person { Id = 9, Name = "Dodsworth Anne" });

list = list.OrderBy(x => Guid.NewGuid()).ToList();

Or you can use this approach:

Random random = new Random();
list = (from x in list
       let r = random.Next()
       orderby r
       select x).ToList();
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

July 15th, 2010 at 10:07 am

ASP .NET MVC: How to render View into a string

leave a comment

Sometimes a developer needs to render a View as string. Practical scenario would be to create an obvious View and send it via e-mail instead displaying it in browser. Here is a simple way to extract content from a rendered View:

Implement RenderViewToString method

public class HomeController : Controller
{
  protected string RenderViewToString(string viewName, object model)
  {
    string result = null;
    var view = ViewEngines.Engines.FindView(this.ControllerContext, viewName, null).View;
    if (view != null)
    {
      var sb = new StringBuilder();
      using (var writer = new StringWriter(sb))
      {
        var viewContext = new ViewContext(this.ControllerContext, view,
              new ViewDataDictionary(model), new TempDataDictionary(), writer);
        view.Render(viewContext, writer);
        writer.Flush();
      }
      result = sb.ToString();
    }
    return result;
  }
}

Call it in your action method

//Somewhere in HomeController...
public ActionResult Index()
{
    //Render a View named 'Email' to string variable named 'content'
    //Second parameter (model) can be null
    string content = RenderViewToString("Email", new EmailModel());

    //Do something with the content, e.g. send it to e-mail

    //This does nothing to do with rendered string
    return View();
}
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

March 31st, 2010 at 10:38 pm

System.Web.HttpException: Request is not available in this context

leave a comment

Use HttpContext.Current.Request instead of Request

i.e.

HttpContext.Current.Request.UserHostAddress

not

Request.UserHostAddress

VN:F [1.9.3_1094]
Rating: 2.5/5 (2 votes cast)
VN:F [1.9.3_1094]
Rating: +2 (from 2 votes)

WriteableBitmap does not Render()?!

leave a comment

We spent quite some time working on a Silverlight deep zoom application. Like in other projects, a problem appears sooner or later. This time with the WriteableBitmap that couldn’t take screenshot of a basic shape.

//Simple ellipse (green circle)
Ellipse element = new Ellipse()
{
	Width = 50,
	Height = 50,
	Fill = new SolidColorBrush(Colors.Green)
};

//WriteableBitmap current = new WriteableBitmap(50, 50);
//current.Render(element, new MatrixTransform()); //DOES NOT WORK!!! - renders blank transparent image

//But with the constructor works fine
WriteableBitmap bitmap = new WriteableBitmap(element, new MatrixTransform());

//Ellipse captured as raster image painted on a panel's background
Grid grid = new Grid()
{
	Width = 50,
	Height = 50,
	Background = new ImageBrush() { ImageSource = bitmap }
};

Summary for the Render() method says: “Renders an element within the bitmap.”
Render() method didn’t output required result but using constructor instead of the method did do the job. Input parameters were the same.

Maybe Render() method do something else, maybe it is a problem with Vista 64-bit…

Anyway, WriteableBitmap is very useful in Silverlight 3, luckily it works.

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

December 9th, 2009 at 5:36 pm

Silverlight: inherit a generic class from UserControl

leave a comment

Note! This blog post is just an idea than well tested solution, more a review that detailed description.
In Silverlight UserControl and Page classes are usually used with xaml. Root tags in xaml define the type, like so:

xaml
<UserControl x:Class="MyView">
...
</UserControl>

code-behind
namespace MyNamespace
{
  class MyView : UserControl
}

Sometimes, developers want to extend UserControl, i.e. as View by MVVM pattern.

xaml
<v:ViewBase x:Class="MyNamespace.MyView" xmlns:v="clr-namespace:MyNamespace">
...
</v:ViewBase>

code-behind
namespace MyNamespace
{
  class MyView : ViewBase /* ViewBase is a custom class */
}

Step further, every View should have it’s specialized model (ViewModel), thus base class could integrate a Model property. To avoid casting one should use generics, like ViewBase<MyViewModel>.

xaml
<!-- There's a problem, generics cannot be written in xaml. -->

code-behind
namespace MyNamespace
{
  class MyView : ViewBase<MyViewModel> /* ViewBase is a custom class */
}

Generics cannot be written directly in xaml? There is a workaround:
1. Use a wrapper, described here
2. Create a new non-generic class, like in this sample:

xaml
<v:MyViewBase x:Class="MyNamespace.MyView" xmlns:v="clr-namespace:MyNamespace">
...
</v:MyViewBase>

code-behind
namespace MyNamespace
{
  class MyView : MyViewBase
}

public abstract class MyViewBase : ViewBase<MyViewModel>
{
  /* non-generic class */
}

Appendix: ViewBase<TViewModel> class

public abstract class ViewBase<TViewModel> : UserControl, INotifyPropertyChanged where TViewModel : ViewModelBase, new()
{
	private TViewModel model;
	public TViewModel Model
	{
		get
		{
			if (this.model == null)
			{
				this.model = new TViewModel();
				base.DataContext = this.model;
			}
			return this.model;
		}
		set
		{
			if (this.model != value)
			{
				this.model = value;
				base.DataContext = this.model;
				OnPropertyChanged("Model");
			}
		}
	}
}

References:

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

November 30th, 2009 at 6:57 pm

Sequence number generator in DOS prompt from Command window

leave a comment

FOR /L %variable IN (start,step,end) DO command [command-parameters] The set is a sequence of numbers from start to end, by step amount. So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would generate the sequence (5 4 3 2 1)

Example:
FOR /L %i IN (1,1,5) DO @echo %i

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 25th, 2009 at 8:55 pm

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

Serializing object, write or log all object fields into string, object ToString()

leave a comment

Use this universal mini snippet to log your objects as serialized strings:

public static string SerializeToString(T obj)
{
	StringWriter sw = new StringWriter();
	XmlSerializer serializer = new XmlSerializer(typeof(T));
	serializer.Serialize(sw, obj);
	return sw.ToString();
}

If you have problems when doing Serialization use this simple function:

public static string ObjectToString(object obj)
{
	Type type = obj.GetType();
	PropertyInfo[] props = type.GetProperties();
	StringBuilder sb = new StringBuilder();
	foreach (var prop in props)
	{
		sb.Append(prop.Name);
		sb.Append("=");
		sb.Append(prop.GetValue(obj, null));
		sb.Append(Environment.NewLine);
	}
	return sb.ToString();
}
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 30th, 2009 at 11:28 am

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

The custom tool ‘MSLinqToSQLGenerator’ failed. Could not retrieve the current project.

leave a comment

To correct this, open up the Visual Studio 2008 command prompt (or any command prompt and navigate to the location of the VS exe ‘devenv.exe’) and type the following command:

devenv /ResetSkipPkgs

Then open your LinqToSql file(s) (*.dbml) and save to trigger the code generator tool.  After that, you should hopefully be up and running once more.

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 4th, 2009 at 3:30 pm