Using custom application class for global variables in Xamarin c# - c#

I'm using a custom application class for storing my global variables but i don't seem to be able to get it to work.
here is my class :
#if DEBUG
[assembly: Application(Debuggable = true)]
#else
[assembly: Application(Debuggable=false)]
#endif
internal class MyApp : Application
{
private Customer loginedCustomer;
private List<string> sefareshItems;
public Boolean isOnline { set; get; }
public MyApp(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
}
public override void OnCreate()
{
// If OnCreate is overridden, the overridden c'tor will also be called.
base.OnCreate();
}
public void SetLCustomer(Customer customer)
{
loginedCustomer = customer;
}
public Customer GetLCustomer()
{
return loginedCustomer;
}
public void SetItems(List<string> items)
{
sefareshItems = items;
}
public List<string> GetItems()
{
return sefareshItems;
}
}
and since i could find any documentation about using such class and by looking at the java examples both of these code gives me the "unable to cast from source to destination" exception
MyApp m = (MyApp)Application;
and
Myapp m=(MyApp)ApplicationContext;
could you help me figure this out?
and i have another question.is it a good practice to get or set variables using methods or using a public static one?
thank you

Application is a class definition.
You will need an instance of Application to cast as MyApp.
Make MyApp a static Class.
Make your method's static methods.
Then you can simply access Replace all references to Application with MyApp, and use it that way.

Related

Having similar method name with same parameter inside a class just with Interface name change

Just came across a code where a method with the same name is implemented within the class twice.
Once with the name only
Second with the Interface name and then the method name.
What is the concept called? I am unable to find the right direction. And if someone can explain it that would be great.
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
var obj = new AuthClass();
Console.WriteLine(obj.Login());
var obj2 = new AuthClass() as IAuth;
Console.WriteLine(obj2.Login());
//------------
}
}
public class AuthClass : IAuth
{
public string Login()
{
return "Method : You can be a developer";
}
string IAuth.Login()
{
return "Interface: Please learn the concepts";
}
}
public interface IAuth
{
string Login();
}

Get the current filename from a Visual Studio text adornment extension

