Twitter and Winform C# app is making me go bald - c#

Ok twitter might be great for social media but for a small app that I am trying to create just for fun has turned into a nightmare. I have searched everywhere and can't find a good explanation on how to use the api.
I am using the TweetSharp api and all I want to do is for user to allow my app and be able to post from the app to their twitter.
My problem comes when the app gives out a pin code for the user to type in...where would the user type it in at? Ok so this is what I have so far..if anyone can help i would be most greatful so I can stop pulling my hair..
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 TweetSharp;
using System.Configuration;
using Hammock.Authentication.OAuth;
using System.Diagnostics;
namespace testtweet
{
public partial class Form1 : Form
{
//I already have these values not showing here for obvious reasons.
TwitterService service = new TwitterService("ConsumerKey", "ConsumerSecret");
public Form1()
{
InitializeComponent();
// Pass your credentials to the service
// Step 1 - Retrieve an OAuth Request Token
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
Form2 frm = new Form2(uri.ToString());
frm.Show();
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
IEnumerable<TwitterStatus> mentions = service.ListTweetsMentioningMe();
}
}
}
on my Form2
public Form2(string url)
{
InitializeComponent();
webBrowser1.Navigate(url);
}
Here is where I am lost. As you see Step 3 is wating for the pin code..How would I set it in there? I had an idea to write directly in the app.config but
how do I know when it has been generated? Should I make a 3rd form to have the user input the pin code there?

so this is what I've got (add a webbrowser named webBrowser1 in the designer)
public partial class TwitterBrowser : Form
{
public TwitterBrowser()
{
InitializeComponent();
webBrowser1.Navigated += OnNavigate;
}
private void OnNavigate(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.ToString() != #"https://api.twitter.com/oauth/authorize")
return;
if (webBrowser1.Document != null)
{
var regex = new Regex("<code>([0-9]*)</code>", RegexOptions.Multiline);
VerificationCode = regex.Match(webBrowser1.DocumentText).Groups[1].Value;
Close();
}
}
public string VerificationCode { get; private set; }
#region Implementation of ITwitterUserInteraction
public void NavigateTo(Uri uri)
{
webBrowser1.Navigate(uri);
}
#endregion
}
Then use it like this:
var browser = new TwitterBrowser();
browser.NavigateTo(uri);
browser.ShowDialog();
result = browser.VerificationCode;

Related

Refresh Page with new data from APi by searchHandler Xamarin C#

I have a question about the function search Handler in xamarin. I am just starting to learn xamarin, and I am trying in my project with search handler in xamarin to refresh my page with new data from the API. Currently, I am already lucky to retrieve the data, but when I do this, it creates a new page so to speak, but this is not what I want. He would kind of reload the page with new data. I have also already tried to delete previous page with "Shell.Current.Navigation.PopAsync();" But with no residual result. Anyone knows how I can achieve what I want? In addition, I would also like to remove that blur you get after the search. Thanks in advance!
using Eindproject.Models;
using Eindproject.Repository;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Eindproject.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Weather : ContentPage
{
private string icao = "EBBR";
public Weather()
{
InitializeComponent();
}
public Weather(string icao)
{
InitializeComponent();
this.icao = icao;
frontend(icao);
}
public async void frontend(string par_icao)
{
// Get weather
Models.WeatherModel weather = await DataRepository.GetWeatherAsync(par_icao);
// Set data to labels
lblLocation.Text = weather.Station.Name;
lblCode.Text = weather.Code;
lblTemp.Text = weather.Temperature.C.ToString();
lblHumidity.Text = weather.Humidity.Percent.ToString();
lblWind.Text = weather.Wind.Degrees.ToString();
lblPressure.Text = weather.Presure.Hpa.ToString();
lblDate.Text = weather.Date.ToString("G");
lblMetar.Text = weather.Metar;
lblCloud.Text = weather.Clouds[0].text;
// Get sunrise and sunset
SunTimes sunrise = await DataRepository.GetSunTimesAsync("EHBK");
// Set data to labels
lblSunrise.Text = sunrise.Sunrise.ToString("G");
lblSunset.Text = sunrise.Sunset.ToString("G");
}
private void ToolbarItem_Clicked(object sender, EventArgs e)
{
}
}
public class CustomSearchHandler : SearchHandler
{
// When user press enter and confirm get the icao code and search for the weather
protected override void OnQueryConfirmed()
{
// Get the icao code
string icao = Query;
// Call wheather object
Weather weather = new Weather();
// Call frontend
weather.frontend(icao);
}
}
}
this is creating a new instance of Weather and calling its frontend method. That won't do anything useful.
Weather weather = new Weather();
weather.frontend(icao);
Instead you need to use the existing instance that is already displayed to the user
there are many ways to do this, but this might be the simplest
// get the current page
var page = App.Current.MainPage;
// cast it to the correct type
var weather = (Weather)page;
// call its frontend method
page.frontend(icao);

