Friday, March 29, 2013

How to enable MS Dynamics CRM 2011 to integrate with Windows Azure

Hi,

I'm writing this article to explain a good architecture design for integrating your Microsoft Dynamics CRM 2011 with windows azure.

Let's  say you have on-premise CRM 2011 instance, and you want to use Windows Azure Blob storage to store Customer's documents on the cloud. How would you do that ?

The example i'm giving is applicable to any other windows azure service such as: SQL Azure, Mobile Notification Service, AppFabric Features..etc.

Since Windows azure is a scalable Cloud platform, you can easily integration your CRM 2011 with the windows azure on the cloud in 4 main steps.

Before going through the details, I'd like to explain the architecture of the proposed solution.

MS CRM 2011 has a backend windows service called "CRM Asynchronous Service" this is the component that will be in charge to communicate with the windows azure through a service bus.

MS CRM 2011 has 2 types of plugins, out-of-the box (OOB) and custom plugins. The OOB plugins runs  with full trust but the custom plugins runs with partial trust, and we will develop a custom plugin to connect to a listener through azure service bus.

The solution has the following components:

1) Configure CRM to be Windows Azure Aware.

2) We need to configure a service bus on Azure with an endpoint to communicate with the CRM server.

3) A listener hosted in Windows Azure to communicate with the asyncrhounous service, specificially listening to CRM assembly "Microsoft.Xrm.Sdk" with RemoteExecuteContext defined. so we need to develop a listener and deploy it on windows azure.

4) A custom CRM Plugin to communicate with the Windows Azure Listener.


How To accomplish, configure and develop this solution:

1) To accomplish step 1 , "Configure CRM for Integration with Windows Azure" :
http://technet.microsoft.com/en-us/library/gg328249.aspx

2) To accomplish step 2, "Configure Windows Azure ACS on Azure" :
http://technet.microsoft.com/en-us/library/jj863635.aspx

3) How to write a windows azure listener:
http://technet.microsoft.com/en-us/library/gg309615.aspx

C# Sample code - Listener:
http://technet.microsoft.com/en-us/library/gg309657.aspx

4) To accomplish step 4, "How to write Azure Aware CRM Plugin":
http://technet.microsoft.com/en-us/library/gg328194.aspx

Note, if you want to develop a custom workflow activity:
http://technet.microsoft.com/en-us/library/gg327854.aspx

Registration step - FINAL:
http://technet.microsoft.com/en-us/library/gg328524.aspx


**Here is some sample code for all what i mentioned above "listeners & plugins":
http://technet.microsoft.com/en-us/library/gg334712.aspx

Note: you should be having CRM SDK and Windows Azure SDK 1.7 or higher to be able to exercise and develop the solution.

Hope this helps.


Reference:
-Azure Extensions for Microsoft Dynamics CRM 2011:
http://technet.microsoft.com/en-us/library/gg309276.aspx



 

Wednesday, March 27, 2013

Fix It: Application deployment Failed, Please try again in VS 2012

Hi,

A well-known error message is being thrown from VS 2012 when you try to run the emulator for Windows Phone 8. After you installed all the tools and trying to see your application on the emulator you get the above error and it is a show stopper! It's so frustrating and annoying not to be able to view your running code.

After i was stuck for 3 days, and posting my question in MSDN and contributing on StackOverflow and other forums, all of these suggestions didn't work with me.

My case is fairly simple: I have a brand new laptop, Lenovo AMD E1500 (Supports SLAT) with 4GB RAM on Windows 8 Pro 64bit with VS 2012.

Every time i try to run my windows phone 8 application after selecting "WVGA 512MB" Emulator, it takes forever and i got this error:

Application Deployment Failed, Please try again.

When i check the output window in VS2012, I see the error happens when the VS 2012 tries to connect to the created VM in Hyper-V.

Here is the steps you have to make sure befor uninstalling the SDK or the other tools:

