Getting around System.UnauthorizedAccessException : Access is denied - c#

I am using Waitin RC2, WatiN-2.0.20.1089, Windows XP OS with IE8 With VS2008 and NUnit-2.5.7.10213. I have added the sites to the trusted list, I have thread sleeps, I have tried "WaitForComplete". yet when the script goes "back" I am still getting an unauthorized access exception.
Here is a chunk of my code, the exceptions are never caught inspite of the fact that most of the code is in try catch blocks.
public string FindAllLinks()
{
/*
* This function is designed to find and use all of the links on a given page.
* After clicking on a link it waits for 400 milliseconds on the page so the page
* has some time to load and then the function "hits the back button" reseting
* to the originating page.
* This function is not meant to be recursive.
*/
string message = "";
bool flag = true;
//Get a list of all links from the browser instance
foreach (Link link in browserInstance.Links)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine(link);
try
{//clicking on the link to make sure it leads somewhere
link.Click(); //If the click fails hopefull we will thrwo out of the try block and not execute the next two commands.
//Console.WriteLine(link);
}
catch (Exception)
{//OOPs we have an error let's log a message.
message = message + "The link titled " + link + " was not found, or did not work.\n";
flag = false;
}
if (flag)
{
System.Threading.Thread.Sleep(1000);
//browserInstance.WaitForComplete;
try { browserInstance.Back(); }
catch (UnauthorizedAccessException)
{
//do nothing
}
}//close if flag
}//close for each
//return the message
return (message);
}//Close function
[STAThread]
[Test]
public void TestTitleHomePage()
{
bool testPassed = false;
if (browserInstance.Title.Contains("<title>"))
{
string message = FindAllLinks();
if (message == "") { testPassed = true; }
}//close if
else { message = "The Title was not the same."; }
Assert.IsTrue(testPassed, message);
}// end TestTitleHomePage

I tried your code and I also get the exception. I think I understand what happens. When you first do Browser.Links, you get all the links of the current page, then you navigate to another page and return to the first page, but for WatiN it is a new page. So your enumeration cannot work because you enumerate though the links of the first page.
What I suggest you could do is to get all the Uri of the links, then try them one by one in a new browser
IEnumerable<Uri> uris = Browser.Links.Select(l => l.Uri);
foreach(Uri uri in Uris)
{
try
{
using(var browser = new IE(uri))
{
// do nothing or detect 404, 403, etc errors
}
// no error
}
catch(exception)
{
// log error
}
}

Related

Why I am getting AADSTS50011 error when using Microsoft OneDrive sample with UWP app

On VS2019, when using this OneDrive sample with UWP from Microsoft, I am getting the following error. An online search shows some relevant links (such as this or this or this) but their context are different (as they are using web apps or Python etc.):
AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '55dbdbc9-xxxxxxxxxxxxx-a24'
I have followed the sample's instructions for Registering and Configuring the app where Redirect URI I have selected is Public client (mobile & desktop), and have set it's value to https://login.microsoftonline.com/common/oauth2/nativeclient
Question: What I may be doing wrong, and how can we resolve the issue?
UPDATE:
Error occurs at line FolderLoaded?.Invoke(this, EventArgs.Empty); of the method shown below. This is line 180 of file OneDriveList.xaml.cs in the sample. And it is not the error OperationCanceledException since error goes to the second catch statement.
private async Task LoadFolderAsync(string id = null)
{
// Cancel any previous operation
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
// Check if session is set
if (AuthenticationService == null) throw new InvalidOperationException($"No {nameof(AuthenticationService)} has been specified");
// Keep a local copy of the token because the source can change while executing this function
var token = _cancellationTokenSource.Token;
// Add an option to the REST API in order to get thumbnails for each file
// https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_list_thumbnails
var options = new[]
{
new QueryOption("$expand", "thumbnails"),
};
// Create the graph request builder for the drive
IDriveRequestBuilder driveRequest = AuthenticationService.GraphClient.Me.Drive;
// If folder id is null, the request refers to the root folder
IDriveItemRequestBuilder driveItemsRequest;
if (id == null)
{
driveItemsRequest = driveRequest.Root;
}
else
{
driveItemsRequest = driveRequest.Items[id];
}
// Raise the loading event
FolderLoading?.Invoke(this, EventArgs.Empty);
try
{
try
{
// Make a API request loading 50 items per time
var page = await driveItemsRequest.Children.Request(options).Top(50).GetAsync(token);
token.ThrowIfCancellationRequested();
// Load each page
await LoadGridItemsAsync(page, token);
token.ThrowIfCancellationRequested();
}
finally
{
// Raise the loaded event
FolderLoaded?.Invoke(this, EventArgs.Empty);
}
}
catch (OperationCanceledException)
{ }
catch (Exception ex)
{
// Raise the error event
LoadingError?.Invoke(this, ex);
}
}

