How to define if default browser opens the needed page? - c#

I have my program written in C#. It has label link. I need to define programmatically, when I click this link (programmatically too), if default browser opens the needed page.
C#

Process.Start("http://example.com"); // <-- put your url there.
Also see this short article on how to use that to greatest effect:
http://code.logos.com/blog/2008/01/using_processstart_to_link_to.html
In summary:
void OpenBrowser(string url)
{
try
{
Mouse.OverrideCursor = Cursors.AppStarting;
Process.Start(url);
}
catch (Exception)
{ //swallow: exception is sometimes thrown even though
} // the call completed without error
finally
{
Mouse.OverrideCursor = null;
}
}

Related

c# Clipboard returns null, but can't be empty

I am trying to get a link which was generated on click and pasted in my clipboard. I tried everything I could find. But I always recieve "null", even though when I paste the link manually in a notepad and what not, I get it.
I tried this code with every defined Dataformat, but everything returned null.
string clipboardText = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
From MSDN: To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.
Example:
using System.Windows.Forms; // Need this for console app
namespace ClipboardTest
{
class Program
{
// Without this attribute, will get null
[STAThreadAttribute]
static void Main(string[] args)
{
try
{
var clipboardText = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
Console.WriteLine(clipboardText);
}
catch (NullReferenceException ex1)
{
// Handle error
}
catch (System.Threading.ThreadStateException ex2)
{
// Will throw this when:
// "The current thread is not in single-threaded apartment (STA) mode and the Application.MessageLoop property value is true."
// Handle error
}
catch (System.Runtime.InteropServices.ExternalException ex3)
{
// Will throw this if clipboard in use
// Handle error
}
}
}
}

How to refresh page when element isn't displayed

I am trying to refresh the page when an element I am trying to find isnt displayed I have written this code but instead of just skipping the if statement the test just fails
while (true)
{
if (Driver.Instance.FindElement(By.LinkText("Leather Utility Vest")).Displayed)
{
var clickButton = Driver.Instance.FindElement(By.LinkText("Leather Utility Vest"));
clickButton.Click();
break;
}
Driver.Instance.Navigate().Refresh();
}
I just used this code instead
while (true)
{
try
{
var clickButton = Driver.Instance.FindElement(By.LinkText("Leather Utility Vest"));
clickButton.Click();
break;
}
catch(Exception)
{
Driver.Instance.Navigate().Refresh();
}
}
This catches the error that the element wasn't found which was why the test was failing and runs the catch block which refreshes the webpage

ThreadAbortException in server transfer in asp.net

I am getting error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack. while executing line
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
so as pointed out by this answer https://stackoverflow.com/a/1252119/1169180 & https://stackoverflow.com/a/11130517/1169180
i changed my code to
protected void Page_Load(object sender, EventArgs e)
{
try
{
UserContext conObj = new UserContext();
HttpContext CurrContext = HttpContext.Current;
if (!IsPostBack)
{
// Code
}
else
{
string userContext = hdnContextObj.Value;
conObj = JsonConvert.DeserializeObject<UserContext>(userContext);
CurrContext.Items.Add("Context", conObj);
try
{
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
}
catch (ThreadAbortException xObj)
{
}
finally
{
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
}
}
}
catch (Exception xObj)
{
Response.Write("Exception : " + xObj.Message);
}
}
still i am getting same exception in out catch block
Also as pointed out here http://support.microsoft.com/kb/312629/EN-US/ i used Server.Execute but it didnt redirect to Payment.aspx page instead it just refreshes.
The exception is raised because the thread running the operation is forced to terminate in multiple locations due to the transfer. As such, it is safe to ignore this exception as your linked answers suggest.
You can ignore the exception by catching the exception and not throwing it.
try
{
Server.Transfer("Payment.aspx?vpc_ChannelId=2", true);
}
catch(ThreadAbortException)
{
// Exception ignored: Thread Abort = discontinue processing on the current page
}
Alternatively, as the MSDN article suggest, you can use Server.Execute instead.
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.
// Clarification on Server.Execute
The MSDN doc clarifies the usage of Server.Execute. It is important to remember this is not a redirect, it acts like a function call. So any code after the call will also be executed. If you do not want the code to execute you can use a return, or Response.End.
In the OP's example, his code might look something like this when using Server.Execute
protected void Page_Load(object sender, EventArgs e)
{
try
{
UserContext conObj = new UserContext();
HttpContext CurrContext = HttpContext.Current;
if (!IsPostBack)
{
// Code
}
else
{
string userContext = hdnContextObj.Value;
conObj = JsonConvert.DeserializeObject<UserContext>(userContext);
CurrContext.Items.Add("Context", conObj);
Server.Execute("Payment.aspx?vpc_ChannelId=2", true);
Response.End(); // or return;
}
}
catch (Exception xObj)
{
Response.Write("Exception : " + xObj.Message);
}
}
Server.Transfer("Payment.aspx?vpc_ChannelId=2", false);
This will work for you. It stops the rest of the remaining code after the transfer code, so that it will not execute that code.
ThreadAbortException exception caused because Response.End called both in Server.Redirect and Server.Transfer internally.Try something like this
Response.Write("<script language=\"javascript\" type=\"text/javascript\">window.location.href = 'Your.aspx'; </script>");