1) Turn off windows firewall.
2) Make sure that you are running VS 2012 as an administrator.
3) Make sure that you are a member of Hyper-V Administrator on your machine.
4) Open Hyper-V and check the you have a VM called "Emulator WVGA 512MB" since this is the VM that VS 2012 is trying to deploy the xap file into.
NOTE: IF YOU DON'T HAVE THE VM, THIS POST IS NOT INTENTED TO FIX IT.

5) Check the connection type for "Windows Phone Emulator Internal Switch" in Hyper-V manager by clicking on Virtual Switch Manager link on the right pane is Internal.

6) In the control panel, Check Network and Sharing Center and then click on change adapter settings --> you should be able to find 3 adapters starts with vEthernet, those are being used with Hyper-V.
Don't change any configuration by your self without any direction from a network guy! missing around these configuration might need you to re-install all the tools and rebuild all virtual switches!

7) Check below Article for MSDN and verify you have the following configuration for "vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch)"

http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681694(v=vs.105).aspx

8) IMPORTANT: Turn off  any antivirus real time scanning, This turns into scanning all communications which slow down the VS/Emulator and times out the emulator running process so you won't be able to deploy your application. THIS WAS MY FINDING AFTER SPENT 3 DAYS!

After following all above instructions you shouldn't have any issues with running your WP8 Emulator.

Have Fun.




VS 2012 Update 1 is available

Hi,

Yesterday, Microsoft released a new update for VS 2012. In this first update for VS 2012, They included a lot of enhancements in terms of TFS services, SharePoint Development ALM, .NET Framework enhancements, Mobile development Enhancements and IDE fixes.

The complete list of all the updates in details are listed here:

http://support.microsoft.com/kb/2797915

So, if you are developing using VS 2012, it is strongly recommended to install this update, this is the download link:

http://www.microsoft.com/en-us/download/details.aspx?id=35774

Hope this helps.

Sunday, March 24, 2013

Generic Failure in WP8 Emulator and Error when opening Hyper-V Switch Manager!

Hi,

I was developing a windows phone 8 application using VS 2012, and after i did some changes in the network adapter by disabling the hyper-v virtualization protocol "vEthernet" and all its components, the emulator stops working!.

The reason i did this because i wasn't able to give a static IP to my machine so i can access it from my second machine, installing TCP/IP 4 to set the static IP and unchecked Hyper-V protocol screw my virtual Ethernet adapter and emulator components that are using it.


I was looking and searching what caused this problem, the only thing i was sure about it it is something related to the network adapter settings! since the network adapter doesn't have the required settings for the Hyper-V neither The emulator nor the Hyper-V switch manager is working and throwing errors.

The emulator was throwing an error: Generic Failure in VS 2012.

The Hyper-V Switch manager is throwing this error message: An error occurred while trying to retrieve a list of virtual switches.


To cleanup your machine and get back developing on the emulator, do the following:

1) Open Hyper-V Manager, you will find a VM created for your emulator, Delete this VM.

2) From Control Panel, Open Add or Remove windows Features -> Un check Hyper-V. This will un install all Hyper-V configuration. Reboot your machine.

3) From Control Panel, Add back Hyper-V to your windows, this will install Hyper-V manager and install all required vEthernet and other components that are required to run the emulator.

4) Open Hyper-V Manager, Click on "Add Virtual Switch Manager" and then add a virtual switch of type Internal.
Notice: you won't get the error message we had earlier!

5) Open your visual studio, and run your WP8 application, this will configure the emulator VM and all its components.
Notice: The first will take a longer time to run, since the windows will install all required drivers and create the VM used by the emulator and setup the network adapters between the PC and the VM.

6) If you check the Hyper-V manager after the first run for your application, VS 2012 has created a new VM and used the new Virtual Switch we created earlier.

Hope this helps!

Drop me a line if you have this problem and have other solutions or workarounds to it.

Thanks.



Wednesday, March 20, 2013

Calling Stored procedure from EF takes long time and times out!


Hi Folks,
 
I was going through an interesting performance issue when calling a stored procedure from my web application more than one time and the WCF was timing out because of the stored procedure execution takes long time to execute.
 
