How to compress JPEG image using C#

Here is a C# snippet which helps to compress JPEG image. Also displays how much size got reduced.

public static void CompressJpeg(string path, int quality)
{
    if (quality < 0 || quality > 100)
    {
        throw new
            ArgumentOutOfRangeException("Quality must be between 0 and 100.");
    }
    //Creating temp. file and
    string tempFile = Path.GetTempFileName();
    File.Copy(path, tempFile, true);
    using (var image = Image.FromFile(tempFile))
    {
        // Encoder parameter for image quality
        var qualityParam =
            new EncoderParameter(Encoder.Quality, quality);
        // Jpeg image codec
        var jpegCodec = ImageCodecInfo.GetImageEncoders()
            .Where(imageCodecInfo => imageCodecInfo.MimeType == "image/jpeg")
            .FirstOrDefault();
        var encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;
        //Save the compressed image.
        image.Save(path, jpegCodec, encoderParams);
        //Getting the file image sizes.
        var prevImageSize = new FileInfo(tempFile).Length;
        var nextImageSize = new FileInfo(path).Length;
        Console.WriteLine("Image compressed. Size saved :{0} bytes",
            prevImageSize - nextImageSize);
    }
    //Removing the temp. file.
    File.Delete(tempFile);
}
Posted in .Net, .Net 3.0 / 3.5, .Net 4.0 | Tagged , , , | 1 Comment

How to get Build Definitions and Build Details from TFS 2010

This snippet which will connect to TFS Server and get all running builds for all build definitions, using TFS Client API.

try
{
    var tfsName = "http://dotnetthoughts:8080/tfs/defaultcollection";
    var tfs = new TeamFoundationServer(tfsName, new UICredentialsProvider());
    tfs.EnsureAuthenticated();
    if (tfs.HasAuthenticated)
    {
        var bs = tfs.GetService(typeof(IBuildServer)) as IBuildServer;
        //Select all Build definitions
        var spec = bs.CreateBuildQueueSpec("*", "*");
        var buildResults = bs.QueryQueuedBuilds(spec);
        foreach (IQueuedBuild queuedBuild in buildResults.QueuedBuilds)
        {
            Console.WriteLine("Status :{0} - {1} - Requested by : {2} Controller :{3}",
                queuedBuild.Status, queuedBuild.BuildDefinition.Name,
                queuedBuild.RequestedBy, queuedBuild.BuildController.Name);
        }
    }
}
catch (Exception exception)
{
    MessageBox.Show(exception.Message);
    throw;
}

Please make sure you are adding of the following assemblies.

  1. Microsoft.TeamFoundation.dll
  2. Microsoft.TeamFoundation.Build.Client.dll
  3. Microsoft.TeamFoundation.Build.Common.dll
  4. Microsoft.TeamFoundation.dll

which will be available under – C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\ location.

Happy GREEN builds :)

Posted in .Net, .Net 4.0 | Tagged , , , , , | 2 Comments

Webcams in Silverlight 4.0

Microsoft Silverlight 4.0 supports Webcam and microphone access from Web Applications like Flash. This feature enables a number of scenarios, such as capturing and displaying images, uploading profile pictures to social networking applications etc. Here is code part, which will start the webcam, stop the webcam and captures the image.

Initialize the web cam

private CaptureSource _captureSource;
private VideoBrush _videoBrush;
private ImageBrush _imageBrush;

_captureSource = new CaptureSource();
_captureSource.CaptureImageCompleted += (o, e) =>
{
    _imageBrush = new ImageBrush();
    _imageBrush.ImageSource = e.Result;
    rectWebCamView.Fill = _imageBrush;
};
_captureSource.CaptureFailed += (o, e) =>
{
    MessageBox.Show(e.ErrorException.Message);
};

Start the web cam, the rectWebCamView is a Rectangle.

if (_captureSource.State != CaptureState.Started)
{
    _captureSource.VideoCaptureDevice =
        CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
    _videoBrush = new VideoBrush();
    _videoBrush.SetSource(_captureSource);
    rectWebCamView.Fill = _videoBrush;

    if (CaptureDeviceConfiguration.RequestDeviceAccess())
    {
        _captureSource.Start();
    }
}

The RequestDeviceAccess() method invokes a request dialog for accessing the webcame like this.

Request Access dialog

Request Access dialog

Note: The RequestAccess must be called in response to a user initiated event, such as a Button Click event.

Stop the web cam

_captureSource.Stop();

And finally the capture image.

if (_captureSource.State == CaptureState.Started)
{
    _captureSource.CaptureImageAsync();
}

The method will invoke CaptureImageCompleted event, and which will capture the image and display it in the rectangle. The XAML code contains only 3 buttons and one rectangle, so I am not posting the XAML code.

Happy programming :)

Posted in .Net, ASP.Net, Silverlight | Tagged , , , , | 1 Comment

Introduction to Code First development with Entity Framework

The Database First approach is interesting when the database already exists. You use Visual Studio and the Entity Framework Designer to generate the C# and VB.NET classes which reflect the existing database model. You may then change relations using the Designer (or the XML mapping files) later to further optimize the model. The priority is the database – the code and the model are only secondary. When your priority is the code and you want to begin from scratch without any existing schema or XML mapping files using source code, then the approach is called CodeFirst. Code-First enables an easy development workflow. It enables you to:

  1. Develop without opening the designer or mapping in XML files.
  2. Define model objects by simply writing POCO(Plain old CLR object) with no base classes required
  3. Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything

You can download the latest version of code first from this url : ADO.NET Entity Framework 4.1 – Update 1.

You can also install via NuGet.

install-package entityframework

Quick CRUD example with EF Code first.

