Can we have genric Properties? - c#-4.0

Can we have a Generic properties?I have a requirement of storing the data.So i have taken class with Generic Properties.When i add the data to that Property am getting an error that "Object reference not set to an instance of an object" .please suggest me some idea.
class GeneralClass
{
private List<int> _student_rollnumber;
public List<string> _student_name;
public List<int> Student_RollNumber
{
get { return _student_rollnumber; }
set { _student_rollnumber = value; }
}
public List<string> Student_Name
{
get { return _student_name; }
set { _student_name = value; }
}
}
i have used the Class in Button Click.
private void btn_save_Click(object sender, EventArgs e)
{
try
{
GeneralClass obj = new GeneralClass();
obj.Student_RollNumber.Add(int.Parse(txtbx_rollnum.Text));
obj.Student_Name.Add(txtbx_SName.Text);
MessageBox.Show("Data saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message from form");
}
}

This has got nothing to do with generics.
You simply didn’t initialize your member variables, i.e. _student_rollnumber and _student_name, so they’re null when you try to Add values to them.

class GeneralClass
{
public GeneralClass
{
_student_rollnumber = new List<int>();
_student_name = new List<string>();
}
private List<int> _student_rollnumber;
public List<string> _student_name;
public List<int> Student_RollNumber
{
get { return _student_rollnumber; }
set { _student_rollnumber = value; }
}
public List<string> Student_Name
{
get { return _student_name; }
set { _student_name = value; }
}
}

You're not initialising the lists, so they default to null, which means that you get a NullReferenceException when you try to add to them in your click-handler method.
class GeneralClass
{
// initialise to a new List<int>, otherwise it will default to null
private List<int> _student_rollnumber = new List<int>();
// initialise to a new List<string>, otherwise it will default to null
private List<string> _student_name = new List<string>();
public List<int> Student_RollNumber
{
get { return _student_rollnumber; }
// chances are that you don't need the setter, uncomment it if you do
//set { _student_rollnumber = value; }
}
public List<string> Student_Name
{
get { return _student_name; }
// chances are that you don't need the setter, uncomment it if you do
//set { _student_name = value; }
}
}

You can get help from following link.
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

Related

AltBeacon api return empty collection while ranging beacons

I am trying to range beacons and I am doing exactly what it is written here:
http://altbeacon.github.io/android-beacon-library/samples.html
didRangeBeaconsInRegion method is firing but always with empty collection.
I have installed "locate" by altbeacon and it located 3 beacons.
this is my code: am I missing something?
public class BeaconSingletone implements BeaconConsumer {
private static BeaconSingletone instance;
private final org.altbeacon.beacon.BeaconManager beaconManager2;
private ArrayList<BeaconThin> listNearBeacons = new ArrayList<>();
BeaconRegion region = new BeaconRegion("ranged region",
UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null);
private List<EventInterface> listeners = new ArrayList<EventInterface>();
private BeaconSingletone()
{
beaconManager2 = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(ar_activity.get());
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
beaconManager2.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager2.bind(this);
public static BeaconSingletone getInstance() {
if(instance == null) {
instance = new BeaconSingletone();
}
return instance;
}
private void showNotification(Region region, final List<Beacon> list) {
listNearBeacons.clear();
listNearBeacons.add(new BeaconThin(3514,7580,-1));
for (Iterator<EventInterface> i = listeners.iterator(); i.hasNext(); ) {
EventInterface item = i.next();
//item.NewBeaconFound(list.get(0).getMajor(),list.get(0).getMinor(),Utils.computeAccuracy(list.get(0)));
item.NewBeaconsFound(listNearBeacons);
}
return;
}
#Override
public void onBeaconServiceConnect() {
beaconManager2.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<org.altbeacon.beacon.Beacon> beacons, org.altbeacon.beacon.Region region) {
if (beacons.size() > 0) {
Log.i("BeaconManager", "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away.");
}
}
});
try {
beaconManager2.startRangingBeaconsInRegion(new org.altbeacon.beacon.Region("mybeacons", null, null, null));
} catch (RemoteException e) { }{
}
}
#Override
public Context getApplicationContext() {
return ar_activity.get();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
ar_activity.get().unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return ar_activity.get().bindService(intent, serviceConnection, i);
}
}
You need to add a beacon layout for the beacon type you are using (iBeacon?). Replace this line:
beaconManager2.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
With the proper layout from here:
https://beaconlayout.wordpress.com

