Monday, 1 August 2016

QueryExpressions in MSCRM

QueryExpressions with MSCRM using multiple Condtions
_____________________________________________________________________________


public EntityCollection getAllContacts(IOrganizationService Service, Guid accountNumbers)
        {
            EntityCollection EntityResult = new EntityCollection();
            Entity contract = new Entity();
            QueryExpression Query = new QueryExpression()
            {
                ColumnSet = new ColumnSet("ownerid","new_fullname"),
                EntityName = "contract",
                Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression("customercode", ConditionOperator.Equal, accountNumbers),                                      
                        new ConditionExpression("statecode", ConditionOperator.Equal, 2),
                        new ConditionExpression("new_flag", ConditionOperator.Equal,false)
                    }
                }
            };

            EntityResult = Service.RetrieveMultiple(Query);
            return EntityResult;
        }

---------------------------------------------------------------------------------------------
single Condtion In QueryExpression in MSCRM



ColumnSet Columns = new ColumnSet("new_region", "new_country", "new_state", "name");
        QueryExpression parentAccounts = new QueryExpression()
               {
                   EntityName = "new_EntitySchemaName",
                   ColumnSet = Columns,
                   Criteria =
                   {
                       Conditions =
                    {
                        new ConditionExpression
                            {
                                 AttributeName = "new_accountnumber",
                                 Operator = ConditionOperator.Equal,
                                 Values = {"1EDH897"}
                            }
                    }
                   }
               };
        EntityCollection Results = service.RetrieveMultiple(parentAccounts);


--------------------------------------------------------------------------------------------------------
Muiltiple Conditions with QueryExpressions In MSCRM
-----------------------------------------------------------------------------------------------------------------
 public EntityCollection Contractdetails(IOrganizationService service, Entity entityname, ColumnSet colunms)
        {
            EntityCollection ContractDetals;
            //ColumnSet colunms = new ColumnSet("new_billtype");
            QueryExpression query = new QueryExpression()
            {
                EntityName = "entityname",
                ColumnSet = colunms,
                Criteria =
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression
                        {
                         
                            AttributeName = "new_opportunityid",
                            Operator = ConditionOperator.Equal,
                            Values = {((EntityReference)result.Attributes["new_opportunityid"]).Id}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="statecode",
                            Operator = ConditionOperator.Equal,
                            Values={0}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="new_Titlesubtype",
                            Operator = ConditionOperator.Equal,
                            Values={3}
                        }
                    }
                }
            };
            ContractDetals = service.RetrieveMultiple(query);
            return ContractDetals;
        }


QueryExpressions in MSCRM

QueryExpressions with MSCRM using multiple Condtions
_____________________________________________________________________________


public EntityCollection getAllContacts(IOrganizationService Service, Guid accountNumbers)
        {
            EntityCollection EntityResult = new EntityCollection();
            Entity contract = new Entity();
            QueryExpression Query = new QueryExpression()
            {
                ColumnSet = new ColumnSet("ownerid","new_fullname"),
                EntityName = "contract",
                Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression("customercode", ConditionOperator.Equal, accountNumbers),                                      
                        new ConditionExpression("statecode", ConditionOperator.Equal, 2),
                        new ConditionExpression("new_flag", ConditionOperator.Equal,false)
                    }
                }
            };

            EntityResult = Service.RetrieveMultiple(Query);
            return EntityResult;
        }

---------------------------------------------------------------------------------------------
single Condtion In QueryExpression in MSCRM



ColumnSet Columns = new ColumnSet("new_region", "new_country", "new_state", "name");
        QueryExpression parentAccounts = new QueryExpression()
               {
                   EntityName = "new_EntitySchemaName",
                   ColumnSet = Columns,
                   Criteria =
                   {
                       Conditions =
                    {
                        new ConditionExpression
                            {
                                 AttributeName = "new_accountnumber",
                                 Operator = ConditionOperator.Equal,
                                 Values = {"1EDH897"}
                            }
                    }
                   }
               };
        EntityCollection Results = service.RetrieveMultiple(parentAccounts);


