Saturday, November 14, 2009

Using Reflection to Get and Set values of Properties

The assembly that is generated for .Net Framework has metadata that describes the structure of the assembly and its classes. By using reflection we can investigate the structure of classes and the data that assembly holds dynamically at runtime.

You can dynamically get/set values from/to properties of object. #

Get value

foreach (PropertyInfo info in myObject.GetType().GetProperties())
{
if (info.CanRead)
object o = info.GetValue(myObject, null);
}

Set value

object myValue = "Any_Value";
if (info.CanWrite)
this.info.SetValue(myObject, myValue, null);

It's very helpful and easy to use. Isn't is ?

Wednesday, November 11, 2009

SyncToy 2.1 Available for Download


How many times have you tried to copy a huge number of files only to accidently hit space or escape cancelling the transfer and you don't want to re-start from scratch? Well there's a better way to sync files between directories and drives, SyncToy. You might remember this from the XP PowerToys days, the ease of use makes it a very popular download.

SyncToy 2.1 has just been released to the Microsoft Download center. SyncToy 2.1 is a free application that synchronizes files and folders between locations. Typical uses include sharing files, such as photos, with other computers and creating backup copies of files and folders.

SyncToy2.1 is powered by the latest synchronization engine from Microsoft Sync Framework 2.0 and provides better performance and robustness. The new features and improvements included in SyncToy 2.1 release are:
Better Performance: The speed of file copy operations is significantly increased across the board.
Improved Robustness: Much more resilient to transient network and file system errors, and better error reporting that pinpoints which file the sync failed on in case there’s a fatal error that stops the sync.

Folder pair configuration backup: Folder pair configuration is automatically backed up under %localappdata%\microsoft\synctoy\2.0. You can replace SyncTopDirPairs.bin with the backup copy to resolve the last saved configuration.

Bug Fixes:
o Fixed the data corruption issue when using SyncToy with NAS drives.
o Fixed the bug that prevented uploading files to SharePoint when using SyncToy 2.0.
o Fixed bugs that prevented delete changes from being synchronized when sync option was set to
“Echo”.

SyncToy 2.1 is now available for download from: http://www.microsoft.com/downloads/details.aspx?familyid=C26EFA36-98E0-4EE9-A7C5-98D0592D8C52&displaylang=en.

Wednesday, November 4, 2009

Use Temp Table in SQL SERVER 2005 Reporting Services

I was working on 2005 SSRS to generate a reprot which required a use of Temporary Tables in the dataset. But unfortunately SSRS 2005 doesn't support it. 2008 supports both Table Datatype and Temp Tables.

To resolve the issue we can use Table DataType. Below is the example:

DECLARE @TempTable TABLE (
ID INT,
DOJ DATETIME,
NameVarchar(100)
)

INSERT INTO @TempTable VALUES(1, GETDATE(), 'Ranjit');
INSERT INTO @TempTable VALUES(2, GETDATE(), 'Ranjitsingh');

SELECT * FROM @TempTable
This way you can resolve the Temp table issues by using Table Datatype.

PostBack in ASP.Net showModalDialog opens a new window

When working with Modal Dialog Windows in ASP.Net you have experience that postback opens up a new window. This behavior is by default.

I was using window.showModalDialog() to open a ASPX Page from the parent page using JavaScript. But whenever the postback happens in the modal window during a button click or dropdown value changes, it would spawn off a new window.

You can change the behaviour by just including below tag line in the <head> of the modal window (that is aspx page).
<base target="_self">

I hope this would help you resolving the problem.

Missing ASP.NET and ASP.NET Web Service Project Templates


Missing ASP.NET and ASP.NET Web Service Project Templates?

You are at the right place to solve your problem. Just visit the below link and dlwonload the .msi file.
http://download.microsoft.com/download/9/0/6/906064ce-0bd1-4328-af40-49dca1aef87c/WebApplicationProjectSetup.msi

After instalation ASP.NET web aplication template and WebService appears in New Project Promt .

Isn't it simple solution?

Friday, August 28, 2009

eService Accelerator for CRM Online - Video


Its a very good video for eService Accelerator for CRM. You can find it here.