I'm new to VS extension development. I'm currently working with the text adornment sample in VS 2015 and have been able to get coloured boxes showing correctly. Now I want to extend the sample so the adornment only appears on certain file names.
Googling has said I can use ITextDocumentFactoryService.TryGetTextDocument interface with the IWpfTextView.TextBuffer property to get a filename. This sounds great. But I can't seem to actually get the interface.
In my class I have:
[Import]
public ITextDocumentFactoryService TextDocumentFactoryService = null;
But it is always NULL.
How can I get ITextDocumentFactoryService?
namespace Test
{
internal sealed class TestAdornment
{
[Import]
public ITextDocumentFactoryService TextDocumentFactoryService = null;
public TestAdornment(IWpfTextView view)
{
}
/// <summary>
/// Adds the scarlet box behind the 'a' characters within the given line
/// </summary>
/// <param name="line">Line to add the adornments</param>
private void CreateVisuals(ITextViewLine line)
{
// TextDocumentFactoryService is NULL
}
}
}
TextAdornmentTextViewCreationListener.cs
[Export(typeof(IWpfTextViewCreationListener))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal sealed class TextAdornmentTextViewCreationListener : IWpfTextViewCreationListener
{
[Import]
public ITextDocumentFactoryService textDocumentFactory { get; set; }
//...
public void TextViewCreated(IWpfTextView textView)
{
new TextAdornment(textView, textDocumentFactory);
}
}
TextAdornment.cs
internal sealed class TextAdornment
{
private readonly ITextDocumentFactoryService textDocumentFactory;
private ITextDocument TextDocument;
//...
public TextAdornment(IWpfTextView view, ITextDocumentFactoryService textDocumentFactory)
{
//...
this.textDocumentFactory = textDocumentFactory;
//...
}
internal void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
var res = this.textDocumentFactory.TryGetTextDocument(this.view.TextBuffer, out this.TextDocument);
if (res)
{
//this.TextDocument.FilePath;
}
else
{
//ERROR
}
}
}
You got it via dependency injection.
As you only submitted 2 lines of code I suppose your context is set up, either explicitly by you, either implicitly by some environment who calls your code.
You should declare property instead of field
It should be public
Then automagically big brother will set it for you before you first access to it.
...or...
You can use constructor injection instead. Note: It is not you who will create your class.
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
[ImportingConstructor]
internal YourClass(ITextDocumentFactoryService textDocumentFactoryService)
{
_textDocumentFactoryService = textDocumentFactoryService;
}
So in my case I needed to put the import statement into the AdornmentTextViewCreationListener. This implements IWpfTextViewCreationListener and is the one with the following decorating the class.
[Export(typeof(IWpfTextViewCreationListener))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
Then I can add
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
[ImportingConstructor]
to my class

Get a reference to the object that called a method?

I have a dll that includes:
public abstract class Module
{
internal int ID;
public abstract void ModuleStart();
}
public void function1() {}
public void function2() {}
//etc...
And then I have another dll that references the above dll and has:
class MyModule : Module
{
public override void ModuleStart()
{
function1();
}
}
What I'd like to be able to do is have function1 known the value of the calling module's ID, without it being passed in. Is there a way to do this? Basically what I'm trying to do is, the main Module DLL is loaded up, a method is run that loads in the second dll, uses reflection to make sure it has a child of Module, assigns it an ID and runs ModuleStart. MyModule can then do what it needs, calling functions from the first dll in order to access internal protected memory, but when the functions are called they need to know the ID of the Module that called them. Is this possible? MyModule has no knowledge of its ID, nor an ability to change it.
.NET 4.5 adds some functionality to do something similar to this with the CallerMemberNameAttribute. Here's a sample from the docs:
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
A few people have suggested using the call stack to get the module information. If you want to get the type of object that made the call, it's not too bad. Unfortunately there is no feasible (ie: simple, portable and functional) method to extract instance information from data in the call stack. There are several reasons why, including problems with optimization inlining methods that then do not show on the stack... which can interfere with calling type detection as well.
Given this fact, the short answer is that you have to provide a Module object as a parameter to the methods you are calling in the DLL. The method suggested by #p.s.w.g is one way of achieving this, but has the disadvantage of potentially polluting the symbol space of the Module class. This can be solved by having the Module class implement a protected or public API member that exposes the functions you want to provide:
public abstract class Module
{
internal int ID;
public class APIWrapper
{
Module module;
public APIWrapper(Module module)
{
this.module = module;
}
public void method1() { apiimpl.method1(this.module); }
public int method2() { return apiimpl.method2(this.module); }
}
public readonly APIWrapper API;
public Module()
{
ID = generate_module_identity();
API = new APIWrapper(this);
}
public abstract void ModuleStart();
}
internal static class apiimpl
{
public static void method1(Module module) { ... }
public static int method2(Module module) { ... }
}
The other developers can then use it this way:
class MyModule : Module
{
public override void ModuleStart()
{
API.method1();
}
}
This encapsulates the methods that your DLL exposes, without introducing too much pollution of the symbol space of the Module class hierarchy.
[opinion type="my" value="YMMV"]
However, I suggest that you seriously reconsider using this type of abstraction. If the methods you are calling require some information about the specific Module instance that is calling them, it should be clear in the method's parameters. Encouraging your team to follow guidelines that lead to clarity can be more important than finding ways to abstract away small details.
[/opinion]
If what you really want is just to retrieve the ID at run-time, without passing any arguments into function1, you can use inherited methods:
public abstract class Module
{
internal int ID;
public abstract void ModuleStart();
protected void function1()
{
System.Console.WriteLine ("function1 called from module {0}", this.ID);
}
}
Then, from your other modules, calling function1 looks as simple as this:
class MyModule : Module
{
public override void ModuleStart()
{
this.function1(); // the 'this.' is not required
}
}
However, I get the sense from your comments that you want to make keep these functions separate from your Module class, since you are routinely adding new functions. You can do almost the exact same thing using extension methods to maintain the appearance of not passing any parameters:
public abstract class Module
{
internal int ID;
public abstract void ModuleStart();
}
public static class ModuleExtensions
{
public static void function1(this Module module)
{
innerFunction1(module.ID);
}
internal static void innerFunction1(int ID)
{
System.Console.WriteLine ("function1 called from module {0}", ID);
}
}
Then, from your other modules, calling function1 looks as simple as this:
class MyModule : Module
{
public override void ModuleStart()
{
this.function1(); // the 'this.' is required
}
}

Auto-generate a Wrapper class in C# using Composition

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.

Internal global property..bad smell?

I have run into a bit of a desgin issue with some code that I have been working on:
My code basic looks like this:
Main COM wrapper:
public class MapinfoWrapper
{
public MapinfoWrapper()
{
Publics.InternalMapinfo = new MapinfoWrapper();
}
public void Do(string cmd)
{
//Call COM do command
}
public string Eval(string cmd)
{
//Return value from COM eval command
}
}
Public static class to hold internal referance to wrapper:
internal static class Publics
{
private static MapinfoWrapper _internalwrapper;
internal static MapinfoWrapper InternalMapinfo
{
get
{
return _internalwrapper;
}
set
{
_internalwrapper = value;
}
}
}
Code that uses internal wrapper instance:
public class TableInfo
{
public string Name {
get { return Publics.InternalMapinfo.Eval("String comman to get the name"); }
set { Publics.InternalMapinfo.Do("String command to set the name"); }
}
}
Does this smell bad to anyone? Should I be using a internal property to hold a reference to the main wrapper object or should I be using a different design here?
Note: The MapinfoWrapper object will be used by the outside world, so I don't really want to make that a singleton.
You are reducing the testability of your TableInfo class by not injecting the MapInfoWrapper into the class itself. Whether you use a global cache of these MapInfoWrapper classes depends on the class -- you need to decide whether it is necessary or not, but it would improve your design to pass a wrapper into TableInfo and use it there rather than referencing a global copy directly inside TableInfo methods. Do this in conjunction with the definition of an interface (i.e., "refactor to interfaces").
I would also do lazy instantiation in the getter(s) of Publics to make sure the object is available if it hasn't already been created rather than setting it in the constructor of MapInfoWrapper.
public class TableInfo
{
private IMapinfoWrapper wrapper;
public TableInfo() : this(null) {}
public TableInfo( IMapinfoWrapper wrapper )
{
// use from cache if not supplied, could create new here
this.wrapper = wrapper ?? Publics.InternalMapInfo;
}
public string Name {
get { return wrapper.Eval("String comman to get the name"); }
set { wrapper.Do("String command to set the name"); }
}
}
public interface IMapinfoWrapper
{
void Do( string cmd );
void Eval( string cmd );
}
public class MapinfoWrapper
{
public MapinfoWrapper()
{
}
public void Do(string cmd)
{
//Call COM do command
}
public string Eval(string cmd)
{
//Return value from COM eval command
}
}
internal static class Publics
{
private static MapinfoWrapper _internalwrapper;
internal static MapinfoWrapper InternalMapinfo
{
get
{
if (_internalwrapper == null)
{
_internalwrapper = new MapinfoWrapper();
}
return _internalwrapper;
}
}
}
Now, when you test the TableInfo methods, you can mock out the MapInfoWrapper easily by providing your own implementation to the constructor. Ex (assuming a hand mock):
[TestMethod]
[ExpectedException(typeof(ApplicationException))]
public void TestTableInfoName()
{
IMapinfoWrapper mockWrapper = new MockMapinfoWrapper();
mockWrapper.ThrowDoException(typeof(ApplicationException));
TableInfo info = new TableInfo( mockWrapper );
info.Do( "invalid command" );
}
I thought about adding this to my original response, but it is really a different issue.
You might want to consider whether the MapinfoWrapper class needs to be thread-safe if you store and use a cached copy. Anytime you use a single, global copy you need to consider if it will be used by more than one thread at a time and build it so that any critical sections (anywhere data may be changed or must be assumed to not change) are thread-safe. If a multithreaded environment must be supported -- say in a web site -- then this might argue against using a single, global copy unless the cost of creating the class is very high. Of course, if your class relies on other classes that are also not thread-safe, then you may need to make your class thread-safe anyway.

Categories