jgrowl message is displayed unwantedly

try{
myConnection.Open();
SqlCommand myCommd = new SqlCommand(StrMemberId, myConnection);
myCommd.Parameters.AddWithValue("#MemberId", TxtEnterMemberId.Text);
int value=(int)myCommd.ExecuteScalar();
if (value!= 0 )
{
Response.Redirect("GeneralExamination.aspx? MemberId=" + this.TxtEnterMemberId);
}
else
{
string js = "$.jGrowl(' Invalid Member Id Try Again ');";
Page.ClientScript.RegisterStartupScript(typeof(string), "jgrowlwarn", js, true);
TxtEnterMemberId.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally {
myConnection.Close();
}
}
What I am trying to do here is search a Member if does not exist or invalid input jgrowl will show a message(works fine).
i.) Now the problem is when i give the correct memberId a message is generated saying "thread was being aborted." but it does gets redirected to the destined page.What isthe exception about?
ii.) When i go to the next page and click on the back button.A msg box says"To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier." if i click resend the growl is displayed again. How to deal with that?
Please help to overcome the problems..
I) I think that the exception is for making a Response.Redirect inside a try/catch block, to avoid the exception you could add a false parameter to Redirect.
more info: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Cannot cancel deletion in List Item event receiver ItemDeleting method in CMSPUBLISHINGSITE#2

Using the SharePoint 2010 RC I am having issues canceling the deletion of a list item using event receivers. My code is firing, setting the cancel property of the SPItemEventProperties, setting an error message, and throwing an error back to the calling thread. This approach works fine in the adding/updating methods, however, when used in the deleting method I can watch the code fire in a debugger, but the item is still moved to the site's recycling bin.
Further, I am seeing this behavior in a site created from the "CMSPUBLISHINGSITE#2" template from stsadm, but not from a site created from the "Team Site" template via Central Administration.
The misbehaving code follows:
public override void ItemDeleting(SPItemEventProperties properties)
{
if (!(properties.UserLoginName == "SHAREPOINT\\system"))
{
try
{
throw new CreatorIdAliasingException("Please contact support if you feel a release web site has been inappropriately assigned to your organization.");
}
catch (CreatorIdAliasingException ex)
{
properties.Cancel = true;
properties.ErrorMessage = ex.ToString();
properties.InvalidateListItem();
throw;
}
}
}
For reference, identical code is contained in the ItemAdding method and works as expected.
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
if (!(properties.UserLoginName == "SHAREPOINT\\system"))
{
try
{
throw new InvalidCreatorIdException("Please contact support to add a known URL to your list of release web sites.");
}
catch (InvalidCreatorIdException ex)
{
properties.Cancel = true;
properties.ErrorMessage = ex.ToString();
properties.InvalidateListItem();
throw;
}
}
}
I would recommend you to not be using Exceptions as part of your business logic. Exceptions are expensive and should only be used in exceptional cases which are not handled by normal logic.
Instead, use something like this:
public override void ItemDeleting(SPItemEventProperties properties)
{
if (properties.UserLoginName.ToLower().CompareTo("sharepoint\\system") != 0)
{
properties.Cancel = true;
properties.ErrorMessage = "Some error has occured....";
}
}
And, by the way, you are throwing an additional exception within the event handler which probably is the reason that you see this behavior you are experiencing.

Categories