i added a property 'WrmVersion' in interface IResourcePolicy but i am not getting those thing in the implementation side means here it should come in the List
view data. means SubItems.Add(((IResourcePolicy)Data).WrmVersion is not getting
This is the interface
public interface IResourcePolicy
{
DataVersion WrmVersion
{
get;
set;
}
bool ResourcePolicyEnabled
{
get;
set;
}
}
i am implementing it in
public new IResourcePolicy Data
{
get
{
return (IResourcePolicy)base.Data;
}
}
protected override void OnUpdate()
{
if(Data != null)
{
Text = base.Data.Name;
if(SubItems.Count == 1)
{
SubItems.Add(((IResourcePolicy)Data).ResourcePolicyEnabled.ToString());
}
Yes it is i am referencing Old DLL ,,what actually happened is i created test application added only relevant forms to test application.So i need to copy the Dll from test application to Original side
Related
I have some actions in a view.
public class AView
{
public Action Show { get; set; }
public Action Hide { get; set; }
}
and I'm trying to set those actions inside another class, by passing them as a parameter (I don't want to pass the whole class)
_reloader.SetupActions(Show, Hide);
Reloader is abstract, because there might be different ways of handling how Hide/Show must behave depending on the scenario we're in.
public abstract class Reloader : IReloader
{
public void SetupActions(Action show, Action hide)
{
show = Show;
hide = Hide;
}
protected virtual void Show() { ... } //what should be done when Show is invoked
protected virtual void Hide() { ... } //same for Hiding
}
And for the current view, I might be using a RapidReloader, SafeReloader, etc. This bit is irrelevant, except that the injected reloader is specific to the current view.
Now my problem is simple and logic : when I'm in SetupActions, all parameters are null (because Actions haven't been set), and setting Show into null obviously does not work.
What can I do so that when Show.Invoke() happens my view, the ShowCode from the relevant reloader is called? I would like to avoid passing the whole view as a parameter.
Also, if you have a better design, I'm all ears. We might be in an XY problem situation
You will need to use System.ValueTuple nuget package if you don't use .Net Framework 4.7 or newer.
public interface IReloader
{
(Action Show, Action Hide) GetActions();
}
public abstract class Reloader : IReloader
{
public (Action Show, Action Hide) GetActions()
{
return (Show, Hide);
}
protected virtual void Show() { }
protected virtual void Hide() { }
}
public class FastReloader : Reloader { }
public class AView
{
public Action Show{ get; set; }
public Action Hide{ get; set; }
public void IwantTheNewActions()
{
var reloader = new FastReloader();
var actions = reloader.GetActions();
Show = actions.Show;
Hide = actions.Hide;
}
}
I'm very new in C# and i need some help to use nested classes on my "Hello World" proyect.
I'm trying to create a class callable using class1.subclass1.function(args...) (to create groups of related functions), and I've done something that is working but I think that is not the best way to do it.
My code needs to share a variable between principal class and nested classes (a db handle), and I'm using and argument at class initialization to do it.
namespace SameAsPrincipal
{
public class class1
{
public SQLiteConnection handle = null;
public _subclass1 subclass = null;
public class1(string db_file)
{
handle = new SQLiteConnection(db_file);
subclass1 = new _subclass1(handle);
}
public _subclass1
{
private SQLiteConnection handle = null;
public _subclass1(SQLiteConnection handle)
{
this.handle = handle;
}
public void function(args...)
{
//Do something here
}
}
}
}
Someone knows a better way to create nested classes and share objects between main and nested?
Thanks!!
I am unclear as to why you would want to use a nested class in this instance. The way you have it written, the subclass is all you need. If you want multiple methods (or as you called them "functions") just add your methods.
Is there some hidden reason you would want to use nested classes here? As a general rule, nested classes are rarely needed.
namespace SameAsPrincipal
{
public class Class1
{
private SQLiteConnection handle;
public Class1(string db_file)
{
handle = new SQLiteConnection(db_file);
}
public int AddRecord(Record record)
{
// use handle to add record and get record Id
return record.Id;
}
public void DeleteRecord(int id)
{
// Use handle to delete record
}
}
}
When you instantiate the object you will pass in your db_file and the connection object will be created. Then every method could use that connection object when they are called. However it is usually a better idea to create the connection for each method when it is called and disposing of the connection as soon as you the operation is completed. This, of course, depends on your operations and if they are transnational. For the most part using a "using" block to instantiate your connection is a good way to use connection objects. The sooner you release the connection the sooner the machine will reuse that connection, you can lookup connection pooling to learn more.
Here is an example method that is using the "using" to add a person using a stored procedure:
public int AddPerson(Person person)
{
using (var connection = new SQLiteConnection(dbFile))
{
connection.Open();
using (var command = new SQLiteCommand("spAddPerson",connection))
{
command.CommandType = CommandType.StoredProcedure;
var idParameter = new SQLiteParameter("#Id", DbType.Int32);
idParameter.Direction = ParameterDirection.Output;
command.Parameters.Add(idParameter);
command.Parameters.AddWithValue("#FirstName", person.FirstName);
command.Parameters.AddWithValue("#LirstName", person.LastName);
command.ExecuteNonQuery();
}
}
return person.Id;
}
edit: In regard to your comment below
A few things:
Use namespaces not a parent class to group classes.
Instead of sub-classes you should just add all the database methods to the database class and create classes to model your objects.
Each class should be in it's own file
The namespace parts are ..[]* I.E. Music class has the namespace YourApplication.YourProject.Models - inside the YourProject project, within a first level folder named Music you will find a file named Music.cs and with in that file you will find your music class. This is not a requirement, the compiler does not care about structure like that. It will only make your life easier when you start to get more code developed.
Here is an example of the code structure I am speaking of (remember each of these sections is it's own file)
Create a folder at the root of your project called Models. In this Models folder create a file named Music.cs
namespace YourApplication.YourProject.Models
{
public class Music
{
public int Id { get; set; }
public string Title { get; set; }
public double Length { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
}
}
In this same (Models) folder create a file called Film.cs
namespace YourApplication.YourProject.Models
{
public class Film
{
public int Id { get; set; }
public string Title { get; set; }
public double Length { get; set; }
public string Director { get; set; }
public string[] Actors { get; set; }
}
}
Now back at the project root (no longer in Models folder) create a new folder called Persistence.
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using YourApplication.YourProject.Models;
namespace YourApplication.YourProject.Persistence
{
public static class DatabaseActions
{
public static string dbFile;
public static Music[] ListMusic()
{
var musicList = new List<Music>();
// database call to get all music
using (var connection = new SQLiteConnection(dbFile))
{
connection.Open();
using (var command = new SQLiteCommand("spGetMusic", connection))
{
var reader = command.ExecuteReader();
// The try finally blocks are not strictly needed as these will are suppose to be called upon disposal
try
{
// loop through records creating music objects
while (reader.Read())
{
var music = new Music();
music.Id = reader.GetInt32(0);
music.Title = reader.GetString(1);
musicList.Add(music);
}
}
finally
{
reader.Close();
connection.Close();
}
}
}
return musicList.ToArray();
}
public static int SaveMusic(Music music)
{
if (music.Id == 0)
{
// database stuff - getting the newly created database id
}
else
{
// database calls to update record
}
return music.Id;
}
public static int SaveFilm(Film film)
{
if (film.Id == 0)
{
// database stuff - getting the newly created database id
}
else
{
// database calls to update record
}
return film.Id;
}
public static Music GetMusic(int id)
{
var music = new Music();
// database call and setting of values on music
return music;
}
public static Film GetFilm(int id)
{
var film = new Film();
// database call and setting of values on music
return film;
}
}
}
Now finally create a file on the root called WorkHarness.cs
using System;
using YourApplication.YourProject.Persistence;
namespace YourApplication.YourProject
{
public class WorkHarness
{
public void Initialize()
{
DatabaseActions.dbFile = "your db file";
}
public void ShowMusicList()
{
// list the id and title so user can select by Id
foreach (var music in DatabaseActions.ListMusic())
{
Console.WriteLine("{0,-10}{1}",music.Id,music.Title);
}
}
public void DisplayMusicItem(int id)
{
var music = DatabaseActions.GetMusic(id);
Console.WriteLine("Title: " + music.Title);
Console.WriteLine("Length: " + music.Length);
Console.WriteLine("Artist: " + music.Artist);
Console.WriteLine("Album: " + music.Album);
}
}
}
Without more context as to what the specific application is, it's hard to tell if it's appropriate or not. I agree with the previous answer that it is generally more correct to have separate classes. Your class B can still take a DB handle reference in its constructor, and class A can even pass it to it. That's fine. It's not so much that they are sharing the variable as that they both have a reference to the same DB handle.
The only time I've ever seen sub/inner classes and not thought it was weird was for like simple data objects that are only ever used within the parent class (although they may be referenced outside). For example, if I made a linked list class, I may choose to have the node class be an inner class. For just grouping functionality, regular classes should do that.
Namespaces can also be used for further grouping. For example, maybe all my text operations are in a "MyApp.Text" namespace, but then they are further grouped into classes like "NumberUtils", "NameUtils", and "ZipUtils".
Instead of nesting the objects, create two classes (at the same scope) and have one use the other, such as this:
public class ClassA
{
public ClassB InstanceOfClassB { get; set; }
public ClassA()
{
InstanceOfClassB = new ClassB();
}
//More code here
}
public class ClassB
{
//Code here
}
Using Nested classes in a HelloWorld project? Not a good sign!!
I would suggest not to use nested types Unless you know what you're doing and you have very good explanation to give when asked. Also a note of advice by .NET Framework Guidelines which explicitly recommend against creating public nested classes.
For data sharing in Object oriented programming we have inheritance feature which is the best way to share data/members access across classes based on relationship/association.
to create groups of related functions
As #Nex Terren suggested (with a little modification), you can do something like this, here your Principle class will work as Factory and different classes will provide Aggregation of related functions by their instance
public class PrincipleClass
{
public ClassB InstanceOfClassB { get; private set; }
public ClassA InstanceOfClassA { get; private set; }
public PrincipleClass(string db_file)
{
InstanceOfClassA = new ClassA(new SQLiteConnection(db_file));
InstanceOfClassB = new ClassB();
}
//More code here
}
public class ClassA
{
public ClassA(SQLiteConnection handle)
{
// your code here
}
public void FunctionOfA1() { }
public void FunctionOfA2() { }
}
public class ClassB
{
public void FunctionOfB1() { }
public void FunctionOfB2() { }
}
Now you'll have your group of function together like
new PrincipleClass.InstanceOfClassA.FunctionOfA1();
new PrincipleClass.InstanceOfClassB.FunctionOfB1();
Note - This may also not be a best solution but this is way better than using Nested types.
I'm having trouble with the Service Reference Manager in my Silverlight application substituting the get and set methods of a property with a generic one.
My example: I have a Rule class in my Service that has three public properties that all use the same private member.
[DataContract]
public class RulesReadable
{
[DataMember]
private bool? m_passed;
...
[DataMember]
public bool? State
{
get { return m_passed; }
set { m_passed = value; }
}
[DataMember]
public bool HasPassed
{
get { return (m_passed == true) ? true : false; }
set { m_passed = value; }
}
[DataMember]
public bool HasFailed
{
get { return (m_passed == false) ? true : false; }
set { m_passed = !value; }
}
}
When I call the service, get this data type back, and try to get/set the properties I find that each property has been given its own variable instead of sharing one between the three. If I go to the definition of the class on the Silverlight side I see that this is in fact what has happened:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Manager.RulesReadable", Namespace="http://schemas.datacontract.org/2004/07/MyWebApp.Services")]
public partial class ManagerRulesReadable : object, System.ComponentModel.INotifyPropertyChanged {
private bool HasFailedField;
...
[System.Runtime.Serialization.DataMemberAttribute()]
public bool HasFailed {
get {
return this.HasFailedField;
}
set {
if ((this.HasFailedField.Equals(value) != true)) {
this.HasFailedField = value;
this.RaisePropertyChanged("HasFailed");
}
}
}
...
}
How do I get the class on the Silverlight side to behave like the class on the Service side?
First add the assemblies that these classes are in as references to your Silverlight project. When creating your service reference select the "Reuse types in referenced assemblies" checkbox and either reuse all referenced assemblies or pick and choose specific assemblies to reuse. The assemblies that are referenced by the service directly (and any dependencies) will then be a part of the Silverlight application as well.
Don't use Service References. They are evil. If you google "Silverlight WCF without Service Reference" you will find several good tutorials.
This should be simple, but I can't find anything out there.
I have a class in one assembly (a shared library -- it's a set of proxy classes for a Web Service)
I have a class in another assembly (web project)
There is a class called "Profile" which is in the Proxy assembly.
There is a set of classes that "use" a Profile in the web project.
When there is no user logged in, a GenericProfile is used.
Following the principle of "separation of concerns"....
The Proxy assembly is used by other projects and is concerned with only the Web Service stuff.
The web project just has web stuff in there
However, now there is this need for a "GenericProfile" -- think of it as "Guest User".
The logical thing to do is to build an interface called IProfile and cause both classes to derive from it. But that would create a circular dependency between the two assemblies.
The next best idea is to create a 3rd assembly called MyInterfaces and put the IProfile in there -- but that causes a violation of the Separation of Concerns principle in my opinion. At the very least, one instance of this problem seems too small a reason to spring for making an extra module in my solution.
Enter the wrapper class -- or the Composite wrapper class (whatever you want to call it)
I'm looking for something that ends up generating something like this below. Is there a tool or Visual Studio extension that will do it? Maybe a .tt file?
namespace WebProject
{
public interface IProfile
{...}
class MyWrapperClass : IProfile
{
Proxy.Profile _profile;
public MyWrapperClass(Proxy.Profile proxy)
{
_profile = proxy;
}
public string IProfile.Property1{ get { return _profile.Property1; } set { _profile.Property1 = value; } }
public string IProfile.Property2{ get { return _profile.Property2; } set { _profile.Property2 = value; } }
public string IProfile.Property3{ get { return _profile.Property3; } set { _profile.Property3 = value; } }
}
}
In Visual Studio 2017
Create your class
namespace WebProject
{
public interface IProfile
{...}
class MyWrapperClass : IProfile
{
private IProfile _wrapped;
}
}
locate your cursor on the IProfile of class MyWrapperClass : IProfile and hit ctrl-. select Implement interface through _wrapped. No need for ReSharper.
I don't completely understand what you are trying to accomplish, but below is how I would generate a wrapper class with ReSharper.
Personally if my employer doesn't want to pay for ReSharper, I buy it. It makes me a better developer. I strongly suggest you consider acquiring it as an investment in your career. Anti-Disclaimer - I am not at all connected with or sponsored by ReSharper.
add the interface to the class you wish to be the wrapping class
class MyWebElement : IWebElement { }
Find/Click "Delegate implementation of "YourInterfaceHere" to a new field
Select your options
Click finish and enjoy your new class
class MyWebElement : IWebElement
{
private IWebElement _webElementImplementation;
public IWebElement FindElement(By #by)
{
return _webElementImplementation.FindElement(#by);
}
public ReadOnlyCollection<IWebElement> FindElements(By #by)
{
return _webElementImplementation.FindElements(#by);
}
public void Clear()
{
_webElementImplementation.Clear();
}
public void SendKeys(string text)
{
_webElementImplementation.SendKeys(text);
}
public void Submit()
{
_webElementImplementation.Submit();
}
public void Click()
{
_webElementImplementation.Click();
}
public string GetAttribute(string attributeName)
{
return _webElementImplementation.GetAttribute(attributeName);
}
public string GetCssValue(string propertyName)
{
return _webElementImplementation.GetCssValue(propertyName);
}
public string TagName
{
get { return _webElementImplementation.TagName; }
}
public string Text
{
get { return _webElementImplementation.Text; }
}
public bool Enabled
{
get { return _webElementImplementation.Enabled; }
}
public bool Selected
{
get { return _webElementImplementation.Selected; }
}
public Point Location
{
get { return _webElementImplementation.Location; }
}
public Size Size
{
get { return _webElementImplementation.Size; }
}
public bool Displayed
{
get { return _webElementImplementation.Displayed; }
}
}
If I was faced with your original problem, I'd put IProfile in your shared library, alongside the Profile class. Your web project can then implement the GenericProfile class that it needs, nothing else needs to know about it, and other clients of the library can do the same as needed. It would also be useful for testing the library.
I am working on a webform project, where I want to implement MVP Pattern.
I have gone through few articles and project based on MVP. It seems fine to me.
At most of the places, If there is any need to display error message, it has been made
a method in the view interface. I am giving an example here for clarity.
public interface IAdminSettingsView
{
string Name { get; set; }
string Password { get; set; }
string Email { get; set; }
void ShowErrorMessage(string errorMessage);
}
here is my control implementing IAdminSettingsView
public partial class AdminSettingsEdit : BaseControl, IAdminSettingsView
{
private AdminSettingsPresenter _adminSettingsPresenter;
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
_adminSettingsPresenter = new AdminSettingsPresenter(this);
}
protected void BtnSave_Click(object sender, EventArgs e)
{
_adminSettingsPresenter.Save();
}
#region Implementation of IAdminSettingsView
public string Name
{
get { return AdminName.Text; }
set { AdminName.Text = value; }
}
public string Password
{
get { return AdminPassword.Text; }
set { AdminPassword.Text = value; }
}
public string Email
{
get { return AdminEmail.Text; }
set { AdminEmail.Text = value; }
}
public void ShowErrorMessage(string errorMessage)
{
lblErrorMessage.Text = errorMessage;
}
#endregion
}
here is my presenter
public class AdminSettingsPresenter
{
public AdminSettingsPresenter(IAdminSettingsView view)
{
_view = view;
}
private IAdminSettingsView _view;
public void Save()
{
try
{
//Trying Save Data Here
}
catch (Exception exception )
{
_view.ShowErrorMessage("Couldnt Save Data");
}
}
}
My question is, how can I seperate Error Related messages into a different Interface and then make a communication between them. for example if I have an interface
interface IShowErrorMessage
{
//somemethod here
}
how to use this interface to work with my main IAdminSettingsView interface.
Your help will be appreciated. If there is any better solution to this problem, I would love to hear.
Regards
Parminder
At the lowest level (for example the Utility DLL) I put the classes for error handling. One of which is a interface that forms can implement. On startup the software registers the form implementing the interface with the low level DLL. This form can be defined at the highest level (the EXE).
When an error occurs at any level of the software the appropriate calls can be made to the error framework and if a form implemented the display error interface then a form will display at that point.
As an aside I do this as well for status and progress messages. There is a IStatusDisplay interface and a IProgressDisplay interface. The EXE registers the forms or classes that implement these interfaces
First, in IShowErrorMessage, define the properties/methods needed to show an error message.
Something like:
interface IShowErrorMessage
{
void Show(string errorMessage);
}
Next, your view will implement that interface.
The view's implementation of Show(string) will setup a literal.
The presenter will remain unchanged.
Create some unit tests and you are good!
Hope it helps.