Dropbox API windows application not working - dropbox

I have used the ready made dropbox simple api code and I have included my appkey in the "XXXXXXX" space, and I added the :
Redirect URIs
http://127.0.0.1:52475/ in app consle od drop box:
but it is not working with me, I just need a simle function that I can pass dropbox token and file detination to eighter download or upload, I have used the existing code below or you can get the whole project from https://github.com/dropbox/dropbox-sdk-dotnet/tree/main/dropbox-sdk-dotnet/Examples/SimpleTest
from. If there is other code that can serve the purpose please help
I need a simple nethoed where I can pass parameter like tokens, appkey, file destination, and access the file (Download or upload)
namespace SimpleTest
{
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Dropbox.Api;
using Dropbox.Api.Common;
using Dropbox.Api.Files;
using Dropbox.Api.Team;
partial class Program
{
// Add an ApiKey (from https://www.dropbox.com/developers/apps) here
private const string ApiKey ="xxxxxxxxxxxxxxxxxxx";
// This loopback host is for demo purpose. If this port is not
// available on your machine you need to update this URL with an unused port.
private const string LoopbackHost = "http://127.0.0.1:52475/";
// URL to receive OAuth 2 redirect from Dropbox server.
// You also need to register this redirect URL on https://www.dropbox.com/developers/apps.
private readonly Uri RedirectUri = new Uri(LoopbackHost + "authorize");
// URL to receive access token from JS.
private readonly Uri JSRedirectUri = new Uri(LoopbackHost + "token");
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[STAThread]
static int Main(string[] args)
{
Console.WriteLine("SimpleTest");
var instance = new Program();
try
{
var task = Task.Run((Func<Task<int>>)instance.Run);
task.Wait();
return task.Result;
}
catch(Exception e)
{
Console.WriteLine(e);
throw e;
}
}
private async Task<int> Run()
{
DropboxCertHelper.InitializeCertPinning();
var accessToken = await this.GetAccessToken();
if (string.IsNullOrEmpty(accessToken))
{
return 1;
}
// Specify socket level timeout which decides maximum waiting time when no bytes are
// received by the socket.
var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 })
{
// Specify request level timeout which decides maximum time that can be spent on
// download/upload files.
Timeout = TimeSpan.FromMinutes(20)
};
try
{
var config = new DropboxClientConfig("SimpleTestApp")
{
HttpClient = httpClient
};
var client = new DropboxClient(accessToken, config);
await RunUserTests(client);
// Tests below are for Dropbox Business endpoints. To run these tests, make sure the ApiKey is for
// a Dropbox Business app and you have an admin account to log in.
/*
var client = new DropboxTeamClient(accessToken, userAgent: "SimpleTeamTestApp", httpClient: httpClient);
await RunTeamTests(client);
*/
}
catch (HttpException e)
{
Console.WriteLine("Exception reported from RPC layer");
Console.WriteLine(" Status code: {0}", e.StatusCode);
Console.WriteLine(" Message : {0}", e.Message);
if (e.RequestUri != null)
{
Console.WriteLine(" Request uri: {0}", e.RequestUri);
}
}
return 0;
}
/// <summary>
/// Run tests for user-level operations.
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <returns>An asynchronous task.</returns>
private async Task RunUserTests(DropboxClient client)
{
await GetCurrentAccount(client);
var path = "/DotNetApi/Help";
var folder = await CreateFolder(client, path);
var list = await ListFolder(client, path);
var firstFile = list.Entries.FirstOrDefault(i => i.IsFile);
if (firstFile != null)
{
await Download(client, path, firstFile.AsFile);
}
var pathInTeamSpace = "/Test";
await ListFolderInTeamSpace(client, pathInTeamSpace);
await Upload(client, path, "Test.txt", "This is a text file");
await ChunkUpload(client, path, "Binary");
}
/// <summary>
/// Run tests for team-level operations.
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <returns>An asynchronous task.</returns>
private async Task RunTeamTests(DropboxTeamClient client)
{
var members = await client.Team.MembersListAsync();
var member = members.Members.FirstOrDefault();
if (member != null)
{
// A team client can perform action on a team member's behalf. To do this,
// just pass in team member id in to AsMember function which returns a user client.
// This client will operates on this team member's Dropbox.
var userClient = client.AsMember(member.Profile.TeamMemberId);
await RunUserTests(userClient);
}
}
/// <summary>
/// Handles the redirect from Dropbox server. Because we are using token flow, the local
/// http server cannot directly receive the URL fragment. We need to return a HTML page with
/// inline JS which can send URL fragment to local server as URL parameter.
/// </summary>
/// <param name="http">The http listener.</param>
/// <returns>The <see cref="Task"/></returns>
private async Task HandleOAuth2Redirect(HttpListener http)
{
var context = await http.GetContextAsync();
// We only care about request to RedirectUri endpoint.
while (context.Request.Url.AbsolutePath != RedirectUri.AbsolutePath)
{
context = await http.GetContextAsync();
}
context.Response.ContentType = "text/html";
// Respond with a page which runs JS and sends URL fragment as query string
// to TokenRedirectUri.
using (var file = File.OpenRead("index.html"))
{
file.CopyTo(context.Response.OutputStream);
}
context.Response.OutputStream.Close();
}
/// <summary>
/// Handle the redirect from JS and process raw redirect URI with fragment to
/// complete the authorization flow.
/// </summary>
/// <param name="http">The http listener.</param>
/// <returns>The <see cref="OAuth2Response"/></returns>
private async Task<OAuth2Response> HandleJSRedirect(HttpListener http)
{
var context = await http.GetContextAsync();
// We only care about request to TokenRedirectUri endpoint.
while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
{
context = await http.GetContextAsync();
}
var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]);
var result = DropboxOAuth2Helper.ParseTokenFragment(redirectUri);
return result;
}
/// <summary>
/// Gets the dropbox access token.
/// <para>
/// This fetches the access token from the applications settings, if it is not found there
/// (or if the user chooses to reset the settings) then the UI in <see cref="LoginForm"/> is
/// displayed to authorize the user.
/// </para>
/// </summary>
/// <returns>A valid access token or null.</returns>
private async Task<string> GetAccessToken()
{
Console.Write("Reset settings (Y/N) ");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
Settings.Default.Reset();
}
Console.WriteLine();
var accessToken = Settings.Default.AccessToken;
if (string.IsNullOrEmpty(accessToken))
{
try
{
Console.WriteLine("Waiting for credentials.");
var state = Guid.NewGuid().ToString("N");
var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ApiKey, RedirectUri, state: state);
var http = new HttpListener();
http.Prefixes.Add(LoopbackHost);
http.Start();
System.Diagnostics.Process.Start(authorizeUri.ToString());
// Handle OAuth redirect and send URL fragment to local server using JS.
await HandleOAuth2Redirect(http);
// Handle redirect from JS and process OAuth response.
var result = await HandleJSRedirect(http);
if (result.State != state)
{
// The state in the response doesn't match the state in the request.
return null;
}
Console.WriteLine("and back...");
// Bring console window to the front.
SetForegroundWindow(GetConsoleWindow());
accessToken = result.AccessToken;
var uid = result.Uid;
Console.WriteLine("Uid: {0}", uid);
Settings.Default.AccessToken = accessToken;
Settings.Default.Uid = uid;
Settings.Default.Save();
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return null;
}
}
return accessToken;
}
/// <summary>
/// Gets information about the currently authorized account.
/// <para>
/// This demonstrates calling a simple rpc style api from the Users namespace.
/// </para>
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <returns>An asynchronous task.</returns>
private async Task GetCurrentAccount(DropboxClient client)
{
var full = await client.Users.GetCurrentAccountAsync();
Console.WriteLine("Account id : {0}", full.AccountId);
Console.WriteLine("Country : {0}", full.Country);
Console.WriteLine("Email : {0}", full.Email);
Console.WriteLine("Is paired : {0}", full.IsPaired ? "Yes" : "No");
Console.WriteLine("Locale : {0}", full.Locale);
Console.WriteLine("Name");
Console.WriteLine(" Display : {0}", full.Name.DisplayName);
Console.WriteLine(" Familiar : {0}", full.Name.FamiliarName);
Console.WriteLine(" Given : {0}", full.Name.GivenName);
Console.WriteLine(" Surname : {0}", full.Name.Surname);
Console.WriteLine("Referral link : {0}", full.ReferralLink);
if (full.Team != null)
{
Console.WriteLine("Team");
Console.WriteLine(" Id : {0}", full.Team.Id);
Console.WriteLine(" Name : {0}", full.Team.Name);
}
else
{
Console.WriteLine("Team - None");
}
}
/// <summary>
/// Creates the specified folder.
/// </summary>
/// <remarks>This demonstrates calling an rpc style api in the Files namespace.</remarks>
/// <param name="path">The path of the folder to create.</param>
/// <param name="client">The Dropbox client.</param>
/// <returns>The result from the ListFolderAsync call.</returns>
private async Task<FolderMetadata> CreateFolder(DropboxClient client, string path)
{
Console.WriteLine("--- Creating Folder ---");
var folderArg = new CreateFolderArg(path);
try
{
var folder = await client.Files.CreateFolderV2Async(folderArg);
Console.WriteLine("Folder: " + path + " created!");
return folder.Metadata;
}
catch (ApiException<CreateFolderError> e)
{
if (e.Message.StartsWith("path/conflict/folder"))
{
Console.WriteLine("Folder already exists... Skipping create");
return null;
}
else
{
throw e;
}
}
}
/// <summary>
/// Lists the items within a folder inside team space. See
/// https://www.dropbox.com/developers/reference/namespace-guide for details about
/// user namespace vs team namespace.
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <param name="path">The path to list.</param>
/// <returns>The <see cref="Task"/></returns>
private async Task ListFolderInTeamSpace(DropboxClient client, string path)
{
// Fetch root namespace info from user's account info.
var account = await client.Users.GetCurrentAccountAsync();
if (!account.RootInfo.IsTeam)
{
Console.WriteLine("This user doesn't belong to a team with shared space.");
}
else
{
try
{
// Point path root to namespace id of team space.
client = client.WithPathRoot(new PathRoot.Root(account.RootInfo.RootNamespaceId));
await ListFolder(client, path);
}
catch (PathRootException ex)
{
Console.WriteLine(
"The user's root namespace ID has changed to {0}",
ex.ErrorResponse.AsInvalidRoot.Value);
}
}
}
/// <summary>
/// Lists the items within a folder.
/// </summary>
/// <remarks>This demonstrates calling an rpc style api in the Files namespace.</remarks>
/// <param name="path">The path to list.</param>
/// <param name="client">The Dropbox client.</param>
/// <returns>The result from the ListFolderAsync call.</returns>
private async Task<ListFolderResult> ListFolder(DropboxClient client, string path)
{
Console.WriteLine("--- Files ---");
var list = await client.Files.ListFolderAsync(path);
// show folders then files
foreach (var item in list.Entries.Where(i => i.IsFolder))
{
Console.WriteLine("D {0}/", item.Name);
}
foreach (var item in list.Entries.Where(i => i.IsFile))
{
var file = item.AsFile;
Console.WriteLine("F{0,8} {1}",
file.Size,
item.Name);
}
if (list.HasMore)
{
Console.WriteLine(" ...");
}
return list;
}
/// <summary>
/// Downloads a file.
/// </summary>
/// <remarks>This demonstrates calling a download style api in the Files namespace.</remarks>
/// <param name="client">The Dropbox client.</param>
/// <param name="folder">The folder path in which the file should be found.</param>
/// <param name="file">The file to download within <paramref name="folder"/>.</param>
/// <returns></returns>
private async Task Download(DropboxClient client, string folder, FileMetadata file)
{
Console.WriteLine("Download file...");
using (var response = await client.Files.DownloadAsync(folder + "/" + file.Name))
{
Console.WriteLine("Downloaded {0} Rev {1}", response.Response.Name, response.Response.Rev);
Console.WriteLine("------------------------------");
Console.WriteLine(await response.GetContentAsStringAsync());
Console.WriteLine("------------------------------");
}
}
/// <summary>
/// Uploads given content to a file in Dropbox.
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <param name="folder">The folder to upload the file.</param>
/// <param name="fileName">The name of the file.</param>
/// <param name="fileContent">The file content.</param>
/// <returns></returns>
private async Task Upload(DropboxClient client, string folder, string fileName, string fileContent)
{
Console.WriteLine("Upload file...");
using (var stream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(fileContent)))
{
var response = await client.Files.UploadAsync(folder + "/" + fileName, WriteMode.Overwrite.Instance, body: stream);
Console.WriteLine("Uploaded Id {0} Rev {1}", response.Id, response.Rev);
}
}
/// <summary>
/// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition
/// and also enable capability to track upload progerss.
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <param name="folder">The folder to upload the file.</param>
/// <param name="fileName">The name of the file.</param>
/// <returns></returns>
private async Task ChunkUpload(DropboxClient client, string folder, string fileName)
{
Console.WriteLine("Chunk upload file...");
// Chunk size is 128KB.
const int chunkSize = 128 * 1024;
// Create a random file of 1MB in size.
var fileContent = new byte[1024 * 1024];
new Random().NextBytes(fileContent);
using (var stream = new MemoryStream(fileContent))
{
int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize);
byte[] buffer = new byte[chunkSize];
string sessionId = null;
for (var idx = 0; idx < numChunks; idx++)
{
Console.WriteLine("Start uploading chunk {0}", idx);
var byteRead = stream.Read(buffer, 0, chunkSize);
using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead))
{
if (idx == 0)
{
var result = await client.Files.UploadSessionStartAsync(body: memStream);
sessionId = result.SessionId;
}
else
{
UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx));
if (idx == numChunks - 1)
{
await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName), memStream);
}
else
{
await client.Files.UploadSessionAppendV2Async(cursor, body: memStream);
}
}
}
}
}
}
/// <summary>
/// List all members in the team.
/// </summary>
/// <param name="client">The Dropbox team client.</param>
/// <returns>The result from the MembersListAsync call.</returns>
private async Task<MembersListResult> ListTeamMembers(DropboxTeamClient client)
{
var members = await client.Team.MembersListAsync();
foreach (var member in members.Members)
{
Console.WriteLine("Member id : {0}", member.Profile.TeamMemberId);
Console.WriteLine("Name : {0}", member.Profile.Name);
Console.WriteLine("Email : {0}", member.Profile.Email);
}
return members;
}
}
}