At the first, I have a parameterized stored procedure that takes different parameters. First time it executes as expected.
 
The second time, the EF calls the stored procedure and i don't get any results back to my application. i thought there is an issue in the Stored procedure but no because the stored procedure works as expected from the SQL management studio.
 
 
This means, there is something is going on between the EF bindings and getting results to mapped views/entities we have in the DBML file.
 
I was searching and trying to find any clue why this could happen ? I tried different things but it didn't work, until i read the following articles about performance issues in EF:
 
http://msdn.microsoft.com/en-us/library/cc853327.aspx
 
I realized that i don't have issues in terms of the SQL performance, but EF does have some overhead on executing any stored procedure and getting the results back to mapped view objects. Since this search stored procedure return list of objects to one of my entities, i want to know why does it take long time to execute and i don't get my results back ?!
 
I found the solution for my problem by doing 2 steps:
 
1) Since i don't want to track any loaded objects for my entities, i added the following merge option with No Tracking when i call my stored procedure.

C# Code:

this.ObjectContext.Search(EmpId,EmpName, DeptId,DeptName, System.Data.Objects.MergeOption.NoTracking).ToList();


2) Since SQL Server has a known performance issue called Paramter sniffing, which means the SQL Server engine allows to compile the plan for the stored procedure and reuse this plan for subsequent calls of the same stored procedure with different paramters! and this was my case, i pass long list of parameters but with different values. the first time executes as expected because the server chose to compile the plan with the results but the second time it re-uses the compiled plan which might not work well with the results that i want and this takes long time to get the expected results!
 
This is a known issue when your stored procedure inlcudes Like keyword in your queries and you use the input paramters directly to filter your results without using other temp paramters assigned from the input parameters.
 
What you need to do is to force SQL to compile the query each call and not to use a precompiled plan and this can be accomplished by using : RECOMPILE query hints along with your query. This is supported in SQL 2005 and above. I'm using SQL 08 R2 server.

Select * FROM myView
WHERE DeptName like '%' + @DeptName+ '%' 
OPTION (RECOMPILE); -- This enhance the performance query and fix the parameter sniffing issue for multiple calls stored procedure.

 After these 2 changes, I ran my web application, the application works as expected and no times out for the stored procedure that is being called twice!

Hope this helps.


Reference:
1) Table Hints in SQL Server:
http://msdn.microsoft.com/en-us/library/ms181714.aspx

2)  Paramter Sniffing in SQL Enginer:
http://blogs.technet.com/b/mdegre/archive/2012/03/19/what-is-parameter-sniffing.aspx


 
 

Tuesday, March 19, 2013

What do you expect from Entity Framework 6 Alpha ?

Hi,
 
I was reading the MSDN magazine March 2013 and i found an article by Julie Lerman about EF 6 Alpha features.
 
If you haven't had the chance to read the article, here is a summary of this article for .NET developers and architects:
 
1)      EF 6 will be supporting multiple schemas. So in your dbml file you will be able to reference and import multiple schemas in your database.
 
Julie has written a detailed article about this feature, here is the link for this:
 
2)      EF6 will be supporting the asynchronous processing (Async).
Since we have Asynchronous pattern supported in .NET 4.5. The EF 6 will be bringing some of these features by having: SaveChangesAsync(), ExecuteSqlCommandAsync and FindAsync() functions that don't block the UI while executing and you will be able to write asynchronous code in your application in EF 6.
 
For Linq to Entities, they have added bunch of other Async methods for enumerations such as: ToListAsync(), FirstOrDefaultAsync(), MaxAsync().
 
This is a very important feature especially for Silverlight, WPF and Windows Phone developers in addition to web developers.
 
3)      Enum and Spatial support
EF 6 will be supporting enums and Spatial data types. Unlike earlier version where dependent on the .NET framework you are using/targeting. The new EF 6 will be supporting this no matter which .NET framework you are targeting. So you can use enums and spatial support even you are targeting .NET 4.0 framework that doesn’t support certain EF 6 features.
 
Hope this helps.

Monday, March 11, 2013

