How to retrieve static marketing list member in Dynamics CRM 2011

To retrieve static marketing list member in Dynamics CRM 2011 follow below steps:

  • Use Link Entities to get relationship entity details
  • Passing list Guid as object and it will return static marketing list member
 private EntityCollection RetrieveMarketingListMembers(IOrganizationService service, object strList)
        {
            QueryExpression qe = new QueryExpression();
            qe.EntityName = "contact";
            //Initialize columnset
            ColumnSet col = new ColumnSet();

            //add columns to columnset for the contact to retrieve each contact from the marketing list
            col.AddColumns(new string[] { "contactid", "lastname", "address1_line1", "address1_line2", "address1_city", "address1_stateorprovince", "address1_postalcode" });

            qe.ColumnSet = col;

            // link from contact to listmember
            LinkEntity le = new LinkEntity();
            le.LinkFromEntityName = "contact";
            le.LinkFromAttributeName = "contactid";
            le.LinkToEntityName = "listmember";
            le.LinkToAttributeName = "entityid";

            //link from listmember to list
            LinkEntity le2 = new LinkEntity();
            le2.LinkFromEntityName = "listmember";
            le2.LinkFromAttributeName = "listid";
            le2.LinkToEntityName = "list";
            le2.LinkToAttributeName = "listid";
            le2.LinkCriteria.AddCondition("listid", ConditionOperator.Equal, strList);

            //add linkentity2 to linkentity
            le.LinkEntities.Add(le2);

            qe.LinkEntities.Add(le);

            EntityCollection listmemberec = service.RetrieveMultiple(qe);
            return listmemberec;
        }
Posted in MS CRM 2011 | Tagged , | 2 Comments

How to debug offline plugin in Dynamics CRM 2011 for Outlook Offline

Following are the steps to start debug a offline plugin in Dynamics CRM 2011 for outlook offline mode:

  • Build the solution on your machine
  • Register the plugin on the server
  • Register the step deployment as server and offline
  • Synchronize the organization with the outlook
  • Go Offline
  • Attach the debugger to the process “Microsoft.Crm.Application.Hoster.exe”
  • Place a breakpoint in the code.
  • Reproduce the scenario and debug.
Posted in MS CRM 2011 | Tagged , , | Leave a comment

How to retrieve campaign and target product in Dynamics CRM 2011

To retrieve campaign and target products in Dynamics CRM 2011 follow below steps:

  1. Use Link Entities to get N:N relationship entity details
  2. Passing Campaign Activity Guid array and it will return campaign details and target products associated with campaign
private EntityCollection RetrieveCampaign(Guid[] campaignactivityids, IOrganizationService service)
        {
            EntityCollection ecCampaigns = new EntityCollection();
            try
            {
                QueryExpression query = new QueryExpression();
                query.EntityName = "campaignactivity";
                query.ColumnSet = new ColumnSet("regardingobjectid", "activityid");
                query.Criteria = new FilterExpression();
                query.Criteria.AddCondition(new ConditionExpression("activityid", ConditionOperator.In, campaignactivityids));
                LinkEntity objcamp = new LinkEntity("campaignactivity", "campaign", "regardingobjectid", "campaignid", JoinOperator.Inner);
                objcamp.Columns = new ColumnSet("new_campaignpriority");
                objcamp.EntityAlias = "campaign";
                LinkEntity objcamp1 = new LinkEntity("campaign", "campaignitem", "campaignid", "campaignid", JoinOperator.Natural);
                LinkEntity product = new LinkEntity("campaignitem", "product", "entityid", "productid", JoinOperator.Inner);
                product.Columns = new ColumnSet("productid");
                product.EntityAlias = "camapignproduct";
                objcamp1.LinkEntities.Add(product);
                objcamp.LinkEntities.Add(objcamp1);
                query.LinkEntities.Add(objcamp);
                ecCampaigns = service.RetrieveMultiple(query);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured while executing the workflow. Error Details : " + ex.ToString());
            }
            return ecCampaigns;
        }
Posted in MS CRM 2011 | Tagged , , | Leave a comment