C# - Process with an id of "xxxxxx" is not running

I have a windows form and I make the following call to open chrome up with a URL:
string uri = Uri.EscapeUriString(URL.ToString());
Process process = Process.Start("chrome", uri + " --new-window");
return process.Id;
The problem is that I get the error: "Process with an id of "xxxxxxx" is not running" when I call the following:
procsChrome = Process.GetProcessById(processID);
The processID is the one returned in the previous code snippet. Now, this WORKS when I have NO CHROME WINDOW OPEN.
But if I have another chrome window open, I get this error. I monitored the processes in Task Manager and when no chrome is open, a new process with the the process id returned from the code snippet 1 is created.
When one or more chrome windows are already open, I get a process id from code snippet 1, but the newly opened chrome window is running under some other id. Why is this happening?
Edit 2:
Here is the method I get the error on. The parameter int processID is the process.Id returned above from code snippet 1.
public static string GetCodeFromURL(int processID)
{
Process procsChrome = null;
try
{
if (processID == -1)
{
Console.WriteLine("-1 returned as ID");
return null;
}
procsChrome = Process.GetProcessById(processID); //I GET ERROR HERE
// the chrome process must have a window
if (procsChrome.MainWindowHandle == IntPtr.Zero)
MessageBox.Show("Process failed");
// to find the tabs we first need to locate something reliable - the 'New Tab' button
AutomationElement root = AutomationElement.FromHandle(procsChrome.MainWindowHandle);
var SearchBar = root.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
if (SearchBar != null)
{
bool noCode = false;
while (noCode == false)
{
string fullURL = (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
if (!(fullURL.Contains("code") && fullURL.Contains("state")))
{
if (procsChrome.HasExited)
{
Console.WriteLine("Process failed. User closed browser.");
procsChrome.Close();
noCode = true;
}
}
else
{
string stateToken = HttpUtility.ParseQueryString(fullURL.Substring(new[] { 0, fullURL.IndexOf('?') }.Max())).Get("state");
if (stateToken.Equals("296bc9a0-a2a2-4a57-be1a-d0e2fd9bb601"))
{
noCode = true;
string code = HttpUtility.ParseQueryString(fullURL.Substring(new[] { 0, fullURL.IndexOf('?') }.Max())).Get("code");
procsChrome.CloseMainWindow();
procsChrome.Close();
return code;
}
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("An exception occured on getting the URL. Please try again. The exception is: " + exception.ToString());
return null;
}
return null;
}
Thanks.
Chrome seems to behave in this way by default, creating anothing process and closing the original one, which means you end up with an incorrect Process ID. And when you have multiple Chrome processes with the same website/title you end up having no control over it.
As some suggested using the parameter "--incognito" will solve it, whoever this would also create other unwanted behavioural issues.
I've looked at the Chrome parameters list and tried a few, using the parameter "--no-service-autorun" seems to have solved the issue.
Not sure why chrome is behaving like that. Can you try to have your code launch chrome in incognito mode?
Using the test code below i was able to launch 2 distinct incognito processes each with their own process id. Note: these launched in the same browser window as 2 tabs.
I think using --incognito will get you out of trouble.
public class LaunchChromeProof
{
private readonly ITestOutputHelper _output;
public LaunchChromeProof(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void CanLaunchChromeIcognito_AndFetchProcesses_ByID()
{
var chromePath = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
var chromeProcess = Process.Start(chromePath, "www.google.com --incognito");
Assert.NotEqual(0, chromeProcess.Id);
//launch a second session
var chrome2ndProcess = Process.Start(chromePath, "www.google.com --incognito");
Assert.NotEqual(0, chrome2ndProcess.Id);
_output.WriteLine($"Session 1 ProcessID: {chromeProcess.Id}");
_output.WriteLine($"Session 2 ProcessID: {chrome2ndProcess.Id}");
//check we can fetch the correct process by the process id for each session
var fetchProcess1 = Process.GetProcessById(chromeProcess.Id);
Assert.Equal(chromeProcess.Id, fetchProcess1.Id);
var fetchProcess2 = Process.GetProcessById(chrome2ndProcess.Id);
Assert.Equal(chrome2ndProcess.Id, fetchProcess2.Id);
_output.WriteLine($"Fetched Session 1 Process: {fetchProcess1.Id}");
_output.WriteLine($"Fetched Session 2 Process: {fetchProcess2.Id}");
}

Selenium ChromeDriver will consistently fail to load web resources such as Bootstrap, JQuery, etc

It's all in the title. I will start chrome driver with the code that I have below, and it will only load up the resources such as JQuery, Bootstrap, and others. It will take an exceptionally long time to load the page as well when this happens. I'll get errors saying that the resource failed to load due to them timing out.
I'm pretty ignorant on what I need to do, so any documentation that someone is willing to throw my way which helped them find the solution, or ever something that is similar will be greatly appreciated. Here's what I've tried:
1) disabling the proxy settings using the ChromeOptions object
2) Disabling SSL certificates
3) Disabling AVG
4) Disabling firewall
5) Internet connection is fine in my room
Another thing that I tried doing was looking at the log file with ChromeOptions.SetLogginPreference(string, logLevel), which worked in ChromeDriver75 but it no longer works in ChromeDriver76. The same code for looking at logs doesn't work the same across drivers.
//SETTING UP THE DRIVER WITH SOME OPTIONS
public static IWebDriver GetDriver()
{
IWebDriver iwd;
ChromeOptions co = new ChromeOptions(){Proxy = null};
co.AddAdditionalCapability("ACCEPT_SSL_CERTS", true, true);
co.AddAdditionalCapability("ACCEPT_INSECURE_CERTS", true, true);
co.AddArguments("--ignore-certificate-errors", "--ignore-ssl-errors");
co.SetLoggingPreference("all", logLevel: LogLevel.All);
iwd = new ChromeDriver("path/to/driver", co);
}
//ME TRYING TO LOAD THE SITE 10 TIMES
public bool TryLoad()
{
//bool for if it was completed or not
bool b = false;
for (int i = 0; i < 9; i++)
try
{
Console.WriteLine();
Gen.Write("\r\nLoading New Page==>", false, ConsoleColor.Cyan);
p.iwd_Driver.GoTo(p.sURL);
if (WasEverythingWasLoaded(p))
{
Gen.Write(" (/) Page Done!", true, ConsoleColor.Green);
b = true;
return b;
}
Gen.Write($"{(i == 0 ? "Failed to load resources" : $"Failed to load resources {i + 1} times")}.", false, ConsoleColor.Red);
}
catch (WebDriverException e)
{
Gen.Write($"\r\n\r\nFATAL::Failed to load the page {p.sURL}\r\nException info: {e}\r\n\r\n", true, ConsoleColor.Red, ConsoleColor.White);
}
finally
{
if (!b)
Gen.Write($"\r\nAttempting again==>", true, ConsoleColor.DarkYellow);
}
try
{
Gen.Write("\r\nLoading New Page==>", false, ConsoleColor.Cyan);
p.iwd_Driver.GoTo(p.sURL);
if (WasEverythingWasLoaded(p))
{
Gen.Write(" (/) Page Done!", true, ConsoleColor.Green);
b = true;
return b;
}
}
catch (WebDriverException e)
{
Gen.Write($"Something is very wrong and needs to be acknowledged here... try flushing the DNS, restarting VS, restarting computer," +
$" canceling some services etc. because it isn't just Selenium that is being a problem here...\r\nException Info: {e}");
}
catch (Exception e)
{
Gen.Write($"\r\n\r\nFATAL::Exception when loading {p.sURL}\r\nException info: {e}\r\n\r\n", true, ConsoleColor.Red, ConsoleColor.DarkGray);
}
finally
{
if (!b)
p.iwd_Driver.Terminate();
}
return b;
}
//trying to interogate the log files. I want to check to see if everything was
//successfully loaded. If not, then I'm going to try again. This works with
// chormedriver75 but not with chromedriver76 for some reason...
private static bool WasEverythingWasLoaded(Page p)
{
ILogs v = p.iwd_Driver.Manage().Logs;
IReadOnlyCollection<LogEntry> logs;
try
{
logs = p.iwd_Driver.Manage().Logs.GetLog(LogType.Browser);
}
catch (NullReferenceException)
{
Gen.Write("Looks like I can't take logs with this version...", true, ConsoleColor.Blue, ConsoleColor.White);
return true;
}
//spit out the logs
foreach (LogEntry le in logs)
Gen.Write($"LogEntry: {le.Message}", true, ConsoleColor.Red, ConsoleColor.White);
//if the count of the relevant logs is greater than a certain amount, then fail it
return logs.Where(x =>
x.Level == LogLevel.Severe
&& x.Message.ToLower().Contains("failed to load resource")
&& !x.Message.Contains(#"https://wes.sandbook.ca/favicon.ico - Failed to load resource: the server responded with a status of 404 (Not Found)")
).ToList().Count() < 1;
}
Expecting:
I'm expecting my driver to simply open and go to the page that I ask it to consistently. I only sort of understand what those chrome options are doing, so let me know if it looks out of place.
Found a fix. Super gimicky, but it works.
It definitely has to do with something getting slowed down and it times out. What I did is a took all of the resources that I need, created an HTML doc that contained nothing but
<html>
<head>
<script src="...the_guds..."></script> <!--could be for bootstrap, favicon, or whatever-->
</head>
</html>
for each resource that I needed to include and I systematically load each one after initialising the driver. After that, the resource gets cached, and it makes loading it super fast after that.

Message Box popping on wrong page wp7

I have a page which is fetching data from a webservice using async call.
If i get the response from webservice control goes to catch where a message box is pooped.
The code is given below:
string uri = "http://free.worldweatheronline.com/feed/weather.ashx?key=b7d3b5ed25080109113008&q=Mumbai&num_of_days=5";
UriBuilder fullUri = new UriBuilder("http://free.worldweatheronline.com/feed/weather.ashx");
fullUri.Query = "key=b7d3b5ed25080109113008&q=Mumbai&num_of_days=5";
HttpWebRequest forecastRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
// set up the state object for the async request
ForecastUpdateState forecastState = new ForecastUpdateState();
forecastState.AsyncRequest = forecastRequest;
// start the asynchronous request
forecastRequest.BeginGetResponse(new AsyncCallback(HandleForecastResponse), forecastState);
This part is response
private void HandleForecastResponse(IAsyncResult asyncResult)
{
try
{
// get the state information
ForecastUpdateState forecastState = (ForecastUpdateState)asyncResult.AsyncState;
HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;
// end the async request
forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);
Stream streamResult;
string newCityName = "";
//int newHeight = 0;
// get the stream containing the response from the async call
streamResult = forecastState.AsyncResponse.GetResponseStream();
// load the XML
XElement xmlWeather = XElement.Load(streamResult);
}
catch (Exception ex)
{
MessageBox.Show("Connection Error");
}
}
Problem :
when the page is loaded it starts fetching data from webservice(consider the case when the web service is not responding and control goes to catch part).
In the mean time if we press the back button or navigate the page the message box popps on the new page.
How could i stop that.
Thanks and Regards
Haven't tested it, but it may work:
1/ Store the value of the NavigationService.CurrentSource property somewhere it can be retrieved (the best would be in the asyncState parameter, but a property may work as well
2/ In the HandleForecastResponse, compare the old and new value of the NavigationService.CurrentSource. This way, you should be able to deduce if the active page has changed or not.
ifixed that problem by add
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
});
try this
private void HandleForecastResponse(IAsyncResult asyncResult)
{
try
{
// get the state information
ForecastUpdateState forecastState = (ForecastUpdateState)asyncResult.AsyncState;
HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;
// end the async request
forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);
Stream streamResult;
string newCityName = "";
//int newHeight = 0;
// get the stream containing the response from the async call
streamResult = forecastState.AsyncResponse.GetResponseStream();
// load the XML
XElement xmlWeather = XElement.Load(streamResult);
}
catch (Exception ex)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Connection Error");
});
}
}
Finally solved it.
catch (Exception x)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var currentPage = ((App)Application.Current).RootFrame.Content as PhoneApplicationPage;
if ((currentPage.ToString()).Equals("MumbaiMarathon.Info.News"))
{
MessageBox.Show("Connection Error");
}
});
}
I just checked at the time of popping the message box the name of the Current UI application page. If its same as the page from which message box is initiated than it pops otherwise not.

