C#: Security accessibility of the overriding method must match the security accessibility of the method being overriden

I was porting a .Net 2.0 assembly to .Net 4.0 plugin assembly and faced this particular challenge.

The project had a test app(A WinForm app) and it worked fine on the desktop but when I deployed the logic on server to run as a plugin it gave the following error

xyz..GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Security accessibility of the overriding method must match the security accessibility of the method being overriden.
Just notice, the spelling for “overridden” is also not correct. But this is what .Net framework threw.
After some research I found that this behavior is “By Design” i.e. as per security transparency model defined in .Net v4.0. It basically has two models:
1. Level1 (High Level) for v2.0
2. Level2 for v4.0
Here is a a list of critical operations:

1. Call native code

2. Contain unverifiable code

3. Call critical code

4. Perform security asserts

5. Satisfy link demands

6. Derive from non-transparent types

7. Override security critical virtuals

And only full trust code can be security critical.

Hence an overridden member should have the same security accessibility (Critical, Safe Critical or Transparent).
To resolve this error take the following step:
Go to the AssemblyInfo.cs class to your project and add following attributes to it. And this should resolve the exception.

[assembly: SecurityRules(SecurityRuleSet.Level1)] 
[assembly: AllowPartiallyTrustedCallers]

I believe it might be helpful to many as there are lot of Dynamics CRM implementations being upgraded.

Reference links to the differences between both and transparency rules:
http://blogs.msdn.com/b/shawnfa/archive/2009/11/12/differences-between-the-security-rule-sets.aspx
http://blogs.msdn.com/b/shawnfa/archive/2009/11/03/transparency-101-basic-transparency-rules.aspx

C#: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

Hello guys,

Before some time I had a situation where my console application would not run and without showing any screen/anything else it gave me this alert mentioned below:

The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.

Most of the google links will guide you to check your VC++ runtime and their versions. I checked everything and everything was as expected as other applications were working smooth without any error.

Also, I checked with a simple “Hello world!” console application but the output was same. And with no clue to my mind I removed the .config file from the directory.

If same is your situation then, suggested solution would be to rename the extension of the .config file to .xml file and run/parse it to any browser. In my case the .xml file did not meet with the standards as an value contained & (ampersand) and it was breaking the it to be well formed xml document.

Check with the standard list of invalid xml characters so that you can avoid this kind of situation in future. Check this link – http://www.w3.org/TR/2000/REC-xml-20001006#charsets to see well-formed xml document rules.

CRM 2011, C#, v3.5: Type ‘OptionSetValue’ with data contract name ‘OptionSetValue:http://schemas.microsoft.com/xrm/2011/Contracts’ is not expected

We already have discussed how to achieve connection of CRM 2011 through .net version 3.5 from below mentioned post. https://consultrikin.wordpress.com/2013/09/20/crm-2011-c-entity-class-redefined-with-net-framwork-3-5-to-connect-crm-2011/

Once this is achieved and you start working on CRUD operations, you will find some run time exceptions thrown like one I have described below.

Type ‘OptionSetValue’ with data contract name ‘OptionSetValue:http://schemas.microsoft.com/xrm/2011/Contracts’ is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.’.  Please see InnerException for more details.

The same thing will be repeated for EntityReference and PicklistAttributeMetadata.

Resolution:

1. Explore the reference.cs from the project in Windows Explorer and open it.

2. Search for class Entity and class EntityReference

3. Add below lines to both partial classes.
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]

4. Now search for “class OrganizationRequest”.
Add these lines above it:

     [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(PrincipalAccess))]
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]

5. Continue adding to classes for which you’re getting these exceptions.

6. Build the solution and run your code again.

Happy Programming! 🙂

CRM 2011, C#: OrganizationRequest and OrganizationResponse with .Net version 3.5

We already discussed how a CRM 2011 web service can help us create object of OrganizationServiceProxy or Instance of IOrganizationService in my previous posts. This is the case when we’re not using assemblies from SDK and thus several SDK request and response messages will not be available to you like RetrieveAttributeRequest/Response etc.

All we have is OrganizationRequest and OrganizationResponse and in this case you will have to use OrganizationRequest and OrganizationResponse to request data from CRM 2011. See below example which uses similar example for RetrieveAttributeRequest.

OrganizationRequest request = new OrganizationRequest();
request.RequestName = "RetrieveAttribute";
request.Parameters = new ParameterCollection();
request.Parameters.Add(new KeyValuePair<string, object>("EntityLogicalName", "salesorder"));
request.Parameters.Add(new KeyValuePair<string, object>("RetrieveAsIfPublished", true));
request.Parameters.Add(new KeyValuePair<string, object>("LogicalName", "new_cardtype"));

try
{
    OrganizationResponse response = (OrganizationResponse)CrmHelper.OrgService.Execute(request);
    PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.Results[0].Value;
}
catch (FaultException<OrganizationServiceFault> ex)
{
    throw new Exception("Error details: " + ex.Message);
}

