I am seeing some very odd behavior when trying to do a redirect with .NET MVC. I read somewhere to not do the redirect in a subroutine so I changed that part of the code, but I am still having the problem. This only happens in production (particularly with bots), and I can't reproduce it in the dev environment. I added in some logging to try to help but still don't understand what is happening (it was a poor man's solution because I don't have access to put debug symbols on the production server). The call stack doesn't even make sense because it says there is a recursive call that doesn't exist. Thanks in advance for any help!
Error details:
Step Number: 16, LangID: 1033, Language: en, Culture: us - System.NullReferenceException: Object reference not set to an instance of an object.
at [REMOVED]_Web.Controllers.MVC.HomeController.setLanguage(String language, String _culture)
User Name: Anonymous
URL: [REMOVED]'A=0User Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; pt-PT; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)Exception Details:
System.Exception: Step Number: 16, LangID: 1033, Language: en, Culture: us - System.NullReferenceException: Object reference not set to an instance of an object. at [REMOVED]_Web.Controllers.MVC.HomeController.setLanguage(String language, String _culture) at [REMOVED]_Web.Controllers.MVC.HomeController.setLanguage(String language, String _culture) at [REMOVED]_Web.Controllers.MVC.HomeController.Init(String language, String culture) at [REMOVED]_Web.Controllers.MVC.HomeController.ProdCatSearch(String language, String culture) at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) at System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Source code:
Private Sub setLanguage(language As String, _culture As String)
Dim stepNumber As Integer = 0
Try
Dim langCookie As HttpCookie
Dim hasException As Boolean = False
Try
If (String.IsNullOrEmpty(language) OrElse String.IsNullOrEmpty(_culture)) Then
language = "en"
_culture = "us"
End If
stepNumber = 1
Dim languages = clsAppSettings.Instance.GetAppSettingTable(Of String)("Language")
For Each lang In languages
supportedLangs.Add(New LanguageInfo(lang))
Next
supportedLangs.Sort(Function(x, y) x.SortOrder.CompareTo(y.SortOrder))
langCookie = HttpContext.Request.Cookies.Get("langID")
stepNumber = 2
If langCookie IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(langCookie.Value) Then
stepNumber = 3
LangId = langCookie.Value
CultureInfo.CreateSpecificCulture(language + "-" + _culture)
stepNumber = 4
Else
stepNumber = 5
Dim culture As CultureInfo
If language.ToLower = "en" And _culture.ToLower = "us" Then
stepNumber = 6
Dim langIdFromBrowser As String = String.Empty
Dim browserLangs = Request.UserLanguages
For Each browserLang In browserLangs
culture = CultureInfo.CreateSpecificCulture(browserLang.ToLowerInvariant().Trim())
langIdFromBrowser = culture.LCID.ToString
If Not String.IsNullOrWhiteSpace(langIdFromBrowser) Then
If (From items In supportedLangs Where items.Id = CInt(langIdFromBrowser)).Any Then
LangId = langIdFromBrowser
Exit For
End If
End If
Next
stepNumber = 7
If String.IsNullOrEmpty(LangId) Then
LangId = "1033"
End If
Else
stepNumber = 8
culture = CultureInfo.CreateSpecificCulture(language + "-" + _culture)
LangId = culture.LCID.ToString
If Not String.IsNullOrWhiteSpace(LangId) Then
If Not (From items In supportedLangs Where items.Id = CInt(LangId)).Any Then
LangId = "1033"
End If
End If
stepNumber = 9
End If
' Correct for the fact that SharePoint uses Spanish Traditional vs Spanish Modern Sort
If LangId = "1034" Then
LangId = "3082"
End If
stepNumber = 10
End If
Catch ex As CultureNotFoundException
stepNumber = 11
If String.IsNullOrEmpty(LangId) Then
LangId = "1033"
End If
hasException = True
Finally
' Final check to ensure NO empty value ever makes it past this point.
If String.IsNullOrWhiteSpace(LangId) Then
LangId = "1033"
End If
langCookie = New HttpCookie("langID", LangId)
langCookie.Expires = Date.Now().AddYears(1)
Web.HttpContext.Current.Response.Cookies.Add(langCookie)
stepNumber = 12
If hasException OrElse CultureInfo.CreateSpecificCulture(language + "-" + _culture).LCID.ToString() <> LangId Then
stepNumber = 13
Dim newCulture As New CultureInfo(CInt(LangId))
stepNumber = 14
Dim cultureValues As String() = newCulture.Name.Split("-"c)
Dim rUrl As String = Request.Url().OriginalString()
Dim replacement As String = (cultureValues(0) + "-" + cultureValues(1)).ToLower()
rUrl = rUrl.Replace((language + "-" + _culture), replacement)
'Response.Redirect(rUrl, False)
'HttpContext.ApplicationInstance.CompleteRequest()
End If
stepNumber = 15
ViewData("SelectedLang") = LangId
ViewData("SupportedLangs") = supportedLangs
transObj = Translations.GetTranslations(LangId)
ViewData("Translations") = New JavaScriptSerializer().Serialize(transObj)
stepNumber = 16
End Try
Catch ex As Exception
Throw New Exception(String.Format("Step Number: {0}, LangID: {1}, Language: {2}, Culture: {3} - {4}", stepNumber, LangId, language, _culture, ex.ToString()))
End Try
End Sub
To resolve this post so no one potentially wastes time on reading that huge method and to potentially help someone, I'm going to write up the solution.
First of all, #b.pell started off on the right foot by suggesting to fix the logging. I changed stepNumber to be a list of ints then just did String.Join(" ", steps) to print it to the log.
Secondly, this was a poor use of Finally. Finally should really just be used for cleanup. In this case, the code in the Finally block shouldn't be running when an exception is thrown.
Another obstacle is this method is huge, making things difficult to isolate, especially when you are running with no debug symbols and just have a stack trace.
Ultimately, this line of code was creating the null causing the NullReferenceException. So the fix is just a simple null check.
culture = CultureInfo.CreateSpecificCulture(language + "-" + _culture)
This could have been tracked down very quickly if we were able to drop the debug symbols on the production server or done some of the other things I mentioned.
Related
Code:
TwitterService twitter = new TwitterService(oauth_consumer_key, oauth_consumer_secret);
twitter.AuthenticateWith(oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_token_secret);
TwitterSearchResult res = twitter.Search(new SearchOptions { Q = hashtag, Count = 10, MaxId = max_id });
Error:
Arithmetic operation resulted in an overflow
Stacktrace:
at Newtonsoft.Json.Utilities.ConvertUtils.Int32Parse(Char[] chars, Int32 start, Int32 length)
at Newtonsoft.Json.JsonTextReader.ParseNumber()
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonTextReader.ReadInternal()
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
I want to get all the tweets with particular keyword in it. Sometimes the response is proper while sometime i get this error.
I am stuck here. I can't get the solution to print out into the listbox. I just can't find out what I am missing. I need help. Anything you see would be a big help. This is all the code from my program:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For years As Integer = 3 To 20
Lifebox.Items.Add(years.ToString)
Next years
Lifebox.SelectedIndex = 0
End Sub
Private Sub CloseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseButton.Click
Me.Close()
End Sub
Private Sub DisplayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayButton.Click
Dim cost As Double
Dim life As Double
Dim period As Double
Dim numberperiod As Double
Dim salvage As Double
Dim depreciation As Double
Dim isConvertedCost As Boolean
Dim isConvertedLife As Boolean
Dim isConvertedSalvage As Boolean
isConvertedCost = Double.TryParse(Assetbox.Text, cost)
isConvertedLife = Double.TryParse(Lifebox.Text, life)
isConvertedSalvage = Double.TryParse(SalavageBox.Text, salvage)
For numberperiod = 1 To period Step 1
depreciation = Financial.DDB(cost, salvage, life, numberperiod)
DepBox.Text += numberperiod.ToString & " -> " & Convert.ToString(depreciation) _
& ControlChars.NewLine
Next numberperiod
If isConvertedCost AndAlso isConvertedLife AndAlso isConvertedSalvage Then
DepBox.Text = " Year Depreciation "
Else
MessageBox.Show("The cost, life, and salvage values must be numeric.",
"Sonheim Manufacturing Company", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Assetbox.Focus()
End If
End Sub
End Class
This one has kept me stumped for a couple of days now.
It's my first dabble with CLR & UDF ...
I have created a user defined function that takes a multiline String as input, scans it and replaces a certain line in the string with an alternative if found. If it is not found, it simply appends the desired line at the end. (See code)
The problem, it seems, comes when the final String (or Stringbuilder) is converted to an SqlString or SqlChars. The converted, returned String always contains the Nul character as every second character (viewing via console output, they are displayed as spaces).
I'm probably missing something fundamental on UDF and/or CLR.
Please Help!!
Code (I leave in the commented Stringbuilder which was my initial attempt... changed to normal String in a desperate attempt to find the issue):
[Microsoft.SqlServer.Server.SqlFunction]
[return: SqlFacet(MaxSize = -1, IsFixedLength = false)]
//public static SqlString udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
public static SqlChars udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
if (omaIn == null || omaIn.ToString().Length <= 0) return new SqlChars("");
String[] lines = Regex.Split(omaIn.ToString(), "\r\n");
Regex JobTag = new Regex(#"^JOB=.+$");
//StringBuilder buffer = new StringBuilder();
String buffer = String.Empty;
bool matched = false;
foreach (var line in lines) {
if (!JobTag.IsMatch(line))
//buffer.AppendLine(line);
buffer += line + "\r\n";
else {
//buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber + "\r\n");
matched = true;
}
}
if (!matched) //buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber) + "\r\n";
//return new SqlString(buffer.ToString().Replace("\0",String.Empty)) + "blablabla";
// buffer = buffer.Replace("\0", "|");
return new SqlChars(buffer + "\r\nTheEnd");
}
I know in my experiences, the omaIn parameter should be of type SqlString and when you go to collect its value/process it, set a local variable:
string omaString = omaIn != SqlString.Null ? omaIn.Value : string.empty;
Then when you return on any code path, to rewrap the string in C#, you'd need to set
return omaString == string.empty ? new SqlString.Null : new SqlString(omaString);
I have had some fun wrestling matches learning the intricate hand-off between local and outbound types, especially with CLR TVFs.
Hope that can help!
Here is my Action:
Imports PagedList
<EmployeeAuthorize()>
Function SearchFoods(Optional ByVal date1 As String = "", Optional ByVal keyword As String = "", Optional page As Integer = 1) As ActionResult
If String.IsNullOrEmpty(date1) Then
date1 = Date.Now
End If
If String.IsNullOrEmpty(keyword) Then
keyword = Nothing
End If
Dim food = db.Tbl_Foods.Where(Function(x) x.Shrt_Desc.Contains(keyword)).OrderBy(Function(x) x.Food_ID).ToList
For Each item In food
item.Shrt_Desc = item.Shrt_Desc.Replace(",", ", ")
Next
ViewBag.MyDate = date1
ViewBag.MyKeyword = keyword
' set the page size and number
Dim pageSize = 20
Dim pageNumber = page
TempData("CurrentPage") = "My Wellness"
TempData("CurrentWellnessPage") = "Food Log"
Return View("", "_FinalWellnessSubPageLayout", food.ToPagedList(pageNumber, pageSize))
End Function
I believe this is caused, somehow, by the "ToPagedList" since this is the first time I am using it. It works fine on local, but not when I publish to the server. The stack trace looks like this:
[VerificationException: Operation could destabilize the runtime.]
PagedList.PagedList1..ctor(IEnumerable1 superset, Int32 pageNumber,
Int32 pageSize) +0
PagedList.PagedListExtensions.ToPagedList(IEnumerable`1 superset,
Int32 pageNumber, Int32 pageSize) +62
It also says:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
What is the exception? How can I find what exception "occurred during the execution?"
Does anyone know how to fix this error on the server? Thank you.
I also faced the same problem with IIS 7.5 it was working fine with IIS 6.0 so I reinstalled the Pagedlist package and it worked like a charm.
I have an ASP.NET 2010 app hitting a SQL 2005 db. I am attempting to build a stored proc dynamically, depending on the values selected on a search screen. I have done this many times in previosu versions of .net & sql with no problem. However, now, my IF statement always always acts as though no data was passed in. I have debugged the app and am sure that data is being set. I should note that when I run the procedure directly, with or without data, the correct data is returned.
Here is the rather simple stored proc..
ALTER PROCEDURE get_cases_by_search_criteria
#vin as varchar(30) = null
AS
declare #sqlstr varchar(1000)
set #sqlstr = 'SELECT
[Case].CaseID,
[Case].VIN,
[Case].Make,
[Case].Model,
[Case].VehicleYear,
if #vin is not null and #vin <> ''
set #sqlstr = #sqlstr + ' and ' + ('[Case].VIN = ''' + convert(varchar,#vin) + '''')
exec(#sqlstr)
RETURN
And here is the code that calls the stored proc...
Public Function GetCases(ByVal oSearchCriteria As SearchCriteria) As List(Of BE.Case)
Dim lstCase As New List(Of BE.Case)
Dim oCase As BE.Case
Dim oProviderFactory As New ProviderFactory
Dim oConnection As DbConnection
Dim oReader As System.Data.IDataReader
Dim oFactory As DbProviderFactory
Dim oCmd As DbCommand
Dim param1 As System.Data.Common.DbParameter
Try
'call my class to get an instance of the DBProviderFactory class
oFactory = oProviderFactory.GetFactory
'call another class of mine. pass in the DBProviderFactory class which will create a non-provider-specific connection object
oConnection = oProviderFactory.GetProviderConnection(oFactory)
'non-specific create command
oCmd = oConnection.CreateCommand
'non-specific parameter
If oSearchCriteria.VIN.Length = 0 Then
param1 = oFactory.CreateParameter()
param1.ParameterName = "#vin"
param1.DbType = DbType.String
param1.Value = DBNull.Value
oCmd.Parameters.Add(param1)
Else
param1 = oFactory.CreateParameter()
param1.ParameterName = "#vin"
param1.DbType = DbType.String
param1.Value = oSearchCriteria.VIN
oCmd.Parameters.Add(param1)
End If
oCmd.CommandType = CommandType.StoredProcedure
oCmd.CommandText = "get_cases_by_search_criteria"
Using (oConnection)
oConnection.Open()
oReader = oCmd.ExecuteReader()
While oReader.Read
oCase = New BE.Case
'Case
If oReader("CaseID") IsNot System.DBNull.Value Then oCase.CaseID = oReader("CaseID")
If oReader("Make") IsNot System.DBNull.Value Then oCase.Make = oReader("Make")
If oReader("Model") IsNot System.DBNull.Value Then oCase.Model = oReader("Model")
If oReader("VehicleYear") IsNot System.DBNull.Value Then oCase.VehicleYear = oReader("VehicleYear")
If oReader("VIN") IsNot System.DBNull.Value Then oCase.VIN = oReader("VIN")
lstCase.Add(oCase)
End While
oConnection.Close()
End Using
Catch ex As Exception
Throw ex
End Try
Return lstCase
End Function