calling a property from method - c#

can I call my property TaskAll from the method Task
My code is
private ObservableCollection<TaskExecutionHistoryModel> _TaskAll;
public ObservableCollection<TaskExecutionHistoryModel> TaskAll
{
get{ return _TaskAll;}
set
{
_TaskAll = value;
base.NotifyPropertyChanged(x => x.TaskAll);
}
}
public Task(ObservableCollection<TaskExecutionHistoryModel> ExecutionHistory)
{
}

Yes.
public Task(ObservableCollection<TaskExecutionHistoryModel> ExecutionHistory)
{
ObservationCollection<TaskExecutionHistoryModel> model = TaskAll;
}

Yes you can by simply calling it:
public Task(ObservableCollection<TaskExecutionHistoryModel> ExecutionHistory)
{
TaskAll = someValue;
someOtherValue = TaskAll;
}

Related

How to assign roles from helper class,MVC5

I am doing something like in action(Get),
[Authorize(Roles = SmartRoles.smclientadmin,SmartRoles.smclientbranchadmin)]
public ActionResult Index()
{
return View();
}
And Helper Class
public class SmartRoles
{
public static string smclientadmin
{ get { return smclientadmin; }
set { smclientadmin = "SMClientAdmin"; } }
public static string smclientbranchadmin
{ get { return smclientbranchadmin; }
set { smclientbranchadmin = "SMClientBranchAdmin"; } }
public static string smclientoperator
{ get { return smclientoperator; }
set { smclientoperator = "SMClientOperator"; } }
}
Error its giving is "name attribute argument expected".... Is there a
right way to use this method?? If so please help...thanks for your
time...
You creating an infinite loop (the getter is calling itself). Change the getter to return a value (no setter is required)
public static string smclientadmin
{
get { return "SMClientAdmin"; }
}
The property accesors would end up in a recursive call. Also, the attribute arguments must be constant expression. Change your code to as below:
[Authorize(Roles = SmartRoles.smclientadmin)]
public ActionResult Index()
{
return View();
}
public class SmartRoles
{
public const string smclientadmin = "SMClientAdmin";
public const string smclientbranchadmin = "SMClientBranchAdmin";
}

How to solve StackOverflowException

I try to write this class:
public class ModelManager
{
public OmniacareHomeProductionEntities _db;
public CategoriaManager categoriaManager
{
get { return categoriaManager; }
set
{
if (categoriaManager == null)
{
categoriaManager = new CategoriaManagerImpl();
}
}
}
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ModelManager));
public ModelManager()
{
_db = new OmniacareHomeProductionEntities();
}
}
CategoriaManager is an Interface and CategoriaManagerImpl is a class that implements CategoriaManager.
I use ModelManager class in this mode:
ModelManager modelManager = new ModelManager();
modelManager.categoriaManager.saveLocalCategory(category, true);
so when I try to run this code, I have a StackOverflowError at this line
get
{
return categoriaManager;
}
Where is my error? Can you help me?
Your problem is clearly here
public CategoriaManager categoriaManager
{
get
{
return categoriaManager;
}
set
{
if (categoriaManager == null)
{
categoriaManager = new CategoriaManagerImpl(); //HERE !!!!!!!!!
}
}
}
the name of the member is the same of the property, change it like this, for example:
public CategoriaManager CatManager //NAME OF HE PROPERTY ISCHANGED !!!!
{
get
{
return categoriaManager;
}
set
{
if (categoriaManager == null)
{
categoriaManager = new CategoriaManagerImpl();
}
}
}
General guideline:
for properties use names starting from upper case
for fields use names starting from low case
So your code would lool like this:
ModelManager modelManager = new ModelManager();
modelManager.CatManager.saveLocalCategory(category, true);
You should change it like this:
private CategoriaManager _categoriaManager;
public CategoriaManager CategoriaManager
{
get { return _categoriaManager; }
set
{
if (_categoriaManager == null)
{
_categoriaManager = new CategoriaManagerImpl();
}
}
}

Return modified generic type

