Show Image using byte array in WPF

Convert your image in to byte array
private byte[] GetImageAsByteArray(string imageName)
{
var streamResourceInfo =
Application.GetResourceStream(new Uri("YourProjectNameSpace;component/ImageFolderName/"+imageName)",
UriKind.Relative));
byte[] image = {};
if (streamResourceInfo != null)
{
var length = streamResourceInfo.Stream.Length;
image = new byte[length];
streamResourceInfo.Stream.Read(image, 0, (int)length);
}
return image;
}

Sample Usage
var yourViewModel = new ViewModel();
yourViewModel.Image=GetImageAsByteArray("jemi.jpg");

Bind the property to the image control

<Image Source=”{Binding Image}”></Image>

How Layout Process works in WPF?

Before you design the layout you need to understand what’s going behind the scenes when you create layouts in your applications. If you have knowledge about the layout process, you know what happens with your elements and you can build really great layouts.

The Layout process is two step process. It consists of the steps Measure andArrange . In the first step, the Measure step elements calculate their desired size.That means each element calculate their own size.To do this an element calls the Measure method in each direct child.After this , the DesiredSize property of the child is set. The parent element can access this DesiredSize and calculate it’s own desired size.The whole process walks down the element tree so it starts at the parent element,which calls measure on each direct child and each direct child again calls Measure on its direct children.
In the second step,the Arrange step,elements arrange their children. They do this by calling Arrange method on each direct child.The Arrange method takes a position and a final size.That means child knows the position for render and size as well.After the two process rendering occurs.

Theil’s Inequality Algorithm using C#

TheilsInequality

public class TheilInEqualityAlgorithm
{
private readonly int _holdOutPeriod;
private readonly IEnumerable _actualAndPredictedValues;
public TheilInEqualityAlgorithm(int holdOutPeriod, IEnumerable actualAndPredictedValues)
{
_holdOutPeriod = holdOutPeriod;
_actualAndPredictedValues = actualAndPredictedValues;
}
private double CalculateRootMeanSquareDeviation()
{
double sum = 0;
foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues)
{
double difference = actualAndPredictedValue.Actual - actualAndPredictedValue.Predicted;
double squareOfdifference = Math.Pow(difference, 2);
sum = sum + squareOfdifference;
}

double rootMeanSquareDeviation = Math.Sqrt(sum / _holdOutPeriod);
return rootMeanSquareDeviation;
}
public Dictionary<string,double> CalculateTheilInEquality()
{
var results=new Dictionary<string, double>();
double calculatedRootMeanSquareDeviation = CalculateRootMeanSquareDeviation();
results.Add("RMSD",calculatedRootMeanSquareDeviation);
double actualSquareSum = 0;
double predictedSquareSum = 0;
foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues)
{
double actualSquare = Math.Pow(actualAndPredictedValue.Actual, 2);
double predictedSquare = Math.Pow(actualAndPredictedValue.Predicted, 2);
actualSquareSum = actualSquareSum + actualSquare;
predictedSquareSum = predictedSquareSum + predictedSquare;
}
double sqrtOfActualSum = Math.Sqrt(actualSquareSum / _holdOutPeriod);
double sqrtOfPredictedSum = Math.Sqrt(predictedSquareSum / _holdOutPeriod);
double theilInEquality = (calculatedRootMeanSquareDeviation) / (sqrtOfActualSum + sqrtOfPredictedSum);
results.Add("TheilInEquality", theilInEquality);
return results;
}
}
public class ActualAndPredictedValue
{
public double Actual { get; set; }
public double Predicted { get; set; }
}

Pass actual and predicted values for the periods

var actualPredictedCollection = new List
{
new ActualAndPredictedValue
{
Actual =-659505.150000,
Predicted =-900587.246911
}};
var results = new TheilInEqualityAlgorithm(12,actualPredictedCollection).CalculateTheilInEquality();
double theilInEquality=results[“TheilInEquality”];
Enjoy coding…

Change Telerik GridViewCellColor based on value

