siva's profilesiva's spacePhotosBlogLists Tools Help

siva's space

May 14

How to limit WCF Service access to few clients

Hi,
 
If you want to deny access to WCF service by client IP address, you can do like below.
 

System.ServiceModel.OperationContext operationContext = OperationContext.Current;
System.ServiceModel.Channels.
MessageProperties messageProperties = operationContext.IncomingMessageProperties;
System.ServiceModel.Channels.
RemoteEndpointMessageProperty endpointMessageProperty =messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

//If client is not local machine deny access to WCF service

if (endpointMessageProperty.Address != "127.0.0.1")
{
   throw new System.Security.SecurityException("Unauthorized to Access My WCF Service");
}

-Siva

March 04

ADO.Net Entity Framework: EntityKey values cannot be changed once they are set

Hi,
 
Some times you may need to change ADO.Net Entity key values at runtime, especially if you are maintaing entities locally.
If you try to change key values of entity, you will get error saying
 
InvalidOperationException: EntityKey values cannot be changed once they are set.
 
To fix this error, you can do work around like below
 
//Construct Entity Keys first.
//Entity object named entity1. entity1 has 3 keys

IEnumerable<KeyValuePair<string,object>> entityKeys = new KeyValuePair<string,object>[]
{
new KeyValuePair<string,object>(entity1.EntityKey.EntityKeyValues[0].Key,"value1"),
new KeyValuePair<string,object>(entity1.EntityKey.EntityKeyValues[2].Key,"value2"),
new KeyValuePair<string,object>(entity1.EntityKey.EntityKeyValues[2].Key,"value3")};


//construct new entity key
System.Data.EntityKey entityKey = new System.Data.EntityKey(entity1.EntityKey.EntityContainerName+"."+entity1.EntitySetName,entityKeys);


//Assign new EntityKey to entity1
entity1.EntityKey = entityKey;


Using this code you can achieve the desired result by avoiding EntityKey values cannot be changed exception.

-Siva

February 26

Microsoft.ReportingServices.Diagnostics.Utilities.SecureConnectionRequiredException: The operation you are attempting requires a secure connection (HTTPS)

Hi,
 
if you are trying to deploy report model project to SQL Server 2008, you may get error like below
 
Microsoft.ReportingServices.Diagnostics.Utilities.SecureConnectionRequiredException: The operation you are attempting requires a secure connection (HTTPS)
 
For not using SSL when deploying you need to modify following section in reportserver.config file
This file locates under C:\Program Files\Microsoft SQL Server\MSRS10.<ServerInstance>\Reporting Services\ReportServer
 
Line to be changed is:
 <Add Key="SecureConnectionLevel" Value="2"/>
 
Change value to 0 from 2.
 
-Siva
February 25

MSBuild: How to change multiple appSettings values of app.config using XmlUpdate

Hi,
 
Here is sample msbuild project code for changing multiple appSettings values of app.config file using XmlUpdate.
XmlUpdate is one of the many useful tasks of MSBuild community tasks.
 
I have two keys named Key1 and Key2 in App.config file under Configuration/appSettings Section.
 
<Target Name="UpdateConfigs" Condition="'$(CONFIGURATION)'=='Release'">    
    <XmlUpdate XmlFileName="WPFApplication1.exe.config" XPath="configuration/appSettings/add[@key='Key1']/@value" Value="somekey1value" />
   <XmlUpdate XmlFileName="WPFApplication1.exe.config" XPath="configuration/appSettings/add[@key='Key2']/@value" Value="somekey2value" />
  </Target>
 
-Siva

ADO.Net Entity Framework: Modify EntityConnection connection string values at runtime

Hi,
 
If you want to change SQL connection string values of EntityConnection at runtime, you can do it like below.
 
My requirement is User Id and Password of SQL connection need to be changed at runtime depending on environment.
 
//Object Context name is objectcontext1.
//First Call default constructor for object context. This gets connection information from app.config

objectcontext1 context = new objectcontext1();

//Get the connection string from app.config and assign it to sqlconnection string builder

SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity =
false;
sb.UserID ="User1"
;
sb.Password = "Password1";

