Make a Web method in Web service that validate user on to the CRM 2011 Online

Risposta suggerita Make a Web method in Web service that validate user on to the CRM 2011 Online

  • Wednesday, May 02, 2012 9:22 AM
     
     

    Hi,

    I am new in web service. I want to make a web method that validate user's credentials at CRM 2011 Online end.

    I have made some web methods that returns leads data in that i am hard coding my credentials and get logged in ..But i want to validate user first and then want to user show data by calling other web methods.

All Replies

  • Wednesday, May 02, 2012 9:41 AM
    Moderator
     
     

    Are you creating a custom webservice, any specific reason, in your webservice you can create a webmethod which takes username,password as parameter and can use these information to authenticate user.


    Mahain : Check My Blog
    Follow me on Twitter
    Make sure to "Vote as Helpful" and "Mark As Answer",if you get answer of your question.


  • Wednesday, May 02, 2012 9:51 AM
     
      Has Code
    For authenticating user i am using the following code.
    Hope it will helps you
    public IOrganizationService authenticateUser(string _userName, string _userPassword)
        {
            try
                {
                credentials.UserName.UserName = _userName;
    
                credentials.UserName.Password = _userPassword;
    
                deviceCredentials.UserName.UserName = "DeviceUserName";
                deviceCredentials.UserName.Password = "DevicePassword";
    
                organizationUri = new Uri("organizationURI");
    
                homeRealmUri = null;
                using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, deviceCredentials))
                {
    IOrganizationService service = (IOrganizationService)serviceProxy;
                    return service;
    
                }
            }
            catch (System.Exception excep)
            {
                return null;
            }
        }
    If you need more information please let me know


    I hope this helps. If my response answered your question, please mark the response as an answer and also vote as helpful.
    Mubasher Sharif
    Check out my about.me profile!
    http://mubashersharif.blogspot.com
    Linked-In Profile
    Follow me on Twitter!



  • Wednesday, May 02, 2012 9:58 AM
     
     

    Hi Mahender Pal,

    Thanks for Reply.yes ,i am creating a custom web service in which i am creating some web methods that returns a data.

    Ya as you said i have created a web method which takes username,password as parameter but what will be the return type... And further how can i retrieve data based on that authenticated user ?

  • Wednesday, May 02, 2012 10:03 AM
     
      Has Code

    Hi MubasherSharif,

    Thank you for response.

    Now how can i use this for other method?

    my code is as below...

    [System.Web.Services.WebMethod()]
        public DataTable getAllLead()
        {
            Uri OrganizationUri = new Uri("https://*****.api.crm.dynamics.com/XRMServices/2011/Organization.svc");
    
            var liveIDCreds = new ClientCredentials();
            liveIDCreds.UserName.UserName = "username";
            liveIDCreds.UserName.Password = "password";
    
            var deviceIDcreds = new ClientCredentials();
            deviceIDcreds.UserName.UserName = "11ltfz36jrxd4sdycpkfk7a0gq";
            deviceIDcreds.UserName.Password = "aeKwQN#c/V`RR!!ObqFA,Pz7";
    
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, liveIDCreds, deviceIDcreds);
            serviceProxy.EnableProxyTypes();
    
            IOrganizationService _service = (IOrganizationService)serviceProxy;
    
            var query = new QueryExpression
            {
                EntityName = "lead",
                ColumnSet = new ColumnSet("leadid", "subject", "fullname", "companyname", "telephone1", "emailaddress1", "statuscode", "createdon", "ownerid"),
            };
    
            var request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
            request["Query"] = query;
            OrganizationResponse response = _service.Execute(request);
            EntityCollection results = (EntityCollection)response["EntityCollection"];
            DataTable dt = new DataTable("Leads");
            dt.Columns.Add("Id", Type.GetType("System.Int32"));
            dt.Columns.Add("LeadId", Type.GetType("System.String"));
            dt.Columns.Add("Topic", Type.GetType("System.String"));
            dt.Columns.Add("Name", Type.GetType("System.String"));
            dt.Columns.Add("CompanyName", Type.GetType("System.String"));
            dt.Columns.Add("BusinessPhone", Type.GetType("System.String"));
            dt.Columns.Add("E-mail", Type.GetType("System.String"));
            dt.Columns.Add("StatusReason", Type.GetType("System.String"));
            dt.Columns.Add("CreatedOn", Type.GetType("System.DateTime"));
            dt.Columns.Add("Owner", Type.GetType("System.String"));
            int idCount = 1;
            foreach (Entity leads in results.Entities)
            {
                DataRow dr;
                dr = dt.NewRow();
                dr["Id"] = idCount++;
    
                if (leads.Attributes.Contains("leadid"))
                {
                    dr["LeadId"] = leads.Attributes["leadid"].ToString();
                }
    
                if (leads.Attributes.Contains("subject"))
                {
                    dr["Topic"] = leads.Attributes["subject"].ToString();
                }
    
                if (leads.Attributes.Contains("fullname"))
                {
                    dr["Name"] = leads.Attributes["fullname"].ToString();
                }
    
                if (leads.Attributes.Contains("companyname"))
                {
                    dr["CompanyName"] = leads.Attributes["companyname"].ToString();
                }
    
                if (leads.Attributes.Contains("telephone1"))
                {
                    dr["BusinessPhone"] = leads.Attributes["telephone1"].ToString();
                }
    
                if (leads.Attributes.Contains("emailaddress1"))
                {
                    dr["E-mail"] = leads.Attributes["emailaddress1"].ToString();
                }
    
                if (leads.Attributes.Contains("statuscode"))
                {
                    dr["StatusReason"] = leads.FormattedValues["statuscode"];//leads.Attributes["statuscode"].ToString();
                }
    
                if (leads.Attributes.Contains("createdon"))
                {
                    dr["CreatedOn"] = leads.Attributes["createdon"].ToString();
                }
    
                if (leads.Attributes.Contains("ownerid"))
                {
                    dr["Owner"] = ((EntityReference)leads.Attributes["ownerid"]).Name.ToString();
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    
        [System.Web.Services.WebMethod()]
        public DataTable getLeadbyId(string LeadId)
        {
            Uri OrganizationUri = new Uri("https://*****.api.crm.dynamics.com/XRMServices/2011/Organization.svc");
    
            var liveIDCreds = new ClientCredentials();
            liveIDCreds.UserName.UserName = "username";
            liveIDCreds.UserName.Password = "password";
    
            var deviceIDcreds = new ClientCredentials();
            deviceIDcreds.UserName.UserName = "11ltfz36jrxd4sdycpkfk7a0gq";
            deviceIDcreds.UserName.Password = "aeKwQN#c/V`RR!!ObqFA,Pz7";
    
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, liveIDCreds, deviceIDcreds);
            serviceProxy.EnableProxyTypes();
    
            IOrganizationService _service = (IOrganizationService)serviceProxy;
    
            var query = new QueryExpression
            {
                EntityName = "lead",
                ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("leadid", "subject", "fullname", "companyname", "telephone1", "emailaddress1", "statuscode", "createdon", "ownerid"),
            };
    
            var request = new OrganizationRequest() { RequestName = "Retrieve" };
            request["Query"] = query;
            Guid leadId = new Guid(LeadId);
            Entity _LeadInfo = (Entity)_service.Retrieve("lead", leadId, new ColumnSet(new string[] { "leadid", "subject", "fullname", "companyname", "telephone1", "emailaddress1", "statuscode", "createdon", "ownerid" }));
            DataTable dt = new DataTable("LeadByID");
            dt.Columns.Add("Id", Type.GetType("System.Int32"));
            dt.Columns.Add("LeadId", Type.GetType("System.String"));
            dt.Columns.Add("Topic", Type.GetType("System.String"));
            dt.Columns.Add("Name", Type.GetType("System.String"));
            dt.Columns.Add("CompanyName", Type.GetType("System.String"));
            dt.Columns.Add("BusinessPhone", Type.GetType("System.String"));
            dt.Columns.Add("E-mail", Type.GetType("System.String"));
            dt.Columns.Add("StatusReason", Type.GetType("System.String"));
            dt.Columns.Add("CreatedOn", Type.GetType("System.DateTime"));
            dt.Columns.Add("Owner", Type.GetType("System.String"));
    
            DataRow dr;
            dr = dt.NewRow();
    
            if (_LeadInfo.Attributes.Contains("leadid"))
            {
                dr["LeadId"] = _LeadInfo.Attributes["leadid"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("subject"))
            {
                dr["Topic"] = _LeadInfo.Attributes["subject"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("fullname"))
            {
                dr["Name"] = _LeadInfo.Attributes["fullname"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("companyname"))
            {
                dr["CompanyName"] = _LeadInfo.Attributes["companyname"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("telephone1"))
            {
                dr["BusinessPhone"] = _LeadInfo.Attributes["telephone1"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("emailaddress1"))
            {
                dr["E-mail"] = _LeadInfo.Attributes["emailaddress1"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("statuscode"))
            {
                dr["StatusReason"] = _LeadInfo.FormattedValues["statuscode"];//leads.Attributes["statuscode"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("createdon"))
            {
                dr["CreatedOn"] = _LeadInfo.Attributes["createdon"].ToString();
            }
    
            if (_LeadInfo.Attributes.Contains("ownerid"))
            {
                dr["Owner"] = ((EntityReference)_LeadInfo.Attributes["ownerid"]).Name.ToString();
            }
            dt.Rows.Add(dr);
            return dt;
        }

    I want to make that authentication code in one more web method method.

    How can i use string value as return type and then further for requesting using IOrganizationService object?

  • Wednesday, May 02, 2012 10:06 AM
     
     

    I have tried this...

    But when you uses it as Web method ,it will say it is not serializable object.

  • Wednesday, May 02, 2012 10:11 AM
     
     

    It gives me following error....

    Cannot serialize interface Microsoft.Xrm.Sdk.IOrganizationService.

  • Wednesday, May 02, 2012 10:12 AM
    Moderator
     
     Proposed Answer

    Hi,

    Create a globel object for IOrganizationService, in your class

    IOrganizationService _service;

    Create one function having below code to initialize IorganizationService object, and then in every web method use this global object pass that object

    public IOrganizationService GetServiceObject(string _UserName,string _Password)
             {

    Uri OrganizationUri = new Uri("https://*****.api.crm.dynamics.com/XRMServices/2011/Organization.svc");

           
    var liveIDCreds = new ClientCredentials();
            liveIDCreds
    .UserName.UserName = _UserName;
            liveIDCreds
    .UserName.Password = _Password;

           
    var deviceIDcreds = new ClientCredentials();
            deviceIDcreds
    .UserName.UserName = "11ltfz36jrxd4sdycpkfk7a0gq";
            deviceIDcreds
    .UserName.Password = "aeKwQN#c/V`RR!!ObqFA,Pz7";

           
    OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, liveIDCreds, deviceIDcreds);
            serviceProxy
    .EnableProxyTypes();

           
    _service = (IOrganizationService)serviceProxy;


    }


    Mahain : Check My Blog
    Follow me on Twitter
    Make sure to "Vote as Helpful" and "Mark As Answer",if you get answer of your question.


  • Wednesday, May 02, 2012 10:21 AM
     
     Proposed Answer Has Code
    What i think is you need to store the values of your logged in user in session Call my function as i have written above.
    Pass the values that are in your session and the code returns you the IOrganizationService
    IOrganizationService _service = authnticateUser(session["userNAme"], session["password"]);
    If you need more information please let me know

    I hope this helps. If my response answered your question, please mark the response as an answer and also vote as helpful.
    Mubasher Sharif
    Check out my about.me profile!
    http://mubashersharif.blogspot.com
    Linked-In Profile
    Follow me on Twitter!


  • Wednesday, May 02, 2012 11:16 AM
     
     

    Hi Mubasher,

    I have created authenticate function as you have shown in your previous post.

    I am getting error when i am calling that function as below.

  • Wednesday, May 02, 2012 11:18 AM
     
      Has Code

    are you setting UserName and password in Session before calling this function?

    Session["userName"] = userName;
                Session["password"] = password;


    I hope this helps. If my response answered your question, please mark the response as an answer and also vote as helpful.
    Mubasher Sharif
    Check out my about.me profile!
    http://mubashersharif.blogspot.com
    Linked-In Profile
    Follow me on Twitter!


  • Wednesday, May 02, 2012 11:21 AM
     
     

    Should i have set it in authenticateUser function or on before where i am calling this function?

    I have set it in authenticateUser function...

  • Wednesday, May 02, 2012 11:24 AM
     
     

    Before calling the function but only once.
    for other methods your above code works fine.
    And make sure your username and password is correct.
    If problem does not solve please paste your code here

    I hope this helps. If my response answered your question, please mark the response as an answer and also vote as helpful.
    Mubasher Sharif
    Check out my about.me profile!
    http://mubashersharif.blogspot.com
    Linked-In Profile
    Follow me on Twitter!



  • Wednesday, May 02, 2012 11:28 AM
     
     

    If i am setting in other function(before calling function) then i will have to take username and password as parameter na?

    In my web method getallLead() i will have to take username and password as parameter?

  • Wednesday, May 02, 2012 11:33 AM
     
     

    If it is so then it is like when i am calling this web method it will ask me username and password and by validating that i will get result combine.

    But i want like once user aunthenticated by one method and after that call other function.


  • Thursday, May 03, 2012 5:05 AM
     
     

    What is the need is that when we run our web service we see the list of web methods on first screen. And by clicking one of the method it will run. Such a way i want to make one web method which authenticate user and give a valid token then only user can run other web methods,if the token is not valid then it will not allow to user to run other methods because the user is not authenticated.

    What here is happening that when user click on one web method it will have to ask username and password within other parameter.So authentication and running the web services is going together... I want to separate user authentication first and then can do operation.... Is it possible?