Sunday, May 27, 2012

crm 2011- LINQ to retrieve associated cases

 var query1 = (from co in orgSrvContext.CreateQuery<Contact>()
                        join ca in orgSrvContext.CreateQuery<Incident>() on co.ContactId equals ca.CustomerId.Id
                        where co.MobilePhone == mobilenumber
                        select ca).ToList();
          Ins = new ObservableCollection<Incident>(query1);

To retrieve associated  records in plugin or custom workflow activity
   var  retrievedGunTransaction=   service.Retrieve(jmh_guntransaction.EntityLogicalName, context.PrimaryEntityId, new ColumnSet(true));
                  var gunTransaction = retrievedGunTransaction.ToEntity<jmh_guntransaction>();
                  var query = from trancationentry in orgServiceContext.CreateQuery<jmh_guntransactionentry>()
                              where trancationentry.jmh_guntransaction.Id == retrievedGunTransaction.Id
                              select trancationentry;

                  foreach (var transEntry in query)
                      {
                                 
                      }

Friday, May 11, 2012

CRM 2011-Retreiving data from crm using LINQ with early binding and OrganisationServiceContext

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel.Description;
using System.ComponentModel;
using System.ServiceModel;

namespace CrmTestApp
{
   
    public partial class MainWindow : Window
    {
      
        public ObservableCollection<Contact> collect { get; set; }
        public static EntityCollection result;
        public static OrganizationServiceProxy _serviceProxy;
       public static OrganizationServiceContext context;
  
        public MainWindow()
        {
            InitializeComponent();
         
        }
   
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {  
             
         
            IServiceConfiguration<IOrganizationService> orgConfigInfo =
                ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri("http://ntiercrm/cca/XRMServices/2011/Organization.svc"));
           
            var creds = new ClientCredentials();
            using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
            {
                _serviceProxy.EnableProxyTypes();  //To support early binding
                context = new OrganizationServiceContext(_serviceProxy);
                var query = from c in context.CreateQuery<Contact>()
                            where c.MobilePhone == textBox1.Text
                             select c;
                collect = new ObservableCollection<Contact>(query.ToList()); //Converting IQueriable to Observable collection
                dataGrid1.ItemsSource = collect;
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            IServiceConfiguration<IOrganizationService> orgConfigInfo =
                ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri("http://ntiercrm/cca/XRMServices/2011/Organization.svc"));

            var creds = new ClientCredentials();
            using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
            {
                _serviceProxy.EnableProxyTypes();  //To support early binding
                context = new OrganizationServiceContext(_serviceProxy);
                var query = from c in context.CreateQuery<Contact>()
                            select c;
                collect = new ObservableCollection<Contact>(query.ToList()); //Converting IQueriable to Observable collection
                dataGrid1.ItemsSource = collect;
            }
        }

     }
}

Crm 2011- Generating early bound classes using crmsvcutil.exe


1. Open the visual studio 2010 and click Tools->External tools
2. Now click Add button and type as following
  • Title:
crmsvcutil tool 
  •   Command:
 E:\AKILAN\CRM Training\SDK\sdk\bin\crmsvcutil.exe
                (path of crmsvcutil.exe in sdk)
  •  Arguments:
 /url:http://<serverName>/<organizationName>/XRMServices/2011/Organization.svc
 /out:Xrm.cs
/username:<username> /password:<password> /domain:<domainName>
/namespace:Xrm /serviceContextName:XrmServiceContext
(organization service url, output file name,username,password) 
  •   Initial directory:
 d:\  
(Path of the output files to be stored)
Uncheck the “Close on exit” and click ok
3. Now click tools-> crmsvcutil tool to generate early bound classes

Note: to use crmcvcutil in windows xp, windows identity foundation must be installed.
To install windows identity foundation in xp,  Copy C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation folder to to C:\Program Files\Reference Assemblies\Microsoft folder from windows server 2008/7 OS to windows xp.

Reference:
http://msdn.microsoft.com/en-in/library/gg327844.aspx

Thursday, May 10, 2012

CRM 2011-Retrieving data from crm 2011 using FetchXML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel.Description;
using System.ComponentModel;

namespace CrmTestApp
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<contact> collect { get; set; }
        public static EntityCollection result;
        public static OrganizationServiceProxy _serviceProxy;
        public MainWindow()
        {
            InitializeComponent();          
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
           
            string fetch = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='contact'>
    <attribute name='fullname' />
    <attribute name='parentcustomerid' />
    <attribute name='telephone1' />
    <attribute name='emailaddress1' />
    <attribute name='contactid' />
    <order attribute='fullname' descending='false' />
    <filter type='and'>
      <condition attribute='ownerid' operator='eq-userid' />
      <condition attribute='statecode' operator='eq' value='0' />
   <condition attribute='mobilephone' operator='eq' value='" + textBox1.Text + @"' />
    </filter>
  </entity>
</fetch>";

            IServiceConfiguration<IOrganizationService> orgConfigInfo =
                ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(
new Uri("http://ntiercrm/cca/XRMServices/2011/Organization.svc"));
    
            var creds = new ClientCredentials();
            using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
            {

                result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetch));

                collect = new ObservableCollection<contact>();
                foreach (var c in result.Entities)
                {

                    collect.Add(new contact()
                    {
                        Email = c.Attributes["emailaddress1"].ToString(),
                        Id = c.Attributes["contactid"].ToString(),
                        Name = c.Attributes["fullname"].ToString()
                    });
                }
            }
                      dataGrid1.ItemsSource = collect;
        }
    }
  public class contact
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Id { get; set; }

    }
}

