How to resolve Value cannot be null. Parameter name: source in linq? - c#

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!

Related

Nullable enabled, but 'Value cannot be null' [duplicate]

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!

SQLite transaction save Point Issue

i've a strange error in SQLite using a transaction, that i cannot figured out....
below there is my code:
_connection.RunInTransaction(() =>
{
_connection.UpdateAll(objProposte);
foreach (Proposte objProposta in objProposte)
{
string propostaID = objProposta.PropostaID;
List<ProposteDetails> lstProdDet = _connection.Table<ProposteDetails>().Where(x => x.PropostaID == propostaID).ToList();
if (lstProdDet != null && lstProdDet.Count() > 0)
{
//AN UPDATE GIVE ME THE SAME ERROR
_connection.DeleteAll(lstProdDet);
_connection.InsertAll(lstProdDet);
}
}
});
Seems that the _connection.UpdateAll(objProposte); works correctly, but when i try to do something else in the same transaction i got the following exception:
System.ArgumentException: savePoint is not valid, and should be the
result of a call to SaveTransactionPoint. Parameter name: savePoint
at SQLite.Net.SQLiteConnection.DoSavePointExecute (System.String
savePoint, System.String cmd) [0x00063] in
<8f2bb39aeff94a30a8628064be9c7efe>:0 at
SQLite.Net.SQLiteConnection.Release (System.String savepoint)
[0x00000] in <8f2bb39aeff94a30a8628064be9c7efe>:0 at
SQLite.Net.SQLiteConnection.RunInTransaction (System.Action action)
[0x0001d] in <8f2bb39aeff94a30a8628064be9c7efe>:0 at
SQLite.Net.SQLiteConnection.InsertAll (System.Collections.IEnumerable
objects, System.Boolean runInTransaction) [0x0001e] in
<8f2bb39aeff94a30a8628064be9c7efe>:0
Reading on the internet seems something related to a nested transaction, but is not my situation because is all done in the same transaction.
Thanks,
L-
edit 28-05-2018 12:16: That configuration works.... but should do the same things of the above :(
string my_transaction_point = null;
try
{
my_transaction_point = _connection.SaveTransactionPoint();
_connection.UpdateAll(objProposte, runInTransaction: false);
foreach (Proposte objProposta in objProposte)
{
string propostaID = objProposta.PropostaID;
List<ProposteDetails> lstProdDet = _connection.Table<ProposteDetails>().Where(x => x.PropostaID == propostaID).ToList();
if (lstProdDet != null && lstProdDet.Count() > 0)
{
_connection.DeleteAll(lstProdDet);
_connection.InsertAll(lstProdDet, runInTransaction: false);
}
}
_connection.Commit();
}
catch (Exception ex)
{
_connection.RollbackTo(my_transaction_point);
throw new Exception("UpdateProposta, " + ex.Message, ex);
}
.UpdateAll runs within its own transaction by default, you can turn that off by overriding the second parameter which defaults to true:
_connection.RunInTransaction(() =>
{
_connection.UpdateAll(objProposte, false);
// perform the rest of your CRUD operations
~~~
~~~
});

How to call Guide.BeginShowMessageBox

I have a problem calling Guide.BeginShowMessageBox
Here is my code:
public object FuelTypeIndex { get; private set; }
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var messageCommands = new Dictionary<string, Action>()
{
{ "Diesel", () => {FuelTypeIndex = 0;}},
{ "Petrol", () => {FuelTypeIndex = 1;}},
{ "Other", () => {FuelTypeIndex = 2;}},
};
var result = Guide.BeginShowMessageBox("Title", "Message", messageCommands.Keys, 0, MessageBoxIcon.Warning, null, null);
result.AsyncWaitHandle.WaitOne();
int? choice = Guide.EndShowMessageBox(result);
if (choice.HasValue)
messageCommands.ElementAt(choice.Value).Value.Invoke();
}
I get the following exception:
An exception of type 'System.ArgumentException' occurred in
Microsoft.Xna.Framework.GamerServices.ni.dll but was not handled in
user code
Additional information: The argument is invalid. It must contain
between 1 and 2 strings. The strings cannot be null or empty, and must
be less than 256 characters long.
By debugging I located the problem to messageCommands.Keys, because if I call the function with a static array it works just fine.
So what am I doing wrong?
The problem is the number of requested buttons in the call to Guide.BeginShowMessageBox. According to the documentation the maximum number of buttons is two on Windows Phone.

Using DynamicObject to simulate DependencyProperties

I'm looking to create something akin to one of the features of VS or Blend whereby when one selects multiple objects, the property grid shows the value for any property that is shared by all objects and shows nothing for properties that differ between the objects.
I've managed to implement this behaviour for CLR properties using a dynamic object:
_knownProperties is just a list of properties which have previously been requested
_collection is an IEnumerable instance
public override bool TryGetMember( GetMemberBinder binder, out object result ) {
Debug.WriteLine( "Getting " + binder.Name + "..." );
if (!_knownProperties.Contains( binder.Name ))
_knownProperties.Add( binder.Name );
IEnumerator it = _collection.GetEnumerator();
if (!it.MoveNext()) {
result = null;
Debug.WriteLine( "No elements in collection" );
return true;
}
Type t = it.Current.GetType();
PropertyInfo pinf = t.GetProperty( binder.Name );
if (pinf == null) {
result = null;
Debug.WriteLine( "Property doesn't exist." );
return true;
}
result = pinf.GetValue( it.Current, null );
if (result == null) {
Debug.WriteLine( "Null result" );
return true;
}
while (it.MoveNext())
if (!result.Equals( it.Current.GetType().GetProperty( binder.Name ).GetValue( it.Current, null ) )) {
result = null;
Debug.WriteLine( "Null result" );
return true;
}
Debug.WriteLine( "Result: " + result.ToString() );
return true;
}
I'm accessing these properties via WPF Bindings.
Can anyone think of a way to implement this for DependencyProperties? If I attempt to bind to an attached property on the object, I get an ArgumentNullException in the property system (where the object that is null can't possibly be null according to the source I have)
{Binding Selection.SomeClrProperty,...} works fine (Selection is one of the dynamic objects, SomeClrProperty is a property on every element of the collection.
{Binding Selection.(SomeClass.SomeAttachedProperty),...} Fires an error in the property system
The Exception:
System.ArgumentNullException was unhandled
Message=Key cannot be null.
Parameter name: key
Source=System
ParamName=key
StackTrace:
at System.Collections.Specialized.HybridDictionary.get_Item(Object key)
at System.ComponentModel.PropertyChangedEventManager.PrivateAddListener(INotifyPropertyChanged source, IWeakEventListener listener, String propertyName)
at System.ComponentModel.PropertyChangedEventManager.AddListener(INotifyPropertyChanged source, IWeakEventListener listener, String propertyName)
at MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)
at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
at MS.Internal.Data.ClrBindingWorker.AttachDataItem()
at System.Windows.Data.BindingExpression.Activate(Object item)
...
Use OneTime bindings to prevent WPF from trying to put a listener on the attached property:
{Binding Selection.(SomeClass.SomeAttachedProperty), Mode=OneTime, ...}

Having problem with Culture and NullReferenceException

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") {}

Categories

Resources