Update Rollup 6 for Microsoft Dynamics CRM 4.0 (KB 970148)


Microsoft has release rollup 6for CRM 4. KB952858 can be downloaded here.

This is a tested, cumulative set of updates for Microsoft Dynamics CRM 4.0. It includes performance enhancements that are packaged together for easy deployment.

Please note that if you have customized Microsoft Dynamics CRM 4.0 Help files, back up your customized files before you install this update !!!

Overview
Microsoft has released Update Rollup 6 for Microsoft Dynamics CRM 4.0 Server, Microsoft Dynamics CRM for Microsoft Office Outlook, Microsoft Dynamics CRM Data Migration Manager, Microsoft Dynamics CRM 4.0 Language Pack, and Microsoft Dynamics CRM 4.0 E-mail Router.

For more information about this release, see Microsoft Knowledge Base article 970148:
Update Rollup 6 is available for Microsoft Dynamics CRM 4.0

To maintain parity between the application components of Microsoft Dynamics CRM 4.0, this update rollup includes packages for Microsoft Dynamics CRM 4.0 Server, Microsoft Dynamics CRM for Outlook, Microsoft Dynamics CRM Data Migration Manager, Microsoft Dynamics CRM Language Packs, and Microsoft Dynamics CRM 4.0 E-mail Router.

Tuesday, August 11, 2009

New Visual Studio Templates for MS CRM


The CRM SDK version 4.0.9 included three Visual Studio templates to help speed up your CRM-related development efforts:

Available Templates

  • Plug-in
  • Workflow activity
  • CRM Add-on web page

The templates may be found in the visualstudiotemplates folder when you unzip the SDK package.
Each template has an accompanying readme.doc file with instructions for installation and usage notes.

Installation
Installation is fairly straightforward, just perform these steps:

1) Navigate to the Visual Studio Folder:
%Documents and Settings%\Visual Studio 2008\Templates\ProjectTemplates\Visual C#

2) Create a folder called CRM.

3) Copy each of the three template’s .zip file to the CRM folder.

The templates should now be installed and ready to use.

Thursday, July 16, 2009

RollUp 5 release for MS CRM 4.0


Microsoft has release rollup 5for CRM 4. KB952858 can be downloaded here.

This is a tested, cumulative set of updates for Microsoft Dynamics CRM 4.0. It includes performance enhancements that are packaged together for easy deployment.

Please note that if you have customized Microsoft Dynamics CRM 4.0 Help files, back up your customized files before you install this update !!!

Monday, July 13, 2009

Crystal Report 4.6 - Error 20540; Missing or out of date Export DLL


I was happen to install Crystal Report 4.6. for one of my project. As soon as I call the Crystal Report via VB 6.0 Code, i got the below error -

Calling a report from an application using the Crystal Report Control (Crystl32.ocx) version 4.6 results in one of the following:
- not all of the export options are available - error 20540; Missing or out of date Export DLL.


If you are getting the same error as above please follow the below steps to resolve the issue:
Solution
Seagate Crystal Reports version 4.6 installs the Crystal export DLLs into the
\Program Files\Microsoft Visual Studio\Common\Tools\REPORTS directory, rather than putting them in a Windows\Crystal, or Windows\system directory

This does not create a problem conducting an export from the Crystal Reports Designer,
From a Microsoft Visual Basic application, the export DLLs are not found.

Workaround:There are two ways around this:

1. Add the \Program Files\Microsoft Visual Studio\Common\Tools\REPORTS directory to your Path statement so that the operating system searches that directory for needed DLLs.

2. Copy the export DLLs to the Windows\system directory. The export DLLs are the u2*.dll files.
Reference : Crystal Care Technical Support.
http://support.crystaldecisions.com/

Isn't it easy !!! Happy Development.

Tuesday, June 23, 2009

System.IO.FileNotFoundException: The Web application could not be found.


If you are getting the above error when performing some operation in you Web Service / Web Appliation with Sharepoint server. You can resolve this by adding the Sharepoint application pool in you custom Web Service / Web Appliation :

In the IIS, you need to open the property page of the Web Service / Web Appliation that you host. under "Home Directory" Tab, you can chose the appliction pool. make sure that your sharepoint web appliction and your webservice sharing the same application pool name.