//set the object context connection string back from string builder. This will assign modified connection string.
((
EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString;

-Siva

February 17

Fix for WPF UserControl Design time error

Hi,
 
If you include UserControl in a WPF page or window, you may get design time error for that page or window.
This is because Usercontrol does not have access to application resources at design time.
To fix it, you need to define resources in UserControl too.
 
Sample Code:

<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="..\Simple Styles.xaml"/>
<ResourceDictionary Source="..\ControlStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>

-Siva

February 06

System.Servicemodel.Dispatcher.Netdispatcherfaultexception: The formatter threw an exception while trying to deserialize the message.The maximum read depth (32) has been exceeded because XML data being read has more levels of nesting than is allowed.

Hi,
 
I am using ADO.Net Entity Framework in my application. Our objects have quite a few nested sub entities. I got below error when WCF try to pass collection.
 
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter. The InnerException message was 'There was an error deserializing the object of type. The maximum read depth (32) has been exceeded because XML data being read has more levels of nesting than is allowed by the quota. This quota may be increased by changing the MaxDepth property on the XmlDictionaryReaderQuotas object used when creating the XML reader.
 
I solved this issue by increasing readerQuotas maxDepth value. Default value is 32.
 

<readerQuotas maxDepth="200" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />

-Siva

February 03

What is the difference between IS NULL and = NULL in SQL Server

Hi,
 
We can search null values of a column two ways like below.

SELECT * FROM TABLE WHERE COLUMN IS NULL

Or

SELECT * FROM TABLE WHERE COLUMN = NULL

If you SET ANSI_NULLS ON, first query returns all the records where column value is null as expected.Second query does not return results as expected.

That's because when ANSI_NULLS ON, two NULL values are not equal because two seperate values are not unknown. 
With ANSI_NULLS off two seperate null values are equal.
 
Remember to always use IS NULL when you check for null value.
 
-Siva
 
 
 
 
January 28

How to change collation for a SQL Server 2008 database

Hi,
 
If you need to change the collation for a SQL Server database, you can use below tsql command. You need to close all existing connections.
 
//Change collation of AdventureWorks database to SQL_Latin1_General_CP1_CI_AS

alter

database AdventureWorks collate SQL_Latin1_General_CP1_CI_AS

This does not change the collation of existing objects under this database.

For finding collation of columns under a perticular table you can use below command

select
column_name, collation_name from INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table1'
 

-Siva

How to get Begin Date and Last Date of Previous month using TSQL

Hi,
 
Here is the TSQL code for getting First Day of the Previous Month
 
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - 1, 0)
 
TSQL code for Last Day of the Previous Month
 
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0,
CURRENT_TIMESTAMP), 0))
 
-Siva
January 26

Unable to copy windows service run time libraries while building project

Hi,
 
If you have windows service project and installed service from project output path, you get error saying "Unable to copy file.The process cannot access the file because it is being used by another process." when you are building project.
 
To fix this problem, easy solution is to stop and start the service in Build Events.
 
//Stop the service called service1 in Pre-build event command line:
net stop service1
 
//Start the service in Post-build event command line on successful build:
net start service1
 
-Siva
January 23

WCF Exception: System.InsufficientMemoryException

Hi,
 
When I tried to pass huge volume of data from WCF Server to client, i got exception saying Insufficient memory avaliable to complete the operation. Exception type in service trace viewer is System.InsufficientMemoryException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 
I solved this problem by switching from WsHttpBinding to BasicHttpBinding. Changed TransferMode to "Streamed".
 
Here are the configuration details for basicHttpBinding


<
basicHttpBinding>
<
binding name="BasicBinding" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" transferMode="Streamed"
openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="524288">
<
security mode="None">
<
transport clientCredentialType="None" />
</
security>
</
binding>
</
basicHttpBinding>

-Siva

January 15

How to filter records in ADO.Net DataTable using Linq

Hi,
 
If you want to filter rows in ADO.Net DataTable using C# and Linq, here is sample code.
 
Let's say if you have following fields in DataTable
 
Field Name                                           Type                                         Nullable
Field1                                                  int                                              no
Field2                                                  int                                              yes
Field3                                                  string                                          yes
 
C# Code:
 

EnumerableRowCollection<System.Data.DataRow> filteredTable= DataTable1.AsEnumerable();

