How to create Redirect URI OAuth2 in C# Console App with Dropbox API? - c#

I've tried to create a Redirect URI, but seems that it is wrong. Actually, it's my first time trying to work with Dropbox API using .Net and I don't know many things.
As I said, I'm using Console Application in Visual Studio 2017. I wrote the code down below.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(Properties.Settings.Default.AccessToken))
{
this.GetAccessToken();
}
else
{
this.GetFiles();
}
}
private void GetAccessToken()
{
var login = new DropboxLogin("wbjcj6pa94berli", appKey, "https://www.dropbox.com/developers/apps/info/wbjcj6pa94berli", false, false);
login.Owner = this;
login.ShowDialog();
if (login.IsSuccessfully)
{
Properties.Settings.Default.AccessToken = login.AccessToken.Value;
Properties.Settings.Default.Save();
}
else
{
MessageBox.Show("Error...");
}
}
private void GetFiles()
{
}
}
I've created this Redirect URI in My App on Dropbox's site for Developers.
Redirect URI on Dropbox's WebPage:
[![enter image description here][1]][1]
I'm getting that MessageBox with "Error..." because, obviously, something is wrong.
Could any of you guys help me with this? Thanks a lot.

Related

Remove RoleInstance from data sent to Azure Application Insights from WPF

I'm trying to add Application Insights to a WPF app using this documentation: https://learn.microsoft.com/en-us/azure/azure-monitor/app/windows-desktop. The basic integration is working. I am now trying to remove the RoleInstance property from the submitted data, as described in the documentation, as this contains the user's computer name (personally identifiable information). Here's my code, based on the documentation above:
Telemetry.cs
public static class Telemetry
{
public static TelemetryClient Client;
public static void Close()
{
if (Client != null)
{
Client.Flush();
System.Threading.Thread.Sleep(1000);
}
}
public static void Initialize()
{
TelemetryConfiguration.Active.InstrumentationKey = "xxxxxxxx";
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Client = new TelemetryClient(TelemetryConfiguration.Active);
Client.Context.Session.Id = Guid.NewGuid().ToString();
Client.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
}
private class MyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
{
telemetry.Context.Cloud.RoleInstance = null;
}
}
}
}
App.xaml.cs
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
Telemetry.Close();
base.OnExit(e);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Telemetry.Initialize();
}
}
When I call Telemetry.Client.TrackEvent(), Telemetry.Initialize() runs, and RoleInstance is null from the start. But, the data sent to AI contains my computer name as the RoleInstance. Not sure how to debug further.
Note: the documentation describes integration into WinForms, and I'm in WPF, so I've guessed at using App.OnStartup instead of Main.
I just found something interesting, if you set a dummy value for RoleInstance, it really takes effect. Maybe the null/empty value will be checked and replaced by the real RoleInstance in the backend. As a workaround, you can just specify a dummy value instead of null/empty value.
Here is my test result with a dummy value:
in azure portal:

C# WinForms crashes with no Exception