To interact with a SharePoint Server from out side the SharePoint web server it self, you need to write a SharePoint web service. SharePoint web services are nothing bur regular web service, only difference is that they are configured into the SharePoiint site configurations. And from inside the Web service you can do whatever possible with the Object model.

To get the SPSite instance from inside the web service, you even dont need to specify domain names, ip etc. Just doing the following you can have an instance of SPSite

SPSite siteCollection = SPControl.GetContextSite(HttpContext.Current); OR
SPWeb subSite = SPControl.GetContextWeb(HttpContext.Current);

After creating and deploying a web service into the SharePoint you can talk to the web service from anywhere of the world and the web service will actually make use of object model to talk to SharePoint.

Could not verify the version of Microsoft Dynamics CRM - VPC 2009 Error


I download the MS CRM VPC 2009 and did the windows update. When I reboot the system the MS CRM Web Application was not getting loaded.

I confirm that all the MS SQL SERVER and MS CRM services are running. Finally I check the Event Log and found the below error:
Could not verify the version of Microsoft Dynamics CRM at http://crm/Contoso.
The remote name could not be resolved: 'crm'

To resolve this issue, simply add the entry in HOST file.
Browse "C:\WINDOWS\system32\drivers\etc\" and open the HOSTS file in notepad and add the below entry at the end of the file :
127.0.0.1 crm

Save and close the file.
Refresh you browser.... Here your MS CRM app will get loaded....

Saturday, June 13, 2009

Microsoft Dynamics CRM SDK Version 4.0.9 Released

Download this new version of the SDK or view it on MSDN.

This release provides continuing support for the on-premise user and new information for online users.

The following are some highlights. For a complete list of changes, see the Release History on the first page.
Server-to-Server Authentication Sample. This sample shows how to authenticate and impersonate the logged-on user in a server-to-server scenario with Microsoft Dynamics CRM Online.
Metadata Browser - Over 100 pages from the metadata browser have been incorporated into the SDK so that Online users have access to this information.

Visual Studio Templates. Added three new Microsoft Visual Studio template projects for you to use to start your projects: CRM Web page, plug-in, and custom workflow activity. For more information, see List of Samples in the SDK Download.

Dependent Picklist Sample - This sample shows how to make the options available in a picklist field dependent on the selected option of another picklist. It supports chaining several picklist fields together. This sample also includes best practices for defining functions in the OnLoad event and reusing them in other form events.

Updated WSDLS for CRM Online. Added new properties available only on Online and a new Discovery service method that retrieves the logged-on user's ID in Microsoft Dynamics CRM Online.
Delete Async Records Sample - This sample shows how to remove completed records from the async table.

KB Article Topics - added topics that describe knowledge base article states, how to create, publish and remove the articles, and how to search for published knowledge base articles in Microsoft Dynamics CRM.

Updated Visual Studio projects to work for both VS 2005 and VS2008.
Updated support information for plug-in and workflow assembly backwards compatibility.
More sample code updates and miscellaneous bug fixes.

Cheers !!!!!

Saturday, May 30, 2009

How to UnRegister .NET Windows Service ?


Use the below script to unregister a windows Service.

Step 1: Create a batch file (eg., UnRegister.bat) and put it in the same foler where your windows service executable file resides).

Step 2: Copy the below script and paste it in above "UnRegister.bat" file.

@ECHO OFF

REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%

echo UnInstalling WindowsService...
echo ---------------------------------------------------
net stop WINDOWS_SERVICE_NAME
InstallUtil /u WINDOWS_SERVICE.EXE
echo ---------------------------------------------------
pause
echo Done.

Step 3: Replace your windows Service executable file with "WINDOWS_SERVICE_NAME" and "WINDOWS_SERVICE.EXE" string.

Step 4: Save -> Exit from the file. Now the batch file is reay to uninstall the windows service. Just double click the "UnRegister.bat" file.

How to Register .NET Windows Service ?

Registering a Windows Service is always a challenge .

I personally prefer to write / use a script. Below is a script which will install a Windows Service and start it once its installed properly. By default it will set the Mode "Automatic When windows OS starts".