I am trying to modify an object after its creation. I would like to set the properties of this object to -1 for int or string.empty "" for a string. Bellow is a sample code of what I already have.
class TestClassAccess{
public int MyPropInt { get; set { ModifyOnAccessDenied<int>(value); } }
public string MyPropString { get; set { ModifyOnAccessDenied<string>(value); } }
public TestClassAccess() { }
private T ModifyOnAccessDenied<T>(T propertyToChange) {
var _hasAccess = false; //not really important how this is made
if (!_hasAccess)
{
if (propertyToChange is string)
propertyToChange = string.Empty;
else if (propertyToChange is int)
propertyToChange = -1;
}
return propertyToChange;
}
}
so.. issues i am having.
It doesn't compile as I cannot convert property to change to string or int.
I don't knot if i can use set methods like this.
Is this possible or am i being to ambitious.
Thank.s
KJ
If you are checking for specific types in a generic function you are probably doing something wrong. In this case you can easily just pass in a default value rather than having it hard coded:
private T ModifyOnAccessDenied<T>(T newValue, T defaultValue) {
var _hasAccess = false; //not really important how this is made
if (!_hasAccess)
{
newValue = defaultValue;
}
return newValue;
}
I've also renamed propertyToChange to newValue because what you have in this function is the new value, not a property.
Also your property definitions will not work. If you need to include any logic in your getter or setting you cannot use the auto-initializer syntax and must implement the property with a backing field.
There doesn't seem to be a point in making this function generic if it needs specific action for each type. This seems more appropriate.
class TestClassAccess
{
public int MyPropInt { get; set { ModifyOnAccessDenied<int>(value); } }
public string MyPropString { get; set { ModifyOnAccessDenied<string>(value); } }
public TestClassAccess() { }
private static volatile bool _hasAccess = false;
private string ModifyOnAccessDenied<string>(string propertyToChange)
{
if (!_hasAccess)
return string.Empty;
return propertyToChange;
}
private int ModifyOnAccessDenied<int>(int propertyToChange)
{
if (!_hasAccess)
return -1;
return propertyToChange;
}
}
You can however do this using dynamics, but this does require .NET 4.0
private T ModifyOnAccessDenied<T>(T propertyToChange)
{
if (!_hasAccess)
{
if (propertyToChange is string)
return (dynamic)string.Empty;
else if (propertyToChange is int)
return (dynamic)(int)-1;
}
return propertyToChange;
}
Fully working sample:
static class Program
{
[STAThread]
static void Main()
{
TestClassAccess test = new TestClassAccess();
test.MyPropInt = 4;
test.MyPropString = "TEST";
Console.WriteLine("MyPropInt {0}, MyPropString '{1}'",test.MyPropInt, test.MyPropString);
// Prints "MyPropInt -1, MyPropString ''
}
class TestClassAccess
{
private int myPropInt = 0;
public int MyPropInt { get { return myPropInt; } set { myPropInt = ModifyOnAccessDenied<int>(value); } }
private string myPropString = string.Empty;
public string MyPropString { get { return myPropString; } set { myPropString = ModifyOnAccessDenied<string>(value); } }
public static volatile bool _hasAccess = false;
private T ModifyOnAccessDenied<T>(T propertyToChange)
{
if (!_hasAccess)
{
if (propertyToChange is string)
return (dynamic)string.Empty;
else if (propertyToChange is int)
return (dynamic)(int)-1;
}
return propertyToChange;
}
}
}

NavigationService WithParam of Caliburn Micro for WP

As is well known, CM doesn't support passing a object of complex type through NavigationService like MVVM Light. So I searched for a workaround and did it like this.
There are two viewmodels: MainPageViewModel and SubPageViewModel.
I first defined 3 classes, namely GlobalData, SnapshotCache and StockSnapshot. StockSnapshot is the type of which the object I want to pass between the 2 viewmodels.
public class SnapshotCache : Dictionary<string, StockSnapshot>
{
public StockSnapshot GetFromCache(string key)
{
if (ContainsKey(key))
return this[key];
return null;
}
}
public class GlobalData
{
private GlobalData()
{
}
private static GlobalData _current;
public static GlobalData Current
{
get
{
if (_current == null)
_current = new GlobalData();
return _current;
}
set { _current = value; }
}
private SnapshotCache _cachedStops;
public SnapshotCache Snapshots
{
get
{
if (_cachedStops == null)
_cachedStops = new SnapshotCache();
return _cachedStops;
}
}
}
public class StockSnapshot
{
public string Symbol { get; set; }
public string Message { get; set; }
}
Next, I call the navigation service on MainPageViewModel like this:
StockSnapshot snap = new StockSnapshot {Symbol="1", Message = "The SampleText is here again!" };
GlobalData.Current.Snapshots[snap.Symbol] = snap;
NavigationService.UriFor<SubPageViewModel>().WithParam(p=>p.Symbol,snap.Symbol).Navigate();
And on SubPageViewModel I've got this:
private string _symbol;
public string Symbol
{
get { return _symbol; }
set
{
_symbol = value;
NotifyOfPropertyChange(() => Symbol);
}
}
public StockSnapshot Snapshot
{
get { return GlobalData.Current.Snapshots[Symbol]; }
}
And that's where the problem lies. When I run the program, I find out that it always runs to the getter of Snapshot first, when Symbol hasn't been initialized yet. So later I've tried adding some extra code to eliminate the ArgumentNullException so that it can run to the setter of Symbol and then everything goes fine except that the UI doesn't get updated anyway.
Could anyone tell me where I've got wrong?
Thx in advance!!
Why not just use:
private string _symbol;
public string Symbol
{
get { return _symbol;}
set
{
_symbol = value;
NotifyOfPropertyChange(() => Symbol);
NotifyOfPropertyChange(() => Snapshot);
}
}
public StockSnapshot Snapshot
{
get { return Symbol!=null? GlobalData.Current.Snapshots[Symbol]:null; }
}
In this case you don't try and get the data from GlobalData when Symbol is null (sensible approach anyway!) and when "Symbol" is set you call NotifyOfPropertyChange() on Snapshot to force a re-get of the property.