--------------------------------------------------------------------------------------------------------
Muiltiple Conditions with QueryExpressions In MSCRM
-----------------------------------------------------------------------------------------------------------------
 public EntityCollection Contractdetails(IOrganizationService service, Entity entityname, ColumnSet colunms)
        {
            EntityCollection ContractDetals;
            //ColumnSet colunms = new ColumnSet("new_billtype");
            QueryExpression query = new QueryExpression()
            {
                EntityName = "entityname",
                ColumnSet = colunms,
                Criteria =
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression
                        {
                         
                            AttributeName = "new_opportunityid",
                            Operator = ConditionOperator.Equal,
                            Values = {((EntityReference)result.Attributes["new_opportunityid"]).Id}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="statecode",
                            Operator = ConditionOperator.Equal,
                            Values={0}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="new_Titlesubtype",
                            Operator = ConditionOperator.Equal,
                            Values={3}
                        }
                    }
                }
            };
            ContractDetals = service.RetrieveMultiple(query);
            return ContractDetals;
        }


Mscrm Plugin to call the WebService Using C#

Mscrm Plugin to call WCF Service Using Custom bindings
--------------------------------------------------------------------------------------------

BasicHttpBinding myBinding = new BasicHttpBinding();
                myBinding.Name = "BasicHttpBinding_GetOpportunityDetails";
                myBinding.Security.Mode = BasicHttpSecurityMode.None;
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress endPointAddress = new EndpointAddress("http://10.1980.89/LoginPortal/Services/LoginPortal.svc?wsdl");
                ServiceReference1.ConTractDetailsClient Case = new ServiceReference1.ConTractDetailsClient(myBinding, endPointAddress);
                string str = Case.UpdateStatus(CaseNumber, UpdateStatus, Comments, ContactName,
PhoneNumber);

-------------------------------------------------------------------------------------------

Mscrm to connect C#

Mscrm to connect Specific Organization by passing UserId and Pwd
--------------------------------------------------------------------------------------

 public IOrganizationService ConnectMSCRM( string UserId,string Pwd,string Url)
    {
        ClientCredentials cre = new ClientCredentials();
        cre.UserName.UserName = UserId;
        cre.UserName.Password = Pwd;
        Uri serviceUri = new Uri(Url);
        OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, cre, null);
        IOrganizationService service = (IOrganizationService)proxy;
        return service;
    }

-----------------------------------------------------------------------------------------------
Retrieving Data From Mscrm using C#


 ColumnSet attributes = new ColumnSet(new string[] { "new_name", "new_education", "new_courseid", "new_gender", "new_joindate" });
        Entity obj = service.Retrieve("new_test_a", new Guid("8CFADFE4-46C7-E511-80E2-3863BB3DEF88"), attributes);
        bool gg = Convert.ToBoolean(obj.Attributes["new_gender"]);
        string edname = ((Microsoft.Xrm.Sdk.OptionSetValue)(obj.Attributes["new_education"])).Value.ToString();
        string cc = ((Microsoft.Xrm.Sdk.EntityReference)(obj.Attributes["new_courseid"])).Name.ToString();



--------------------------------------------------------------------------------------------------------------------

Sample Plugin in MSCRM

public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(null);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "email")
                {

                           ColumnSet attributes = new ColumnSet(new string[] { "description", "subject", "from" });
                            Entity emailEntity = service.Retrieve(entity.LogicalName, entity.Id, attributes);
                            if (emailEntity.Contains("description") && emailEntity.Attributes["description"] != null)
                            {
                                String htmlEmailBody = emailEntity.Attributes["description"].ToString();
                                emailSubject = emailEntity.Attributes["subject"].ToString();

                                EntityCollection Recipients = emailEntity.GetAttributeValue<EntityCollection>("from");

                                foreach (var party in Recipients.Entities)
                                {
                                    senderAddress = party.Attributes["addressused"].ToString();
                                }

                            }

                }

            }

        }









Friday, 29 January 2016

setRecordStatus



public static void SetState(Entity record, int stateCode, int statusCode, ITracingService trace, IOrganizationService service)
{
trace.Trace("Entered SetState Method");
trace.Trace(string.Format("LogicalName:{0}, StatusCode:{1}, StateCode:{2}", record.LogicalName, statusCode, stateCode));

// Create SetState Request
SetStateRequest setStateRequest = new SetStateRequest()
{
EntityMoniker = new EntityReference
{
Id = record.Id,
LogicalName = record.LogicalName
},
State = new OptionSetValue(stateCode),
Status = new OptionSetValue(statusCode)
};

// Execute the request
service.Execute(setStateRequest);

trace.Trace("Exiting SetStatus Method");
}

