Get userstream from twitter - c#

A month ago a build a twitter tool in c# Windows Form Application. I can send tweets and view the hometimeline,friendtimeline and the mentiontimeline. I used the twitterizer dll with the OAuthTokens method, but there is a refresh limit and it is very slow.
Now i want to start a streaming twitter application but i cant find a proper example or documentation for this. I started but i didn't find the function who can start the stream and but it in a string or textbox. My question is how to get the stream from the hometimeline.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Twitterizer;
using Twitterizer.Streaming;
namespace Twww
{
public partial class Form1 : Form
{
public OAuthTokens tokens = new OAuthTokens();
private string userAgent = null;
public Form1()
{
InitializeComponent();
/* input tokens removed in example code */
tokens.AccessToken = accessToken;
tokens.AccessTokenSecret = accesssecret;
tokens.ConsumerKey = consumerKey;
tokens.ConsumerSecret = consumerSecret;
}
private void Form1_Load(object sender, EventArgs e)
{
Twitterizer.Streaming.UserStreamOptions options = new UserStreamOptions();
OAuthTokens token = new Twitterizer.OAuthTokens ();
TwitterStream stream = new TwitterStream(token, userAgent, options);
}
}
}
I tried to make it work for a user stream, but i get 401 or 403 errors, who says i have no rights
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Twitterizer;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
OAuthTokens tokens = new OAuthTokens();
string consumerKey = "XX";
string consumerSecret = "XX";
string accessToken = "XX";
string accesssecret = "XX";
tokens.AccessToken = accessToken;
tokens.AccessTokenSecret = accesssecret;
tokens.ConsumerKey = consumerKey;
tokens.ConsumerSecret = consumerSecret;
string url = "https://userstream.twitter.com/1.1/user.json?with=followings&replies=all";
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("XX", "XX");
StreamReader reader = new StreamReader(wc.OpenRead(url));
string line;
while ((line = reader.ReadLine()) != null)
{
dynamic json = JsonConvert.DeserializeObject(line);
if (json.text != null)
{
Console.WriteLine(json.text);
}
}
}
}
}

Check this, you have a very well designed guide of TwitterStream in twitterizer:
http://thewayofcode.wordpress.com/tag/json/

Related

Fetching the contents of discussion board from share point using console application

I tried to fetch the discussion items from the discussion form available on the SharePoint using client side code CSOM and I am connected successfully but unable to fetch the discussions...
Here is the link of the sharePoint :--
https:///sites//GlobalDiscussion/SitePages/Community%20Home.aspx
Below is my code :------
using System.Security;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using MongoDB.Driver;
using MongoDB.Bson;
using Microsoft.SharePoint;
namespace ConnectToSPO
{
class Program
{
static void Main(string[] args)
{
string webSPOUrl = "";
string userName = "";
SecureString password = new NetworkCredential("", "").SecurePassword;
try
{
using (var context = new ClientContext(webSPOUrl))
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
context.AuthenticationMode = ClientAuthenticationMode.Anonymous;
context.Credentials = new SharePointOnlineCredentials(userName, password);
Web web = context.Web;
context.ExecuteQuery();
Console.WriteLine(web.ServerRelativeUrl);
var filePath = web.ServerRelativeUrl + "/GlobalDiscussion/SitePages/Community%20Home.aspx";
Console.WriteLine(filePath);
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, filePath);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error is: " + ex.Message);
}
}
}
}
It will be great if anyone can help me out ...
Thank you...

WebClient.DownloadString: Invalid JSON primitive:

I am trying to download a JSON string from a PHP file on my webserver with WebClient.
This is my code:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Web.Script.Serialization;
using System.Collections.Generic;
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static bool GetProgramInfo (string secret_key)
{
try
{
ServicePointManager.ServerCertificateValidationCallback += Methods.ValidateRemoteCertificate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(username, password);
client.Headers.Add(HttpRequestHeader.UserAgent, useragent);
string jsonData = client.DownloadString(url);
MessageBox.Show(jsonData);
}
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
}
I tried removing all code that has to do with JSON, including the using statements.
The program goes into break mode exactly at string jsonData = client.DownloadString(url); and I get the error System.ArgumentException: 'Invalid JSON primitive: .'. The error still shows when I try to use .ToString().
The PHP script returns the data from a SQL table as shown here:
$stmt = $conn->prepare("SELECT id, value FROM `kl_general`");
$stmt->execute();
while ($row = $stmt->fetch()) {
if (intval($row['id'] == 5))
$version = $row['value'];
else if (intval($row['id']) == 6)
$hash = $row['value'];
}
$jsonFormat = json_encode(array('version' => $version, 'hash' => $hash));
die($jsonFormat);
When I directly access the file on my server I get the indented results: {"version":"3.0.0","hash":"a28fa7bab9878e42121efccb4e9277a8"}
Update
I attempted using HttpClient instead of WebClient using the code below with the same error being produced:
using System.Net;
using System.Net.Http;
var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) }
using (var client = HttpClient(handler))
{
var result = client.GetStringAsync(url);
MessageBox.Show(result.Result);
}