Happy Programming!

CRM 2011, C#: Entity Class redefined with .net framwork 3.5 to connect CRM 2011

Look at my previous post on connecting CRM 2011 using .net framework 3.5 without CRM 2011 SDK. https://consultrikin.wordpress.com/2013/09/19/crm-2011-c-connect-crm-2011-without-using-sdkusing-net-framework-3-5/

Here, if you use Entity Class to create Entity records the same way we create records in .net framework 4.0 with SDK in late bound; this requires following syntax.

Entity entity = new Entity();
entity.LogicalName = "contact";
entity.Attributes = new ServiceReference1.AttributeCollection();
entity.Attributes.Add(new KeyValuePair<string, object>("firstname", "test first name"));
entity.Attributes.Add(new KeyValuePair<string, object>("lastname", "test last name"));
OrgService.Create(entity);

Here, you must add an attribute value as a new KeyValuePair<string, object>. Or you need to access the attributes by their indexes like:

Entity entity = new Entity();
entity.LogicalName = "contact";
entity.Attributes = new ServiceReference1.AttributeCollection();
entity.Attributes[0] = "test first name";
entity.Attributes[1] = "test last name";
OrgService.Create(entity);

This code does not have readability as you need to find int index every time you access entity. While I found the same extended Entity Class from the posts I mentioned in my previous post. Here they are listed. Just add them to your project and you will be able to add attributes with string parameters.

/// <summary>
/// Entity Class
/// </summary>
partial class Entity
{
	/// <summary>
	/// Initializes a new instance of the <see cref="Entity" /> class.
	/// </summary>
	public Entity()
	{
		this.FormattedValuesField = new FormattedValueCollection();
		this.RelatedEntitiesField = new RelatedEntityCollection();
	}

	/// <summary>
	/// Gets the attribute value.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="attributeLogicalName">Name of the attribute logical.</param>
	/// <returns></returns>
	public T GetAttributeValue<T>(string attributeLogicalName)
	{
		if (null == this.Attributes)
		{
			this.Attributes = new AttributeCollection();
		};
		object value;
		if (this.Attributes.TryGetValue(attributeLogicalName, out value))
		{
			return (T)value;
		}

		return default(T);
	}

	/// <summary>
	/// Gets or sets the <see cref="System.Object"/> with the specified attribute name.
	/// </summary>
	/// <value>
	/// The <see cref="System.Object"/>.
	/// </value>
	/// <param name="attributeName">Name of the attribute.</param>
	/// <returns></returns>
	public object this[string attributeName]
	{
		get
		{
			if (null == this.Attributes)
			{
				this.Attributes = new AttributeCollection();
			};

			return this.Attributes.GetItem(attributeName);
		}
		set
		{
			if (null == this.Attributes)
			{
				this.Attributes = new AttributeCollection();
			};

			this.Attributes.SetItem(attributeName, value);
		}
	}
}

And Add following Class-

/// <summary>
/// CollectionExtensions Class
/// </summary>
public static class CollectionExtensions
{
	/// <summary>
	/// Gets the item.
	/// </summary>
	/// <typeparam name="TKey">The type of the key.</typeparam>
	/// <typeparam name="TValue">The type of the value.</typeparam>
	/// <param name="collection">The collection.</param>
	/// <param name="key">The key.</param>
	/// <returns>returns TValue</returns>
	/// <exception cref="System.Collections.Generic.KeyNotFoundException">Key =  + key</exception>
	public static TValue GetItem<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key)
	{
		TValue value;
		if (TryGetValue(collection, key, out value))
		{
			return value;
		}

		throw new System.Collections.Generic.KeyNotFoundException("Key = " + key);
	}

	/// <summary>
	/// Sets the item.
	/// </summary>
	/// <typeparam name="TKey">The type of the key.</typeparam>
	/// <typeparam name="TValue">The type of the value.</typeparam>
	/// <param name="collection">The collection.</param>
	/// <param name="key">The key.</param>
	/// <param name="value">The value.</param>
	public static void SetItem<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
	{
		int index;

		if (TryGetIndex<TKey, TValue>(collection, key, out index))
		{
			collection.RemoveAt(index);
		}

		//If the value is an array, it needs to be converted into a List. This is due to how Silverlight serializes
		//Arrays and IList<T> objects (they are both serialized with the same namespace). Any collection objects will
		//already add the KnownType for IList<T>, which means that any parameters that are arrays cannot be added
		//as a KnownType (or it will throw an exception).
		Array array = value as Array;
		if (null != array)
		{
			Type listType = typeof(List<>).GetGenericTypeDefinition().MakeGenericType(array.GetType().GetElementType());
			object list = Activator.CreateInstance(listType, array);
			try
			{
				value = (TValue)list;
			}
			catch (InvalidCastException)
			{
				//Don't do the conversion because the types are not compatible
			}
		}

		collection.Add(new KeyValuePair<TKey, TValue>(key, value));
	}

	/// <summary>
	/// Determines whether the specified collection contains key.
	/// </summary>
	/// <typeparam name="TKey">The type of the key.</typeparam>
	/// <typeparam name="TValue">The type of the value.</typeparam>
	/// <param name="collection">The collection.</param>
	/// <param name="key">The key.</param>
	/// <returns>returns true or false</returns>
	public static bool ContainsKey<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key)
	{
		int index;
		return TryGetIndex<TKey, TValue>(collection, key, out index);
	}

	/// <summary>
	/// Tries the get value.
	/// </summary>
	/// <typeparam name="TKey">The type of the key.</typeparam>
	/// <typeparam name="TValue">The type of the value.</typeparam>
	/// <param name="collection">The collection.</param>
	/// <param name="key">The key.</param>
	/// <param name="value">The value.</param>
	/// <returns>returns true or false</returns>
	public static bool TryGetValue<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key, out TValue value)
	{
		int index;
		if (TryGetIndex<TKey, TValue>(collection, key, out index))
		{
			value = collection[index].Value;
			return true;
		}

		value = default(TValue);
		return false;
	}

	/// <summary>
	/// Tries the index of the get.
	/// </summary>
	/// <typeparam name="TKey">The type of the key.</typeparam>
	/// <typeparam name="TValue">The type of the value.</typeparam>
	/// <param name="collection">The collection.</param>
	/// <param name="key">The key.</param>
	/// <param name="index">The index.</param>
	/// <returns>returns true or false</returns>
	private static bool TryGetIndex<TKey, TValue>(IList<KeyValuePair<TKey, TValue>> collection, TKey key, out int index)
	{
		if (null == collection || null == key)
		{
			index = -1;
			return false;
		}

		index = -1;
		for (int i = 0; i < collection.Count; i++)
		{
			if (key.Equals(collection[i].Key))
			{
				index = i;
				return true;
			}
		}

		return false;
	}
}

