Get a company followers count on LinkedIn - c#

I'm trying to get the number of followers of a company on Linked in.
I use this code:
HttpWebRequest request = WebRequest.Create("http://api.linkedin.com/v1/companies/?id=SomeCompanyID:(num-followers)") as HttpWebRequest;
request.Method = "Get";
request.Credentials = new NetworkCredential("MyAppClientID", "MyAppClientSecret");
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // I'm getting "(401) Unauthorized" exception at this line.
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
System.IO.File.WriteAllText(#"WriteText.txt", result);
Console.WriteLine(reader.ReadToEnd());
}
I'm not sure about my syntax and the way I provide credentials, but I don't know how to do so correctly, and documentation is not clear at this point.
Your help is appreciated.

It looks like you haven't registered your application or more accurately you haven't updated the code sample with your own ClientKey and Secret value.
You obtain them from https://www.linkedin.com/developer/apps/
You can also find more information about it here https://developer.linkedin.com/support/faq
Where can I find my API key?
Click on the My Apps link in the top navigation menu to manage your
LinkedIn applications.
From here, you can create a new application if you don't already have
one or view the details of your existing applications. You will find
your Client ID (otherwise known as API Key/ID or Consumer Key/ID)
listed in the "Authentication" side nav link, underneath the header
"Authentication Keys".
Alternatively, you may be using an old format of Rest API call, accoring to this page (https://developer.linkedin.com/docs/company-pages), the new format is as follows
https://api.linkedin.com/v1/companies/{id}/num-followers?format=json
Get a company's followers, by segment
If you choose to target content that you share on behalf of a company,
there is a minumum number of followers that must make up the segment
you are targeting before you will be able to successfully share the
targeted content. This request allows you to get a follower-count for
a specific segment to ensure you are at or over the minimum
requirement for the target segment for the company specified by the
{id} value in the request. Optional Parameters
https://api.linkedin.com/v1/companies/{id}/num-followers?format=json
sample response
1147037

Related

How to create and redeem coupons in Recurly, programmatically?

++++++++++++++
Actual Scenario: I am working on a site (ASP.Net using C#) where the system will have 3 different subscription plans i.e. monthly, quarterly and yearly. All the subscription plans have their own cost and pricing. Now, if the system/admin wants to give any discounts to any subscribed user (regardless of subscription plan) on their on-going subscription based on some business logic (for example, for some user it may be $4 and for other it may be $25). How can I achieve this goal. I tried PayPal and Recurly, but stuck in-between.
++++++++++++++
I have to create a coupon and redeem the same using Recurly dynamically in C#. But, as per the code mentioned in "https://docs.recurly.com/api/v1/subscription-plans", we have to use Recurly API v2, but we don't have the code to create and redeem the coupon. So, please help me on how can I create coupons and redeem the same.
When we are using below code in mentioned URL "Recurly PUT request working but returning server error", it causes error while getting response.
uri = "https://" + subdomain + ".recurly.com/v2/subscriptions/" + uuid + "/reactivate";
try
{
string xml = "<subscription><timeframe>now</timeframe></subscription>"; //also tried with blank string.
byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
HttpWebRequest renewRequest = (HttpWebRequest)WebRequest.Create(uri);
renewRequest.Headers.Add("Authorization", "Basic " + encodeB64);
renewRequest.Method = "PUT";
renewRequest.ContentType = "text/XML";
renewRequest.ContentLength = arr.Length;
Stream datastream = renewRequest.GetRequestStream();
datastream.Write(arr, 0, arr.Length);
datastream.Close();
HttpWebResponse renewResponse = (HttpWebResponse)renewRequest.GetResponse();
}
Looking for kind response and help...
We (recurly.com) just made available a release candidate of an all new API client for C# compatible with Recurly APIv2 that we highly recommend using. The client API is stable and this release will shortly become the final release pending new show-stopping bugs.
Here's how to get started using it.
Be sure set up your configuration.
Here's how to create a coupon.
Here's how to redeem coupons.
More examples are available here.
If you have further questions please don't hesitate to ask our support team! support#recurly.com.

How to create an otrs ticket using a soap request

The lack of documentation on this subject coupled with the fact that I'm struggling with a learning curve on all fronts and making me really confused about where to start. I need to get this done using C# if possible. I apologize for the vagueness of this question, but I'm really lost. I would love links to comprehensive guides/references.
In my efforts to get this done, I've run into the following problems/questions:
I've created a web service using the otrs gui, with the operation CreateTicket, but requests via C# to my chosen namespace are returning 404 (not found). When I try to add a service reference or web reference with that namespace, I get the same error. However, when I plug that namespace into my browser as the url, it displays "customer.pl".
Can I send a soap request without adding the web service as a service reference in visual studio? Given the previous problem I'm having I can't do it that way. Would I just build the soap request string and write it to the web request's data stream with http://domain/rpc.pl as the uri?
If the answer to the previous question is yes... When trying the below code segment I get an internal server error (500) on the last line. However the header looks like a SOAP header which confuses me because I wouldn't have thought it got that far.
var document = new StringBuilder();
document.Append("<UserLogin>some user login</UserLogin>");
document.Append("<Password>some password</Password> ");
document.Append("<Ticket>");
document.Append("<Title>some title</Title> ");
document.Append("<CustomerUser>some customer user login</CustomerUser>");
document.Append("<Queue>some queue</Queue>");
document.Append("<State>some state</State>");
document.Append("<Priority>some priority</Priority>");
document.Append("</Ticket>");
document.Append("<Article>");
document.Append("<Subject>some subject</Subject>");
document.Append("<Body>some body</Body>");
document.Append("<ContentType>text/plain; charset=utf8</ContentType>");
document.Append("</Article>");
//var uri = new Uri("http://domain/injest");
var uri = new Uri("http://domain/rpc.pl");
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(document.ToString());
httpWebReq.Timeout = 5 * 1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
httpWebReq.ContentType = "text/xml;charset=utf-8";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
Even if all you can offer is where to start, it would help me to know how to proceed, as I'm stumped.
You're using the rpc.pl endpoint which is part of the 'old' RPC-style interface.
You mention you added the web service via the GUI which means you're using the 'new' Generic Interface, which is indeed much easier from .Net.
The address of the endpoint is /otrs/nph-genericinterface.pl/Webservice/GenericTicketConnector or whatever you have called the web service in the admin section.

(403) Forbidden upon WebRequest

I'm trying to create a general whereabouts locator for my chat program. It currently shows IP, Username and I'm trying to add Location. I'm attempting to use this piece of code:
var location = "";
List<string> HTML_code = new List<string>();
WebRequest request = WebRequest.Create("http://www.maxmind.com/app/locate_demo_ip?ips=" + IP);
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string line;
while ((line = stream.ReadLine()) != null)
{
HTML_code.Add(line);
}
}
location = (HTML_code[296].Replace("<td><font size=\"-1\">", "")).Replace("</font></td>", "");
return location;
This, however returns an exception about WebResponse:
The remote server returned an error: (403)
Forbidden.(System.Net.WebResponse GetResponse())
Why am I getting this? And how can I prevent it?
You must have a license key in order to use this service, as written here:
All of the services take the same parameters as inputs. The only difference between them is the URI they use and the data they return. The two parameters that each service takes are the IP address to look up and your MaxMind license key.
Once you get such a key, you have to add it to the URL in addition to the IP address.
I could not find the documentation of that particular REST API call, but it is clear from the company's website that this service is not free (at least not without a license key). This is a classic approach (you accompany each request you make to the API with your app/license key), for example both Twitter and Facebook have it.
Take a look at this link, where they give a code example of how to use their GeoIP service from C#. Also, consider taking a look at their free databases.

How to read returned xml value from google maps

I am trying to call google maps geocode and am following the example on their webpage to try and apply it to mine
http://code.google.com/apis/maps/documentation/geocoding/index.html
in this example, the Geocoding API requests an xml response for the
identical query shown above for "1600 Amphitheatre Parkway, Mountain
View, CA":
http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
The XML returned by this request is shown below.
Now i am trying to run that url like this in my c# winforms application
string url = "http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false";
WebRequest req = HttpWebRequest.Create(url);
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
try
{
Match coord = Regex.Match(sr.ReadToEnd(), "<coordinates>.*</coordinates>");
var b = coord.Value.Substring(13, coord.Length - 27);
}
finally
{
sr.Close();
}
However it doesnt seem to be returning anything and as such my var b line gives an index out of bounds error. Can anyone point me in the right direction for at least getting the example to work so i can apply the logic to my own application?
Thanks
If you visit your link "http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false" directly in a browser you can see what it's returning. It's giving me a REQUEST DENIED error.
The problem is caused by the sensor=true_or_false parameter. You have to choose if you want it to be true or false. Google put it this way in their example so that you have to explicitly decide for yourself. This setting indicates if your application is using a location sensor or not. In your case, I'm guessing not, so set it to false.
If you change the link you're using to http://maps.googleapis.com/maps/api/geocode/xml?address=1600%20Amphitheatre%20Parkway,%20Mountain%20View,%20CA&sensor=false, I think you'll get the results you were expecting.

Reading and posting to web pages using C#

I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.
Small coding examples like the ones linked to at http://www.csharp-station.com/HowTo/HttpWebFetch.aspx tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.
For the record, I'm not building a malicious and/or spam related product.
So how do I go read web pages that require a few steps of normal browsing to reach first?
You can programmatically create an Http request and retrieve the response:
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
Of course, this code will return an error since Google uses GET, not POST, for search queries.
This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:
Capture the page
Strip out the form
Create a POST string based on the form fields
FWIW, I think something like Perl or Python might be better suited to that sort of task.
edit: x-www-form-urlencoded
You might try Selenium. Record the actions in Firefox using Selenium IDE, save the script in C# format, then play them back using the Selenium RC C# wrapper. As others have mentioned you could also use System.Net.HttpWebRequest or System.Net.WebClient. If this is a desktop application see also System.Windows.Forms.WebBrowser.
Addendum: Similar to Selenium IDE and Selenium RC, which are Java-based, WatiN Test Recorder and WatiN are .NET-based.
What you need to do is keep retrieving and analyzing the html source for each page in the chain. For each page, you need to figure out what the form submission will look like and send a request that will match that to get the next page in the chain.
What I do is build a custom class the wraps System.Net.HttpWebRequest/HttpWebResponse, so retrieving pages is as simple as using System.Net.WebClient. However, my custom class also keeps the same cookie container across requests and makes it a little easier to send post data, customize the user agent, etc.
Depending on how the website works you can either manipulate the url to perform what you want. e.g to search for the word "beatles" you could just open a request to google.com?q=beetles and then just read the results.
Alternatively if the website does not use querystring values (url) to process page actions then you will need to work on a webrequest which posts the required values to the website instead. Search in Google for working with WebRequest and webresponse.

Categories