Step 1: Create a batch file (eg., Register.bat) and put it in the same foler where your windows service executable file resides).

Step 2: Copy the below script and paste it in above "Register.bat" file.

@ECHO OFF

REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%

echo Installing WindowsService...
echo ---------------------------------------------------
InstallUtil /i WINDOWS_SERVICE_NAME
net start WINDOWS_SERVICE.EXE
echo ---------------------------------------------------
pause
echo Done.


Step 3: Replace your windows Service executable file with "WINDOWS_SERVICE_NAME" and "WINDOWS_SERVICE.EXE" string.

Step 4: Save -> Exit from the file.

Now the batch file is reay to install the windows service. Just double click the "Register.bat" file.

Isn't it very easy !!!!

Monday, May 18, 2009

RollUp 4 release for MS CRM 4.0


Microsoft has release rollup 4 for CRM 4. KB952858 can be downloaded here.

This is a tested, cumulative set of updates for Microsoft Dynamics CRM 4.0. It includes performance enhancements that are packaged together for easy deployment.

Please note that if you have customized Microsoft Dynamics CRM 4.0 Help files, back up your customized files before you install this update !!!

Sunday, May 17, 2009

Invalid Action - The selected action was not valid.


I download new MS CRM VPC (April 2009), When I browse the MS CRM Default organization (contoso)I discovered that we were receiving a very descriptive "Invalid Action: The selected action was not valid" error message.