Happy Programming!!

Could not load file or assembly ‘microsoft.crm.sdk.proxy’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Hello!!

If you are getting below error when you have deployed your web application which connects to Microsoft Dynamics CRM 2011 online/on premise version.

Could not load file or assembly ‘microsoft.crm.sdk.proxy’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Then probably you have used wrong IIS Application Pool. You might want to change the .Net version of assigned Application Pool to 4.0. And re-run the site.

This should solve the error you were facing.

C#: Set Dictionary as a data source for Drop Down List

There are situations when you need to create a list of key pair values after fetching data from the database and attach them to some Web Controls on your web page. Unlike Windows Application where you can attach whole Data List of Class to the control and the controller will act as a container, Web Controls do not support the same way. Either you need to create a new class with two properties; one for Key and second for Value part.

In this case, you can go for using Disctionary<T key, T value>, T can be used as any datatype with standard .Net datatype. You can go through the loop and create a new Dictionary object and assign the Dictionary object to the web control. And set DataTextField to Key and DataValueField to Value.

Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("item 1", "Item 1");
list.Add("item 2", "Item 2");
list.Add("item 3", "Item 3");
list.Add("item 4", "Item 4");

dropDownList.DataSource = list;
dropDownList.DataTextField = "Value";
dropDownList.DataValueField = "Key";
dropDownList.DataBind();

C# Get Plain Text from HTML String

Below function will help to remove all HTML tags, scripts, css, styles from html string and convert it to a plain text.

private string GetPlainTextFromHtml(string htmlString)
{
    string htmlTagPattern = "<.*?>";
    var regexCss = new Regex("(\\<script(.+?)\\</script\\>)|(\\<style(.+?)\\</style\\>)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    htmlString = regexCss.Replace(htmlString, string.Empty);
    htmlString = Regex.Replace(htmlString, htmlTagPattern, string.Empty);
    htmlString = Regex.Replace(htmlString, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
    htmlString = htmlString.Replace("&nbsp;", string.Empty);

    return htmlString;
}

Enjoy!!

C# Winforms TableLayoutPanel middle align the control

TableLayoutPanel control represents a panel that dynamically lays out its contents in a table format. You want to use a TableLayoutPanel in complex and sophisticated applications where you need to create dynamic layouts.TableLayoutPanel

By default when you add controls to the TableLayoutPanel, it sets them to the top left corner. When you want to align these controls (for exam, Button) to be middle, Set the value of the Button control’s Anchor property to None. The Button control moves to the center of the cell.

C# How to sort a List?

A simple method to sort a list would be:

List<Account> accountList = GetAccountList();
accountList.Sort(
    delegate(Account a1, Account a2)
    {
        return a1.AccountDate.CompareTo(a2.AccountDate);
    }
);

If you need to sort the list in-place then you can use the Sort method, passing a Comparison<T> delegate:

listAccount.Sort((x, y) => x.AccountDate.CompareTo(y.AccountDate));

The second method is more preferable if you do not have to compare more than one attributes.