You can change Gridview cell color based on a value by using CellStyleSelector in GridViewDataColumn.
First you have to add a class by inheriting StyleSelector and override SelectStyle method
public class MyStyle:StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
if(item is Student)
{
var objEntity = item as Student;
if (objEntity.Mark > 60)
{
return Green;
}

}
return null;
}
public Style Green { get; set; }
}
Add a Grid Resource

<Grid>
<Grid.Resources>
<my:MyStyle x:Key="myStyle">
<my:MyStyle.Yellow>
<Style TargetType="telerik:GridViewCell">
<Setter Property="Background" Value="Green" />

</Style>
</my:MyStyle.Yellow>
</my:MyStyle>
</Grid.Resources>

</Grid>

Apply the style to GridViewDataColumn CellStyleSelector Attribute

<telerik:GridViewDataColumn DataMemberBinding="{Binding Mark}" CellStyleSelector="{StaticResource myStyle}">
</telerik:GridViewDataColumn>

Happy coding…

How to Catch Exceptions thrown by a WCF service In Client

You can easily get the server side Unhandled exceptions thrown by a WCF service in Client by using FaultException

Set includeExceptionDetailInFaults to true in your service behaviours

<serviceBehaviors>
<behavior name=””>
<serviceMetadata httpGetEnabled=”false” />
<serviceDebug includeExceptionDetailInFaults=”true” />
</behavior>
</serviceBehaviors>

and then in client side you can catch exceptions like below
try
{
//your service call
}
catch (FaultException ex)
{
string msg = "FaultException: " + ex.Message;
MessageFault fault = ex.CreateMessageFault();
if (fault.HasDetail)
{
System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
if (reader.Name == "ExceptionDetail")
{
var detail = fault.GetDetail<Exception>();
msg += "\n\nStack Trace: " + detail.StackTrace;
}
}
//TraceService.Trace(msg);
}

Enjoy Programming…

Insert,Update,Delete,Select using StoredProcedure Without EDMX in EntityFramework

In this article I am going to explain How to execute stored Procedure without EntityFramework EDMX.

Here I am using EntityFramework 5.0.0.0 (Install from here) and for my sample project I am using a simple Department table like below

1

Put your connection string in config file like below

<connectionStrings>

<add name="DbConnectionContext" connectionString="Data Source=JAMEELM\SQL2012DEV; Initial Catalog=jSchool; Integrated Security=True; MultipleActiveResultSets=True;Pooling=False;" providerName="System.Data.SqlClient" />

</connectionStrings>

You no need to specify metadata in connection string like EDMX.
Create a new class named InitializeDbContext by inherting DbContext class. In this class I have written five method for Insert,Update,Delete,Select and select By id operations.For every operation we can use same ExecuteStoreQuery method.This method will handle everything related to CRUD operations
Source Code : InitializeDbContext class

using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;