filteredTable =

from record in filteredTable

//Where Field1 equals 10
where record.Field<Int32>("Field1") == 10
select record;  

//Nullable Integer Field
//Where Field2 equals 100
filteredTable = from record in filteredTable
where record.Field<Int32?>("Field2") == 100
select record;
 

//Where Field3 equals "some string"
filteredTable = from record in filteredTable
where record.Field<string>("Field3") == "some string"
select record; 

//Convert Filtered Datatable to DataView
DataView dv1 = filteredTable.AsDataView(); 

Enjoy
-Siva

January 14

ADO.Net Entity Framework: The object can not be added to the ObjectStateManager because it already has an EntityKey.

Hi,
 
When you are using ADO.Net Entity Framework context for adding a record to table, you may get error saying "The object can not be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key."
 
You will get above error if you are trying to add a record with sub entity. I fixed above error by setting child entity to null and created child entity reference manually. Here is the code snippet.
 
//Create child entity reference

EntityReference

<child_entity> childReference = new EntityReference<child_entity>();

//Set the entity key
childReference.EntityKey = ParentEntity.child_entity.EntityKey;

//Set the child entity to null
parentEntity.child_entity =
null;

//Set the child entity reference from previously created reference

parentEntity.child_entityReference = childReference;

You can attach to context and insert record as below.
context.AddToparentEntity(parentEntity);
context.SaveChanges();

-Siva

January 13

How to Update endpoint address in WCF service and client config files using MSBuild Community tasks

Hi,
 
We need to update WCF endpoint address in Service and Client config files when we migrate our code to different environments(eg: Dev,Prod..). This can be done easily with MSBuild community tasks using XmlUpdate method. I am giving below the code. I have written this in msbuild project file.
 

<?xml version="1.0" encoding="utf-8"?>
<
Project DefaultTargets="UpdateConfigs" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<
Import Project="MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>

<

PropertyGroup>
<
CONFIGURATION Condition="'$(CONFIGURATION)'==''">Release</CONFIGURATION>
<
COMPILETYPE Condition="'$(COMPILETYPE)'==''">All</COMPILETYPE>
<
WCFSERVER Condition="'$(WCFSERVER)'==''">WCFServer1</WCFSERVER>
<
HTTPPORT Condition="'$(HTTPPORT)'==''">8622</HTTPPORT>
</PropertyGroup>

<

Target Name="UpdateConfigs">
<!-- Update in WCF Service config File -->

<
XmlUpdate XmlFileName="WCFService.exe.config" XPath="configuration/system.serviceModel/client/endpoint/@address" Value=http://$(WCFSERVER):$(HTTPPORT)/WCFService />

<!-- Update WCF client config file -->
<
XmlUpdate XmlFileName="WCFUI.exe.config" XPath="configuration/system.serviceModel/services/service/host/baseAddresses/add/@baseAddress" Value=http://$(WCFSERVER):$(HTTPPORT)/WCFService />
</
Target>
</
Project>

Enjoy
-Siva

January 08

How to prevent Navigating away from current WPF page

Hi,
 
If you want to prevent navaigating from current page depending on some condition you can write code like below.
I am giving below codebehind in C#
 
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
 

public partial class Page1 : Page

{

private

NavigationService ns;

public

Page1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
this.Unloaded += new RoutedEventHandler(Page_UnLoaded);
}

private

void Page_Loaded(object sender, RoutedEventArgs e)
{
//Attach Navigating Event to NavigationService
this.NavigationService.Navigating += new NavigatingCancelEventHandler(NavigationService_Navigating);
}

private void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
{
//Assign NavigationService to class variable
ns =
this.NavigationService;

if (a != b)
{
e.Cancel = true;
}
}

private void Page_Unloaded(object sender, RoutedEventArgs e)
{
//Detach Navigating Event from Navigation Service
ns.Navigating -=
new NavigatingCancelEventHandler(NavigationService_Navigating);
}
}

Enjoy,
Siva

January 06

System.ServiceModel.AddressAccessDeniedException exception

Hi,
 
If you are registering your WCF service as windows service and you may get following error depending on loginid you use
 