First we will create the model classes.

public class Task
{
    public int TaskId { get; set; }
    public string TaskDescription { get; set; }
    public DateTime TaskDate { get; set; }
    public short TaskPriority { get; set; }
    public bool TaskIsDone { get; set; }
}

Now we need to create a Context for this. Context is required to use the POCO classes for DataAccess. It can be implemented by deriving it from DbContext class. The DbContext class is available under System.Data.Entity namespace.

public class TaskContext : DbContext
{
    public DbSet Tasks { get; set; }
}

We are done. :) Now we can use this class for communicating to Database.

Inserting records to Database.

using (TaskContext taskContext = new TaskContext())
{
    taskContext.Tasks.Add(new Task()
    {
        TaskDate = DateTime.Today,
        TaskDescription = "Create a blog post",
        TaskIsDone = false,
        TaskPriority = 1
    });
    if (taskContext.SaveChanges() != 0)
    {
        Console.WriteLine("Task added.");
    }
}

Updating records, updating the first task from Tasks, if the Task date is today.

using (TaskContext taskContext = new TaskContext())
{
    var currentTask = taskContext.Tasks.Where
		(task => task.TaskDate == DateTime.Today).FirstOrDefault();
	currentTask.TaskIsDone = true;
    if (taskContext.SaveChanges() != 0)
    {
        Console.WriteLine("Task updated.");
    }
}

Removing records, removing first task from Tasks, if the Task is completed.

using (TaskContext taskContext = new TaskContext())
{
    var completedTask = taskContext.Tasks.Where
        (task => task.TaskIsDone == true).FirstOrDefault();
    taskContext.Tasks.Attach(completedTask);
    taskContext.Tasks.Remove(completedTask);
    if (taskContext.SaveChanges() != 0)
    {
        Console.WriteLine("Task Deleted.");
    }
}

And retriving records, retriving all the tasks.

using (TaskContext taskContext = new TaskContext())
{
	var tasks = taskContext.Tasks.Where
		(task => task.TaskDate == DateTime.Today);
	tasks.ToList().ForEach(task =>
        Console.WriteLine("Task : {0} IsCompleted : {1}",
        task.TaskDescription, task.TaskIsDone));
}

It is very easy right? Another interesting question is where this data is getting stored? Because we didn’t specified any Database, or Connection string. By default the database will be created on local instance of SQLEXPRESS (localhost\SqlExpress). The database is named after the fully qualified name of your derived context, in our case that it will be “EFCodeFirst.TaskContext”. You can control this by providing connection string or by setting DefaultConnectionFactory.

You can provide connectionstring either in App.Config / Web.Config file or in code.

If you are providing the connection string in config, file the name of the connection string element should be same as Context class name. Like this

<connectionStrings>
  <add name="TaskContext"
  connectionString="Server=.\SqlExpress; Integrated Security=SSPI; Database=TaskDb;"
  providerName="System.Data.SqlClient"/>
</connectionStrings>

And if you want to use your own connection string name, you can do this using CreateConnection() method of the DefaultConnectionFactory class. You can also specify the connection string. You need to provide this information before creating the instance of task context.

Database.DefaultConnectionFactory.CreateConnection("TaskDbConnection");
using (TaskContext taskContext = new TaskContext())
{
	//Code.
}

Entity Framework also supports various databases also, like SQL CE, MySql etc. This can be achive either using the provider name is the config settings or by using DefaultConnectionFactory propery of Database class. Following statement helps to use SqlCe database instead of Sql Server

Database.DefaultConnectionFactory =
	new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
using (TaskContext taskContext = new TaskContext())
{
	//Code.
}

Model validations also supported by entity framework. I may cover them in another post.

Happy 2012 :)

Posted in .Net, .Net 4.0, ASP.Net, ASP.Net MVC, SQL Server, WPF | Tagged , , , , , , | 4 Comments

How to configure a WCF service to use Port Sharing

Windows Communication Foundation (WCF) provides a new TCP-based network protocol (net.tcp://) for high-performance communication. WCF also introduces a new system component, the Net.TCP Port Sharing Service that enables net.tcp ports to be shared across multiple user processes. Yesterday I got a chance to work on the same, I thought it was complex. But it is very simple in WCF, only we need to modify the PortSharingEnabled property of the NetTcpBinding. Like the following

string baseAddress = "net.tcp://localhost:8080/MyService1";
Uri[] addresses = { new Uri(baseAddress) };
using (var serviceHost = new ServiceHost(typeof(Service), addresses))
{
    var nettcpbinding = new NetTcpBinding();
    nettcpbinding.PortSharingEnabled = true;
    serviceHost.AddServiceEndpoint(typeof(IService),
        nettcpbinding, "IService");

    serviceHost.Open();
    Console.ReadKey(true);
    serviceHost.Close();
}

Also even if set the PortSharingEnabled to true, we also require to start the Net.Tcp port sharing service from the control panel. By default it will be disabled. If the service not started, and your tried to listen two services in same port number, you may get an exception like this AddressAlreadyInUseException – There is already a listener on IP endpoint 0.0.0.0:8080. This could happen if there is another application already listening on this endpoint or if you have multiple service endpoints in your service host with the same IP endpoint but with incompatible binding configurations.

Net.Tcp port sharing service in Services console.

Net.Tcp port sharing service in Services console.

You can also set the property via App.Config file also.

<bindings>
    <netTcpBinding>
        <binding portSharingEnabled="true" />
    </netTcpBinding>
</bindings>

Now you are able to run two services with same port number, in this port number 8080.

Happy Programming :)

Posted in .Net, .Net 3.0 / 3.5, .Net 4.0, WCF | Tagged , , , , , | 1 Comment