I have a C# WinForms application.
I'm using the Unity Container nuget package to inject my service classes. If I get the service class in the Program.cs and make a call to my web api to authenticate a username and password using odata, it works successfully. If I call Application.Run(myForm), where myForm is a Telerik RadForm, and asynchronously run the same call, the application closes with no exceptions thrown.
I am using Application.ThreadException and registering Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) but this does not catch anything.
The line that is causing the application to crash is a call to System.Net.Http.HttpClient.PostAsync(). This call is made from within the service class located in a separate .Net Standard 2.0 Class Library. The main application is a .NET Framework 4.7.2 Windows Application and the UI controls are located in a .NET Framework 4.7.2 Class Library. Again, this call is successful if called outside of the Telerik RadForm.
From within the Telerik RadForm I have tried to execute the call using:
private async void btnLogin_Click(object sender, System.EventArgs e)
var t = new Thread(() => Runner.DoWork(new Credentials(u, p, CLIENT_ID)))
An asynchronous call to a static method without using await
I did get a different result when I called LoginAsync(...).Result on the service class. This caused the application to enter a thread lock state, but did not crash the app.
UPDATE:
There are two RadForms; a DashboardForm and a LoginForm. Program.cs launches the Dashboard which checks for an existing Bearer token. If the token does not exist, the Dashboard displays the Login using .ShowDialog() to prevent using the Dashboard until authenticated. The Login then uses the service class described above.
If instead of launching the Dashboard in Program.cs using Application.Run() I launch the Login, the service call to authenticate is successful.
I then tried launching the Login, from the Dashboard in a new thread, but this resulted in the same problem described above.
Why does the System.Net.Http.HttpClient.PostAsync() crash the application (with no exceptions) if it is called from a Form displayed by another Form?
Program
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
WinInjectionHelper.Register(UnityConfig.RegisterComponents);
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.Run(new DashboardForm());
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("Big error...");
}
Dashboard
public partial class DashboardForm : Telerik.WinControls.UI.RadForm, IDashboard
{
private readonly IProductService _service;
public DashboardForm()
{
this._service = WinInjectionHelper.Generate2<IProductService>();
this.InitializeComponent();
}
private void DashboardForm_Load(object sender, EventArgs e)
{
if (this.NotAuthenticated())
{
var frm = new LoginForm();
if (frm.ShowDialog() != DialogResult.OK)
{
this.Close();
}
}
else
{
//TODO: display error to user
this.Close();
}
}
}
Login
public partial class LoginForm : Telerik.WinControls.UI.RadForm
{
private const string CLIENT_ID = "...";
private readonly IAuthenticationService _service;
public LoginForm()
{
this._service = WinInjectionHelper.Generate2<IAuthenticationService>();
this.InitializeComponent();
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private async void btnLogin_Click(object sender, System.EventArgs e)
{
var u = this.txtUsername.Text.Trim();
var p = this.txtPassword.Text.Trim();
if (string.IsNullOrWhiteSpace(u))
{
MessageBox.Show("Username is required!", "NOTICE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (string.IsNullOrWhiteSpace(p))
{
MessageBox.Show("Password is required!", "NOTICE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
try
{
var jwt = await this._service.LoginAsync(new Credentials(u, p, CLIENT_ID));
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, u),
new Claim(ClaimTypes.Email, u),
new Claim(ClaimTypes2.AccessToken, jwt.AccessToken),
}, "JWT");
((GenericPrincipal)Thread.CurrentPrincipal).AddIdentity(identity);
this.DialogResult = DialogResult.OK;
this.Close();
}
catch
{
MessageBox.Show("An error occurred while processing your request.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You can check the Windows Event Viewer and look under application to find the crash logs. I had the same issue with an application I was working on and this was the only place that had any information on it. It actually helped me resolve the issue which was related to targeting a specific .NET Framework version. Click on the bottom left Window button and type in "event viewer" in there an then click on the icon that shows up.
Easiest way to do it is to run the application and have it crash and then immediately go to event viewer so it will be at the top of the list.
I resolved the issue by calling the Login form first and then displaying the Dashboard before closing the Login and changed program.cs so that closing the Login did not exit the application. This does require calling Application.Exit() when the application does need to close.
Program
internal static class Program
{
[STAThread]
private static void Main()
{
...
new LoginForm().Show();
Application.Run();
}
}

c# Using a Proxy in WebBrowser with login and password

I use Gecko browser (from Mozilla).
using System;
using System.Windows.Forms;
using Skybound.Gecko;
namespace shit_browser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Xpcom.Initialize(#"C:\XPCOM");
}
private void button1_Click(object sender, EventArgs e)
{
geckoWebBrowser1.Navigate("http://google.ru", 0, "", null, "");
}
}
}
You need to use a proxy. Log in via login, password and ip. How can this be realized?
You can use Selenium - Web Browser Automation.
ChromeDriver _driver;
WebDriverWait _wait;
_driver.Navigate().GoToUrl("......./homepage.htm");
_driver.Navigate().GoToUrl("...../index.htm");
_driver.Navigate().GoToUrl("....../login.jsp");
_wait.Until(ExpectedConditions.ElementExists(By.Id("kullaniciAdi")));
var userNameField = _driver.FindElementById("username");
var userPasswordField = _driver.FindElementById("password");
var loginButton =
_driver.FindElementByXPath("//input[#value='Login']");
userNameField.SendKeys("USERNAME");
userPasswordField.SendKeys("PASSWORD");
loginButton.Click();
Hmm sorry, i found like this maybe it'll work, didnt try.
public static void main(String[] args) {
// Create proxy class object
Proxy p=new Proxy();
// Set HTTP Port to 7777
p.setHttpProxy("localhost:7777");
// Create desired Capability object
DesiredCapabilities cap=new DesiredCapabilities();
// Pass proxy object p
cap.setCapability(CapabilityType.PROXY, p);
// Open firefox browser
WebDriver driver=new FirefoxDriver(cap);
// from here onwards code will be same as normal script
}
}

Visio Interop Application events causing undesired behaviour

I'm trying to use Visio Application events. When instantiating a new Application object, and setting any event (i.e. BeforeDocumentClose), this appears to result in unable to restore the Visio window after minimizing it.
I'm using VS/C# 2013, Windows Forms, Visio 2013 (on Windows 7). Though my main code project is huge implementing exchange between various office applications using Add-Ins, the following simple code reproduces the same issue. It is a Windows Forms project (with added Reference to Microsoft.Office.Interop.Visio).
using Visio = Microsoft.Office.Interop.Visio;
Visio.Application app;
bool initialised = false;
private void visioButton_Click(object sender, EventArgs e)
{
init();
app.Documents.Add("c:\\test.vst"); // creates new document from template
}
void init()
{
if (!initialised)
{
// only initialise once
app = new Visio.Application();
app.BeforeDocumentClose += app_BeforeDocumentClose;
initialised = true;
}
}
void app_BeforeDocumentClose(Visio.Document doc)
{
}
Issue #1: This is the main issue. Creating one or more Visio Documents, the Visio Window is not maximized after being minimized. No Exceptions thrown as far as I can see. Windows just does it's audible error 'ping'.
Issue #2: This is a secondary issue. Creating two or more Visio Documents, hovering over the Windows Taskbar, the preview windows show the waiting cursor instead of normal document preview.
Conditions: Issue #1 only occurs when using an event on the Application. Document, Page/Shape events don't cause any problem. All events are captured fine. Issue #2 always occurs, but this is less important for me.
I've been searching for this issue for a while, but can't find anything related to it, so any help is greatly appreciated.
I am not quite sure what is causing Visio to not respond to restore, but you can try the approach with "AddAdvise" instead:
[ComVisible(true)]
public partial class Form1 : Form, Visio.IVisEventProc
{
public Form1()
{
InitializeComponent();
}
Visio.Application app;
bool initialised = false;
private void button1_Click(object sender, EventArgs e)
{
init();
app.Documents.Add("C:\\test.vst"); // creates new document from template
}
void init()
{
if (!initialised)
{
// only initialise once
app = new Visio.Application();
// app.BeforeDocumentClose += app_BeforeDocumentClose;
app.EventList.AddAdvise(DocCloseEventCode, this, null, null);
initialised = true;
Application.DoEvents();
}
}
const short DocCloseEventCode = unchecked((short)Visio.VisEventCodes.visEvtDoc + (short)Visio.VisEventCodes.visEvtDel);
object Visio.IVisEventProc.VisEventProc(short eventCode, object source, int eventID, int eventSeqNum, object subject,object moreInfo)
{
if (eventCode == DocCloseEventCode)
app_BeforeDocumentClose(subject as Visio.Document);
return null;
}
void app_BeforeDocumentClose(Visio.Document doc)
{
}
}
To provide the completed solution for multiple events using Nikolay's advice, here is the completed code including both events and (de)initialisation of Visio Application, and without using templates. (Note that the Message boxes may turn up in the background, behind the Visio window.)
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Visio = Microsoft.Office.Interop.Visio;
namespace VisioInteropTest
{
[ComVisible(true)]
public partial class TestForm : Form, Visio.IVisEventProc
{
Visio.Application app;
bool initialised = false;
// all AddAdvise events:
// https://msdn.microsoft.com/en-us/library/office/ff768620.aspx
const short appCloseEventCode = (short)(Visio.VisEventCodes.visEvtApp | Visio.VisEventCodes.visEvtBeforeQuit);
const short docCloseEventCode = (short)(Visio.VisEventCodes.visEvtDoc | Visio.VisEventCodes.visEvtDel);
public TestForm()
{
InitializeComponent();
}
private void visioButton_Click(object sender, EventArgs e)
{
if (init())
{
app.Documents.Add("");
}
}
bool init()
{
if (!initialised)
{
app = new Visio.Application();
app.EventList.AddAdvise(appCloseEventCode, this, null, null);
app.EventList.AddAdvise(docCloseEventCode, this, null, null);
initialised = true;
}
return initialised;
}
object Visio.IVisEventProc.VisEventProc(short eventCode, object source, int eventID, int eventSeqNum, object subject, object moreInfo)
{
switch (eventCode)
{
case appCloseEventCode: app_BeforeAppClose((Visio.Application)subject); break;
case docCloseEventCode: app_BeforeDocumentClose((Visio.Document)subject); break;
}
return null;
}
void app_BeforeAppClose(Visio.Application app)
{
initialised = false;
MessageBox.Show("App closed");
}
void app_BeforeDocumentClose(Visio.Document doc)
{
MessageBox.Show("Doc closed");
}
}
}

Console C# check for internet availability and wait until it is not available

I have been searching for the code which will help me if the internet connection breaks in between.
I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.
I got good ans here
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
Console.WriteLine("Complete.");
writer.Close();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
{
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
}
else
{
ConnectToPUServer();
}
}
This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?
you can use the below mentioned code for it you have to use
using System.Net.NetworkInformation;
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}

Categories