System.ServiceModel.AddressAccessDeniedException:
HTTP could not register URL http://+:8731/WCFService/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details). ---> System.Net.HttpListenerException: Access is denied
at System.Net.HttpListener.AddAll()
at System.Net.HttpListener.Start()
at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()

To fix this error you need to run following command at command prompt on Windows 2003 server

httpcfg set urlacl -u http://+:<PORT>/<SERVICE URL>/ -a "D:(a;;GX;;;<SID>)

To get SID of an user id you need to run below command at command prompt on Windows 2003 server

dsquery user -name "<UserID>"|dsget user -samid -sid

 

Enjoy

-Siva

December 15

Security Support Provider Interface (SSPI) authentication failed

Hi,
 
If you are running WCF service and Client on two different domains if you get following error.
 
{"Security Support Provider Interface (SSPI) authentication failed. The server may not be running in an account with identity 'host/machine.domain'. If the server is running in a service account (Network Service for example), specify the account's ServicePrincipalName as the identity in the EndpointAddress for the server. If the server is running in a user account, specify the account's UserPrincipalName as the identity in the EndpointAddress for the server."}
 
You may fix it by editing client config file like below

 

<identity>
<servicePrincipalName />
</identity>

-Siva

October 30

WCF Exception: The request channel timed out while waiting for a reply

For Fixing WCF exception The request channel timed out while wating for a reply,  we need to change binding setting in WCF cleint config like below.
Setting to be changed is sendTimeout. Changed value to 10 minutes from default value 1 minute.
 

<bindings>
<wsHttpBinding>

<binding name="WSHttpBinding_IRASService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
</binding>

</

wsHttpBinding>
</bindings>

-Enjoy
 
October 29

ADO.NET Entity Framework: The version of SQL Server in use does not support datatype 'datetime2'

Hi,
 
I genereated ADO.Net Entity framework edmx using SQL Server 2008 version. When i pointed my application to SQL Server 2000 with the same database schema got error saying SQL Server in use does not support datatype datetime2.
 
To fix this i opened edmx file in xml editor and changed ProviderManifestToken from 2008 to 2000.

<edmx:Runtime>

<!-- SSDL content -->

<

edmx:StorageModels>

<

Schema Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2000" >

</Schema>

</edmx:StorageModels>

- Enjoy

October 14

How to set style for WPF control at run time

Hi,
 
Usually we can set style for a textbox control like below in xaml
<TextBox Name="txtValue" Style="{StaticResource TextBoxStyle}" Width="80"></TextBox>
 
You can set same in code behind like below
txtValue.Style = (Style)(App.Current.FindResource("TextBoxStyle"));
 
--Enjoy
September 10

Grid, DockPanel and Stack Panel in WPF

Before you add any controls to WPF Window or Page, you must add layout panel. There are 3 commonly used layout panels. They are Grid, DockPanel and StackPanel
 
  • A Grid control arranges child elements in a layout of rows and columns similar to table in html. This is default layoutroot provided by Visual studio when you create new window or page
  • A Dockpanel control arranges child elements so that they stay to one edge of the panel. Left, Top, Right or Bottom
  • A StackPanel control arranges child elements into a single line that can be oriented horizontally or vertically

-Enjoy

 

September 08

Difference Between Dynamic Resource and Static Resource in WPF

Static Resource gets the object from the resources collection once. Depending on the type of object any changes you make to that object may be refreshed right away.
<Window.Resources>
<SolidColorBrush x:Key="Button_Style0" Color="Blue" />
</Window.Resources>
<Button Background="{StaticResource Button_Style0}" Text="Test" />
 
Dynamic Resource gets the object from the resource collection every time it's referenced. You can place totally new object with the same key and dynamic resource would refresh new change.Overhead assoicated with dynamic resource.Only use dynamic resource when you plan to change your resource objects programmatically.
<Window.Resources>
<SolidClorBrush x:Key="Button_Style0" Color="Blue" />
</Window.Resources>
<Button Background="{DynamicResource Button_Style0}" Text="Test" />
 
Now you can change value of Dynamic Resource Programatically like blow.
this.Resources["Button_Style0"] = new SolidColorBrush(Colors.Red);
 
-Enjoy
 
 
 
Photo 1 of 33

siva pinnaka