Conditional using statement in C# debug versus Release

Hi Folks,

I'm writing this blog post to share how to write conditional using statements in C#. The meaning of this is how to use using statements in Debug mode versus Release mode in reference to different dlls. This is needed when you are using any testing/sandbox DLLs that use any non production environment and you want your code to use other reference when you build a Release for your application in reference to production dlls.

The below code is using In-App Purchase library for Windows Phone 8.

C# Code:

#if DEBUG
using MockIAPLib;
using Store = MockIAPLib;
#else
using Windows.ApplicationModel.Store;
#endif
Notice: you give the same alias name for the testing Libaray namespace as the one that will be used in production so you don't need to re-write your code.

Then, you can use any class for the referenced namespace:

ProductListing p = new ProductListing();


Tip: You should select Release before your deploy your application to products so the application will refer to the production assemblies and not the ones are used in the debug mode.


Hope this tip helps!

 

Tuesday, January 22, 2013

Adding Custom Propeties to EF 4.0 that doesn't exist in the DB model

Hi Folks,

I was extending my EF 4.0 model by having custom propeties that don't exist in my DB, Since EF 4.0 doesn't support adding custom properties if it doesn't exist in the DB, I found a workaround for that by creating a partial class with my custom properties in it.
 

public partial class myEntityName: EntityObject

{

     
[DataMemberAttribute()]
public string customerName{ get; set; }

[DataMemberAttribute()]
public int customerCode{ get; set; }

}


Implementing this workaround will help you to add any properties you would like to add in your EF 4.0 entities.


You might encounter this error since you are adding properties to your entity that doesn't exist in the edm file:

"The number of members in the conceptual type does not match with the number of members on the object side type .Make sure the number of members are the same."

The fix for error; Remove "EdmScalarPropertyAttribute" attribute from your custom propeties:

//[EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = true)] 
[DataMemberAttribute()]
public string customerName{ get; set; }


 Hope this helps!

Wednesday, January 02, 2013

WCF Error: The service cannot be activated because it does not support ASP.NET compatibility.

Hi Folks,

I was developing a secure WCF service that allows only authenticated windows users to access this service in IIS 7.5. After disabling the anonymous access i figured that wsHttpBinding will not work because you have to enable it to make the WCF binding working, then i changed the WCF binding to basicHttpBinding and passed the user credentials from the web application by using below line of code:

C# Code:
svc.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

The above line passed the user credentials from the client web application to the service.

Passing the credentials from the client web application wasn't accepted by the WCF service because i was getting another error message from the wcf service:

"The underlying provider failed on Open WCF when hosting in IIS with impersonation is enabled"

Since i have enabled the impersonation to pass the user credentials from the web application to the wcf i was missing the step to add the following configuration in the web.config of the WCF service:

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>

"The default is false. When this attribute is set to true, requests to Windows Communication Foundation (WCF) services flow through the ASP.NET HTTP pipeline, and communication over non-HTTP protocols is prohibited"

One last thing you should add in the service class "aspNetCompatibilityEnabled" attribute to comply with configuration entry otherwise still your service won't work because it will use the default IIS account to access your database.

C# Code:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class myService : ImyService
// your implementation to the service.
}


Hope this helps!

References:

1) WCF serviceHostingEnvironment element:
http://msdn.microsoft.com/en-us/library/ms731336(v=VS.110).aspx



Thursday, December 13, 2012

How to parse comma delimited string into IN Clause in SQL Server

Hi Folks,

Today i was trying to pass multi-value parameter into my select query in SQL Server. To accomplish this i stored the multi-value parameter in a comma delimited string. Then, i want to pass it in my IN clause of the select statement. here is an example to what i want to accomplish:

Delcare @myVar varchar(500)
Set @myVar='1,2,3,4,5,7'

Select * from Employee
where EmployeeId IN (@myVar)

You will get this error:
Msg 245, Level 16, State 1, Line 7
Conversion failed when converting the varchar value '1,2,3,4,5,7' to data type int.


It makes sense, because i have a varchar that holds all my values and i want to pass those in the IN clause that only accepts integer values!.