Related

Memory Issues with Worksheets

I am seeing what I perceive to be excessive memory use when attempting to get the names of all of the worksheets in a workbook. As soon as I try and open the worksheets inside of the package (excelPackage.Workbook.Worksheets) my test uses ~ 400 MB of memory and takes around 20 seconds to finish that line of code. I am wondering if this is a normal amount of load for the tool to be using for a 30 MB .xlsx file with 3 worksheets. My larger issue is that the tool seems to be keeping around 1.2 GB of memory even after I am done with this ListWorksheets task. So a) 1.2 GB seems excessive for a 30 MB file and b) the memory should be deallocated when the tool is done with it should it not?
Memory plot
[TestMethod]
public void WorkBook_OpenAndCloseWorkBook_MemoryBehavesCorrectly()
{
var template = Path.Combine(testDocumentsRootDirectory, #"Templates\30MB_File.xlsx");
var outputSmokeTest = Path.Combine(testDocumentsRootDirectory, #"Results\MemTest.xlsx");
for (int x = 20; x > 0; x--)
{
smokeTestWorkbook = new Workbook(key);
if (File.Exists(outputSmokeTest))
File.Delete(outputSmokeTest);
smokeTestWorkbook.Open(template);
var worksheets = smokeTestWorkbook.ListWorksheets();
smokeTestWorkbook.SaveAs(outputSmokeTest);
smokeTestWorkbook.Close();
//GC.Collect();
System.Threading.Thread.Sleep(5000);
}
}
/// <summary>
/// Opens a reference to the workbook
/// </summary>
/// <returns></returns>
public void Open(string workbookPath)
{
var loggerString = "Open";
if (File.Exists(workbookPath))
{
try
{
logger.Track(loggerString);
excelPackage = new ExcelPackage(new FileInfo(workbookPath));
}
catch (Exception ex)
{
logger.TrackException(loggerString, ex);
}
}
}
/// <summary>
/// Obtain an array of worksheet names
/// </summary>
/// <returns></returns>
public string[] ListWorksheets()
{
var returnValue = new List<string>();
var loggerString = "ListWorksheets";
try
{
logger.Track(loggerString);
returnValue.AddRange(excelPackage.Workbook.Worksheets.Select(excelWorksheet => excelWorksheet.Name));
}
catch (Exception ex)
{
logger.TrackException(loggerString, ex);
throw;
}
return returnValue.ToArray();
}
/// <summary>
/// SaveAs document
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void SaveAs(string filename)
{
var loggerString = "SaveAs";
try
{
logger.Track(loggerString);
excelPackage.SaveAs(new FileInfo(filename));
}
catch (Exception ex)
{
logger.TrackException(loggerString, ex);
throw;
}
}
/// <summary>
/// Closes the document
/// </summary>
/// <returns></returns>
public void Close()
{
var loggerString = "Close";
try
{
logger.Track(loggerString);
excelPackage.Dispose();
}
catch (Exception ex)
{
logger.TrackException(loggerString, ex);
throw;
}
}

Selenium Tests Failing when running them all in one go

I have the below code which initiates the browser in each test. However the first Test runs OK correctly starting the browser. The second Test on wards start to fail
public class BrowserFactory
{
private static IWebDriver driver;
public static IWebDriver Driver
{
get
{
if (driver == null)
throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
return driver;
}
set
{
driver = value;
}
}
public static void InitBrowser(string browserName)
{
switch (browserName)
{
case "Firefox":
if (driver == null)
{
driver = new FirefoxDriver();
driver.Manage().Window.Maximize();
}
break;
case "IE":
if (driver == null)
{
driver = new InternetExplorerDriver();
driver.Manage().Window.Maximize();
}
break;
case "Chrome":
if (driver == null)
{
driver = new ChromeDriver();
driver.Manage().Window.Maximize();
}
break;
}
}
And this is how I initiate and quit browser in each test
[TestFixture]
public class AdminUserHasAccessToDashboard
{
[SetUp]
public void GotoHomePage()
{
BrowserFactory.InitBrowser("Chrome");
BrowserFactory.LoadApplication(ConfigurationManager.AppSettings["URL"]);
}
[TearDown]
public void Quit()
{
BrowserFactory.CloseAllDrivers();
}
It looks like you are probably setting driver instance in your first test and other tests are false on if (driver == null), so other instances will never be created. Your code is incomplete so I can't be sure, but it seems to be an issue here.
How are you closing your driver after first test is completed?
Include the method mentioned below in your browser factory and call at the end of each test, or set up before the tests are run then use the single instance for each test and tear down at the end.
public static void Quit(){
if (Driver!= null)
Driver.Quit();
}
I use a static "Driver" class which is referenced in each test class (not each test case)
I include this in each class(they are nunit C# tests)
#region Initialise and clean up
[OneTimeSetUp]
public void Init()
{
Driver.Initialise();
}
[OneTimeTearDown]
public void CleanUp()
{
Driver.Quit();
}
#endregion
Then my driver class is as below, the appstate region wont apply but can be edited to suit your needs.
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using AdaptiveAds_TestFramework.PageFrameworks;
namespace AdaptiveAds_TestFramework.Helpers
{
/// <summary>
/// Contains functionality for browser automation.
/// </summary>
public static class Driver
{
#region Variables
private static IWebDriver _instance;
private static Period _waitPeriod;
#endregion//Variables
#region Properties
/// <summary>
/// Browser automation object.
/// </summary>
public static IWebDriver Instance
{
get { return _instance; }
set { _instance = value; SetWait(WaitPeriod); }
}
/// <summary>
/// Duration automation framework must wait before throwing an error.
/// </summary>
public static Period WaitPeriod
{
get { return _waitPeriod; }
set
{
_waitPeriod = value;
SetWait(_waitPeriod);
}
}
#endregion//Properties
#region Methods
#region set-up and tear-down
/// <summary>
/// Sets up a new automation object.
/// </summary>
public static void Initialise()
{
Quit();
Instance = new FirefoxDriver(new FirefoxBinary(ConfigData.FireFoxPath), new FirefoxProfile());
Instance.Manage().Window.Maximize();
WaitPeriod = ConfigData.DefaultWaitPeriod;
}
/// <summary>
/// Disposes of the automation object.
/// </summary>
public static void Quit()
{
if (Instance != null)
Instance.Quit();
}
#endregion //set-up and tear-down
#region NavigableLocations
/// <summary>
/// Navigate browser to a given location.
/// </summary>
/// <param name="location">Location to navigate to.</param>
/// <param name="logInIfNeeded">Logs in if authentication is required.</param>
/// <param name="errorIfNotReached">Errors if the location was not reached.</param>
public static void GoTo(Location location, bool logInIfNeeded, bool errorIfNotReached)
{
// Navigate browser to the location.
Instance.Navigate().GoToUrl(Helper.RouteUrl(location));
Thread.Sleep(500);// wait for system to navigate
bool needToLogIn = false;
if (logInIfNeeded)
{
try
{
IsAt(Location.Login);
needToLogIn = true;
}
catch
{
// Not at login page so Login not needed.
}
if (needToLogIn)
{
LoginPage.LoginAs(ConfigData.Username).WithPassword(ConfigData.Password).Login();
GoTo(location, false, errorIfNotReached);
}
}
if (errorIfNotReached)
{
IsAt(location);
}
}
/// <summary>
/// Ensures the Driver is at the specified location, throws a WebDriverException if at another location.
/// </summary>
/// <param name="location">Location to check the browser is at.</param>
public static void IsAt(Location location)
{
string expected = Helper.RouteUrl(location);
string actual = Instance.Url;
// Check the browser is at the correct location.
if (actual != expected)
{
// Driver is not at the specified location.
throw new WebDriverException("Incorrect location.",
new InvalidElementStateException(
"The given location did not match the browser." +
" Expected \"" + expected + "\" Actual \"" + actual + "\""));
}
ActionWait(Period.None, CheckForLavarelError);
}
/// <summary>
/// Ensures the Driver is not at the specified location, throws a WebDriverException if at the location.
/// </summary>
/// <param name="location">Location to check the browser is not at.</param>
public static void IsNotAt(Location location)
{
string expected = Helper.RouteUrl(location);
string actual = Instance.Url;
// Check the browser is not at the correct location.
if (actual == expected)
{
// Driver is at the specified location.
throw new WebDriverException("Incorrect location.",
new InvalidElementStateException(
"The given location matched the browser."));
}
}
#endregion//NavigableLocations
#region WaitHandling
/// <summary>
/// Performs an action with a temporary wait period.
/// </summary>
/// <param name="waitPeriod">Period to wait while executing action.</param>
/// <param name="action">Action to execute.</param>
public static void ActionWait(Period waitPeriod, Action action)
{
// Store the current wait period
Period previousPeriod = WaitPeriod;
// Run task with given wait period
SetWait(waitPeriod);
action();
// Revert to the old wait period
SetWait(previousPeriod);
}
/// <summary>
/// Updates the Automation instance wait period.
/// </summary>
/// <param name="waitPeriod">New wait period.</param>
private static void SetWait(Period waitPeriod)
{
int miliseconds;
ConfigData.WaitPeriods.TryGetValue(waitPeriod, out miliseconds);
// Set the drivers instance to use the wait period.
if (Instance != null)
{
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(miliseconds));
}
}
#endregion//WaitHandling
#region AppState
/// <summary>
/// Checks that the website hasn't crashed from the back end.
/// </summary>
public static void CheckForLavarelError()
{
bool error = false;
try
{
Instance.FindElement(By.ClassName("exception_message"));
error = true;
}
catch
{
// all good, could not find error content.
}
if (error)
{
throw new Exception("Lavarel threw an error");
}
}
/// <summary>
/// Clicks on the main menu button to open or close the main menu.
/// </summary>
public static void OpenCloseMenuBar()
{
try
{
IWebElement menuButton = Instance.FindElement(By.Name(ConfigData.MainMenuButtonName));
menuButton.Click();
}
catch (Exception e)
{
throw new NoSuchElementException("Could not find the Menu button element.", e);
}
}
/// <summary>
/// Asserts the logged in state agents the parameter.
/// </summary>
/// <param name="checkLoggedIn">Parameter to check agents logged in state.</param>
public static void LoggedIn(bool checkLoggedIn)
{
OpenCloseMenuBar();
bool signInFound;
bool signOutFound;
bool isLoggedIn = false;
try { Instance.FindElement(By.Name(ConfigData.SignInName)); signInFound = true; }
catch { signInFound = false; }
try { Instance.FindElement(By.Name(ConfigData.SignOutName)); signOutFound = true; }
catch { signOutFound = false; }
if (!signInFound && !signOutFound)
{
throw new ElementNotVisibleException("Unable to assert state due to unavailability of SignIn/Out links.");
}
if (signOutFound) isLoggedIn = true;
if (signInFound) isLoggedIn = false;
if (isLoggedIn != checkLoggedIn)
{
throw new Exception($"Logged in Expected: {checkLoggedIn} Actual: {isLoggedIn}");
}
}
/// <summary>
/// Signs out of the system.
/// </summary>
/// <param name="errorIfAlreadySignedOut">Determines whether to throw an error if already signed out.</param>
public static void SignOut(bool errorIfAlreadySignedOut = true)
{
try
{
LoggedIn(true);
}
catch (Exception)
{
if (errorIfAlreadySignedOut)
{
throw;
}
return;
}
IWebElement signOut = Instance.FindElement(By.Name(ConfigData.SignOutName));
signOut.Click();
Thread.Sleep(500);// wait for system to logout
}
#endregion//AppState
#endregion//Methods
}
}

swagger xml comments per api version

I have created a new asp.net web api 2 project in visual studio 2015 using ASP.NET Web API 2.1 Custom Route Attributes.
I am using Swagger (SwashBuckle 5.0) for API documentation and wanted to have the documentation per version which i managed to get this document but swagger ui showing same xml comments from both versions.
The xml comments on api/view for version 1 and 2 there some different which does not appears on swagger ui.
Version 1
Version 2
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.MultipleApiVersions(
(apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
(vc) =>
{
vc.Version("2", "Swagger API V2");
vc.Version("1", "Swagger API V1");
});
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{
c.EnableDiscoveryUrlSelector();
});
}
private static string GetXmlCommentsPath()
{
return String.Format(#"{0}\bin\ChartOfAccounts.Api.XML", AppDomain.CurrentDomain.BaseDirectory);
}
private static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
{
var attr = apiDesc.ActionDescriptor.GetCustomAttributes<VersionedRoute>().FirstOrDefault();
if (attr == null)
{
return true;
}
int targetVersion;
if (int.TryParse(targetApiVersion, out targetVersion))
{
return attr.AllowedVersion == targetVersion;
};
return true;
}
}
Version 1 Controller
[VersionedRoute("api/view", 1)]
public class ViewController : ApiController
{
private IChartManager _chartManager;
public ViewController(IChartManager chartManager)
{
_chartManager = chartManager;
}
/// <summary>
/// Returns a single view
/// </summary>
/// <param name="Id">Used to identify view. {Only Guid Accepted} </param>
/// <returns></returns>
public async Task<HttpResponseMessage> GetAsync(Guid Id)
{
Chart chart = await _chartManager.GetChartByIdAsync(Id);
return Request.CreateResponse(HttpStatusCode.OK, chart);
}
}
Version 2 API Controller
[VersionedRoute("api/view", 2)]
public class Viewv2Controller : ApiController
{
private IChartManager _chartManager;
public Viewv2Controller(IChartManager chartManager)
{
_chartManager = chartManager;
}
/// <summary>
/// Returns a single view of the chart
/// </summary>
/// <param name="Id">Used to identify view</param>
/// <returns></returns>
public async Task<HttpResponseMessage> GetAsync(string Id)
{
Guid newGuidId;
if (Guid.TryParse(Id, out newGuidId))
{
Chart chart = await _chartManager.GetChartByIdAsync(newGuidId);
return Request.CreateResponse(HttpStatusCode.OK, chart);
}
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid Guid value for Parameter Id.");
}
}

In WCF BehaviorExtension BeforeSendRequest method is not getting called?I m stuck please help me...below is code

Here is code for the which I m trying.I want to modify the request packet of service. Genarally the request header,body and action
[CustomBehavior]
public class Service1 : IService1
{
.....
......
}
public class CustomHeader : MessageHeader
{
.....
.....
....
}
/// <summary>
/// This class is used to inspect the message and headers on the server side,
/// This class is also used to intercept the message on the
/// client side, before/after any request is made to the server.
/// </summary>
public class CustomMessageInspector : IClientMessageInspector, IDispatchMessageInspector
{
#region Message Inspector of the Service
/// <summary>
/// This method is called on the server when a request is received from the client.
/// </summary>
/// <param name="request"></param>
/// <param name="channel"></param>
/// <param name="instanceContext"></param>
/// <returns></returns>
public object AfterReceiveRequest(ref Message request,
IClientChannel channel, InstanceContext instanceContext)
{
// Create a copy of the original message so that we can mess with it.
MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
Message messageCopy = buffer.CreateMessage();
// Read the custom context data from the headers
ServiceHeader customData = CustomHeader.ReadHeader(request);
// Add an extension to the current operation context so
// that our custom context can be easily accessed anywhere.
ServerContext customContext = new ServerContext();
if (customData != null)
{
customContext.KerberosID = customData.KerberosID;
customContext.SiteminderToken = customData.SiteminderToken;
}
OperationContext.Current.IncomingMessageProperties.Add(
"CurrentContext", customContext);
return null;
}
/// <summary>
/// This method is called after processing a method on the server side and just
/// before sending the response to the client.
/// </summary>
/// <param name="reply"></param>
/// <param name="correlationState"></param>
public void BeforeSendReply(ref Message reply, object correlationState)
{
// Do some cleanup
OperationContext.Current.Extensions.Remove(ServerContext.Current);
}
#endregion
#region Message Inspector of the Consumer
/// <summary>
/// This method will be called from the client side just before any method is called.
/// </summary>
/// <param name="request"></param>
/// <param name="channel"></param>
/// <returns></returns>
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// Prepare the request message copy to be modified
MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
ServiceHeader customData = new ServiceHeader();
customData.KerberosID = ClientContext.KerberosID;
customData.SiteminderToken = ClientContext.SiteminderToken;
CustomHeader header = new CustomHeader(customData);
// Add the custom header to the request.
request.Headers.Add(header);
return null;
}
/// <summary>
/// This method will be called after completion of a request to the server.
/// </summary>
/// <param name="reply"></param>
/// <param name="correlationState"></param>
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
#endregion
}
/// <summary>
/// This class will act as a custom context in the client side to hold the context information.
/// </summary>
public class ClientContext
{
public static string EmployeeID;
public static string WindowsLogonID;
public static string KerberosID;
public static string SiteminderToken;
}
/// <summary>
/// This custom behavior class is used to add both client and server inspectors to
/// the corresponding WCF end points.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class CustomBehavior : Attribute, IEndpointBehavior
{
#region IEndpointBehavior Members
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
return;
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint,
System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
CustomMessageInspector inspector = new CustomMessageInspector();
clientRuntime.MessageInspectors.Add(inspector);
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint,
System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
ChannelDispatcher channelDispatcher = endpointDispatcher.ChannelDispatcher;
if (channelDispatcher != null)
{
foreach (EndpointDispatcher ed in channelDispatcher.Endpoints)
{
CustomMessageInspector inspector = new CustomMessageInspector();
ed.DispatchRuntime.MessageInspectors.Add(inspector);
}
}
}
void IEndpointBehavior.Validate(ServiceEndpoint endpoint) { return; }
#endregion
}
public class MyBehaviorExtensionElement : BehaviorExtensionElement
{
public MyBehaviorExtensionElement() { }
public override Type BehaviorType
{
get { return typeof(CustomBehavior); }
}
protected override object CreateBehavior()
{
return new CustomBehavior();
}
}
You need to add the extension to either your code or configuration: (config example below):
<extensions>
<behaviorExtensions>
<add name="yourMessageInspector"
type="MyBehaviorExtensionElement" />
</behaviorExtensions>
</extensions>
The following references should provide the background you need:
https://msdn.microsoft.com/en-us/library/ms730137%28v=vs.110%29.aspx
wcf :custom message inspector does not get wired up

Request Token for twitter wp7

I am building a twitter app for windows phone 7. But the twitter's OAuth is giving me a lot of problems. I am trying to get a Request Token and every single time I get the message: Failed to validate oauth signature and token. Any help would be appreciated.
here is my code:
Parameters base string:
public static string GetParameterString()
{
SystemParameters SysParameters = new SystemParameters();
Parameters Param = new Parameters();
StringBuilder sb = new StringBuilder();
sb.Append(SysParameters.CallbackUrl()).Append("=");
sb.Append(PercentEncoder(Param.callbackURL)).Append("&");
sb.Append(SysParameters.CosumerToken()).Append("=");
sb.Append(PercentEncoder(Param.consumerKey)).Append("&");
sb.Append(SysParameters.Nonce()).Append("=");
sb.Append(PercentEncoder(GetNonce())).Append("&");
sb.Append(SysParameters.SignatureMethod()).Append("=");
sb.Append(PercentEncoder("HMAC-SHA1")).Append("&");
sb.Append(SysParameters.TimeStamp()).Append("=");
sb.Append(PercentEncoder(GetTimeStamp().ToString())).Append("&");
sb.Append(SysParameters.OauthVersion()).Append("=");
sb.Append(PercentEncoder("1.0"));
return sb.ToString();
}
Signature Base string:
public static string GetSignatureBase()
{
SystemParameters SysParameters = new SystemParameters();
Parameters Param = new Parameters();
StringBuilder sb = new StringBuilder();
sb.Append("POST").Append("&");
sb.Append(PercentEncoder(SysParameters.RequestTokenURL())).Append("&");
sb.Append(PercentEncoder(GetParameterString()));
return sb.ToString();
}
Get signature:
public static string GetSignature()
{
SystemParameters SysParameters = new SystemParameters();
Parameters param = new Parameters();
string signature;
signature = Convert.ToBase64String((new HMACSHA1(Encoding.UTF8
.GetBytes(PercentEncoder(param.consumerSecret) + "&")))
.ComputeHash(Encoding.UTF8.GetBytes(GetSignatureBase())));
return PercentEncoder(signature);
}
get token:
private void button2_Click(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.Append(param.RequestURL)
.Append(OauthHelper.RequestType.RequesToken).Append("?");
sb.Append(sysParam.CallbackUrl()).Append("=");
sb.Append(OauthHelper.PercentEncoder(param.callbackURL)).Append("&");
sb.Append(sysParam.CosumerToken()).Append("=");
sb.Append(OauthHelper.PercentEncoder(param.consumerKey)).Append("&");
sb.Append(sysParam.Nonce()).Append("=");
sb.Append(OauthHelper.PercentEncoder(OauthHelper.GetNonce())).Append("&");
sb.Append(sysParam.Signature()).Append("=");
sb.Append(OauthHelper.PercentEncoder(OauthHelper.GetSignature())).Append("&");
sb.Append(sysParam.SignatureMethod()).Append("=");
sb.Append(OauthHelper.PercentEncoder("HMAC-SHA1")).Append("&");
sb.Append(sysParam.TimeStamp()).Append("=");
sb.Append(OauthHelper.PercentEncoder(OauthHelper.GetTimeStamp().ToString()))
.Append("&");
sb.Append(sysParam.OauthVersion()).Append("=");
sb.Append(OauthHelper.PercentEncoder("1.0"));
WebBrowserTask task = new WebBrowserTask();
task.URL = sb.ToString();
task.Show();
}
I have done this implementation referring another code.. my code goes something like this..
#region web query response methods
/// <summary>
/// Event that initiates QueryResponse for RequestToken request
/// </summary>
/// <param name="sender"></param>
/// <param name="e">Webresponse event argument</param>
void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
var parameters = TwitterHelperMethods.GetQueryParameters(e.Response);
OAuthTokenKey = parameters["oauth_token"];
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;
Dispatcher.BeginInvoke(() =>
{
this.browseTwitter.Navigate(new Uri(authorizeUrl));
});
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
/// <summary>
/// Event that initiates QueryResponse for AccessToken request
/// </summary>
/// <param name="sender"></param>
/// <param name="e">Webresponse event argument</param>
void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
var parameters = TwitterHelperMethods.GetQueryParameters(e.Response);
accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
userID = parameters["user_id"];
userScreenName = parameters["screen_name"];
TwitterHelperMethods.SetKeyValue<string>("AccessToken", accessToken);
TwitterHelperMethods.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret);
TwitterHelperMethods.SetKeyValue<string>("ScreenName", userScreenName);
cacheManager.SaveToIsolatedStorage(Utilities.TwitterID, userID);
cacheManager.SaveToIsolatedStorage(Utilities.TwitterAccessToken, accessToken);
cacheManager.SaveToIsolatedStorage(Utilities.TwitterSecretAccessToken, accessTokenSecret);
// NavigationService.Navigate(new Uri("/HomePage.xaml", UriKind.RelativeOrAbsolute));
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
#endregion
#region Browser events methods
/// <summary>
/// Called after the broswer is loaded
/// </summary>
/// <param name="sender">Browser</param>
/// <param name="e">Routed Event arguments</param>
private void browseTwitter_Loaded(object sender, RoutedEventArgs e)
{
accessToken = TwitterHelperMethods.GetKeyValue<string>("AccessToken");
accessTokenSecret = TwitterHelperMethods.GetKeyValue<string>("AccessTokenSecret");
userScreenName = TwitterHelperMethods.GetKeyValue<string>("ScreenName");
if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret))
{
var requestTokenQuery = TwitterOAuthHelper.GetRequestTokenQuery();
requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
}
/// <summary>
/// Called when browser Initiates Navigation to Uri provided
/// </summary>
/// <param name="sender">Browser</param>
/// <param name="e">Navigating event arguments</param>
private void browseTwitter_Navigating(object sender, NavigatingEventArgs e)
{
if (e.Uri.ToString().StartsWith(TwitterSettings.CallbackUri))
{
cacheManager = new CacheManager();
var AuthorizeResult = TwitterHelperMethods.GetQueryParameters(e.Uri.ToString());
var VerifyPin = AuthorizeResult["oauth_verifier"];
//We now have the Verification pin
//Using the request token and verification pin to request for Access tokens
var AccessTokenQuery = TwitterOAuthHelper.GetAccessTokenQuery(
OAuthTokenKey, //The request Token
tokenSecret, //The request Token Secret
VerifyPin // Verification Pin
);
AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
NavigationService.Navigate(new Uri("/OtherPages/HomePage.xaml", UriKind.RelativeOrAbsolute));
}
}
#endregion
My Twitterhelpermethods class goes like this
public class TwitterHelperMethods
{
public static Dictionary<string, string> GetQueryParameters(string response)
{
Dictionary<string, string> nameValueCollection = new Dictionary<string, string>();
string[] items = response.Split('&');
foreach (string item in items)
{
if (item.Contains("="))
{
string[] nameValue = item.Split('=');
if (nameValue[0].Contains("?"))
nameValue[0] = nameValue[0].Replace("?", "");
nameValueCollection.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
}
}
return nameValueCollection;
}
}
and twitteroauthhelper.cs is
public class TwitterOAuthHelper
{
public static OAuthWebQuery GetRequestTokenQuery()
{
var oauth = new OAuthWorkflow
{
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
RequestTokenUrl = TwitterSettings.RequestTokenUri,
Version = TwitterSettings.oAuthVersion,
CallbackUrl = TwitterSettings.CallbackUri
};
var info = oauth.BuildRequestTokenInfo(WebMethod.Get);
var objOAuthWebQuery = new OAuthWebQuery(info);
objOAuthWebQuery.HasElevatedPermissions = true;
objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
objOAuthWebQuery.SilverlightMethodHeader = "GET";
return objOAuthWebQuery;
}
public static OAuthWebQuery GetAccessTokenQuery(string requestToken, string RequestTokenSecret, string oAuthVerificationPin)
{
var oauth = new OAuthWorkflow
{
AccessTokenUrl = TwitterSettings.AccessTokenUri,
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
Token = requestToken,
Verifier = oAuthVerificationPin,
Version = TwitterSettings.oAuthVersion
};
var info = oauth.BuildAccessTokenInfo(WebMethod.Post);
var objOAuthWebQuery = new OAuthWebQuery(info);
objOAuthWebQuery.HasElevatedPermissions = true;
objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
objOAuthWebQuery.SilverlightMethodHeader = "GET";
return objOAuthWebQuery;
}
}
twittersettings.cs :-
public class TwitterSettings
{
public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";
public static string CallbackUri = "http://www.qwinixtech.com";
public static string StatusUpdateUrl { get { return "http://api.twitter.com"; } }
// #error TODO REGISTER YOUR APP WITH TWITTER TO GET YOUR KEYS AND FILL THEM IN HERE
public static string consumerKey = "Your consumer key here";
public static string consumerKeySecret = "Your consumer secret key here";
public static string AccessToken = "Your access token here";
public static string AccessTokenSecret = "Your Secret access token here";
public static string oAuthVersion = "1.0a";
}
This works perfectly well.. all u need to make this work is Hammock library.. I hope u already have it.. else pls download it..