I have a type mismatch error when reading the contents of table 'ImageHighlight'.
In designer.cs the table is:
public System.Data.Linq.Table<ImageHighlight>ImageHighlights
{
get
{
return this.GetTable<ImageHighlight>();
}
}
In my code I am trying to cache a small table in method LoadStaticCache() at ApplicationStart so I can access its contents later via GetHighlightImages().
public class StaticCache
{
private static ImageHighlight _images = null;
public static void LoadStaticCache()
{
// Get images - cache using a static member variable
using (var datacontext = new MHRDataContext())
{
_images = datacontext.ImageHighlights;
}
}
public static ImageHighlight GetHighlightImages()
{
return _images;
}
}
At code line _images = datacontext.ImageHighlights; I get error
Cannot implicitly convert type
System.Data.Linq.Table<HolidayRentals.Core.Domain.LinqToSql.ImageHighlight>
to HolidayRentals.Core.Domain.LinqToSql.ImageHighlight
They are both the same type.
datacontext.ImageHighlights is a Table which is an IQueryable of ImageHighlight. _imagess type is ImageHighlight. You can not convert these types to each other.
Since you want some caching mechanism and _images indicates that it should contain multiple instance of images then you should change the type of _images.
Change your code to this:
public class StaticCache
{
private static List<ImageHighlight> _images = null;
public static void LoadStaticCache()
{
// Get images - cache using a static member variable
using (var datacontext = new MHRDataContext())
{
_images = datacontext.ImageHighlights.ToList();
}
}
public static List<ImageHighlight> GetHighlightImages()
{
return _images;
}
}
Related
I need to get string from one class to another class,
It is possible to set public string from method I mean like in this code:
class test
{
static void Main(string[] args)
{
load();
}
public class Data
{
public string datacollected { get; set; }
}
public static void load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
Data datacfg = new Data();
var datanew = System.Text.Json.JsonSerializer.Deserialize<List<Data>>(jsonString);
datacfg = datanew.First();
}
public string datacollected = datacfg.datacollected;
}
i want to use string datacollected in another class and in another public void
The datacollected member that is directly in the test class is not a property. It's a field. Fields that have an assignment on the same statement as the declaration are evaluated before* the class's constructor (ie: before the Main method runs).
You probably want it to be a property instead, which is evaluated each time you access the member. The simplest method to fix that is by adding a > after the equals.
public string datacollected => datacfg.datacollected;
You've got two other problems though.
datacollected (in the test class) isn't static. All of your methods are static, and therefor wouldn't be able to access the non-static member.
You've still got the problem where the datacfg is a local variable that is defined inside the load method. You can't use variables outside their defined scope.
Option 1: you only need the parsed file data in the method that called load.
Change load to return the parsed data, rather than save it to a class-global variable.
using System.Text.Json;
static class test
{
static void Main(string[] args)
{
Data loadedData = load();
}
public static Data load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
return JsonSerializer.Deserialize<List<Data>>(jsonString).First();
}
}
public class Data
{
public string datacollected { get; set; }
}
Option 2: If you really need some global variable, put the whole Data object up to a field instead. This doesn't use a property - there's really no advantage in this case.
using System.Text.Json;
static class test
{
// assuming you're using nullable reference types (the "?")
private static Data? loadedData;
static void Main(string[] args)
{
load();
Console.WriteLine(loadedData!.datacollected);
// "!" to tell compiler that you know loadedData
// shouldn't be null when executed
}
public static void load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
loadedData = JsonSerializer.Deserialize<List<Data>>(jsonString).First();
}
}
public class Data
{
public string datacollected { get; set; }
}
I'd go with Option 1 if at all possible.
* I don't remember if it's before, during, or after.
You can declare a class like this
public class UseData
{
private List<Data> _data=null;
public string datacollected
{
get
{
if (_data == null)
LoadData();
return _data.First().datacollected;
}
}
private void LoadData()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
_data = System.Text.Json.JsonSerializer.Deserialize<List<Data>>(jsonString);
}
}
which have a private list of data and it loads from your json file at first time you called. Next time you call it, as the private _data object is filled, it wont load again and the datacollected property returns the first data object's datacollected string property.
What I have is:
public static class IDs {
public static string someID { get; set; }
static IDs() {
log.info(someID);
// use someID here
}
}
public class otherClass {
public void otherMethod(string sym) {
IDs.someID = sym;
}
}
and then using an instance of otherClass like this:
otherClassInstance.otherMethod("someStringSymbol");
I dont have any build errors, but log.info(someID); is printing null.
I was expecting it to be someStringSymbol.
This is because the static constructor is called automatically before the first instance is created or any static members are referenced..
This means that when an instance of otherClass invokes IDs.someID = sym; the first operation that gets executed is the static constructor, i.e. the code inside static IDs().
At this point the static variable has not yet been initialized, and you are basically executing log.info(null);.
After the static constructor completes, the variable is initialized, so you should be able to see its value inside otherMethod, after the first reference of IDs.
Given the OP's requirement:
I want to use the value passed in someID in a switch statement
The solution could be to simply execute a static method whenever a new value is set, with the help of explicit getters and setters:
public static class IDs
{
private static string _someID; // backing field
public static string SomeID
{
get { return _someID; }
set
{
_someID = value;
DoSomethingWithSomeID();
}
}
private static DoSomethingWithSomeID()
{
// Use SomeID here.
switch (IDs.SomeID)
{
...
}
}
}
public class OtherClass
{
public void OtherMethod(string sym)
{
// This will set a new value to the property
// and invoke DoSomethingWithSomeID.
IDs.SomeID = sym;
}
}
DoSomethingWithSomeID will be invoked every time someone sets a new value to SomeID.
I dont think what you are trying to do is suited to static classes. I would try the following
public class IDs{
public string someID{ get; set; }
public IDs(string someId){
this.someID = someId;
log.info(this.someID);
//use someID here
}
}
pulic class otherClass{
public otherMethod(string sym){
IDs id = new IDs(sym);
}
}
public class anotherClass{
//access instance of otherClass in wrp and call otherMethod()
wrp.otherMethod("someStringSymbol")
}
I have a class declared as follows:
public class Eq
{
public bool Equals(ValI x, ValI y)
{
return nilnul.num.ord.Eq.Singleton.Equals( x , y);
//throw new NotImplementedException();
}
public int GetHashCode(ValI obj)
{
return nilnul.num.ord.Eq.Singleton.GetHashCode(obj);
throw new NotImplementedException();
}
static public Eq Singleton=SingletonByDefault<Eq>.Instance;
}
while the SingletonByDefault looks like:
public class SingletonByDefault<YourClass>
where YourClass:new()
//where YourClass:class
{
static protected YourClass _Instance= new YourClass();
static public YourClass Instance
{
get
{
return _Instance;
}
}
protected SingletonByDefault() {
}
}
In most cases when I access Eq.Singleton members, It's fine.
But on one occasion or another, I got a null reference exception which says Eq.Singleton is null.
when I change the static "Singleton" field of class Eq to follows:
//...
static public Eq Singleton{
get{
return SingletonByDefault<Eq>.Instance;
}
}
//....
The exception is gone - at least for now.
I suspect the error is due to the sequence of static field initialization. For now my understanding is that:
1) Eq.Singleton and SingletonByDefault._Instance is initialized to null.
2) when I access Eq.Singleton, Eq.Singleton is intialized to SingletonByDefault.Instance, but
2.1) since now I'm accessing SingletonByDefault.Instance (which in turn accesses SingletonByDefault._Instance), SingletonByDefault._Instance is initialized to new Eq().
3) Eq.Singleton shall now return the "new-ed Eq()". but
3.1) why it's null?
So my understanding must go wrong some where. Anyone would give me some light?
Microsoft's own System.Lazy<> class provides the singleton pattern you need as follows.
public static class MySingletons
{
private static Lazy<Eq> _eq = new Lazy<Eq>( CreateEq );
private static Eq CreateEq()
{
return new Eq();
}
static public Eq Eq { get{ return _eq.Value; }}
}
// usage
var eq = MySingletons.Eq
Update: Here is a further level of generic wrapping as requested by the questioner. This eliminates some repetitive code where the singleton class supports a basic parameter less constructor.
public static class MySingletons
{
static SingletonByLazy<Eq> _eq = new SingletonByLazy<Eq>();
static public Eq Eq
{
get
{
return _eq.Singlton;
}
}
}
public class SingletonByLazy<T> where T: new()
{
Lazy<T> _singltonWrapped = new Lazy<T>( CreateSingleton );
static T CreateSingleton()
{
return new T();
}
public T Singlton
{
get
{
return _singltonWrapped.Value;
}
}
}
I need to store list values impermanent and i need to get to that list values in another c# class. the procedure resemble, Session in Asp.net. Anybody please share a few thoughts regarding this idea.
Here is my code:
class1.cs:
ObservableCollection<SampleEntityList> zoneList = new ObservableCollection<SampleEntityList>();
ObservableCollection<SampleEntityList> ztowList = new ObservableCollection<SampleEntityList>();
I need to store this 2 list values some place locally and i need to get to this two list values to another class.. be that as it may, i would prefer not to go as constructor. I need to store this two rundown values locally..
class2.cs:
??
I have endeavored this code:
Made new static class for setting the Property. What's more, I can't get to the property access outside the class..
Here's my code:
static class GlobalTempStorageVariable
{
ObservableCollection<SampleEntityList> zoneListGlobal
= new ObservableCollection<SampleEntityList>();
ObservableCollection<SampleEntityList> ztowListGlobal
= new ObservableCollection<SampleEntityList>();
public static ObservableCollection<SampleEntityList> CurrentListOfInventories
{
get { return zoneListGlobal; }
set { zoneListGlobal = value; }
}
public static ObservableCollection<SampleEntityList> CurrentSelectedInventories
{
get { return ztwoListGlobal; }
set { ztwoListGlobal= value; }
}
}
But this code is not working. Also i am unable to access CurrentListOfInventories & CurrentSelectedInventories outside the class..
class1.cs:
GlobalTempStorageVariable. ???(its not showing the property)..
Any help would be appreciated..
A Static property cannot access non-static field, zoneListGlobal and ztowListGlobal should also be static in order to be accessible by their Properties :
static class GlobalTempStorageVariable
{
static ObservableCollection<SampleEntityList> zoneListGlobal
= new ObservableCollection<SampleEntityList>();
static ObservableCollection<SampleEntityList> ztowListGlobal
= new ObservableCollection<SampleEntityList>();
public static ObservableCollection<SampleEntityList> CurrentListOfInventories
{
get { return zoneListGlobal; }
set { zoneListGlobal = value; }
}
public static ObservableCollection<SampleEntityList> CurrentSelectedInventories
{
get { return ztowListGlobal; }
set { ztowListGlobal = value; }
}
}
You can build your static class with 2 static methods that return your desired object, like this example:
public static class GlobalTempStorageVariable
{
ObservableCollection<SampleEntityList> zoneListGlobal
= new ObservableCollection<SampleEntityList>();
ObservableCollection<SampleEntityList> ztowListGlobal
= new ObservableCollection<SampleEntityList>();
public static ObservableCollection<SampleEntityList> GetCurrentListOfInventories()
{
return zoneListGlobal;
}
public static ObservableCollection<SampleEntityList> GetCurrentSelectedInventories()
{
return ztowListGlobal;
}
}
I have a static class like this:
public static class ApplicationList
{
public static List<ApplicationsModel> ApplicationsModels { get; set; }
}
I want to use ApplicationsModels in another class
class Program
{
static void Main(string[] args)
{
GetApplicationNameFromAppConfigAndAddToApplicationList();
}
private static void GetApplicationNameFromAppConfigAndAddToApplicationList()
{
List<string> applicationName = ConfigurationManager.AppSettings["AppName"].Split(',').ToList();
foreach (var variable in applicationName)
{
ApplicationList.ApplicationsModels.Add(new ApplicationsModel { DateTime = DateTime.MinValue, Name = variable });
}
}
}
But i my ApplicationList is null and get this error
Object reference not set to an instance of an object.
This is static Prpoerty and we can't create instance form static Prpoerty
Well you have a
public static List<ApplicationsModel> ApplicationsModels { get; set; }
property which is not initialized.
Can do something like this, instead:
public static class ApplicationList
{
private static List<ApplicationsModel> appmodel = new List<ApplicationsModel>();
public static List<ApplicationsModel> ApplicationsModels
{
get { return appmodel ;}
}
//DON'T THINK YOU NEED A SET IN THIS CASE..
// BUT ADD IT, IF NEED
}
You get the null reference exception because the List<ApplicationsModel> ApplicationsModels is still null when you try to use it. Just declaring it as static doesn't means that the compiler or the framework adds for you the call to
ApplicationsModels = new List<ApplicationsModel>();
Short answer, add this line before loading your list:
ApplicationsModels = new List<ApplicationsModel>();
Longer answer:
You need to initialise your List before you can add to it.
This is because a (reference-type) property will be null by default, and it wouldn't make sense to do null.Add(item).
Solution 1: Initialise before loading:
The easy solution is to add an initialisation line before loading your list in your Get... method:
ApplicationsModels = new List<ApplicationsModel>();
However, this will reinitialise the list each time you call the Get method (which may or may not be what you want). You could place a check to only recreate the list if it is null, but if that's the behaviour you're after I'd lean towards one of the other solutions below.
Solution 2: Use an initialised field instead of a property:
Another way is to replace your property with an initialised field. Either:
public static List<ApplicationsModel> ApplicationsModels = new List<ApplicationsModel>();
Or:
public static List<ApplicationsModel> ApplicationsModels
{
get { return _applicationsModels; }
set { _applicationModels = value; } // Do you really want a set?
}
private static List<ApplicationsModel> _applicationsModels = new List<ApplicationsModel>();
Solution 3: Keep a property, but use a static constructor:
Another way is to use a static constructor in ApplicationList:
static ApplicationList()
{
ApplicationsModels = new List<ApplicationsModel>();
}