How to assign values to the class attributes in C#?

I'm new to C# programming and trying to write the following program using "Vihicle" interface properties that are inherited in 'Car', 'Truck' classes. The problem I'm facing is this error:
An unhandled exception of type 'System.StackOverflowException' occurred"
I get this while assigning the values to the Car properties. Here is my code:
namespace Inheritance_Assignment_2
{
interface Vihicle
{
string Make
{
get;
set;
}
String Model
{
get;
set;
}
int Year
{
get;
set;
}
void DisplayInfo();
float calculateMileage();
}
class Car : Vihicle
{
private string make;
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
private string model;
public string Model // read-write instance property
{
get
{
return Model;
}
set
{
Model = value;
}
}
private int year;
public int Year // read-write instance property
{
get
{
return Year;
}
set
{
Year = value;
}
}
public void DisplayInfo()
{
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
}
public float calculateMileage()
{
Random random = new Random();
float value = random.Next(10, 20);
return value;
}
}
class Truck : Vihicle
{
private string make;
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
private string model;
public string Model // read-write instance property
{
get
{
return Model;
}
set
{
Model = value;
}
}
private int year;
public int Year // read-write instance property
{
get
{
return Year;
}
set
{
Year = value;
}
}
public void DisplayInfo()
{
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
}
public float calculateMileage()
{
throw new NotImplementedException();
}
}
class TowingTruck : Truck
{
public string TowingCapacity // read-write instance property
{
get
{
return TowingCapacity;
}
set
{
TowingCapacity = value;
}
}
public void DisplayInfo() // Overrided function of class truck because this function doing some extra printing of
{ //TowingCapacity that is present in this TowingTruck Child of Truck Class
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
Console.WriteLine(TowingCapacity);
}
public float calculateMileage()
{
throw new NotImplementedException();
}
}
class DeliveryTruck : Truck
{
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
public string Model // read-write instance property
{
get
{
return Model;
}
set
{
Model = value;
}
}
public int Year // read-write instance property
{
get
{
return Year;
}
set
{
Year = value;
}
}
/*
public void DisplayInfo()
{
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
}
public float calculateMileage()
{
// throw new NotImplementedException();
return 0;
}
*/
}
class Program
{
static void Main(string[] args)
{
//while (true) // Loop indefinitely
//{
// string name;
// int age;
// double height;
// Console.Write("Enter your name: ");
// name = Console.ReadLine();
// Console.Write("Enter your age: ");
// age = Convert.ToInt32(Console.ReadLine());
// Console.Write("Enter your height: ");
// height = Convert.ToDouble(Console.ReadLine());
// //Print a blank line
// Console.WriteLine();
// //Show the details you typed
// Console.WriteLine( name);
// Console.WriteLine( age);
// Console.WriteLine("Height is ", height);
// Console.WriteLine('\n');
//}
Car C = new Car();
float rnum = C.calculateMileage();
Console.WriteLine("Here is the Milage : " + rnum);
C.Make = System.Console.ReadLine();
System.Console.WriteLine("The employee information:");
System.Console.WriteLine("Employee name: {0}", C.Make);
//Console.Write("Enter your Model : ");
//C.Model = Console.ReadLine();
//Console.WriteLine(C.Model);
//Console.ReadLine();
}
}
}
Look at your properties:
private string make;
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
When you read a value from Make, it internally reads a value from Make (same with writing a value), which results in an infinite recursion. You need to read/write from the variable which holds the value:
private string make;
public string Make // read-write instance property
{
get
{
return make;
}
set
{
make = value;
}
}
A property's internal logic can't reference itself. Something actually has to store the value.
Edit: Unless there's any particular reason to use properties like this (such as requiring more logic in the getters/setters), you can just use auto-generated properties to simplify the code. So instead of this:
private string make;
public string Make // read-write instance property
{
get
{
return make;
}
set
{
make = value;
}
}
You can just use this:
public string Make { get; set; }
The compiler automatically converts the latter into something very similar to the former (maybe with just a different backing variable name).