Use MapReduce to Get Response of Urls in c#

I have following program which get more then 1,00,000 urls from database and use C# HttpWebRequest object to get Response and save into database.
To get response of 1,00,000 urls take long time to run in single server. I want divide this process into thread and want run in multiple server.
It is possible to use such type of code in MapReduce in C# with thread and TPL ?
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Runtime.Serialization;
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
TestApp testapp = new TestApp();
var urls = testapp.GetURls();
//get string from urls
foreach (var url in urls)
{
var responseString=testapp.GetURLString(url);
//now save response into database
testapp.saveResponseToDB(responseString);
}
}
}
public class TestApp
{
public void saveResponseToDB(string response)
{
//save into db
}
public List<string> GetURls()
{
var urls =new List<string>();
//fetching more then 100000 urls from database.
return urls;
}
public string GetURLString(string requestUrl)
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the content.
string responseFromServer = reader.ReadToEnd();
// return the content.
return responseFromServer;
}
}
}
}

C# proxy at webbrowser object

I wanted to create a program in C# that goes to a website, with the use of a proxy server.
If I run this program I got error at line 37 when I debug it. Can you help me please?
I always got the error that the time is occuperd. I changed TimeOut, but
It never does anything.
txtUrl is a textbox where you need to put in the url of the website you wanna visite.
txtProxyPath is a textbox that is used as a openfiledialog,
and there I can select a .txt file with proxy ips in.
Here the code I used:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YoutubeRefresh
{
public partial class Form1 : Form
{
static private ArrayList listProxy = new ArrayList();
static private short proxyShort = 0;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
Uri uriAdress = new Uri(txtUrl.Text);
object[] arrayProxy = listProxy.ToArray();
WebProxy proxyObject = new WebProxy(arrayProxy[proxyShort].ToString());
MessageBox.Show("Proxyserver used: " + arrayProxy[proxyShort].ToString());
proxyShort += 1;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
webRequest.Proxy = proxyObject;
// httpwepresponse error
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
webBrowser1.DocumentStream = receiveStream;
}
private void btnChoosListProxy_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtProxyPath.Text = openFileDialog1.FileName;
}
foreach (var v in File.ReadAllLines(txtProxyPath.Text))
{
listProxy.Add(v.ToString());
}
}
}
}
Thank you very much!
var request = (HttpWebRequest)WebRequest.Create("http://google.com");
request.Proxy = new WebProxy("IP", port);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
Console.WriteLine(streamReader.ReadToEnd());
}
}
}
Also in your App.Config file, (if you don't have one, create one) add the following.
<configuration>
<system.net>
<settings>
<servicePointManager expect100Continue="false"/>
</settings>
</system.net>
</configuration>

Error 400 bing text to speech

I’m using bing’s api TTS, I get the information from: http://msdn.microsoft.com/en-us/library/ff512420.aspx
This is the code (from the webside):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Media;
namespace Apigoogleprova
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Speak();
}
private static void ProcessWebException(WebException e, string message)
{
Console.WriteLine("{0}: {1}", message, e.ToString());
// Obtain detailed error information
string strResponse = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)e.Response)
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
{
strResponse = sr.ReadToEnd();
}
}
}
Console.WriteLine("Http status code={0}, error message={1}", e.Status, strResponse);
}
public static void Speak()
{
string appId = "myappID"; //go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "speak to me";
string language = "en";
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId +"&text;=" + text + "&language;=" + language;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
//httpWebRequest.Proxy = new WebProxy(""); set your proxy name here if needed
WebResponse response = null;
try
{
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}
}
catch (WebException e)
{
//ProcessWebException(e, "Failed to speak");
MessageBox.Show("Error"+e);
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
}
}
}
(I changed “myappID” with the ID that has provided me Microsoft)
When I run the app I get the following error:
Remote Server Error (400) Bad Request
I tried to go to the web with my browsers (firefox, chrome and IE):
http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=myappID&text;=speak to me&language;=en
And the result is:
**Argument Exception**
Method: Speak()
Parameter: text Message: Value cannot be null.
Parameter name: text message
id=3835.V2_Rest.Speak.25BD061A
Anyone know how to solve this problem?
Thank you very much!
Remove the ; from the parameter names in the query string.

Categories