The solution for this problem is to parse this string into set of integers and pass it back to your query in your IN clause. For this reason, i have created a function that return a table of 1 column of type int. This will be passed back to the select statement i have mentioned above.

The function code to parse comma delimited string into set of integers:

-- =============================================
-- Author: Mostafa Elzoghbi
-- Create date: 12/10/2012
-- Description: Parse a string into set of numbers
-- =============================================

CREATE FUNCTION [dbo].[ParseCommaDelimitedString]
( @CommaSeparatedStr
nvarchar(1000) =NULL)
RETURNS @myTable TABLE ([Id] [int] NOT NULL)
AS
BEGIN
declare
@pos int
declare @piece varchar(500)
-- Need to tack a delimiter onto the end of the input string if one doesn't exist
if right(rtrim(@CommaSeparatedStr ),1) <> ','
set @CommaSeparatedStr = @CommaSeparatedStr + ','
set @pos = patindex('%,%' , @CommaSeparatedStr )
while @pos <> 0
begin
set @piece = left(@CommaSeparatedStr , @pos - 1)
-- You have a piece of data, so insert it, print it, do whatever you want to with it.
insert @myTable
select @piece

set @CommaSeparatedStr = stuff(@CommaSeparatedStr , 1, @pos, '')
set @pos = patindex('%,%' , @CommaSeparatedStr )
end
RETURN
END
-- =============================================

What you need after that to re-write your query as follows:

Select *

from Employee
where EmployeeId IN
( select * from ParseCommaDelimitedString(@myVar))

Now, you will be able to pass any comma delimited string, varchar,nvarchar to this function and it returns table of integer that you can set in the IN clause of you select statement or any other T-SQL statements you works with your logic.

Hope this helps.

--ME

Wednesday, December 12, 2012

Error: unable to retrieve column information from the data source in SSIS

Hi Folks,

I was trying to call a stored procedure from OLE DB Source in SSIS. and i getting this error:

"Error: unable to retrieve column information from the data source"

I wasn't even able to get the columns returned from this stored procedure.

My stored procedure is having a dynamic query i'm building based on passed parameters from SSIS package.

My Stored procedure code:

Declare @sqlStatement as nvarchar(1000)
SET @sqlStatement = ' SELECT * FROM dbo.myTable
WHERE ID IN ('+ @Ids + ' )'
-- For tracing purposes
print @sqlStatement
execute sp_executesql @sqlStatement

To fix this problem, the SSIS when it executes the stored procedure in the design time, it doesn't pass any parameters, with that being said, you have to make sure that your stored procedure is working when you pass NULL values by default. and this was the trick to fix the problem. In my case, when i pass NULL values for my parameter that contains multiple values my SQL query statement is not valid!

I fixed my stored procedure through the following:

Declare @sqlStatement as nvarchar(1000)
IF @Ids is not NULL
SET @sqlStatement = ' SELECT * FROM myTable WHERE ID IN (' + @Ids + ' )'
ELSE
SET @sqlStatement = ' SELECT *FROM myTable'

-- For tracing purposes
print @sqlStatement
-- EXEC @sqlStatement
execute sp_executesql @sqlStatement

After fixing my stored procedure to work with null passed values and my dynamic sql statement is correct i was able to view my columns returned from the stored procedure and it works like a charm!

Hope this tip helps you when you create any stored procedure that is being called from SSIS objects such as OLE DB source or SQL Task.

Thanks,
--ME

Sunday, December 09, 2012

Study Material Notes for Programming HTML5 and CSS 3 Microsoft Exam

Hi Folks,

I got a free voucher from Microsoft for programming HTML 5 and CSS 3 Exam. I studied and reviewed online video materials and i want to share with you my study notes and hope this will be helpful for passing the exam. Congratulations in advance for everyone!.