How to create static marketing list and associated marketing list member in Dynamics CRM 2011

To create static marketing list and associated marketing list member in Dynamics CRM 2011 below are the steps:

  1. Create the array of contacts/accounts/leads.
  2. Set type attribute as false to create static list.
  3. Make sure createdfromcode attribute is set as contact/account/lead optionset value.
  4. First create marketing list and then create associated marketing list member.
private void CreateList(Guid[] contactIds, IOrganizationService service)
{
     Entity obj = new Entity("list");
     obj.Attributes["listname"] = "Non-Responded Marketing list";
     obj.Attributes["type"] = false; // false for static marketing list
     obj["createdfromcode"] = new OptionSetValue(2); // Contact optionset value is 2
     obj.Attributes["membertype"] = 2; // Contact type is 2
     Guid listid = service.Create(obj);// Create marketing list
     // Send request to create marketing list member for above created marketing list
     AddListMembersListRequest AddMemberRequest = new AddListMembersListRequest();
     AddMemberRequest.ListId = listid; // above created marketing list id
     AddMemberRequest.MemberIds = contactIds;
     AddListMembersListResponse AddMemberResponse = service.Execute(AddMemberRequest) as AddListMembersListResponse;
}
Posted in MS CRM 2011 | Tagged , , | Leave a comment

How to use FetchXML to retrieve entities in Dynamics CRM 2011.

FetchXML is query language 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.

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0; 
token.OrganizationName = "CRMHUNT";

CrmService service = new CrmService();
service.Url = ""http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Retrieve all accounts.
// Be aware that using all-attributes may adversely affect performance
// and cause unwanted cascading in subsequent updates.
// A best practice is to retrieve the least amount of data required.
string fetch1 = "<fetch mapping='logical'>";
fetch1 += "<entity name='account'><all-attributes/>";
fetch1 += "</entity></fetch>";

// Fetch the results.
String result1 = service.Fetch(fetch1);

// Retrieve all accounts owned by the user who has read access rights to the accounts and
// where the last name of the user is not HUNT.
string fetch2 = @"
   <fetch mapping='logical'>
      <entity name='account'>
<attribute name='accountid'/>
<attribute name='name'/>
<link-entity name='systemuser' to='owninguser'>
   <filter type='and'>
      <condition attribute='lastname' operator='ne' value='HUNT' />
   </filter>
</link-entity>
      </entity>
   </fetch>
   ";

// Fetch the results.
String result2 = service.Fetch(fetch2);
Posted in MS CRM 2011 | Tagged , | 1 Comment

How to calculate current age from Date of Birth using Javascript in Dynamics CRM 2011

To calculate current age from date of birth using javascript in dynamics crm 2011 follow below:

  1. Checking month difference if it is 0 simply subtract the birth year from current year.
  2. If it is negative value simply subtract the birth year from current year and -1.

Try Below Code:

function CalculateAge()
    {
    if(Xrm.Page.getAttribute("birthdate").getValue() != null) 
    { 
           var currentdate = new Date(); 
           var birthdate = Xrm.Page.getAttribute("birthdate").getValue(); 
           var monthdiff = currentdate.getMonth() - birthdate.getMonth();           
	   var currentage;

           if(monthdiff > -1) 
           {
		currentage = currentdate.getFullYear() - birthdate.getFullYear();                     
                Xrm.Page.getAttribute("new_currentage").setValue(currentage);
           }
           else
           {
		currentage = currentdate.getFullYear() - birthdate.getFullYear() - 1
                Xrm.Page.getAttribute("new_currentage").setValue(currentage);
           }
    }
    }
Posted in MS CRM 2011 | Tagged , , | Leave a comment

How to retrieve related entity data in Dynamics CRM 2011

This sample shows how to retrieve multiple entities using the RetrieveMultiple method with QueryExpression along with their related entity columns. The code returns columns from the primary account record as well as the firstname and lastname of the primary contacts associated with the account. It is a simple code where you need to specify the relationship name between two entities:

//Create multiple accounts with primary contacts
    Entity contact = new Entity("contact");
    contact.Attributes["firstname"] = "ContactFirstName";
    contact.Attributes["lastname"] = "ContactLastName";
    Guid contactId = _orgService.Create(contact, null);

    Entity account = new Entity("account");
    account["name"] = "Test Account1";
    EntityReference primaryContactId = new EntityReference("contact", contactId);
    account["primarycontactid"] = primaryContactId;

    Guid accountId1 = _orgService.Create(account, null);
    account["name"] = "Test Account2";
    Guid accountId2 = _orgService.Create(account, null);
    account["name"] = "Test Account3";
    Guid accountId3 = _orgService.Create(account, null);

    //Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
    QueryExpression qe = new QueryExpression();
    qe.EntityName = "account";
    qe.ColumnSet = new ColumnSet();
    qe.ColumnSet.Columns.Add("name");

    qe.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns("firstname", "lastname");
    qe.LinkEntities[0].EntityAlias = "primarycontact";

    EntityCollection ec = _orgService.RetrieveMultiple(qe);

    Console.WriteLine("Retrieved {0} entities", ec.Entities.Count);
    foreach (Entity act in ec.Entities)
    {
       Console.WriteLine("account name:" + act["name"]);
       Console.WriteLine("primary contact first name:" + act["primarycontact.firstname"]);
       Console.WriteLine("primary contact last name:" + act["primarycontact.lastname"]);
    }
Posted in MS CRM 2011 | Tagged , | Leave a comment

How to implement Window Authentication Functionality to a C# Desktop Application

1)  Get currently logged in user details:
We can achieve this by using the WindowsIdentity class of System.Security.Principal namespace. This class provides a static method, getCurrent(), which return a object of WindowsIdentity.

2) Validate windows credentials provided by user:(Ask User Name, Domain and Password from user)
This is little complex compared to above as we need to call a windows API using IntropServices. To accomplish this we need to add a extern function declaration, and then call the function. Following code will help you to understand this better.

[System.Runtime.InteropServices.DllImport("advapi32.dll")]
        public static extern bool LogonUser(string userName, string domainName, string password, int LogonType, int LogonProvider, ref IntPtr phToken);
        public Form1()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            bool issuccess = false;
            string username = GetloggedinUserName();

            if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()) && username.ToLowerInvariant().Contains(txtDomain.Text.Trim().ToLowerInvariant()))
            {
                issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
            }

            if (issuccess)
                MessageBox.Show("Successfuly Login !!!");
            else
                MessageBox.Show("User Name / Password / Domain is invalid !!!");
        }

        private string GetloggedinUserName()
        {
            System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
            return currentUser.Name;
        }

        private bool IsValidateCredentials(string userName, string password, string domain)
        {
            IntPtr tokenHandler = IntPtr.Zero;
            bool isValid = LogonUser(userName, domain, password, 2, 0, ref tokenHandler);
            return isValid;
        }

You can also download a sample code from below link:
http://code.msdn.microsoft.com/Add-Window-Authentication-833ba913#content

Posted in General | Tagged , , | 4 Comments

Writing to an ms access database using C# Window Application

Please try below code to write in MS ACCESS databse using C# Window Application:

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\amar\Documents\Database1.accdb");
conn.Open();
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
     cmd.Connection = conn;
     cmd.CommandText = "Insert Into Employee (UserName, fname, sname, email) values ('amar','Amar Prakash','Jaiswal','[email protected]')";
     cmd.ExecuteNonQuery();
}
conn.Close();
Posted in General | Tagged , , | 3 Comments

How to get date value form one form to another form using C# in Window Application

Create a constructor on form2 with input parameter as date time. And when you create object of form2 in form1 just pass the date value using C# in window application.

form1 coding:
            DateTime objdate = dateTimePicker1.Value;
            form2 objform2= new form2(objdate)
            objform2.show();

Form2 coding:
        DateTime  dateen;	
	// Constructor
        public form2(DateTime str)
        {
            dateen = str;
        }
Posted in General | Tagged , | Leave a comment