Then, I checked the system's Application Event Log. LOL, I found the following error message:
Source: Current active key (KeyType : CrmWRPCTokenKey) is expired. This can indicate that a key is not being regenerated properly. Current Active Key : CrmKey(Id:e1a5b215-d01e-de11-9d16-0003ffd0167c, ScaleGroupId:00000000-0000-0000-0000-000000000000, KeyType:CrmWRPCTokenKey, Expired:True, ValidOn:04/01/2009 15:16:36, ExpiresOn:05/04/2009 15:16:36, CreatedOn:04/01/2009 15:16:36, CreatedBy:NT AUTHORITY\NETWORK SERVICE. Key Setting :


Fortunately, this problem was easily solved by running services.msc and starting the Microsoft CRM Asynchronous Processing Service.

Always look into Event Log messages for quick error resolutions (MS, Pls give more info, dont just put the kb link :( )

Saturday, May 16, 2009

Read a Text File Line by Line using C#


Here is the sample code:

string file_name = @"c:\list.txt";
System.IO.StreamReader ObjReader = new System.IO.StreamReader(file_name);
do
{
MessageBox.Show(ObjReader.ReadLine());
} while (ObjReader.Peek() != -1);


Happy Programming !!!!

Recover Corrupt SQL Server Database


This is quiet common while working on VPC (MS CRM VPC) that when the VPC gets close abnormally.

When you restart the VPC and try to open MS CRM Web you will see some SQL SERVER (Database Corrupt) related error. When you open SQL Server Enterprises studio and we will observe that the database is in SUSPEND mode. And this is due to the VPC gets close abnormally.

But still you can recover the DATABASE. Use the below set of SQL Statement .

EXEC sp_resetstatus 'MicrosoftCRM_MSCRM';
ALTER DATABASE MicrosoftCRM_MSCRM SET EMERGENCY

DBCC checkdb('MicrosoftCRM_MSCRM')
ALTER DATABASE MicrosoftCRM_MSCRM SET SINGLE_USER WITH ROLLBACK IMMEDIATE

DBCC CheckDB ('MicrosoftCRM_MSCRM', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE MicrosoftCRM_MSCRM SET MULTI_USER

MicrosoftCRM_MSCRM is database name (for example purpose). When you use this script to recover the database replace MicrosoftCRM_MSCRM with your database name.

Enjoy. Happy recovering corrupt SQL Server Database.

IsNullOrEmptyOrNoValue() - Extension of IsNullOrEmpty()

public static bool IsNullOrEmptyOrNoValue(string strValue)
{

return (string.IsNullOrEmpty(strValue) ? true : (string.IsNullOrEmpty(strValue.Trim()) ? true : false));

}

Parameters
value
Type: System.String
A String reference.

Return Value
Type: SystemBoolean

true if the value parameter is a null reference (Nothing in Visual Basic) or an empty string (""); or the trim value is empty otherwise, false.

Remarks
IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is a null reference (Nothing in Visual Basic) or its value is Empty or the trim value is empty.


IIS Log File Location


Here is the solution.

Location of IIS log files:

Windows Xp:
C:\WINDOWS\system32\Logfiles\W3SVC1

Windows NT/2000:
C:\WINNT\system32\Logfiles\W3SVC1


Visual Studio 6 Error - Cannot find file ACMBOOT.EXE (or one of its components).


I was happen to install Visual Studio 6.0 for one of my project. As soon as Run the Professional Edition i got the below error -

Cannot find file ACMBOOT.EXE (or one of its components). Check to ensure the path and filename are correct and that all required libraries are available.

If you are getting the same error as above please follow the below steps to resolve the issue:

1. make a copy of your installation cd in your hard drive
2. make a copy of the setup/VS98ENT.STF and name it acmsetup.STF
3. copy entire content of setup/ to previous folder (the one that has acmboot.exe file)
4. run acmsetup.exe instead of setup (the one that's on the same path as acmboot.exe)
5. voala, that's it, your visual studio 6.0 will be installed.

Isn't it easy !!! Happy Development.

Tuesday, April 28, 2009

Retrieve Multiple Dynamic Entity Records Example

Example:





try      
{
BusinessEntityCollection retrieved = RetreiveMultipleEntityDetails(entityName.Trim().ToLower(), new string[] { filterColumn }, new string[] { filterValue }, null);            if (retrieved != null)                  return (DynamicEntity)retrieved.BusinessEntities[0];            return null;      }
 
Function: 
 
 
 
public BusinessEntityCollection RetreiveMultipleEntityDetails(string entityName, string[] filterColumns, string[] filterValues, string[] ColumnList)        
{
RetrieveMultipleResponse retrieved = new RetrieveMultipleResponse();
try
{
/// Create the query object.
QueryByAttribute query = new QueryByAttribute();
query.EntityName = entityName.Trim().ToLower();
if (ColumnList == null)
{
query.ColumnSet = new AllColumns();
}
else
{
ColumnSet columns = new ColumnSet();
columns.Attributes = ColumnList;
query.ColumnSet = columns;
}
query.Attributes = filterColumns;
query.Values = filterValues;
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
 
retrieved = (RetrieveMultipleResponse)Service.Execute(retrieve);
if (retrieved != null)
return retrieved.BusinessEntityCollection;                return null;
}
#region Exception Handling
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new Exception(ex.Detail.InnerText);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
#endregion Exception Handling
}

Friday, April 10, 2009

Get detailed error of Waiting Workflows


If an error occoured during the Workflow execution, and you want to see the detailed error of waiting workflow you just need to simply follow the below steps:

  • In the web client goto the 'System jobs' in the settings area
  • Click "Advanced find"
  • Click "Edit Columns"
  • Click "Add Columns"
  • Select the columns "Error Code" and "Message"
  • Click "OK" twice
  • Click "Find" this will execute the query and bring up the workflows which have executed. If the workflow ran into an error the error code and message column will contain details.

    Note that in case of an exception the message is the same as that logged in the trace files (if enabled)

You can save this query, this will make it available in the View list.


Thursday, March 26, 2009

Unable to Create / Update record for Business Closure.


First, you have to assign the below role (Update Business Closures) to the user.

Second, you have to assign another set of roles to the user:
Go to Service Management tab -> assign Calender entities (Create, Read, Write) roles.


Save and Close Roles record.
Refresh the Business Closures entity record page(http://SERVER:PORT/Organisation_Name/tools/business/business.aspx?pid=02)

Isn't it simple !!!!!

Wednesday, March 25, 2009

Declaration of Custom Workflow Input / Output Parameters


Eveyone struggle to declare the Custom workflow input / output parameters in the custom workflow activity. So here is the solution for it.

The following sample shows how to use each of the types found in Microsoft Dynamics CRM.

Input Parameter Declaration: (Click on the datatype to see the declaration)

Boolean


DateTime

Decimal

Float

Lookup

Money

Number

Picklist

Status

String


Output Parameter Declaration: (Click on the datatype to see the declaration)


Lookup


Hope this will help you in declaring the Custom workflow activity I/O parameters.

Global Javascript Functions in MS CRM 4.0


Global functions provide information about the client application and whether the user is working online.

The following table shows the available global functions.

IsOnline : Checks whether the client application for which this page is rendered is online or offline.

IsOutlookClient :Checks whether the form is shown on either Microsoft Dynamics CRM for Microsoft Office Outlook or Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access.

IsOutlookLaptopClient : Checks whether the form is shown on Microsoft Dynamics CRM for Outlook with Offline Access.

IsOutlookWorkstationClient : Checks whether the form is shown on Microsoft Dynamics CRM for Outlook.

GenerateAuthenticationHeader : Returns a string that represents a correctly formed Microsoft Dynamics CRM authentication header used when making Web service calls with Microsoft Dynamics CRM Web services.

PrependOrgName : Prepends the organization name to the specified path.

Global Javascript Variables in MS CRM 4.0


Global variables provide information about the Microsoft Dynamics CRM deployment and options chose by the user. Below Global variables you can use in ISV, Event Scripts of forms and across all CRM Web Pages.

The following table shows the available global variables.

SERVER_URL : Provides a string that represents the base server URL. When a user is offline, the SERVER_URL points to the local Microsoft Dynamics CRM Web services.

USER_LANGUAGE_CODE : Provides an LCID value that represents the Microsoft Dynamics CRM Language Pack that the user has selected.

ORG_LANGUAGE_CODE : Provides an LCID value that represents the Microsoft Dynamics CRM Language Pack that is the base language for the organization.

ORG_UNIQUE_NAME : Provides the unique text value of the organizations name.

Example
This script displays the values of these global variables.
alert("SERVER_URL="+SERVER_URL );
alert("USER_LANGUAGE_CODE="+USER_LANGUAGE_CODE);
alert("ORG_LANGUAGE_CODE="+ORG_LANGUAGE_CODE);
alert("ORG_UNIQUE_NAME="+ORG_UNIQUE_NAME);

There is an error in xml document (Row, column)


Are you getting this error When Calling retrieve(), retrieveMultiple() ..... and so on CRM Methods ?

The solution is very simple:
remove the existing CRM Web services and Add them again (CrmService, Discovery, Metadata).
Recompile and Run your application.

Wednesday, February 18, 2009

Get Dynamic Entity Primary Attribute Guid Example


Example by CrmSdk


public Guid GetDynamicEntityPrimaryAttributeGuid(DynamicEntity entity)
{
    if (entity != null)
    {
        string strPrimaryKeyAttributeName = entity.Name.ToLower() + "id";
        return ((Microsoft.Crm.Sdk.Key)entity.Properties[strPrimaryKeyAttributeName]).Value;
    }
    return Guid.Empty;
}

Example by Web Service

public Guid GetDynamicEntityPrimaryAttributeGuid(DynamicEntity entity)
{
    if (entity != null)
    {
        string strPrimaryKeyAttributeName = entity.Name.ToLower() + "id";
        for (int i = 0; i < entity.Properties.Length; i++)
        {
            if (entity.Properties[i].Name.ToLower() == strPrimaryKeyAttributeName)
            {
                KeyProperty property = (KeyProperty)entity.Properties[i];
                return property.Value.Value;
            }
        }
    }
    return Guid.Empty;
}

Create Dynamic Entity Record Example


StringProperty firstname = new StringProperty();
firstname.Name = "firstname";
firstname.Value = "Ranjit"; 

StringProperty lastname = new StringProperty();
lastname.Name = "lastname";
lastname.Value = "Singh"; 

// Create the DynamicEntity object.
DynamicEntity contactEntity = new DynamicEntity(); 

// Set the name of the entity type.
contactEntity.Name = EntityName.contact.ToString(); 

// Set the properties of the contact.
contactEntity.Properties = new Property[] {firstname, lastname}; 

// Create the target.
TargetCreateDynamic targetCreate = new TargetCreateDynamic();
targetCreate.Entity = contactEntity; 

// Create the request object.
CreateRequest create = new CreateRequest(); 

// Set the properties of the request object.
create.Target = targetCreate; 

// Execute the request.
CreateResponse created = (CreateResponse) service.Execute(create);

Monday, February 16, 2009

Working with FetchXml()


Fetch is a proprietary query language that is used in Microsoft Dynamics CRM. It is based on a schema that describes the capabilities of the language. The FetchXML language supports similar query capabilities as query expression. It is used primarily as a serialized form of query expression, used to save a query as a user owned saved view in the userquery entity or as an organization owned view in the savedquery entity. A FetchXML query can be executed by using the Fetch method. There are also messages to convert between query expression and FetchXML.

Generally, the RetrieveMultiple method performs faster than the Fetch method because it does not have to parse the query.

Microsoft Dynamics CRM 4.0 supports a new attribute on the link-entity node called visible. Setting visible to false will hide the linked entity in the advanced find user interface. It will still participate in the execution of the query and will return the appropriate results.

The following table lists the messages that work with the FetchXml language.

ExecuteFetch -> Executes a query.
FetchXmlToQueryExpression -> Converts from FetchXML to query expression.
QueryExpressionToFetchXml -> Converts from query expression to FetchXML.
ValidateSavedQuery -> Validates a saved query (view).

NOTE:
Notice that in either case, the privileges of the logged on user will affect the set of records returned. The Fetch method only retrieves records for which the logged on user has read access.

By default FetchXml returns MAX of 5000 records.

Dynamic Entity Add Attribute Helper Methods

Examples: Calling the below methods:

string strDaysAttributeName = "cap_actualeffortdays";
string strHoursAttributeName = "cap_actualefforthours";
 
if (ObjProject.Properties.Contains(strDaysAttributeName))
    ((CrmNumber)ObjProject.Properties[strDaysAttributeName]).Value = iDays;
else
    CrmHelper.AddNumberProperty(ObjProject, strDaysAttributeName, iDays);

 
if (ObjProject.Properties.Contains(strHoursAttributeName))
    ((CrmNumber)ObjProject.Properties[strHoursAttributeName]).Value = iHours;
else
    CrmHelper.AddNumberProperty(ObjProject, strHoursAttributeName, iHours);


public static void AddStringProperty(DynamicEntity entity, string strColumnName, string DefaultValue)
{
    #region If Column attribute not in entity Collection 

        if (!entity.Properties.Contains(strColumnName))
        {
            StringProperty AttributeContactID = new StringProperty();
            AttributeContactID.Name = strColumnName;
            AttributeContactID.Value = DefaultValue;
        }
    #endregion If Column attribute not in entity Collection
}

 

public static void AddNumberProperty(DynamicEntity entity, string strColumnName, int DefaultValue)
{
    #region If Column attribute not in entity Collection 

        if (!entity.Properties.Contains(strColumnName))
        {
            CrmNumberProperty AttributeID = new CrmNumberProperty();
            AttributeID.Name = strColumnName;
            AttributeID.Value = new CrmNumber(DefaultValue);
        }
    #endregion If Column attribute not in entity Collection
}

Update Dynamic Entity Record Example


public static bool UpdateDynamicEntity(ICrmService Service, DynamicEntity entityName)
{
try
{
    // Create the update target.
    TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic(); 

    // Set the properties of the target.
    updateDynamic.Entity = entityName; 

    //   Create the update request object.
    UpdateRequest update = new UpdateRequest(); 

    //   Set request properties.
    update.Target = updateDynamic; 

    //   Execute the request.
    UpdateResponse updated = (UpdateResponse)Service.Execute(update);

    return true;
}
catch (System.Web.Services.Protocols.SoapException ex)
{                
    return false;
}
catch (Exception ex)
{                
    return false;
}
}

Retrieve Dynamic Entity Records Example



DynamicEntity ObjProject = GetDynamicEntity(crmService, "new_timesheet", new Guid("{21CCFA77-FFF8-DD11-AE96-0003FFD751E0}"));


public static DynamicEntity GetDynamicEntity(ICrmService crmService, string strEntityName, Guid EntityGuid)
{
try
            {
#region Retrieve Entity Record Dynamically
// Create the retrieve target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();
// Set the properties of the target.
                targetRetrieve.EntityName = strEntityName;
targetRetrieve.EntityId = EntityGuid;


// Create the request object.
                RetrieveRequest retrieve = new RetrieveRequest();


// Set the properties of the request object.
                retrieve.Target = targetRetrieve;
retrieve.ColumnSet = new AllColumns();


// Indicate that the BusinessEntity should be retrieved as a DynamicEntity.
                retrieve.ReturnDynamicEntities = true; 


// Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)crmService.Execute(retrieve);


// Extract the DynamicEntity from the request.
                DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;
return entity;


#endregion
            }
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new System.Exception(ex.Detail.InnerText);
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
}

Sunday, February 15, 2009

Working with Dynamic Entity

The DynamicEntity feature lets you generically access the data in any attribute on any entity in the system. In order to develop against the Microsoft CRM SDK, you must generate and consume a WSDL during code compilation. Because you must do this against a specific instance of the application, the only entities available are the core set included in the initial installation of Microsoft CRM. The WSDL does contain entity and attribute customizations but it is recommended that your code works with a clean installation. See Using the Microsoft CRM WebServices.


The DynamicEntity class is also used in plug-ins / callouts so that your callout code can work generically with any attribute on any entity without a re-compile.


The DynamicEntity class does not provide a name-base indexer, however, you can write your own. A simple approach to this problem is to loop through the dynamic entities property bag until you find the appropriate property.

Tuesday, January 20, 2009

Update Rollup 2 for Microsoft Dynamics CRM 4.0 is available


Microsoft has release update rollup 2for CRM 4. KB959419 can be downloaded here.

This upate is for Microsoft Dynamics CRM 4.0 Server, Microsoft Dynamics CRM for Microsoft Office Outlook, and Microsoft Dynamics CRM 4.0 E-mail Router.

Please note that if you have customized Microsoft Dynamics CRM 4.0 Help files, back up your customized files before you install this update !!!

Monday, January 19, 2009

Read and assign Owner attribute value to another owner attribute.


When it come to copying Owner attribute value aand assinging it to another owner attribute in CRM Form, its not just like a simple textbox value (where u can directly assing .DataValue property to the another attribute)

Have a look at the below code, which Reads and assign Owner attribute value to another owner attribute on CRM Form.

// Get hold of Owner and default it to the Commission Owner 1
var oOwner = new Array();
oOwner = null;

oOwner = crmForm.all.ownerid.DataValue;

//Create an array to set as the DataValue for the Owner control.
var lookupData = new Array();
var oCommissionOwnerOne = new Object();

if (oOwner[0] != null)
{
// Set the id, typename, and name properties to the object.
oCommissionOwnerOne.id = oOwner[0].id;
oCommissionOwnerOne.typename = oOwner[0].typename;
oCommissionOwnerOne.name = oOwner[0].name;

// Add the object to the array.
lookupData[0] = oCommissionOwnerOne;

// Set the value of the lookup field to the value of the array.
crmForm.all.new_commissionmarginownerone.DataValue = lookupData;
}


Happy copying (and Coding too) !!!!

Friday, January 9, 2009

Supported Entities for Workflow


The following entities can be used to start the messages that trigger the workflow execution.

Entity name
1. account
2. appointment
3. businessunit
4. campaign
5. campaignactivity
6. campaignresponse
7. competitor
8. constraintbasedgroup
9. contact
10. contract
11. contractdetail
12. contracttemplate
13. customeraddress
14. customeropportunityrole
15. customerrelationship
16. discount
17. discounttype
18. email
19. equipment
20. fax
21. incident
22. invoice
23. invoicedetail
24. kbarticle
25. kbarticlecomment
26. kbarticletemplate
27. lead
28. letter
29. list
30. mailmergetemplate
31. opportunity
32. opportunityproduct
33. phonecall
34. pricelevel
35. product
36. productpricelevel
37. queue
38. quote
39. quotedetail
40. relationshiprole
41. report
42. salesliterature
43. salesliteratureitem
44. salesorder
45. salesorderdetail
46. service
47. serviceappointment
48. site
49. subject
50. systemuser
51. task
52. team
53. template
54. territory
55. transactioncurrency