My Notes:

  1. Use accepts:'application/bin,text/xml' to accepts only XML and binary content in HTML responses.
  2. Use the following condition to check if the html response content is binary: If(request.getResponseHeader("Content-Type")=="application/bint"
  3. To show the status of upload is displayed in the progress bar:Xhr.upload.onprogress=
  4. To support 2 way communication between a web page and a worker role, implement the following:
    1. From the main page, use onmessage event handler of the web worker to capture events.
    2. From the web worker, use the onmessage event handler of the main page to capture events.
  5. Standard-complaint screen readers must be able to identify the links contained within the navigation structure automatically: Use semantic markup.
  6. Use appendChild to add a control in DOM document.
  7. To extend a class with a method you should use prototype keyword as follows: Customer.prototype.GetCommission() = funct() {…}
  8. If you want an input control to allow only numeric values, use the following:    type="number"
  9. To pass objects between web page and web worker you can use: JSON,String and JavaScript types.
  10. To register an event listener for the web worker use addEventListenr and to stop a web worker use: self.close();
  11. Anchor selector order:  a:link --> a:visted --> a:hover --> a:active
  12. Use Figure semantic markup to include image and its caption using figcaption markup.
  13. To store user's information you can use: localStorage to get or set  user's data.
  14. To write a code to throw an error: throw new Error("Invalid",200)
  15. To show @ in the email address for a submitted form,   Use: str=$("form").serialize() ;         str=decodeUriComeponent(str);
  16. Apply styles from highest to lowest priority: 
    1. User agent style sheets
    2. Author normal style sheets
    3. Author important style hseets
    4. User normal style sheets
    5. User important style sheets
  17. To make sure that the advertisement section on the right most of the page use:
  18. To handle automatically each time the request status change use xhr.onreadstatechange
  19. Catch specific error number by using e.number and not e.message
  20. To use text-transform in CSS, you should use captalize  semantic tag.
  21. You need to group page content together to maximize search engine readability use article semantic markup.
  22. When  you want the inner paragraph exactly far from the outer paragraph, then you should use Relative.
  23. To show JSON confirmation number in a label: $("#txtValue").text(JSONObject.Confirmation);
  24. To show text around an image is showing in the center of the page use: -ms-wrap-side: both
  25. Use header to apply css or classes to different heading markup such as: H1,H2
**Videos - Jump start from Microsoft Virtual academy:

https://www.microsoftvirtualacademy.com/tracks/developing-html5-apps-jump-start

Good Luck, Feel free to drop a line with any feedback you would like to add.


Wednesday, December 05, 2012

Functions vs. Methods in JavaScript with Encapsulation!

Hi Folks,

I found something interesting to share with all of you in Javascript. Functions in javascript as we all know is defined with function keyword while Method in Javascript is a function but can have a scope and you can hide it as we do in object oriented programming. I will be showing 2 examples that implement function versus method in your web page to add 2 numbers.

1) Function to add 2 numbers in Javascript:

In your script tag, this is the declaration of the function:

<script language=javascript >
function myfunction() {
document.getElementById('txtResult').value = parseInt(document.getElementById('Text1').value) +                                             parseInt(document.getElementById('Text2').value);
</script>

My page, see the result after you change the second text box:

<p>Using Functions</p><input type="text" id="Text1" /><br /><input type="text" id="Text2" onchange="myfunction();" /><br /><input type="text" id="txtResult" /><p>

2) Method to add 2 numbers using Methods:

<script language=javascript >
// Methods
var ops = {

add: function AddTwoNumbers() {
                              document.getElementById('txtResult2').value =
                              parseInt(document.getElementById('Text3').value) +
                                 parseInt(document.getElementById('Text4').value);               
                                               }
         };</script>

My page:

<p>Using Methods</p><input type="text" id="Text3" /><br /><input type="text" id="Text4" onchange="ops.add();" /><br /><input type="text" id="txtResult2" />

You will see that we implemented the add function that has the scope within ops object, and in this way you can design and organize your functions within different scopes and with that being said you implement encapsulation for your methods!.

Anoter note, you gave an alias to your function with "add" alias name and this is not the actual name of the method since if you try to call the method as AddTwoNumbers you won't be able to do that.

The running application:



Hope this helps!