I am using Twitterizer, and am trying to get my ASP.Net app to upload reported traffic incidents to the official Twitter account.
I have looked at similar questions at SO, and the I tried all the recommendations (specify call-back url, check for careless errors and ensure the app has Read-Write permissions), but I still cannot solve the problem. I have some screenshots of the settings and code below. The callback URL does not exist, but is made up. Any help will be greatly appreciated.
Another item to look for is the computer time. Look at the server time in the Twitter response and compare it to the computer you're using. Also, here's a troubleshooting guide from the Twitter site:
https://dev.twitter.com/discussions/204
I came back to this problem, this time I tried regenerating my API keys, and now it is working. Perhaps my previous keys were duds.
public static void UploadTweet(string token, string tokensecreat, byte[] img, string Title)
{
Twitterizer.OAuthTokens tokens = new Twitterizer.OAuthTokens();
tokens.AccessToken = token;
tokens.AccessTokenSecret = tokensecreat;
tokens.ConsumerKey = TWITTER_CONSUMER_KEY;
tokens.ConsumerSecret = TWITTER_CONSUMER_SECRET;
byte[] photo = img;
TwitterResponse<TwitterStatus> response = TwitterStatus.UpdateWithMedia(tokens, Title, photo, new StatusUpdateOptions() { UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/" });
if (response.Result == RequestResult.Success)
{
}
else
{
}
}
Related
(using C#)
I'm trying to authenticate but it always comes back failed. I know my username and password are correct. We may be using OSLC 1.0 if that matters. I'm not sure but I see it a couple times in the services.xml file. The website I'm getting my insight from was using 3.0. Maybe there's a difference? Any idea what I'm doing wrong?
Debug.Log("Authentication Required");
// tried with just j_security_check as well (without "authenticated") as he seems to do both on the site
HttpWebRequest _formPost = (HttpWebRequest)WebRequest.Create(localhost + "authenticated/j_security_check");
_formPost.Method = "POST";
_formPost.Timeout = 30000;
_formPost.CookieContainer = request.CookieContainer;
_formPost.Accept = "text/xml";
_formPost.ContentType = "application/x-www-form-urlencoded";
Byte[] _outBuffer = Encoding.UTF8.GetBytes("j_username=coolcat&j_password=bestPassEvar"); //store in byte buffer
_formPost.ContentLength = _outBuffer.Length;
Stream _str = _formPost.GetRequestStream();
_str.Write(_outBuffer, 0, _outBuffer.Length); //update form
_str.Close();
//FormBasedAuth Step2:submit the login form and get the response from the server
HttpWebResponse _formResponse = (HttpWebResponse)_formPost.GetResponse();
string _rtcAuthHeader = _formResponse.Headers["X-com-ibm-team-repository-web-auth-msg"];
//check if authentication has failed
if ((_rtcAuthHeader != null) && _rtcAuthHeader.Equals("authfailed"))
{
Debug.Log("Authentication Failed");
return;
}
Ugh. I'm such a dummy. Username/Password were correct, but I was encoding it twice before using it! (not seen in code above as I hard-coded it for obvious security reasons).
You can find some sample code that communicates with Jazz-based products using OSLC, under this github repository https://github.com/OSLC/lyo-samples.
I found this sample code that particularly deals with Form authentication.
https://github.com/OSLC/lyo-samples/blob/master/oslc4j-client-samples/src/main/java/org/eclipse/lyo/oslc4j/client/samples/ERMSample.java
A number of programs in that same folder try to connect to different Jazz solutions.
First of all, i'm new an http and mjpeg-stream, so it is very possible that I only have a comprehension problem. Maybe someone can help me here anyway.
I had an problem to get the mjpeg stream from my ip camera. The link for calling the stream works fine in the browser and i can watching the livestream.
(e.g. http://192.168.xx.xx:8081/cgi-bin/hi3510/mjpegstream.cgi?-chn=11&-usr=user&-pwd=password, where xx.xx and user, password are placeholders)
If i try to connect in an uwp app to the ip camera i get no stream back. i'v trying so many solutions but no one still works for me. (These are some of the trying solutions:
MjpegProcessor
OZEKI Camera SDK
IP Camera Viewer
Onvif Camera Viewer )
I also read so many useful articles here, but now one has the right answer.
My sourcecode looks like as follows:
var newParams = new[]
{
new KeyValuePair<string, string>("-chn", "11")
};
var baseUrl = new Url("http://192.168.xx.xx:8081");
Debug.WriteLine(baseUrl);
using (var fc = new FlurlClient(baseUrl).EnableCookies())
{
// login on page
var loginResponse = await baseUrl
.WithClient(fc)
.PostUrlEncodedAsync(new
{
usr = "user",
pwd = "password"
});
//StatusCode 200
if (loginResponse.IsSuccessStatusCode)
{
try
{
// get mjepg stream from page
var streamResult = await baseUrl
.AppendPathSegments(new string[] { "cgi-bin", "hi3510", "mjpegstream.cgi" })
.SetQueryParams(newParams)
.WithClient(fc)
.GetStreamAsync();
var memNewStream = new MemoryStream();
await streamResult.CopyToAsync(memNewStream);
memNewStream.Position = 0;
mediaElement.SetSource(memNewStream.AsRandomAccessStream(), "multipart/alternative");
}
catch (FlurlHttpException ex)
{
Debug.WriteLine(ex);
}
}
}
and i got always an:
Flurl.Http.FlurlHttpException: Request to http://192.168.xx.xx:8081/cgi-bin/hi3510/mjpegstream.cgi?-chn=11&-usr=user&-pwd=password failed with status code 401 (Unauthorized) on var streamResult = await baseUrl .AppendPathSegments(new string[] { "cgi-bin", "hi3510", "mjpegstream.cgi" }) .SetQueryParams(newParams).WithClient(fc).GetStreamAsync();.
if i change the baseURL into var baseUrl = new Url("http://192.168.xx.xx:8081/cgi-bin/hi3510/mjpegstream.cgi?-chn=11&-usr=user&-pwd=password"); and try to connect i got the same status code 401.
many thanks in advance!
Update:
The link for calling the stream in the browser htp://192.168.xx.xx:8081/cgi-bin/hi3510/mjpegstream.cgi?-chn=11&-usr=user&-pwd=password.
-> OK
In the Sourcecode example above the first call with
var loginResponse = await baseUrl.WithClient(fc).PostUrlEncodedAsync(new { usr = "user", pwd = "password" });
-> OK Url http://192.168.xx.xx:8081
In the Sourcode example above, the second call with
var streamResult = await baseUrl.AppendPathSegments(new string[] { "cgi-bin", "hi3510", "mjpegstream.cgi" }).SetQueryParams(newParams).WithClient(fc).GetStreamAsync();
-> Exception Flurl.Http.FlurlHttpException: Request to http://192.168.178.35:8081/cgi-bin/hi3510/mjpegstream.cgi?-chn=11 failed with status code 401 (Unauthorized).
Url http://192.168.xx.xx:8081/cgi-bin/hi3510/mjpegstream.cgi?-chn=11
Thats what you want?
401 (Unathorized) code speaks for itself: You have a problem with an authentication:
The problem might be that IP cam cannot authorized You through the credentials
in URL.
(or) You might have a typo elsewhere in credentials.
(or) For remote connection not using browser, the IP cam might require using some other base of authentication. E.g. some browsers are sending this via HTTP header.
have You went through the datasheet for comms of IP? It might require authentication for every time You are trying to connect, which might require sending the credentials during stream openning:
I have just checked link in comments, and they specify credentials examples as:
http://IP-Address:Port/tmpfs/snap.jpg?usr=admin&pwd=instar :: Snapshot (720p / 1280x720 Pixel)
Please note that there is no '-' in front of "usr" or "pwd".
I am building a Asp.net C# application i want to post the user uploaded picture directly to Instagram, but after a quick search i can not found any function in the API somebody help me how to post image on instagram wall by C# code
Below Code I can Get Access Token
private void Authentication()
{
string rest = string.Empty;
GlobusInstagramLib.Authentication.ConfigurationIns config = new GlobusInstagramLib.Authentication.ConfigurationIns("https://instagram.com/oauth/authorize/", ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["consumerSecret"], ConfigurationManager.AppSettings["callbackurl"], "https://api.instagram.com/oauth/access_token", "https://api.instagram.com/v1/", "");
oAuthInstagram _api = oAuthInstagram.GetInstance(config);
rest = _api.AuthGetUrl("likes+comments+basic+relationships");
Response.Redirect(rest);
}
// Call back Url
public ActionResult Instagram()
{
string code = (String)Request.QueryString["code"];
oAuthInstagram objInsta = new oAuthInstagram();
GlobusInstagramLib.Authentication.ConfigurationIns configi = new GlobusInstagramLib.Authentication.ConfigurationIns("https://api.instagram.com/oauth/authorize/", ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["consumerSecret"], ConfigurationManager.AppSettings["callbackurl"], "http://api.instagram.com/oauth/access_token", "https://api.instagram.com/v1/", "");
oAuthInstagram _api = new oAuthInstagram();
_api = oAuthInstagram.GetInstance(configi);
AccessToken access = new AccessToken();
access = _api.AuthGetAccessToken(code);
string accessToken = access.access_token;
string id =access.user.id;
ViewBag.accessToken = accessToken;`enter code here`
ViewBag.Uid = id;
return View();
}
Below Code i have get Access Token and Profile ID
How To Post Image ? some body tall me
You cannot upload photos to Instagram through the API. From Instagram's API documentation https://instagram.com/developer/endpoints/media/:
At this time, uploading via the API is not possible. We made a
conscious choice not to add this for the following reasons:
Instagram is about your life on the go – we hope to encourage photos from within the app.
We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the
Instagram ecosystem. All this being said, we're working on ways to
ensure users have a consistent and high-quality experience on our
platform.
I want to show my user feed on my website and what I intend to do is to authenticate my own user account each time a user visits the page, and in that way buypass that the user have to log in to his instagram account.
My problem is that I'm having a hard time retrieving the instagram access token through a HttpWebRequest..
See the following NON working code sample:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/authorize?client_id=xxxxxxxxxxxxxxxxxxxxxx&redirect_uri=http://mywebsite.com&response_type=token");
request.Method = "POST";
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirectUrl = response.ResponseUri.ToString();
HttpContext.Current.Response.Write(redirectUrl);
HttpContext.Current.Response.End();
If I paste the url in my browser I get a redirect to http://mysite.com/#access_token=xxxxxxxxxxxxxx and everything seems fine, but when I try to execute the code above, I can't retrieve the correct uri due to some in between redirects before the final url.
Any help would be much appriciated..
I recommend you to use Instasharp library. InstaSharp is a C# library that wraps the Instagram API and makes it easy to write applications with Instagram data. It has a very easy method to get access token for a user. Check its API.
Unfortunately the documentation for Instasharp currently provided has a few errors. I.e. The documentation says OAuthInfo, when such a class does not exist.
Here is some code that works for me.
Notice you don't seem to need to pass a User Object at all (not sure why you would need to anyway)
Also note, that the authenticated and non authenticated methods allow you pass different params, count being the most important one. I've noticed that regardless of the count you pass, an arbitrary number of results is returned, e.g. 33 for authenticated and 13 for authenticated for the same search term. InstagramResult is my wrapper class for the object and Config holds the InstagramAuthorisationModel and InstagramAuthorisationModel holds the static keys created when signing up for a developer account.
public class InstagramService : IInstagramService
...
public InstagramConfig Config
{
get{return new InstagramConfig("https://api.instagram.com/v1", "https://api.instagram.com/oauth", InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret, InstagramAuthorisationModel.RedirectUri);}
}
private AuthInfo UserAuthInfo()
{
return new AuthInfo()
{
// User =new UserInfo(){},
Access_Token = GetInstagramAccessToken()
};
}
public string GetInstagramAccessToken()
{
return _socialMediaRepository.GetInstagramAccessToken(_userApiKey);
}
public List<InstagramResult> Search(string searchTag, int count)
{
var auth = UserAuthInfo();
var tags = new InstaSharp.Endpoints.Tags.Authenticated(Config, auth);
var searchresult = tags.Recent(searchTag);
return searchresult.Data.Select(media => new InstagramResult()
{
Media = media,
image = media.Images.LowResolution.Url
})
.ToList();
}
..
So I've looked at all the of the suggestions from the Linq to Twitter documentation regarding 401 statuses with Oauth and I honestly don't know what I'm doing wrong.
var auth = new PinAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
//OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"], //don't include this
//AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"] //or this for new users.
},
//
UseCompression = true,
GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
GetPin = () =>
{
Console.WriteLine("/nAfter twitter authorizes your application you will be returned here or something/n");
Console.Write("Enter Pin here:");
return Console.ReadLine();
}
};
auth.Authorize();
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/",
"https://search.twitter.com/"))
{
try
{
twitterCtx.Log = Console.Out;
Console.WriteLine("Please provide tweet text");
string tweet = Console.ReadLine();
twitterCtx.UpdateStatus(tweet);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I've ran this using the Pin Authentication method as well as the single user method (providing the oauth keys with config file). I'm able to query tweets but I can't update my status or send direct messages (I receive a 403 forbidden when I try to DM). I've provided a callback URL (albeit fake) so I can't think of why this isn't working. Any help would be appreciated.
PS this runs in Main, not sure if that matters
All you need is this overload of the TwitterContext ctor and it will use the proper base URLs:
new TwitterContext(auth)
The example you're using is for v1.0 URLs and LINQ to Twitter is on Twitter API v1.1 now. It will default to the proper base URLs.
If you're querying okay, but getting errors on update and DM, double check to make sure you aren't trying to tweet the same text. That's why I append a DateTime.Now to the end of test tweets - to guarantee uniqueness.