We help IT Professionals succeed at work.

Need a C# Web Service to call external Web Services. How?

Need a C# Web Service to call external Web Services. How?

I need to create a back-end web service which then calls a small handful of external web services in order to complete the calculations. Is this a simple task? Using C# to execute an external web service?

How would I call four different such calls at the same time? Does this qualify as "parallel processing"? Anything fancy needed? Or, can I quickly call one after the other, then get a callback for each?

How does this work?

Thanks
Comment
Watch Question

Software Tead Lead / Business Analyst / System Analyst / Data Engineer
CERTIFIED EXPERT
Commented:
Is this a simple task? Using C# to execute an external web service?

I'm using wcf service in C# to call another webservice for user authentication.

but I only make one call in my situation.

public Message Msg_AuthenticateUser(UserLoginInput input)
        {
            String json = String.Empty;
            LogFile f = new LogFile();
            dynamic rtnObj = new System.Dynamic.ExpandoObject();
            Boolean isValidHeader = true;

            try
            {
                String connStr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                String Key = ConfigurationManager.AppSettings["key"];
                String Auth_UName = ConfigurationManager.AppSettings["auth_uname"];
                String Auth_Pwd = ConfigurationManager.AppSettings["auth_pwd"];

                Auth_UName = CryptoLib.AESGCM.SimpleDecryptWithPassword(Auth_UName, Key);
                Auth_Pwd = CryptoLib.AESGCM.SimpleDecryptWithPassword(Auth_Pwd, Key);

                IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
                String AuthHeader = request.Headers["Authorization"];
                if (AuthHeader == null)
                {
                    // No credentials; anonymous request
                    rtnObj.Output = "No Credentials Available";
                    json = JsonConvert.SerializeObject(rtnObj);
                    isValidHeader = false;
                }
                else
                {
                    AuthHeader = AuthHeader.Trim();
                    if (AuthHeader.IndexOf("Basic", 0) != 0)
                    {
                        //header not correct we do not authenticate
                        rtnObj.Output = "Invalid Authenticated Method";
                        json = JsonConvert.SerializeObject(rtnObj);
                        isValidHeader = false;
                    }
                    else
                    {
                        String encodedCredentials = AuthHeader.Substring(6);
                        byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                        String s = new ASCIIEncoding().GetString(decodedBytes);
                        String[] userPass = s.Split(new char[] { ':' });
                        String UserName = userPass[0];
                        String Password = userPass[1];

                        isValidHeader = ((Auth_UName == UserName) && (Auth_Pwd == Password));
                        if (isValidHeader == false)
                        {
                            rtnObj.Output = "Invalid Authenticated Username or Password";
                            json = JsonConvert.SerializeObject(rtnObj);
                        }
                    }
                }

                if (isValidHeader)
                {
                    System.Threading.Tasks.Task<String> tmp = req_AuthenticateUser(input);
                    json = tmp.Result;
                }
                return WebOperationContext.Current.CreateTextResponse(json, "application/json; charset=utf-8", Encoding.UTF8);
            }
            catch (Exception e)
            {
                f.log.Error(e.ToString());
                if (e.InnerException != null)
                {
                    f.log.Error(e.InnerException.ToString());
                }
                rtnObj.Output = "System Error";
                json = JsonConvert.SerializeObject(rtnObj);

                return WebOperationContext.Current.CreateTextResponse(json, "application/json; charset=utf-8", Encoding.UTF8);
            }
        }

        private async System.Threading.Tasks.Task<String> req_AuthenticateUser(UserLoginInput input)
        {
            String json = String.Empty;
            String PostURL = ConfigurationManager.AppSettings["posturl"];

            LogFile f = new LogFile();
            try
            {
                var values = new Dictionary<string, string>
                {
                    { "UserId", input.UserId },
                    { "Password", input.Password }
                };

                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(PostURL, content).ConfigureAwait(false);

                json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                UserLoginOutput obj;
                dynamic rtnObj = new System.Dynamic.ExpandoObject();

                try
                {
					//Verify the response
					
                    obj = JsonConvert.DeserializeObject<UserLoginOutput>(json);
                    f.log.Information("[req_AuthenticateUser] token = " + obj.token + " ; SomeNo = " + obj.SomeNo);

                    if (obj.token.Trim() == "")
                    {
                        rtnObj.Status = false;
                    }
                    else
                    {
                        rtnObj.Status = true;
                    }
                }
                catch (Exception)
                {
                    rtnObj.Status = false;
                }
                json = JsonConvert.SerializeObject(rtnObj);
                return json;
            }
            catch (Exception e)
            {
                f.log.Error(e.ToString());
                if (e.InnerException != null)
                {
                    f.log.Error(e.InnerException.ToString());
                }

                dynamic rtnObj = new System.Dynamic.ExpandoObject();
                rtnObj.Status = false;
                json = JsonConvert.SerializeObject(rtnObj);
				
                return json;
            }
        }

Open in new window



How would I call four different such calls at the same time? Does this qualify as "parallel processing"? Anything fancy needed?

for parallel processing, I would think the async calling is needed and you need to build that calling structure accordingly
curiouswebsterSoftware Engineer

Author

Commented:
Which line of code is for the external call?
Ryan ChongSoftware Tead Lead / Business Analyst / System Analyst / Data Engineer
CERTIFIED EXPERT
Commented:
Which line of code is for the external call?

well, here we go:

var response = await client.PostAsync(PostURL, content).ConfigureAwait(false);

Open in new window

curiouswebsterSoftware Engineer

Author

Commented:
So, the C# function will freeze there (on await) until a response comes? And this is why the function has a return value of "asynch"?

So, I would need four such calls, perhaps passing PostURL as an input parameter for req_AuthenticateUser (for example), so that I could potentially use just one function call?
Ryan ChongSoftware Tead Lead / Business Analyst / System Analyst / Data Engineer
CERTIFIED EXPERT
Commented:
yes, you can. it depends on how you design your function.

for the benefits of all, here's a good article on explanation of async and await:

Asynchronous programming with async and await
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
curiouswebsterSoftware Engineer

Author

Commented:
thanks