Manipulate the output receiving from command RUN and act accordingly - C#

I guess you all misunderstood my question and closed it at How to run a Command in C# and retrieve data from it?
I had said in that post also :-
want to run a Command from command promt and want its output and maipulate its output. If required, want to close the process and display error or appropriate message. To stop the process, I have to press "F4' key on command prompt. Till the process is stopeed or killed, it has to be alive only.
I have created a class to handle running the cmd. And I keep getting the output. But on reading the output's each line I want to stop or throw exception if found anything improper in the output.
I am tying to connect to server via cmd. Server keeps on giving output. Suppose the server gave output as :
Trying to start .....
Cananot load file
.....
Exiting
While retrieving the output, I want to check for lines like "Cannot find file", "Connected Successfully, etc and set properties ccordingly (like connected = true, errorMsg = "Cannot find file". Where I am calling the class, I can take care of those proeprties and stop if found connected == true or errorMsg.length > 0. With this inform the user that "Connection is achieved or error msg stating regarding "Cannot load file" and disconnect the server if errorMsg found.
I didn't find anywhere doing any manipulation on the output receving and that's where I find myself stuck. I found a lot on internet. Am stuck and trying to figre out this part from last 3-4 days. Then have posted here.
I need help in that. Please help me. If requiried I will psot code snippets. But please help me. AND don't close this thread as answered ithout understanding my question fully. This is no duplicate.
My code is class :
public int ConnectToServer()
{
int error = 0;
connected = false;
try
{
process = Process.Start(processInfo);
process.BeginOutputReadLine();
process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
//if (errorMsg.Length > 0)
// throw new Exception(errorMsg);
}
catch (Exception e)
{
Console.WriteLine("Error Processing ConnectToServer : " + e.Message);
connected = false;
errorMsg = e.Message;
error = -1;
return error;
}
return error;
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
errorMsg = "";
connected = false;
string d = e.Data;
if (!string.IsNullOrEmpty(d))
{
if (sb != null)
sb.Append(d + "\n");
Console.WriteLine("LINE = " + d);
if (d.IndexOf("Initialization Completed") > 0)
{
connected = true;
Console.WriteLine("********* Connected = " + connected);
}
else if (isInValidLine(d))
{
//throw new Exception(d);
connected = false;
errorMsg = d;
return;
}
}
return;
}
private bool isInValidLine(string line)
{
if (line.IndexOf("Cannot load file") > 0)
{
errorMsg = line;
return true;
}
return false;
}
IS THE ABOVE CLASS CODE CORRECT WITH MY REQUIREMENTS ?
In impementation :
while (!oc.Connected)
{
timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
if (timepassed > timeout)
{
oc.DisconnectServer();
connectedToVpn = false;
throw new Exception("NotConnectedException");
} else if (oc.ErrorMessage.Length > 0)
{
oc.DisconnectServer();
connectedToVpn = false;
throw new Exception(oc.ErrorMessage);
}
Thread.Sleep(100);
}
Here what I am doing is, when I get the output line, I check if it states as Conneced or is invalid. If its invalid, I set the line as the errorMsg. In my while loop I keep chekcing for Connected and errorMessage, but the value of errorMessage stays as "" only. It never gets updated, which tell me that the processing output code is never executed. Nor in debug mode I find the cursor at that line, but the Line = is displayed proeprly in Console. So, don't understand what's going wrong and where.
Hope this helps you more understand.
Thanks
once you have redirected the standard output of the process you have executed you could parse what you receive as it arrives, I believe also line by line, then you can post commands to control your process.
to read output you have redirected the standard output, to send input you should also redirect the standard input of the process.

Categories