Thursday, 24 December 2015

Logger file Name

public static void LogInfo(string Message)
        {
            try
            {
                bool EnableLog = true;
                if (EnableLog)
                {
                    string LogFile = "D:\\Logs\\revenu_" +DateTime.Now.Day.ToString("00") + DateTime.Now.Month.ToString("00") +DateTime.Now.Year;
                    StreamWriter sw;
                    if (!string.IsNullOrEmpty(LogFile))
                        LogFile.Replace("revenu__Logs","revenu_" + DateTime.Today.Date.ToString().Substring(0, 10));
                    if (!File.Exists(LogFile))
                    {
                        sw = File.CreateText(LogFile);
                        sw.WriteLine(string.Format("Log File Created: {0}",DateTime.Now.ToString()));
                        sw.Close();
                    }
                    sw = File.AppendText(LogFile);
                    sw.WriteLine(string.Format("{0}: {1}",DateTime.Now.ToString(), Message));
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Thursday, 17 December 2015

WCFRestful Service cusuming using javascript

Jquery ajax functions to calling RESTFUL Service in WCF
====================================================================
Client application:
=============
<script src="Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(Document).ready(function () {
            $("#Button1").click(function () {
               debugger;

                //var input =
                //{
                 
                //    "strArgument1": "DUMMY55",
                //    "strArgument2": "TestDemo5555"
               
                //};

                var dt = {
                    "User": {
                        "Number": "5555",
                        "Name": "Raju",
                        "Id": "Dummy",
                        "Mail": "rajneto"
                    },
                    "Params": {
                        "Code": "Value",
                        "MaxCount": "1000",
                        "MaxCount": "Yeah",
                        "UserContext": "Yes"
                    },
                    "Items": [{
                        "Searchitems": "ten",
                        "Searchlist": "RAVVVVV"
                    }]
                 
                };
                $.ajax({
                    type: "POST",
                    url: "http://localhost:64650/Service.svc/EMPloyee",
                    data: JSON.stringify(dt),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var value = JSON.stringify(response);
                        alert(value);
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                });


            }
                );
        });

    </script>
===================================================================
WCF Service  for I service class;
=============
public interface IService1
    {
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "EMPloyee", RequestFormat = WebMessageFormat.Json, Method = "POST")]
       string SumFields(RootObject Rootobj);

    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    // You can add XSD files into the project. After building the project, you can directly use the data types defined there, with the namespace "WcfServiceLibrary3.ContractType".
   [DataContract]
    public class User
    {
        [DataMember]
        public string Number { get; set; }
         [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Id { get; set; }
       [DataMember]
        public string Mail { get; set; }
    }
    [DataContract]
    public class Params
    {
        [DataMember]
        public string Code { get; set; }
        [DataMember]
        public string MaxCount { get; set; }
        [DataMember]
        public string MaxCount { get; set; }
        [DataMember]
        public string UserContext { get; set; }
    }
    [DataContract]
    public class Item
    {
        [DataMember]
        public string Search { get; set; }
        [DataMember]
        public string SearchCode { get; set; }
    }
    [DataContract]
    public class RootObject
    {
        [DataMember]
        public User User { get; set; }
        [DataMember]
        public Params Params { get; set; }
        [DataMember]
        public List<Item> Items { get; set; }
    }
======================================================

Service.cs file source:
----------------------------

namespace WcfServiceLibrary3
{
   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class Service1 : IService1
    {


       public string SumFields(RootObject RootObject)
        {
            User urs = RootObject.User;
            Params pm = RootObject.Params;
            List<Item> lt =new List<Item>();
            lt = RootObject.Items;
            string data = "" + urs.EmployeeId + "," + urs.EmployeeMail + "," + urs.EmployeeName + "" + urs.EmployeeNumber + "," + pm.CheckMaxCount + "," + pm.CheckUserContext + "," + pm.OpCode + ","+pm.MaxCount+",,,";
            for (int i = 0; i < lt.Count; i++)
            {
                data += lt[i].SearchCode.ToString();
            }

            return data;    
       }
    }
}
================================================
Service.SVC file source code:
------------------------------------
<%@ ServiceHost Service="WcfServiceLibrary3.Service1"  Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>