The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?) fixed

I'm trying to make a web browser application, but when I relaunch Visual Studio Community 2019, it shows me about 500 errors such as The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?).
I tried reloading Visual Studio Community 2019 a few times, but still doesn't work either.
Some project infos:
Target framework: .NET Framework 4.8
NuGet Packages used: EasyTabs, CefSharp.WinForm
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 CefSharp;
using CefSharp.WinForms;
using EasyTabs;
Just before I post the question, I found out that you need to use .NET Framework 4.7.2 in order to fix the problem.
So you're using easy tabs, I have the code for you. create new windows form project, in the project create another form and rename it AppContainer with the caps and everything, then open the app container with framework 4.7.2 then type in C# code
namespace YOUR_PROGRAM_NAME_HERE
{
public partial class AppContainer : TitleBarTabs
{
public AppContainer()
{
InitializeComponent();
AeroPeekEnabled = true;
TabRenderer = new ChromeTabRenderer(this);
}
// Handle the method CreateTab that allows the user to create a new Tab
// on your app when clicking
public override TitleBarTab CreateTab()
{
return new TitleBarTab(this)
{
// The content will be an instance of another Form
// In our example, we will create a new instance of the Form1
Content = new Form1
{
Text = "New Tab"
}
};
}
// The rest of the events in your app here if you need to .....
}
}
also at the top of where it says using please type using EasyTabs and then type using CefSharp. basically every package code you use you need to refer to that package then add a subtitle for Browser. Next Open Form1.cs and type this Code.
// 2. Important: Declare ParentTabs
protected TitleBarTabs ParentTabs
{
get
{
return (ParentForm as TitleBarTabs);
}
}
type this where the namespace of your code is For example.
namespace YOUR_PROGRAM_NAME_HERE
{
public partial class Form1 : Form
{
// 2. Important: Declare ParentTabs
protected TitleBarTabs ParentTabs
{
get
{
return (ParentForm as TitleBarTabs);
}
}
public object HTMLcodeec { get; }
public Form1()
{
InitializeComponent();
}
now co into the program.cs file in your solution explorer and click on it one you do you need to type the following code
namespace YOUR_PROGRAM_NAME_HERE
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppContainer container = new AppContainer();
// Add the initial Tab
container.Tabs.Add(
// Our First Tab created by default in the Application will have as
content the Form1
new TitleBarTab(container)
{
Content = new Form1
{
Text = "New Tab"
}
}
);
// Set initial tab the first one
container.SelectedTabIndex = 0;
// Create tabs and start application
TitleBarTabsApplicationContext applicationContext = new
TitleBarTabsApplicationContext();
applicationContext.Start(container);
Application.Run(applicationContext);
}
}
}
Now open Form1.cs and go to Form1. Load Event and at the top of it type
ChromiumWebBrowser Browser;
private void Form1_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
//Initialize
CefSharpSettings.LegacyJavascriptBindingEnabled = true; // Enable Register JS Object, -- RegisterAsyncJsObject, RegisterJsObject allow
settings.CachePath = "cache";
settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC4
settings.CefCommandLineArgs.Add("disable-gpu", "1");
settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
BrowserSettings browserSettings = new BrowserSettings
{
FileAccessFromFileUrls = CefState.Enabled,
UniversalAccessFromFileUrls = CefState.Enabled,
WebSecurity = CefState.Enabled,
WebGl = CefState.Enabled,
BackgroundColor = (uint)CefState.Enabled,
};
Browser = new ChromiumWebBrowser(AddressText.Text);
this.pContainer.Controls.Add(Browser);
Browser.DownloadHandler = new DownloadHandler();
Browser.Dock = DockStyle.Fill;
Browser.Load("https://ask.com/");
this.AcceptButton = this.NavigateToURL;
Browser.AddressChanged += Browser_AddressChanged;
Browser.TitleChanged += Browser_TitleChanged;
}
before you don any of this please download cefsharp and easy tabs to your project
if you want to see my Browser project I build Go to https://cleverdamontoutube.wixsite.com/downloaddamonic and you can see what iv done
it is a .exe file you can download "if you need any more help subscrie to my youtube channel because ill be making a video on this topic shorrtly"

