0

I'm trying to implement a code in C# that posts to LinkedIn's feed, and I already did it using Postman and it worked fine after generating a token that is valid for 60 days. The problem is that I'm having issues when running the code using C# and when it hits this line:

var httpResponse = await client.PostAsync(builder.Uri, httpContent);

it stucks and keeps running forever, so far I waited for 25 mins. and it didn't work at all.

Here is how I did it in Postman:

Header Header

Body body

Here is how I did it in C#:

public async Task<bool> Post(ObjectToBind post)
    {

        string Body = "";
        try
        {

            using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\SocialMediaModels\Provider\PostLinkedInTemplate.json"))
            {
                Body = reader.ReadToEnd();
            }

            Body = Body.Replace("[person_id]", Settings.PersonId).Replace("[text_value]", Settings.ShareCommentary).Replace("[description_value]", Settings.Description).Replace("[url_value]", Settings.OriginalUrl).Replace("[title_value]", Settings.Title);

            using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Settings.Token}");
                client.DefaultRequestHeaders.Add("X-Restli-Protocol-Version", "2.0.0");


                var builder = new UriBuilder(new Uri("https://api.linkedin.com/v2/ugcPosts"));

                var httpContent = new StringContent(Body, Encoding.UTF8, "application/json");
                var httpResponse = await client.PostAsync(builder.Uri, httpContent);

            }

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
            return false;
        }
        return true;

    }

Note: I double checked the body and the header params. and all are the same as postman, and it never hits the catch block and also I added a break-point inside that block and as i wrote, when it hits that line it stucks in there.

================ UPDATE ====================

Here is where I'm calling the method from:

 public static async Task<List<PostResult>> ProcessPosts(List<ObjectToBind> objects)
    {
        ISocialProvider socialProvider = null;
        List<PostResult> postResults = null;
        string Message = "";
        bool result;
        try
        {               
            if (objects != null)
            {
                var postRes = new PostResult();
                foreach (var post in objects)
                {
                    postRes.language = post.Language;

                    if (post.DatePostedToLinkedIn == null && post.PostToLinkedIn)
                    {
                        socialProvider = new LinkedIn();
                        // HERE IT IS
                        result = await socialProvider.Post(post);

                        postRes.SuccessfyllyPostedToLinkedIn = result;
                        postRes.PostedToLinkedInOn = result ? DateTime.Now : DateTime.MinValue;
                        postRes.LinkedInMessage = Message;

                    }
                }
            }

            return postResults;
        }
        catch (Exception ex)
        {       
            MessageBox.Show(ex.Message);         
            return postResults;
        }
    }
B.Simboliq
  • 55
  • 7
Brainiak
  • 19
  • 4
  • You're silently throwing away *important* exception information. At a *minimum*, log the error. You have no idea what could be wrong because the exceptions are getting tossed. –  Mar 15 '19 at 17:13
  • 1
    I updated the code and it never hits the catch block and also I added a break-point inside that block and as i wrote, when it hits that line it stucks in there. @Amy – Brainiak Mar 15 '19 at 17:16
  • Can you show where this method is called? You have a deadlock in your code, *probably* resulting from an incorrect usage of `async`. See https://stackoverflow.com/questions/34078296/httpclient-postasync-never-return-response –  Mar 15 '19 at 17:18
  • 1
    @Amy I added the code into the post in the update section – Brainiak Mar 15 '19 at 17:23
  • You're throwing away another exception. That's a bad habit. –  Mar 15 '19 at 17:27
  • @Amy Ok, can you tell me which one or where is that happening! – Brainiak Mar 15 '19 at 17:30
  • It's in the last 4 lines of code you just added. You catch an exception, but don't log it or do anything to handle it. –  Mar 15 '19 at 17:32
  • @Amy difinitely I'm not! because and as i mentioned before, I'm having break-points on each line even in the code i added - BTW the code posts to LinkedId but it never hits the return lines or anything else. – Brainiak Mar 15 '19 at 17:34
  • 1
    To be clear, throwing the exceptions away silently isn't the cause of your issue, its just a bad habit that will hurt you. If you're going to catch an exception, *handle it*. It's not clear what the cause of your issue is, yet. I'm hoping this exception contains helpful information on the cause of your issue. –  Mar 15 '19 at 17:35
  • 3
    Yes you are. `catch (Exception) { return postResults; }` silently ignores the exception and pretends it was never thrown, preventing you from ever discerning what raised the exception in the first place and hindering debugging efforts. Again, this isn't the cause of your issue, I'm trying to help you write better error-handling code. –  Mar 15 '19 at 17:36
  • 1
    @Amy Thanks a lot, I do appreciate this, it's just something i forgot, but I found now that the Post call works and posts to LinkedIn but it doesn't return any thing or it never hits even the line after the one that call the api to post. – Brainiak Mar 15 '19 at 17:41
  • 1
    Maybe this will help: https://stackoverflow.com/questions/9895048/async-call-with-await-in-httpclient-never-returns – Wiz Mar 15 '19 at 18:54

0 Answers0