I am trying to code landing page which by reading Culture will decide whether request will be redirected to English site or Slovak site.
This is what the code looks like:
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strCountry = ResolveCountry().ToString();
if (strCountry == "SK")
{
Response.Redirect("/sk/");
}
else
{
Response.Redirect("/en/");
}
}
public static CultureInfo ResolveCulture()
{
string[] languages = HttpContext.Current.Request.UserLanguages;
if (languages == null || languages.Length == 0)
return null;
try
{
string language = languages[0].ToLowerInvariant().Trim();
return CultureInfo.CreateSpecificCulture(language);
}
catch (ArgumentException)
{
return null;
}
}
public static RegionInfo ResolveCountry()
{
CultureInfo culture = ResolveCulture();
if (culture != null)
return new RegionInfo(culture.LCID);
return null;
}
}
The problem is that in browser it looks ok, it redirects you to the site: http://www.alexmolcan.sk
But when checking IIS log, Google Webmaster tools or http://www.rexswain.com/httpview.html I always get 500 ASP Error:
Object·reference·not·set·to·an·instance·of·an·object.
System.NullReferenceException:·Object·reference·not·set·to·an·instance·of·an·object.
Response header:
HTTP/1.1·500·Internal·Server·Error
Connection:·close
Content-Length:·4684
When I debug project locally it always compile without any problems. I don't know what I do wrong
Thank you.
EDIT
Exception
Process information:
Process ID: 4068
Process name: w3wp.exe
Account name: IIS APPPOOL\ASP.NET v4.0
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
at sk_alexmolcan._default.Page_Load(Object sender, EventArgs e) in default.aspx.cs:line 15
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I think you're throwing because when ResolveCountry returns null your .ToString() and if(strcountry == "SK") is going to throw.
Can't turn null into a string. try
CultureInfo cul = ResolveCountry();
string strCountry = cul== null ? string.empty : cul.ToString();
if (strCountry == "SK") {}
Related
I don't know why I get this kind of error. It happens sometimes, and I suspicious of my code that still have thread running while I close my Application. So when I open again it happens.
Value cannot be null.
Parameter name: source
StackTree :
at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
at Susenas2015.ViewModels.Kuesioner.VMVsen15_KVal.SettingValidationAndRange(List`1 listTextBox, List`1 listCheckBox, TabControl tabControl) in d:\handita\Office\Project\Susenas 2015\Aplikasi Template Survei\Susenas2015\ViewModels\Kuesioner\VMVsen15_KVal.cs:line 430
at Susenas2015.ViewModels.Kuesioner.VMVsen15_KVal.vSen15_K_Loaded(Object sender, RoutedEventArgs e) in d:\handita\Office\Project\Susenas 2015\Aplikasi Template Survei\Susenas2015\ViewModels\Kuesioner\VMVsen15_KVal.cs:line 846
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
at System.Windows.Interop.HwndTarget.OnResize()
at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wpa`
My code here it is
private void SettingValidationAndRange(List<TextBox> listTextBox, List<CheckBox> listCheckBox, TabControl tabControl)
{
List<string> listNotDeclare = new List<string>();
foreach (var textB in listTextBox)
{
if (textB.Tag != null)
break;
Metadata metadata = ListMetadataKor.Where(
x => "text" + x.Field == textB.Name // this line 430
).FirstOrDefault();
if (metadata == null)
{
if (!string.IsNullOrEmpty(textB.Name))
listNotDeclare.Add(textB.Name);
}
else
{
metadata.TabControl = tabControl;
textB.Tag = metadata;
}
textB.AddEvents();
textB.AutomateFocus();
}
if (listNotDeclare.Count > 0)
{
Clipboard.SetText(string.Join(",", listNotDeclare.ToArray()));
Dialog.Info("Ada beberapa Metadata tidak ditemukan data sudah dicopy ke clipboard");
}
}
When I start my application for my first time, it doesn't get any error. It happens when I open in 2nd or more. And if I open my application it would stuck in that code.
How I can solve this? I'm pretty sure that my Property ListMetadataKor is not null
And ListMetadataKor is instance of List<Metadata> object that I have created. It happens only in rare cases. And I don't know to solve it
UPDATE
This is my code in image
I fill ListMetadataKor with this code
BWHelper.Run((s, e) =>
{
DataTable dataMetaDataKOR = ExcelHelper.GetDataTableFromExcel(
AppConstants.FILE_METADATA, AppConstants.SHEET_METADATA_KOR
);
DataTable dataKonsistensiKOR = ExcelHelper.GetDataTableFromExcel(
AppConstants.FILE_METADATA, AppConstants.SHEET_KONSISTENSI_KOR
);
listKonsistensiKor = Tools.ToolConvert.GetKonsistensi(dataKonsistensiKOR);
listMetadataKor = Tools.ToolConvert.GetMetadata(dataMetaDataKOR);
foreach (Metadata metadata in listMetadataKor)
{
metadata.Range.ProsesRange();
}
}, (s, e) =>
{
try
{
kor = new VSEN15_K() { Title = "Validasi Susenas - KOR" };
kor.DataContext = new VMVsen15_KVal(rtSusenas.MasterRT, kor, this, listKonsistensiKor, listMetadataKor);
kor.PreviewKeyDown += EventsCollection.EnterAsTabPreviewKeyDown;
vmHome.HideLoading();
UpdateMetaDataEntriKOR(RTSusenas.MasterRT);
kor.ShowDialog();
}
catch (Exception Ex)
{
vmHome.HideLoading();
Dialog.Error(Ex);
}
});
And then I throw the variable through constructor of my class
public VMVsen15_KVal(
MasterRT masterRT,
VSEN15_K vSen15_K,
IDaftarSusenas vmDaftarRTSusenas,
List<Konsistensi> listKonsistensiKor,
List<Metadata> listMetadataKor
)
{
ListArtDetail = new ObservableCollection<ARTDetailVal>();
this.ListKonsistensiKor = listKonsistensiKor;
this.ListMetadataKor = listMetadataKor;
My tools konsistensi like this
public static List<Konsistensi> GetKonsistensi(DataTable dataTable)
{
List<Konsistensi> listMetadata = new List<Konsistensi>();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
Konsistensi k = new Konsistensi();
object[] required = new object[] { DBNull.Value, "" };
k.Field = dataTable.Rows[i][FIELD].ToString();
if (string.IsNullOrWhiteSpace(k.Field)) continue;
k.Message = dataTable.Rows[i][MESSAGE].ToString();
var obj = dataTable.Rows[i][ORDER];
k.Order = !required.Contains(dataTable.Rows[i][ORDER]) ? Convert.ToInt32(dataTable.Rows[i][ORDER]) : (int?)null;
k.Page = !required.Contains(dataTable.Rows[i][PAGE]) ? Convert.ToInt32(dataTable.Rows[i][PAGE]) : (int?)null;
k.Perlakuan = dataTable.Rows[i][PERLAKUAN].ToString();
k.RelFields = dataTable.Rows[i][RELFIELDS].ToString();
k.Rule = dataTable.Rows[i][RULE].ToString();
if (dataTable.Rows[i][LEVEL].ToString().ToUpper() == ("ART"))
k.LevelKonsistensi = LevelKonsistensi.ART;
else if (dataTable.Rows[i][LEVEL].ToString().ToUpper() == ("RT"))
k.LevelKonsistensi = LevelKonsistensi.RT;
else if (dataTable.Rows[i][LEVEL].ToString().ToUpper() == ("RTWARNING"))
k.LevelKonsistensi = LevelKonsistensi.RTWarning;
else if (dataTable.Rows[i][LEVEL].ToString().ToUpper().Contains("ARTWARNING"))
k.LevelKonsistensi = LevelKonsistensi.ARTWarning;
else
k.LevelKonsistensi = LevelKonsistensi.Lain;
//k.LevelKonsistensi = dataTable.Rows[i][LEVEL].ToString().Contains("ART") ? LevelKonsistensi.ART : LevelKonsistensi.RT;
if (k.IsEmpty())
continue;
listMetadata.Add(k);
}
return listMetadata;
}
Error message clearly says that source parameter is null. Source is the enumerable you are enumerating. In your case it is ListMetadataKor object. And its definitely null at the time you are filtering it second time. Make sure you never assign null to this list. Just check all references to this list in your code and look for assignments.
Value cannot be null.
Parameter name: source
Above error comes in situation when you are querying the collection which is null.
For demonstration below code will result in such an exception.
Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();
Here is the output of the above code.
Hello World
Run-time exception (line 11): Value cannot be null.
Parameter name: source
Stack Trace:
[System.ArgumentNullException: Value cannot be null.
Parameter name: source] at Program.Main(): line 11
In your case ListMetadataKor is null.
Here is the fiddle if you want to play around.
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.
System.ArgumentNullException: Value cannot be null. Parameter name:
value
This error message is not very helpful!
You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.
As a generic way to solve this, look at the stack trace or call stack:
Test method GetApiModel threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: value
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.
You can change the code to check for null.
my problem was with spelling It was case sensitive! Few of the columns were sorting properly and rest were throwing this error!
Occasionally, a bug will trigger one of those unrecoverable exceptions (e. g. a StackOverflowException) that causes our entire ASP.NET MVC application to crash. When this happens, the Windows event log typically contains some information about the error, although it is minimal. Currently, for example, we have what we believe is a StackOverflowException being thrown inside a reflection invocation. In such cases, the event log contains some basic information about the outer TargetInvocationException and nothing that will let us pinpoint the problem. My question is, is it possible to configure something in .NET/IIS/Windows to log more information when this happens? If we could get, for example, the first N characters of the full exception (including stack trace and inner exceptions), we could easily debug and fix the issue.
You can't control what another class writes to the log, but you can capture exceptions in the global.asax file and do your own logging. I tend to use a combination of database logging and email notifications.
--global.asax
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception exSvr = Server.GetLastError();
if (exSvr == null)
return;
if (exSvr.Message == "The client disconnected.")
{
// I don't want to be notified everytime someone closes
// the browser mid-request.
return;
}
if (exSvr is System.Threading.ThreadAbortException || exSvr.InnerException is System.Threading.ThreadAbortException || exSvr.Message.StartsWith("Thread was being aborted") || (exSvr.InnerException != null && exSvr.InnerException.Message.StartsWith("Thread was being aborted")))
{
// So we don't get notified everytime .NET kills a thread.
// NOTE: This error is how .NET kills a thread, and will happen every time we call Response.Redirect("", true)
return;
}
ErrorHandler.SendServerErrMsg("Application Error", exSvr, HttpContext.Current);
}
--ErrorHandler
public static void SendServerErrMsg(string codeSection, Exception exSvr, HttpContext context, SeverityLevel lvl = SeverityLevel.Warning)
{
if (_config == null || !_config.EnableEmailAlerts)
return;
if (context != null && context.Request != null && context.Request.Url != null && context.Request.Url.IsLoopback && !_config.SendAlertsInDebugMode)
return;
if (context != null && context.IsDebuggingEnabled && !_config.SendAlertsInDebugMode)
return;
// Attempt to get the currently logged in user.
System.Web.Security.MembershipUser curUsr = null;
try
{ curUsr = System.Web.Security.Membership.GetUser(); }
catch { } // If it fails, don't worry about it.
// Set the message's subject line.
string subject = _config.ApplicationName + " Exception - " + HttpUtility.HtmlEncode(codeSection);
// Build the page body in a StringBuilder object.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (context != null && context.Request != null)
sb.AppendLine(string.Format("<h2>{0}</h2>", HttpUtility.HtmlEncode(context.Request.ApplicationPath)));
sb.AppendLine("<p>The following exception has occurred:</p>");
sb.AppendLine("<ul>");
Exception innerEx = exSvr;
while (innerEx != null)
{
sb.AppendLine(string.Format("<li>{0}</li>", HttpUtility.HtmlEncode(innerEx.Message)));
innerEx = innerEx.InnerException;
}
sb.AppendLine("</ul>");
sb.AppendLine("<p/>");
if (exSvr.TargetSite != null)
sb.AppendLine(string.Format("<p>Target Site: {0} {1} (in {2})</p>", exSvr.TargetSite.MemberType, exSvr.TargetSite.Name, exSvr.TargetSite.DeclaringType));
else
sb.AppendLine("<p>Target Site: N/A</p>");
sb.AppendLine("<p/>");
sb.AppendLine("<hr />");
if (context != null && context.Request != null)
{
HttpRequest req = context.Request;
sb.AppendLine("<p>");
sb.AppendLine(string.Format("<div>Request URL: {0}</div>", HttpUtility.HtmlEncode(req.Url.ToString())));
sb.AppendLine(string.Format("<div>Request Path: {0}</div>", HttpUtility.HtmlEncode(req.FilePath)));
sb.AppendLine(string.Format("<div>User: {0}</div>", (curUsr != null) ? HttpUtility.HtmlEncode(curUsr.UserName) : "Unknown"));
sb.AppendLine(string.Format("<div>User Host Address: {0}</div>", HttpUtility.HtmlEncode(req.UserHostAddress)));
// We're going to try a reverse DNS search on the IP address. Failover,
// just uses the UserHostName value from the HttpContext object.
string hostName = null;
try { hostName = System.Net.Dns.GetHostEntry(req.UserHostAddress).HostName; }
catch { hostName = null; }
if (hostName == null) hostName = req.UserHostName;
sb.AppendLine(string.Format("<div>User Host Name: {0}</div>", HttpUtility.HtmlEncode(hostName)));
sb.AppendLine(string.Format("<div>User Agent: {0}</div>", HttpUtility.HtmlEncode(req.UserAgent)));
sb.AppendLine(string.Format("<div>Server Name: {0}</div>", (context.Server != null ? HttpUtility.HtmlEncode(context.Server.MachineName) : "Unknown")));
sb.AppendLine(string.Format("<div>Request Identity: {0}</div>", (req.LogonUserIdentity != null ? HttpUtility.HtmlEncode(req.LogonUserIdentity.Name) : "Unknown")));
sb.AppendLine("</p>");
sb.AppendLine("<hr />");
}
sb.AppendLine("<p>Stack trace follows:</p>");
Exception ex = exSvr;
while (ex != null)
{
sb.AppendLine("<p>");
sb.AppendLine(string.Format("<b>>> {0}:</b> {1} in {2}<br/>", ex.GetType().Name, HttpUtility.HtmlEncode(ex.Message), HttpUtility.HtmlEncode(ex.Source)));
sb.AppendLine(HttpUtility.HtmlEncode(ex.StackTrace));
sb.AppendLine("</p>");
ex = ex.InnerException;
}
if (context!=null && context.Trace.IsEnabled)
{
sb.AppendLine("<hr />");
sb.AppendLine("<p>Web Trace:</p>");
sb.AppendLine(string.Format("<p>{0}</p>", HttpUtility.HtmlEncode(context.Trace.ToString())));
}
EmailHelper.SendEmail(GetAlertContacts(), subject.Trim(), sb.ToString().Trim(), true);
}
The code sample at http://support.microsoft.com/kb/2527105 is exactly what I need to share sessions between two subdomains. Only problem is it doesn't work in a real life situation. It works fine when the ony file being requested is the page itself, but throws an error 'session state is not available in this context' when other files are part of the request, such as if I add stylesheets or javascript files to the page. The code is generating this error in the "if (context.Session != null &&" line below:
void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication context = (HttpApplication)sender;
HttpCookie cookie = context.Response.Cookies["ASP.NET_SessionId"];
if (context.Session != null &&
!string.IsNullOrEmpty(context.Session.SessionID))
{
cookie.Value = context.Session.SessionID;
if (rootDomain != "localhost")
{
cookie.Domain = rootDomain;
}
cookie.Path = "/";
}
}
You can try a Try Catch Block, then you can trap for a null value.
private HttpSessionState GetSession(HttpApplication context)
{
try
{
//On Abadon or Logout this returns "Session state is not available in this context. "
return context.Session;
}
catch (HttpException)
{
return null;
}
}
I am using Visual Studio 2005 and IIS 6.0.. I have this warning in the event log. I am trying to find what it is. I have never went through this exception when i am working.
What can be done and where can be done to not get the exception warning again. Thanks so much in advance!!
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 10/13/2010 3:20:26 PM
Event time (UTC): 10/13/2010 7:20:26 PM
Event ID: fba7eb72412b4383a4c94bfcfd5c81a1
Event sequence: 708
Event occurrence: 6
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/568802591/Root-1-129314697219905000
Trust level: Full
Application Virtual Path: /
Application Path: C:\Inetpub\wwwroot\kjdfd.live\
Machine name: VME1053
Process information:
Process ID: 472
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
Request information:
Request URL: https://www.kjdfd.com:443/UserTownPage.aspx?tid=0
Request path: /UserTownPage.aspx
User host address: 173.188.124.86
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 11
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at UserTownPage.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Page Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SearchType = CommonHelper.SearchInnerType.Distance;
MakeActive(SearchType);
LoadData(true);
}
}
private void MakeActive(CommonHelper.SearchInnerType sType)
{
DealsActive.Attributes.Remove("class");
PopularActive.Attributes.Remove("class");
DistanceActive.Attributes.Remove("class");
AZActive.Attributes.Remove("class");
switch (sType)
{
case CommonHelper.SearchInnerType.A_Z:
AZActive.Attributes.Add("class", "current");
break;
case CommonHelper.SearchInnerType.Distance:
DistanceActive.Attributes.Add("class", "current");
break;
case CommonHelper.SearchInnerType.Popular:
PopularActive.Attributes.Add("class", "current");
break;
case CommonHelper.SearchInnerType.Deals:
DealsActive.Attributes.Add("class", "current");
break;
default:
AZActive.Attributes.Add("class", "current");
break;
}
}
private void LoadData(bool isSetPageIndex)
{
if (Session["keyword"] != null && Session["city"] != null && Session["state"] != null
&& Session["zipcode"] != null && Session["radius"] != null && Session["category"] != null)
{
string keyword = Session["keyword"].ToString();
string city = Session["city"].ToString();
string state = Session["state"].ToString();
string zipCode = Session["zipcode"].ToString();
double radius = Convert.ToDouble(Session["radius"].ToString());
int categoryID = Convert.ToInt32(Session["category"].ToString());
if (isSetPageIndex) PageIndex = 1;
DisplayRecords(keyword, city, state, zipCode, radius, categoryID, 1);
}
}
The problem appears to be a NullReferenceException is being thrown insed the Page_Load method of the UserTownPage type. More than that is not determinable from the information provided.
What you'll need to do is debug into that method and see exactly where the null reference is occuring.
So in the Global.asax is this:
protected void Application_Error(object sender, System.EventArgs
{
Session["CustomError"] = Server.GetLastError();
Server.ClearError();
Response.Redirect("~/ErrorPage.aspx");
}
And in ErrorPage.aspx is this:
private void Page_Load(object sender, System.EventArgs e)
{
Exception currentException = ((Exception)Session["CustomError"]).InnerException;
// Writes the error message
if (currentException != null)
txtErrorMessage.Text = currentException.Message;
// Loops through the inner exceptions.
currentException = (Exception)Session["CustomError"];
while (currentException != null)
{
message.Append(currentException.Message).Append("\r\n").Append(currentException.StackTrace);
message.Append("\n==============================================\n");
currentException = currentException.InnerException;
}
As this is old 1.0 code it barfs when converted to a 3.5 Global.asax file. It tells me that "Session" is not available and also that I can't redirect?? I think one of the issues may be that there is also an error being thrown from Application_Start. But if I comment out all the application start code I still get errors but they never get redirected to the error page.
This link might help: Exceptional Gotchas!.
In addition, use the web.config file to define your default redirect page for errors.