Hey guys i followed the tutorial here for a school project, https://www.dougv.com/2015/08/posting-status-updates-to-twitter-via-linqtotwitter-part-2-plain-text-tweets/
But when i run it with google chrome nothing is showing up and it just stuck in http://localhost:2860/linq2twitter.aspx which is a blank page, i've checked my twitter the tweet has not been made as well.. from the other sample i've tried i think it is suppose to send me to a authentication page which requires me to login and stuff.. any help is appreciated. Here's my code :
namespace WebApplication3
{
public partial class linq2twitter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
class Program
{
static void Main()
{
Console.WriteLine("Program started.");
try
{
var result = Task.Run(() => SendTweet());
result.Wait();
if(result == null) {
Console.WriteLine("Tweet failed to process, but API did not report an error");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Program completed.");
Console.Read();
}
static async Task<Status> SendTweet()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = "<Twitter consumer key>",
ConsumerSecret = "<Twitter consumer secret>",
AccessToken = "<Twitter access token>",
AccessTokenSecret = "<Twitter access token secret>"
}
};
var context = new TwitterContext(auth);
var status = await context.TweetAsync(
"Hello World! I am testing #dougvdotcom's #LinqToTwitter demo, at " +
"https://www.dougv.com/2015/08/posting-status-updates-to-twitter-via-linqtotwitter-part-2-plain-text-tweets"
);
return status;
}
}
}
}
Fixed after regenerating my secrets and keys.. and removed unintentional spacebar for my keys in the code. Thx
Related
I'm trying to create a UWP service app on the Raspberry Pi3 which provides the access to the on board UART. I'm facing an issue about the AppConnection Request/response.
this is the service method that handles the incoming requests from client apps
internal class Inbound
{
public static async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
var messageDeferral = args.GetDeferral();
var response = new ValueSet();
bool success = false;
var msg = args.Request.Message.Keys;
if (args.Request.Message.TryGetValue(ServiceApiRequests.Keys.Command, out object command))
{
try
{
switch (command)
{
case ServiceApiRequests.CommandValues.UartWrite:
if (args.Request.Message.TryGetValue(ServiceApiRequests.Keys.UartTxBuffer, out object txBuffer))
{
string rxBuff = "";
success = await Pi3.Peripherals.Uart.GerInstance(57600).Write((string)txBuffer);
if (success)
{
Debug.WriteLine("Tx: " + (string)txBuffer);
if (args.Request.Message.TryGetValue(ServiceApiRequests.Keys.ReadUartResponse, out object getResponse))
{
if ((string)getResponse == ServiceApiRequests.ReadUartResponse.Yes)
{
rxBuff = await Pi3.Peripherals.Uart.GerInstance(57600).Read();
Debug.WriteLine("Rx: " + rxBuff);
}
}
}
response.Add(ServiceApiRequests.Keys.UartRxBuffer, rxBuff);
}
break;
}
}
catch (Exception ex)
{
success = false;
}
}
response.Add(new KeyValuePair<string, object>(ServiceApiRequests.Keys.Result, success ? ServiceApiRequests.ResultValues.Ok : ServiceApiRequests.ResultValues.Ko));
var result = await args.Request.SendResponseAsync(response);
if (result == AppServiceResponseStatus.Failure)
{
Debug.WriteLine("Failed to send the response");
}
messageDeferral.Complete();
}
}
As you can figure out, the Uart class is get using the Singleton pattern using the method Pi3.Peripherals.Uart.GerInstance(57600).
Following the code i using for send the request from the client app.
public static class Uart
{
public static IAsyncOperation<string> SendCommand(this AppServiceConnection DriverControllerConnection, string txBuffer, string awaitResponse = ServiceApiRequests.ReadUartResponse.Yes)
{
return _SendCommand(DriverControllerConnection, txBuffer, awaitResponse).AsAsyncOperation();
}
private static async Task<string> _SendCommand(AppServiceConnection DriverControllerConnection, string txBuffer, string awaitResponse)
{
AppServiceResponse response = null;
string response_str = "";
try
{
if (DriverControllerConnection != null)
{
response = await DriverControllerConnection.SendMessageAsync(new ServiceApiRequests.UartWrite().GetCommand(txBuffer, awaitResponse));
if (response.Status == AppServiceResponseStatus.Success)
{
if (response.Message.TryGetValue(ServiceApiRequests.Keys.Result, out object result))
{
if ((string)result == ServiceApiRequests.ResultValues.Ok && awaitResponse == ServiceApiRequests.ReadUartResponse.Yes)
{
response_str = response.Message[ServiceApiRequests.Keys.UartRxBuffer] as string;
}
}
}
}
}
catch (Exception ex)
{
// TODO: log
}
return response_str;
}
}
The system works well just for a while, until i have response.Status == AppServiceResponseStatus.Success , then the result of the request changes and it becomes AppServiceResponseStatus.Failure. This way the program counter never steps into the condition if (response.Status == AppServiceResponseStatus.Success).
Any idea about the cause?
Thank you so much for the help.
EDIT
Follow the suggestions, i added an handler for the ServiceClosed event. This is the main class.
public sealed class DriverListener : IBackgroundTask
{
private BackgroundTaskDeferral backgroundTaskDeferral;
private AppServiceConnection appServiceConnection;
public void Run(IBackgroundTaskInstance taskInstance)
{
backgroundTaskDeferral = taskInstance.GetDeferral();
// taskInstance.Canceled += OnTaskCanceled;
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
appServiceConnection = triggerDetails.AppServiceConnection;
appServiceConnection.RequestReceived += Inbound.OnRequestReceived;
appServiceConnection.ServiceClosed += OnTaskCanceled;
}
private void OnTaskCanceled(AppServiceConnection sender, AppServiceClosedEventArgs reason)
{
if (this.backgroundTaskDeferral != null)
{
Debug.WriteLine("ServiceClosed");
// Complete the service deferral.
this.backgroundTaskDeferral.Complete();
}
}
}
Placing a breakpoint in this function, i see that it was never triggered.
The app connection is opened using the singleton pattern, and putted in a dll that i use in the client app
public static AppServiceConnection GetDriverConnectionInstance()
{
if (_DriverConnectionInstance == null)
{
try
{
_DriverConnectionInstance = OpenDriverConnection().AsTask().GetAwaiter().GetResult();
}
catch
{
}
}
return _DriverConnectionInstance;
}
I also add a Request to the service that toggles a led, and i noticed that the led status changes but the response from the app service is still "Failure" and the message is null.
The AppService has a default lifetime of 25sec, unless it is being requested by the foreground experience. When the service shuts down the connection, your client process will receive the ServiceClosed event, so you know you will need to reopen the connection the next time you want to send a request.
I'm new to Xamarin and I'm trying to create a cross-platform app where users can login using a JSON API call. A token is then returned on a successful login attempt which I can use in other API's to display user data.
It works when I use the same code in a console application, but when I run it in Xamarin the code after await client.GetAsync(url) is never reached and after a while the application breaks and I get an unknown error. Am I experiencing a deadlock?
private async void loginButton_Click(object sender, EventArgs e)
{
var login = await loginAPI(LoginPage.nameEntry.Text, LoginPage.passEntry.Text);
if (login.state == "success")
{
...
}
else
{
...
}
}
public static async Task<LoginData> loginAPI(String username, String password)
{
try
{
using (var client = new HttpClient())
{
var loginUrl = new Uri("https://my-api/login?username=" + username + "&password=" + password);
var result = await client.GetAsync(loginUrl);
return JsonConvert.DeserializeObject<LoginData>(await result.Content.ReadAsStringAsync());
}
}
catch (Exception e)
{
return null;
}
}
public class LoginData
{
[JsonProperty("state")]
public String state { get; set; }
[JsonProperty("token")]
public String token { get; set; }
}
I am trying to connect to a SharePointOnline 2013.
In my C# Console Application everything works fine, but if I try (nearly) the same code in an Universal App, it is not possible to create multiple instances of a ClientContext nor setting the credentials multiple times.
Im using the Microsoft.SharepointOnline.CSOM Version: 16.1.4727.1204 (released on 11.12.2015)
class Program
{
static void Main(string[] args)
{
UseContextMultipleTime();
UseContextMultipleTime();
}
public static void UseContextMultipleTime()
{
using (var context = new ClientContext("https://something.sharepoint.com"))
{
var securePassword = new SecureString();
foreach (char c in "password".ToCharArray()) securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("username", securePassword);
try
{
context.ExecuteQuery();
string status = "OK";
}
catch (Exception ex)
{
string test = ex.ToString();
}
}
}
}
Below the Universal App version, which crashes in the second method call:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
UseContextMultipleTime();
UseContextMultipleTime();
}
public void UseContextMultipleTime()
{
using (var context = new ClientContext("https://something.sharepoint.com"))
{
context.Credentials = new SharePointOnlineCredentials("username", "password");
try
{
context.ExecuteQueryAsync().Wait();
string status = "OK";
}
catch (Exception ex)
{
string test = ex.ToString();
}
}
}
}
When I set the credentials only once, it will work.
Does anybody know a solution for this problem? I will appreciate every kind of hints.
The Problem was solved in the latest CSOM update. Everything works fine now.
I've been driving myself nuts trying to resolve this issue so really hoping someone has some insight.
I have a console application which runs/hosts my signalR server.
I have already successfully connected to it using a web(javascript) client and a windows forms client with no trouble at all.
BUT for the life of me I cannot get a silverlight client to connect to it. Initially I was getting a
'System.Security.SecurityException' occurred in Microsoft.Threading.Tasks error
on
await Connection.Start();
I managed to fix that by force sending the clientaccesspolicy file using code i found on a random thread.
THREAD
However the connection still never establishes. The status goes thru connecting, disconnected, connection closed.
I am at my wits end as to why this won't work. Any input is appreciated. Code below.
MainPage.xaml.cs
public partial class MainPage : UserControl
{
private SignalRClient client;
public MainPage()
{
InitializeComponent();
dataGrid1.ItemsSource = new ItemsCollection();
client = new SignalRClient();
client.RunAsync();
Debug.WriteLine("Init Done");
}
}
-
SignalRClient.cs
public class SignalRClient
{
private HubConnection Connection { get; set; }
private IHubProxy HubProxy { get; set; }
const string url = "http://localhost:8080/";
public SignalRClient()
{
}
public async void RunAsync()
{
Connection = new HubConnection(url, useDefaultUrl: true);
Connection.Closed += Connection_Closed;
Connection.StateChanged += ConnectionDidSomething;
HubProxy = Connection.CreateHubProxy("TickerHub");
HubProxy.On<string>("receiveAllData", data => Debug.WriteLine("RECDATA={0}", data));
try
{
await Connection.Start();
}
catch (HttpClientException e)
{
Debug.WriteLine("Unable to connect to server.1 {0}", e.Message);
return;
}
catch (HttpRequestException e)
{
Debug.WriteLine("Unable to connect to server.2 {0}", e.Message);
return;
}
}
-
Server
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8080/";
using (WebApp.Start(url))
{
Console.WriteLine("SignalR server running on {0}", url);
Console.ReadLine();
}
Console.ReadLine();
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
Console.WriteLine("Configuration");
//Tried this approach too
/*app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});*/
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR<ClientAccessPolicyConnection>("/clientaccesspolicy.xml");
}
}
-
TickerHub.cs
public class TickerHub : Hub
{
public override Task OnConnected()
{
string connectionID = Context.ConnectionId;
Console.WriteLine("New Connection:" + connectionID);
InitNewClient(connectionID);
return base.OnConnected();
}
//send all data to newly connected client
public void InitNewClient(string connectionID)
{
}
//client requested all data
public void GetAllData()
{
Console.WriteLine("Get Data Triggered");
Clients.All.receiveAllData("TESTING123");
}
}
I figured it out! Hopefully this helps someone in the future.
Its quite simple. This is what you need to have in your startup class configuration method.
Below that is the code required to send the clientaccesspolicy.xml.
class Startup
{
public void Configuration(IAppBuilder app)
{
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR<ClientAccessPolicyConnection>("/clientaccesspolicy.xml");
}
}
-
public class ClientAccessPolicyConnection : PersistentConnection
{
public override Task ProcessRequest(Microsoft.AspNet.SignalR.Hosting.HostContext context)
{
string[] urlArray = context.Request.Url.ToString().Split('/');
string path = urlArray[urlArray.Length - 1];
if (path.Equals("clientaccesspolicy.xml", StringComparison.InvariantCultureIgnoreCase))
{
//Convert policy to byteArray
var array = Encoding.UTF8.GetBytes(ClientAccessPolicy);
var segment = new ArraySegment<byte>(array);
//Write response
context.Response.ContentType = "text/xml";
context.Response.Write(segment);
//Return empty task to escape from SignalR's default Connection/Transport checks.
return EmptyTask;
}
return EmptyTask;
}
private static readonly Task EmptyTask = MakeTask<object>(null);
public static Task<T> MakeTask<T>(T value)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(value);
return tcs.Task;
}
public static readonly string ClientAccessPolicy =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<access-policy>"
+ "<cross-domain-access>"
+ "<policy>"
+ "<allow-from http-request-headers=\"*\">"
+ "<domain uri=\"*\"/>"
+ "</allow-from>"
+ "<grant-to>"
+ "<resource path=\"/\" include-subpaths=\"true\"/>"
+ "</grant-to>"
+ "</policy>"
+ "</cross-domain-access>"
+ "</access-policy>";
}
Using the Facebook C# SDK, I'm getting the following error when I try to post a status update:
OAuthException: (#200) The user hasn't authorized the application to perform this action
I am getting this error only with some users. For some other,status is updating fine. App is successfully getting access for all users.
This is the full code :
public partial class Authorize : Form
{
public Authorize()
{
InitializeComponent();
}
public string ApplicationId
{
get
{
return ConfigurationManager.AppSettings["ApplicationId"];
}
}
public string ExtendedPermissions
{
get
{
return ConfigurationManager.AppSettings["ExtendedPermissions"];
}
}
public string AppSecret
{
get
{
return ConfigurationManager.AppSettings["ApplicationSecret"];
}
}
public string AccessToken { get; set; }
private void LoadAuthorize(object sender, EventArgs e)
{
var destinationURL = String.Format(
#"https://www.facebook.com/dialog/oauth?client_id={0}&scope={1}&redirect_uri=http://www.facebook.com/connect/login_success.html&response_type=token",
this.ApplicationId,
this.ExtendedPermissions);
webBrowser.Navigated += WebBrowserNavigated;
webBrowser.Navigate(destinationURL);
}
private void WebBrowserNavigated(object sender, WebBrowserNavigatedEventArgs e)
{
// get token
var url = e.Url.Fragment;
if (url.Contains("access_token") && url.Contains("#"))
{
this.Hide();
url = (new Regex("#")).Replace(url, "?", 1);
this.AccessToken = System.Web.HttpUtility.ParseQueryString(url).Get("access_token");
//MessageBox.Show(facebookCore.AccessToken);
try
{
//var facebooking = new FacebookingTest(facebookCore.AccessToken);
//facebooking.UpdateStatus();
var fb = new FacebookClient(this.AccessToken);
dynamic result = fb.Post("me/feed", new { message = "Hi..Test33" });
var newPostId = result.id;
}
catch (Exception exception)
{
Console.Write(exception);
}
}
}
}
Try opening the file App.Config and modify the last line of the
<appsettings>
section as follows:
<add key="ExtendedPermissions" value="offline_access,publish_stream,publish_actions" />