How To Get Value/Variable From URL?

So I want to write a BTC converter app, I can get the value of it for £1 at https://blockchain.info/tobtc?currency=GBP&value=1
And changing the GBP to USD in the URL changed it to USD naturally, I want to use this and parse the data into a variable and then have it used as a normal. But I want the user to be able to enter their currency and have the url change and then fetch the amounnt in say one canadian dollar. How can I use the GBP as a variable and then have it change depending on user input.
I'm thinking a dropdown box of most popular currencys but I wouldn't know how to use that at all.
Be kind, I'm a noob and trying to make my first useful application
Here is a simply example how you can get the value for the different currencies:
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp5
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetValueAsync("GBP").Result);
Console.WriteLine(GetValueAsync("USD").Result);
Console.WriteLine(GetValueAsync("RUB").Result);
}
public static async Task<string> GetValueAsync(string curr)
{
using (HttpClient client = new HttpClient())
{
var responseString = await client.GetStringAsync("https://blockchain.info/tobtc?currency="+curr+"&value=1");
return responseString;
}
}
}
}
Here
client.GetStringAsync("https://blockchain.info/tobtc?currency="+curr+"&value=1");
is sending asynchronous http get request by the provided URL and returning response as a string.
The site you want to use is returning just the value as a string that's why this is working.
As the request is asynchronous we must use await so that we get response in string.
If you want to do this in WinForm. Here is example. Let's assume that you have already TextBox for input value, Label for showing result and Button for Getting result. They can be added by just drop and down from Toolbox to your form.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_ClickAsync(object sender, EventArgs e)
{
string curr = textBox1.Text;
if (!string.IsNullOrEmpty(curr))
{
label2.Text = "waiting for response";
var res = await GetValueAsync(curr);
label2.Text = res;
}
}
public async Task<string> GetValueAsync(string curr)
{
var responseString = string.Empty;
using (HttpClient client = new HttpClient())
{
string reqString = "https://blockchain.info/tobtc?currency=" + curr + "&value=1";
responseString = await client.GetStringAsync(reqString);
}
return responseString;
}
}
}
Here is the full solution for Win Forms link
Here are useful links for you:
MSDN HttpClient GetStringAsync
WinForm with Async Methods
MSDN C# String Concatenation
MSDN WinForms Click Event
Here is a recording how to do this also:
Recording

C# tweetinvi code 408

