Code below is placed in page_Load. How I should handle this to bypass UrlReferrer when you enter page directly first time and there is no referrer?
What I am missing here?
if (HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Just check UrlReferrerfor null:
if (HttpContext.Current.Request.UrlReferrer != null
&& HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Who says the client passed by the referrer in the HTTP request?
Check if UrlReferrer is null first
if (HttpContext.Current.Request.UrlReferrer != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Why not this way much cleaner than checking nulls
private void Page_Load()
{
if (!IsPostBack)
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
}
}
I believe you need to check if HttpContext.Current.Request.UrlReferrer != null.
If UrlReferrer is null, then the test to AbsolutUri will fail.
Try initially testing UrlReferrer for null, this will probably correct the issue.
Use your debugger. If you're running this out of visual studio, than you might be brought to a debugger window when the exception is thrown. There are multiple tabs at the bottom of the debugger including "Locals" and "Watch" you can use those to see what variables are being stored.
If the above code is indeed what's causing the problem than
HttpContext.Current.Request.UrlReferrer.AbsoluteUri
or
HttpContext.Current.Request.UrlReferrer
or
HttpContext.Current.Request
or
HttpContext.Current
or
HttpContext
is set to null
Related
I have this code snippet here:
public void ReDrawParallelLines(string lineName, string viewType)
{
var referenceLineOne = GetLineParams(viewType + ReferenceEnum.One.ToString() + linename);
var referenceLineTwo = GetLineParams(viewType + ReferenceEnum.Two.ToString() + linename);
if (lineName == referenceLineOne.lineParams.lineName)
{
//Do certain action with referencelineone
}
else if (lineName == referenceLineTwo.lineParams.lineName)
{
//Do same action but with referencelinetwo
}
}
I noticed that if referenceLineOne is null but I have referenceLineTwo, the else statement never gets executed. I'm not sure why? Doesn't it work such that if the bool fails the if then continue to the else and it should pass for the else. It just skips the inside if statement and the else condition entirely because the referenceLineOne is null. Why and how can I correct this check?
Basically, I am passing a line name and I want to check to see if it's equal to one of two lines I get from the GetLineParams function.
Since referenceLineOne is null, you will get an exception, which is why it bypasses the else if and jumps somewhere else.
You should do null checking like this
if (referenceLineOne != null && lineName == referenceLineOne.lineParams.lineName)
{
//Do certain action with referencelineone
}
or this if you use c#6
if (lineName == referenceLineOne?.lineParams.lineName)
{
//Do certain action with referencelineone
}
In the below code i got an error "Object reference not set to an instance of an object" in the line of the 'if' condition. Can any one help me with what is wrong with my code.
public string MemberLogOut()
{
string ret = string.Empty;
try
{
if (HttpContext.Current.Session.Count > 0)
HttpContext.Current.Session.Clear();
ret="1";
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
ret="2";
}
return ret;
}
As long as you have System.Web referenced in your using statements, then you should be able to use this:
if (Session != null) {Session.Clear();}
Or
if (Session != null) {Session.Abandon();}
Im not sure why you would you return a string which holds an integer though. A boolean value would make more sense, but you really shouldn't need anything in this context.
Also, your exception handler is attempting to catch a sqlexception, which could also be a source of an object reference error, as you don't appear to have any SQL objects in this function.
I'd probably do this following:
protected bool MemberLogOut()
{
try {
if (Session != null) {Session.Abandon();}
//do any logging and additional cleanup here
return true;
} catch {
return false;
}
}
Edit: if you are in fact calling from outside of your web project, you can just pass the current httpcontext to the following method:
protected bool MemberLogOut(HttpContext context)
{
try {
if (context != null && context.Session != null) {
context.Session.Abandon();
}
//do any logging and additional cleanup here
return true;
} catch (Exception ex) {
//log here if necessary
return false;
}
}
Can any one help me with what is wrong with my code
I guess that you are running this code outside an ASP.NET application. HttpContext.Current exists only inside the context of a web application. If you ever attempt to run this code outside (for example in a console, desktop, unit test, ...) it's never gonna work.
So if this is some sort of code that is in a class library intended to be reused across different applications you will have to remove the dependency on the HttpContext from it.
Side remark: your if condition seems kinda useless as you are doing exactly the same thing in the else as well as in the if -> clearing the session.
try that code
public string MemberLogOut()
{
string ret = string.Empty;
try
{
if (HttpContext.Current.Session!=null)
{HttpContext.Current.Session.Clear();}
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
return "1";
}
I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.
You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}
Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.
I am having a nullreferenceexception error in my code in this line:
public bool BoundingVolumeIsInView(BoundingSphere sphere)
{
**return (Frustum.Contains(sphere) != ContainmentType.Disjoint);**
}
Please tell me what i am doing wrong?
Thanks
Frustum is probably null. Use a debugger and check it. You could do something like this to prevent null pointer exceptions
if(Frustum != null)
return (Frustum.Contains(sphere) != ContainmentType.Disjoint);
return false;
I am currently refactoring an application which uses exceptions for logic flow. The code is difficult to read and maintain and makes a S.O.L.I.D fanboy like myself cry when reading it (not to mention the longest catch block I've ever seen in my career).
My question is what pattern(s) could you use to make it easier to maintain or how would you go about refactoring?
public void CallExternalServices(ICriteria criteria)
{
try
{
someResult = ExternalService1.SomeMethod(criteria);
}
catch (Service1Exception service1Exception)
{
if (criteria.SomeValue == "1")
{
if (service1Exception.InnerException != null
&& service1Exception.InnerException.InnerException != null
&& service1Exception.InnerException.InnerException is TargetSystemException)
{
TargetSystemException targetSystemException = (TargetSystemException)service1Exception.InnerException.InnerException;
if (targetSystemException.ErrorStatus.IsServiceDownForMaintenance())
{
// Call internal method to perform some action
SendNotification("Service down for maintenance.")
}
}
}
else if (criteria.SomeValue == "2")
{
if (service1Exception.InnerException != null
&& service1Exception.InnerException.InnerException != null
&& service1Exception.InnerException.InnerException is TargetSystemException)
{
TargetSystemException tx = (TargetSystemException)service1Exception.InnerException.InnerException;
if (targetSystemException.ErrorStatus.IsBusy())
{
// Call to some internal method to perform an action
SendDifferentNotification()
criteria.SetSomeFlagToBe = true;
try
{
someResult = ExternalService2.SomeOtherMethod(criteria);
}
catch (Service2Exception service2Exception)
{
if (service2Exception.InnerException != null
&& service2Exception.InnerException.InnerException != null
&& service2Exception.InnerException.InnerException is TargetSystemException)
{
TargetSystemException tx = (TargetSystemException)service1Exception.InnerException.InnerException;
if (targetSystemException.ErrorStatus.HasNumberOfDailyTransactionsBeenExceeded())
{
// Call internal method to perform some action
SendNotification("Number of daily transactions exceeded.")
}
}
else if (service2Exception.InnerException != null
&& service2Exception.InnerException.InnerException != null
&& service2Exception.InnerException.InnerException is FaultException)
{
FaultException faultException = service2Exception.InnerException.InnerException as FaultException;
if (faultException.Detail != null
&& faultException.Detail.FaultMessage.Equals("SomeValueToCheckAgainst", StringComparison.OrdinalIgnoreCase))
{
return someResult;
}
else
{
throw service2Exception;
}
}
else
{
throw service2Exception;
}
}
if (someResult != null)
{
// perform another action
SomeActionInvoker.ExecuteAcitonAgainst(someResult);
}
}
}
else if (service1Exception.InnerException != null
&& service1Exception.InnerException.InnerException != null
&& service1Exception.InnerException.InnerException is FaultException)
{
FaultException faultException = service1Exception.InnerException.InnerException as FaultException;
if (faultException.Detail != null
&& faultException.Detail.FaultMessage.Equals("SomeOtherValueToCheckAgainst", StringComparison.OrdinalIgnoreCase))
{
return someResult;
}
else
{
throw service1Exception;
}
}
else
{
throw service1Exception;
}
}
}
}
All in all I think you would be helped by breaking up some stuff into some helper methods. For example, you could extract your checks that look like this
if (<exception-instance>.InnerException != null &&
<exception-instance>.InnerException.InnerException != null &&
<exception-instance>.InnerException.InnerException is <exception-type>)
Into a boolean method; you call code like this at least 3 times by my cursory glance.
Also, I would recommend extracting that second top-level case into an error-handling method; and perhaps its nested if statements.
Check out Working Effectively with Legacy Code by Michael Feathers, particularly Chapter 22 (I Need to Change a Monster Method and I Can't Write Tests for It). There are a lot of great techniques in there for situations like yours. Personally, in cases like this I usually end up extracting methods from sections of the longer methods, and getting rid of local variables that are used throughout the method; these are almost always trouble.
Start by refactoring the method into multiple methods. You've got waaaaaay too many levels of indentation going on.
After that, consider if some of the new methods could be extracted into other objects, and use an IoC-style approach rather than a procedural one.
That's kind of a high level answer, but I'm tired and don't have the energy to actually rework the code myself :)