namespace EFSP.Manual.Demo
{
public class InitializeDbContext : DbContext where T : class
{
public InitializeDbContext()
: base("name=DbConnectionContext")
{
Database.SetInitializer<InitializeDbContext>(null);
}

public DbSet CurrentDbset { get; set; }
public T AddorUpdate(string procedureName, params object[] parameters)
{
T returnId =
((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery(procedureName, parameters).
SingleOrDefault();
return returnId;
}
public List Get(string procedureName, params object[] parameters)
{
var returnId =
((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery(procedureName, parameters).ToList();
return returnId;
}
public T GetById(string procedureName, params object[] parameters)
{
var returnId =
((IObjectContextAdapter) this).ObjectContext.ExecuteStoreQuery(procedureName, parameters).FirstOrDefault();
return returnId;
}
public T Delete(string procedureName, params object[] parameters)
{
var returnId =
((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery(procedureName, parameters).SingleOrDefault();
return returnId;
}
}
}


Add a new class named DepartmentModel for mapping table to complex type
Source Code : DepartmentModel class

using System.ComponentModel.DataAnnotations.Schema;

namespace EFSP.Manual.Demo
{
[Table("Department")]
public class DepartmentModel
{
public long Id { get; set; }
public string Department { get; set; }
}
}


Add a new class named ScopeIdentity for mapping Insert,Update,Delete identity column
Source Code : ScopeIdentity

namespace EFSP.Manual.Demo
{
public class ScopeIdentity
{
public decimal Id { get; set; }
}
}

Add one more class DepartmentRepository for our Business functionalities
Source Code : DepartmentRepository

using System.Collections.Generic;
using System.Data.SqlClient;

namespace EFSP.Manual.Demo
{
public class DepartmentRepository
{
public List GetDepartments()
{
using (var dbContext = new InitializeDbContext())
{
List deparment = dbContext.Get(StoredProcedure.GetDepartment);
return deparment;
}

}
public DepartmentModel GetDepartmentById(long id)
{
using (var dbContext = new InitializeDbContext())
{
object[] parameters =
{
new SqlParameter("@Id", id),
};
DepartmentModel deparment = dbContext.GetById(StoredProcedure.GetDepartmentById,parameters);
return deparment;
}

}
public ScopeIdentity InsertDepartment(DepartmentModel departmentModel)
{
using (var dbContext = new InitializeDbContext())
{
object[] parameters =
{
new SqlParameter("@Department", departmentModel.Department)
};
ScopeIdentity scopeIdentity = dbContext.AddorUpdate(StoredProcedure.InsertDepartment, parameters);
return scopeIdentity;
}
}
public ScopeIdentity UpdateDepartment(DepartmentModel departmentModel)
{
using (var dbContext = new InitializeDbContext())
{
object[] parameters =
{
new SqlParameter("@Id", departmentModel.Id),
new SqlParameter("@Department", departmentModel.Department)
};
ScopeIdentity scopeIdentity = dbContext.AddorUpdate(StoredProcedure.UpdateDepartment, parameters);
return scopeIdentity;
}
}
public ScopeIdentity DeleteDepartment(int id)
{
using (var dbContext = new InitializeDbContext())
{
object[] parameters =
{
new SqlParameter("@Id", id),
};
ScopeIdentity scopeIdentity = dbContext.Delete(StoredProcedure.DeleteDepartment, parameters);
return scopeIdentity;
}
}
}
}


Stored Procedures

namespace EFSP.Manual.Demo
{
public class StoredProcedure
{
public const string GetDepartment = "Get_Department";
//if any parameters please specify it with procedure name like below.You can pass multiple parameters by comma
public const string GetDepartmentById = "Get_Department_Id @Id";
public const string InsertDepartment = "Insert_Department @Department";
public const string UpdateDepartment = "Update_Department @Id,@Department";
public const string DeleteDepartment = "Delete_Department @Id";
}
}

Calling methods

var departmentRepository = new DepartmentRepository();
//Get all Department
List departments = departmentRepository.GetDepartments();
//Get Deparment By Id
var departmentById = departmentRepository.GetDepartmentById(1);
//Insert new Department
var departmentModel = new DepartmentModel {Department = "Humanities"};
ScopeIdentity scopeIdentity = departmentRepository.InsertDepartment(departmentModel);
//Update Department
var updatedModel = new DepartmentModel { Id = 1,Department = "Zoology" };
ScopeIdentity updatedscopeIdentity= departmentRepository.UpdateDepartment(updatedModel);
//Delete Department
ScopeIdentity deletedIdentity = departmentRepository.DeleteDepartment(1);

Stored Procedures i have used

USE [jSchool]
GO

CREATE PROCEDURE [dbo].[Get_Department]
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM [Department]

END
GO

CREATE PROCEDURE [dbo].[Get_Department_Id]
@Id int
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM [Department]
WHERE Id = @Id

END
GO

CREATE PROCEDURE [dbo].[Insert_Department]
@Department NVARCHAR(100)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [Department](Department)
VALUES (@Department)
SELECT SCOPE_IDENTITY() AS Id

END
GO

CREATE PROCEDURE [dbo].[Update_Department]
@Id int,
@Department NVarchar(100)
AS
BEGIN
SET NOCOUNT ON
UPDATE [Department]
SET Department = @Department
WHERE Id = @Id
SELECT CONVERT(DECIMAL(6,2),@Id) AS Id

END
GO

CREATE PROCEDURE [dbo].[Delete_Department]
@Id int
AS
BEGIN
SET NOCOUNT ON
DELETE FROM [Department]
WHERE Id = @Id
SELECT CONVERT(DECIMAL(6,2),@Id) AS Id
END


Enjoy coding..