i am trying to learn connecting C# to Twitter by using tweetinvi.
i have no problem while connecting with Twitter Key and Twitter Token
then i debug my code, noticed null value on User.GetAuthenticatedUser()
however, i'm already authorize the twitter apps with my own twitter account.
Why does User.GetAuthenticatedUser() return Null Value ?
i got the following picture while trying to pass the error into Message Box
how do i resolve this ?
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 Tweetinvi;
namespace Twitdesk
{
public partial class Form1 : Form
{
Cl_Tweetinvi twitinvi;
Command cmd = new Command();
public Form1()
{
InitializeComponent();
twitinvi = new Cl_Tweetinvi();
var AuthenticatedUser = User.GetAuthenticatedUser();
if(AuthenticatedUser == null)
{
var latestException = ExceptionHandler.GetLastException();
MessageBox.Show(latestException.ToString());
Application.Exit();
}
else
{
var settings = AuthenticatedUser.GetAccountSettings();
}
var tweets = Timeline.GetHomeTimeline();
this.Text = cmd.title;
MessageBox.Show("done");
}
}
}
The problem comes from the fact that you have not initialized your credentials.
You need to call Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"); before performing any operation.
When you have invoked this line any operation will be using these credentials.
Please take a quick look at the wiki for more information. Or let me know if you still encounter any problem.
Though the problem could be different as the error message seems to indicate that you have a timeout problem. Normally authentication problems return 401 exception.

Testing a web service by returning a string of data in a web application form

I've got a web service but need to know how to test it in a windows application form.
here is the start of the service. Would I put the form code inside a button, or just return it in a label? Not exactly overly clued into c# or .net I've called the web service succesfully thougha nd just need to return the string to make sure encryption is working.
<%# WebService Language="C#" Class="UserEncryptionLink.EncryptUserLink" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Text;
using System.Security.Cryptography;
namespace UserEncryptionLink
{
/// <summary>
/// This Web Service is to encrypt user details and display them in the URL when they click on a link taking them to InfoExchange
/// </summary>
[WebService(Namespace = " Webspace name")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EncryptUserLink : System.Web.Services.WebService
{
[WebMethod]
public void TestCypher()
{
var key = "12345";
var vector = "12345";
var username = "YOURDOMAIN\\YOURUSERNAME";
var url = "sitename.com";
var it = GetSingleSignOnUrl(url, username, key, vector);
}
And my form
Yeah I've got my form referencing the service, it looks like this.
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 FormForEncrypt.nameofURL;
using System.Net;
namespace FormForEncrypt
{
public partial class EncryptForm : Form
{
public EncryptForm()
{
InitializeComponent();
}
// creates an instance of the web service as a member of the class, will put it down below, doesn't seem to work though declared in the using statement
private nameofURL.EncryptUserLink userform = new nameofUrl.EncryptUserLink();
[System.Web.Services.WebMethod]
private void testButton_Click_1(object sender, EventArgs e)
{
//method to send on button click, then recieve the string to show it works, it should come out as http://CLIENTNAME.info-exchange.com/yyyyMMddHHmmssDomainUsername
//create instances of the details
string[] it;
//send string
//recieve string and display, it must display the same as what was sent.
}
}
}
Not sure what you mean if you should put the form code inside a button or return it in a label?
Webservices don't have concepts of forms or label or anything. They are just services... no forms, no controls... just somewhat "raw code" waiting to be served up by invoking it and your hosting protocol (such as IIS or WAS or self hosting app) takes care of spinning it up and running the service.
interms of calling it... well, it depends where you want to call it from your application. Could be on a button click, could be on a timer, could be on a form load... depends on you and your application logic.
your current web method, TestChypher, does not return anything at the moment. you need to, I am guessing, return a bool value to indicate if the string matches or not?
again, depends on you and what you want to return. if you wanted to return a string, change the method signature to return a string - so change "void" to "string" and return back, in that method, a string you want to return back.
example - short snip:
[WebMethod]
public void SayHello()
{
return "Hello";
}

Categories

Resources