Thursday, May 3, 2012

PRISM - Communicating Between Loosely Coupled Components

The Prism Library provides the following communication approaches:  

Solution commanding. Use when there is an expectation of immediate action from the user interaction.
Event aggregation. For communication across view models, presenters, or controllers when there is not a direct action-reaction expectation.
Region context. Use this to provide contextual information between the host and views in the host's region. This approach is somewhat similar to the DataContext, but it does not rely on it.
Shared services. Callers can call a method on the service which raises an event to the receiver of the message. Use this if none of the preceding is applicable.

In short
Composite command- communicate among the views in module and shell project
Delegate command-communicate among the views in the same module
Event aggregation-communicate the views in different modules.
Region context- communicate among the views in the same region
Shared services- Use this if none of the preceding is applicable.

Event Aggregation

Composite Command

You publish an event -> all subscribers receive notice and execute code in response
You execute a composite command -> all registered commands get executed and with it their attached code
Asynchronous
Synchronous

If you need the sending of a message to be initiated by a user gesture such as a button click, Commands may be a good choice. If you need the sending of a message to be initiated by business logic code, such as in a controller or presenter, you should consider using the EventAggregator.
When to use:
There are two primary differences between these two.
  1. CanExecute for Commands. A Command can say whether or not it is valid for execution by calling Command.RaiseCanExecuteChanged() and having its CanExecute delegate return false. If you consider the case of a "Save All" CompositeCommand compositing several "Save" commands, but one of the commands saying that it can't execute, the Save All button will automatically disable (nice!).
  2. EventAggregator is a Messaging pattern and Commands are a Commanding pattern. Although CompositeCommands are not explicitly a UI pattern, it is implicitly so (generally they are hooked up to an input action, like a Button click). EventAggregator is not this way - any part of the application effectively raises an EventAggregator event: background processes, ViewModels, etc. It is a brokered avenue for messaging across your application with support for things like filtering, background thread execution, etc.
It's more difficult to say when to use each, but generally if its user interaction that raises the event use a command, for anything else use EventAggregator.


Solution Commanding

 

 if you need to respond to a user gesture, such as clicking on a command invoker (for example, a button or menu item), and if you want the invoker to be enabled based on business logic, use commanding

DelegateCommand, which allows you to call a delegate method when the command is executed.
The DelegateCommand will be used just to connect the View with its Model.

CompositeCommand, which allows you to combine multiple commands.

How does this help you with cross module communication?
Applications based on the Prism Library may have global CompositeCommands that are defined in the shell that have meaning across modules, such as Save, Save All, and Cancel. Modules can then register their local commands with these global commands and participate in their execution.

example code:
publish:

                        MobileNumber = SearchTextBox.Text;
                        ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<SearchCustomerEvent>().Publish(MobileNumber);


subscribe:

  private void Window_Loaded(object sender, RoutedEventArgs e)
        {
                        ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<SearchCustomerEvent>().Subscribe(this.Display, true);
        }
          private void Display(object val)
        {
            MessageBox.Show("Mobile number is" + val);

 
        }

Msdn:
FAQ: Questions and answers:
Event Aggregator:
To understand event aggregator:

Simple example using event aggregator



Sample application using event aggregator
Region Context:
Shared Services:


Wednesday, May 2, 2012

Prism-Composing the User Interface ( View Injection vs View Discovery)

View Injection

IRegion.Add
public void Initialize()
{
    _regionManager.Regions["MainRegion"].Add( new ModuleAView() );
}

View Discovery

IRegionManager.RegisterViewWithRegion
public void Initialize()
{
    _regionManager.RegisterViewWithRegion( "MainRegion", typeof( ModuleAView ) );
}   

When to Use View Discovery vs. View Injection

 

Choosing which view loading strategy to use for a region depends on the application requirements and the function of the region.
Use view discovery in the following situations:
  • Automatic view loading is desired or required.
  • Single instances of a view will be loaded into the region.
Use view injection in the following situations:
  • Your application uses the Navigation APIs.
  • You need explicit or programmatic control over when a view is created and displayed, or you need to remove a view from a region; for example, as a result of application logic or navigation.
  • You need to display multiple instances of the same views in a region, where each view instance is bound to different data.
  • You need to control which instance of a region a view is added to. For example, you want to add a customer detail view to a specific customer detail region. (This scenario requires implementing scoped regions as described later in this chapter.)
Sample Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;

namespace HelloWorldModule
{
    public class HelloWorldModule:IModule
    {
        private readonly IRegionManager regionManager;
        public void Initialize()
        {
            //View Injection
            regionManager.Regions["MainRegion"].Add(new Views.HelloWorldView());

            //View Discovery
            regionManager.RegisterViewWithRegion("MainRegion", typeof(Views.HelloWorldView));

          
        }
      public  HelloWorldModule(IRegionManager regionManager)
        {
            this.regionManager = regionManager;
        }

    }
}