Encapsulating Action<T> and Func<T>?

I'm trying to make a design for some sort of IExecutable interface. I will not get into details, but the point is that I have several Actions that need to be executed from a base class. They may take different parameters (no big deal), and they may/may not return a value.
So far, this is my design:
public abstract class ActionBase
{
// ... snip ...
}
public abstract class ActionWithResultBase<T>: ActionBase
{
public abstract T Execute();
}
public abstract class ActionWithoutResultBase: ActionBase
{
public abstract void Execute();
}
So far, each of my concrete actions need to be a child from either ActionWithResultBase or ActionWithoutResult base, but I really don't like that. If I could move the definition of Execute to ActionBase, considering that the concrete class may or may not return a value, I will have achieved my goal.
Someone told me this could be done with using Func and Action, for which I totally agree, but I can't find a way to have that into one single class so that the caller would know if the action is going to return a value or not.
Brief: I want to do something like:
// Action1.Execute() returns something.
var a = new Action1();
var result = a.Execute();
// Action2.Execute() returns nothing.
var b = new Action2();
b.Execute();
If you want a lightweight solution, then the easiest option would be to write two concrete classes. One will contain a property of type Action and the other a property of type Func<T>:
public class ActionWithResult<T> : ActionBase {
public Func<T> Action { get; set; }
}
public class ActionWithoutResult : ActionBase {
public Action Action { get; set; }
}
Then you can construct the two types like this:
var a1 = new ActionWithResult<int> {
CanExecute = true,
Action = () => {
Console.WriteLine("hello!");
return 10;
}
}
If you don't want to make Action property read/write, then you could pass the action delegate as an argument to the constructor and make the property readonly.
The fact that C# needs two different delegates to represent functions and actions is quite annoying. One workaround that people use is to define a type Unit that represents "no return value" and use it instead of void. Then your type would be just Func<T> and you could use Func<Unit> instead of Action. The Unit type could look like this:
public class Unit {
public static Unit Value { get { return null; } }
}
To create a Func<Unit> value, you'll write:
Func<Unit> f = () => { /* ... */ return Unit.Value; }
The following interfaces should do the trick -- it's essentially copying the Nullable pattern
public interface IActionBase
{
bool HasResult { get; }
void Execute() { }
object Result { get; }
}
public interface IActionBase<T> : IActionBase
{
new T Result { get; }
}
public sealed class ActionWithReturnValue<T> : IActionBase<T>
{
public ActionWithReturnValue(Func<T> action) { _action = action; }
private Func<T> _action;
public bool HasResult { get; private set; }
object IActionBase.Result { get { return this.Result; } }
public T Result { get; private set; }
public void Execute()
{
HasResult = false;
Result = default(T);
try
{
Result = _action();
HasResult = true;
}
catch
{
HasResult = false;
Result = default(T);
}
}
}
public sealed class ActionWithoutReturnValue : IActionBase
{
public bool HasResult { get { return false; } }
object IActionBase.Result { get { return null; } }
public void Execute() { //... }
}
You know that you can ignore the return value of a method right? You don't have to use it.
what about something simple:
public class ActionExecuter
{
private MulticastDelegate del;
public ActionExecuter(MulticastDelegate del)
{
this.del = del;
}
public object Execute(params object[] p)
{
return del.DynamicInvoke(p);
}
}

Categories

Resources