Accessing XPages Data Source in a Plugin

For a plugin (like the extension library) I try to access the datasource with a given "var" name. Accessing the Datasource object is very easy with the following code:
m_DataSourceName contains the name (var) of the datasource.
public DataSource getDataSource() {
if (StringUtil.isNotEmpty(m_DataSourceName)) {
UIViewRoot vrCurrent = getFacesContext().getViewRoot();
if (vrCurrent instanceof UIViewRootEx) {
for (DataSource dsCurrent : ((UIViewRootEx) vrCurrent)
.getData()) {
if (m_DataSourceName.equals(dsCurrent.getVar())) {
return dsCurrent;
}
}
}
}
System.out.println("Datasource name:" + m_DataSourceName);
return null;
}
I'm getting the datasource back and I can cast this datasource:
private TabularDataModel getTDM(DataSource dsCurrent, FacesContext context) {
try {
if (dsCurrent instanceof ModelDataSource) {
ModelDataSource mds = (ModelDataSource) dsCurrent;
AbstractDataSource ads = (AbstractDataSource) mds;
ads.load(context);
System.out.println(ads.getBeanId());
if (ads.getBeanId() == null) {
}
DataModel tdm = mds.getDataModel();
if (tdm instanceof TabularDataModel) {
TabularDataModel tds = (TabularDataModel) tdm;
return tds;
}
}
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
And now I wanna access the TDM.getRowCount() and this point I'm getting a nullpointer exception. The datasource contains a notes view. Did I miss anything to initialize the datasource?
Here is a solution for your problem:
This will give you all lines of a view, not the entry count*. F.e. if you have a categorized view with 5 categories and 1 entry for each category, this will result in 10 lines. The entry count is 5.
First, create a dummy class which implements FacesDataIterator
public class DummyDataIterator implements com.ibm.xsp.component.FacesDataIterator{
public DataModel getDataModel() {
return null;
}
public int getFirst() {
return 0;
}
public int getRowIndex() {
return 0;
}
public int getRows() {
return 0;
}
public void setFirst(int paramInt) {}
public void setRows(int paramInt) {}
}
And then you have to do the following:
Set the data iterator
tdm.setDataControl( new DummyDataIterator() );
Init the row counter for the first time
tdm.getRowCount();
Calculate the exact row count with a navigator
(( com.ibm.xsp.model.domino.viewnavigator.NOIViewNavigatorEx) tdm.getDominoViewDataContainer().getNavigator()).calculateExactCount(tdm.getView());
Now your row count is initialized, you can get the result with a normal getRowCount:
System.out.println("Rows: " + tdm.getRowCount() );
Hope this helps!
*:
tdm.getView().getAllEntries().getCount()

Using Three20 TTPhotoViewController with MonoTouch

I'm trying to use the Three20 TTPhotoViewController with MonoTouch. I've derived FacebookPhoto from TTPhoto and FacebookPhotoSource from TTPhotoSource and am now trying to invoke the TTPhotoViewController but I get the following exception when pushing the view controller:
Objective-C exception thrown. Name: NSInvalidArgumentException Reason: * -[NSPlaceholderString initWithFormat:locale:arguments:]: nil argument
I noticed that the monotouch bindings in this github project: https://github.com/mono/monotouch-bindings/tree/492f68c3c2007f0638452cc8a5a762556db224ba/Three20/binding were missing the photoAtIndex binding, so I added that and recompiled them, but I haven't been able to figure out why I am getting this exception.
Here is how I'm invoking the TTPhotoViewController:
List<Photo> photoList = FacebookGraphApi.Instance.GetAlbumPhotos(album.id);
List<FacebookPhoto> fbPhotoList = photoList.Select(x => new FacebookPhoto(x)).ToList();
var photos = new TTPhotoViewController();
photos.PhotoSource = new FacebookPhotoSource(fbPhotoList);
NavController.PushViewController(photos, true);
Here is the definition of the TTPhotoSource
class FacebookPhotoSource : TTPhotoSource
{
List<FacebookPhoto> _photoList;
public FacebookPhotoSource (List<FacebookPhoto> photoList)
{
_photoList = photoList;
int i = 0;
foreach (FacebookPhoto photo in photoList) {
photo.PhotoSource = this;
photo.Index = i++;
}
}
public override string Title {
get {
return "Facebook Photos";
}
set {
throw new NotImplementedException();
}
}
public override int NumberOfPhotos {
get {
return _photoList.Count;
}
}
public override int MaxPhotoIndex {
get {
return _photoList.Count -1;
}
}
public override TTPhoto PhotoAtIndex(int photoIndex)
{
return _photoList[photoIndex];
}
}
and here is the definition of the FacebookPhoto:
class FacebookPhoto : TTPhoto
{
Photo _photo;
public FacebookPhoto(Photo photo)
{
_photo = photo;
}
public override string Caption {
get {
if(_photo.name == null)
return "";
return _photo.name;
}
set {
throw new NotImplementedException();
}
}
public override TTPhotoSource PhotoSource { get; set; }
public override int Index { get; set; }
public override SizeF Size {
get {
return new SizeF(_photo.width, _photo.height);
}
set {
throw new NotImplementedException();
}
}
public override string URLForVersion (int version)
{
switch (version) {
case 4:
return _photo.picture;
default:
return _photo.source;
}
}
}

Binding a Table to a Sub Property

There are a couple of answers out there for this already, but I have not been able to find anything conclusive. This is the jist of what I am trying to do:
EquityInstrument
public class EquityInstrument : INotifyPropertyChanged
{
private string _Symbol;
public string Symbol
{
get
{
return _Symbol;
}
set
{
_Symbol = value;
OnPropertyChanged("Symbol");
}
}
public EquityInstrument(string Symbol)
{
this.Symbol = Symbol;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string FieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(FieldName);
}
}
}
OptionInstrument
public class OptionInstrument : INotifyPropertyChanged;
{
public readonly EquityInstrument UnderlyingInstrument;
private double _StrikePrice;
public double StrikePrice
{
get
{
return _StrikePrice;
}
set
{
_StrikePrice = value;
OnPropertyChanged("StrikePrice");
}
}
private DateTime _Expiration;
public DateTime Expiration;
{
get
{
return _Expiration;
}
set
{
_Expiration = value;
OnPropertyChanged("Expiration");
}
}
public OptionInstrument(string Symbol, double StrikePrice, DateTime Expiration)
{
this.Symbol = Symbol;
this.StrikePrice = StrikePrice;
this.Expiration = Expiration;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string FieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(FieldName);
}
}
}
This code initiates the Option Table...
GridControl OptionGrid = new GridControl();
BindingList<OptionInstrument> BoundList = new BindingList<OptionInstrument>();
public void InitializeDataTable()
{
OptionGrid.DataSource = new BindingSource() { DataSource = BoundList };
BandedGridColumn Column0 = new BandedGridColumn();
Column0.FieldName = "Symbol";
BandedGridColumn Column1 = new BandedGridColumn();
Column1.FieldName = "StrikePrice";
BandedGridColumn Column2 = new BandedGridColumn();
Column2.FieldName = "Expiration";
BandedGridView MainView = (BandedGridView)OptionGrid.MainView;
MainView.Columns.Add(Column0);
MainView.Columns.Add(Column1);
MainView.Columns.Add(Column2);
BoundList.Add(new OptionInstrument("DELL", 12.22, new DateTime(2012, 10, 12));
BoundList.Add(new OptionInstrument("MSFT", 13.23, new DateTime(2012, 09, 16));
BoundList.Add(new OptionInstrument("SPY", 12.23, new DateTime(2012, 07, 18));
}
What do you think? Are there any good design patterns to accomplish this?

Resources