Coded UI C# - Why I cannot access a ApplicationUnderTest class method using object app.Launch("app path here"); - coded-ui-tests

I would like to understand why #2 is not allowed. I cannot access class method using "app" object?
ApplicationUnderTest app = ApplicationUnderTest.Launch("app exe path here");
ApplicationUnderTest app = new ApplicationUnderTest();
app.Launch("app exe path here");
Note: I have not touched C# or any other programming language since 6 years so my concepts are a bit shaky. Please correct me If I have used wrong terminology. Meanly I wanted to know if I want to call Launch() method why I cannot do it via object app.Launch();

The ApplicationUnderTest class is static, meaning it cannot be instantiated (what you're doing when you call = new ApplicationUnderTest()). Thus, the methods that you're trying to access can only be accessed in the static class. MSDN is a good resource for a more in depth explanation of class accessibility types.

Here's how I do it:
public static ApplicationUnderTest LaunchApplicationUnderTest(string applicationPath,string processName,
bool closeOnPlaybackCleanup)
{
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 0)
{
_application = ApplicationUnderTest.FromProcess(processes[0]);
}
else
{
_application = ApplicationUnderTest.Launch(applicationPath);
_application.CloseOnPlaybackCleanup = closeOnPlaybackCleanup;
}
return _application;
}

Related

Inline C# Object Creation in F#

I'm trying to interop with a C# library in some F# code. Consider the following C# as though it were the library I'm working with (or skip below to see the actual library I'm working with first):
public class Options
{
public Options(string name)
{
Name = name;
}
public string Name { get; }
public string SomeProperty { get; set; }
}
public class ServiceBuilder
{
public ServiceBuilder ApplyOptions(Options options)
{
//Apply Options in some way
return this;
}
public TheService Build()
{
return new TheService();
}
}
public class TheService
{
}
I'm then trying to create the service but keeping it fluent I have the following F# code:
//Valid Approach but not inlined :(
let options = Options("Test")
options.SomeProperty <- "SomeValue"
let theService =
ServiceBuilder()
.ApplyOptions(options)
.Build();
//Invalid Approach because SomeProperty is not virtual
let theService2 =
ServiceBuilder()
.ApplyOptions({
new Options("Test2") with
member _.SomeProperty = "SomeValue2"
})
.Build()
Is there some way for me to initialize the way I want to inline in F# where I try to create "theService2"? In C# I'd just use Object Intializers. F# Object Expressions are out because I don't have control of the class to make the property virtual.
For additional context in what my C# above is mocking, I'm specifically trying to create a Serilog Logger using the Serilog.Sinks.ElasticSearch nuget package and do roughly the code below in F# (again, inlined if possible):
var loggerConfig = new LoggerConfiguration()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200") ){
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
});
In F# you can also assign values to properties at initialization, so to create your Options instance in a single expression you can do the following:
Options("Test", SomeProperty="SomeValue")
For direct translation from C# - property initializers are the way to go, as suggested in #rob.earwaker's answer.
However, note also that in F# everything is an expression. There are no "statements" like in C#, every piece of code has a result of some kind. And this also goes for "composite", so to say, pieces of code, such as let blocks. This means, even if you don't feel like using property initializers, you can still do the initialization inline:
let service =
ServiceBuilder()
.ApplyOptions(
let o = Options("Test")
o.SomeProperty <- "SomeValue"
o
)
.Build()
Or using let .. in and a semicolon to put everything on the same line:
let service =
ServiceBuilder()
.WithOptions(let o = Options("Test") in o.SomeProperty <- "SomeValue"; o)
.Build()
Unlike C#, this approach also works for factoring out initializations into reusable pieces:
let service =
ServiceBuilder()
.WithOptions(let o = Options("bar") in mutateSomeOptions(o); mutateOtherOptions(o); o)
.Build()

how to create models in nodejs

I am a .net developer, trying my hands on nodejs web api development.
I was wondering that whether we can create models in nodejs same as we create in asp.net web api.
For example
public class BaseResponse
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
public class MovieResponse : BaseResponse
{
public int MovieId { get; set; }
public string MovieName { get; set; }
}
This is how we do it in c#.
How can i create such models in nodejs.
Any npm package available?
There's good news and there's bad news. The bad news is the concept of classes and inheritance as you know it from other languages is not supported. The good news, JavaScript attempted to do something along that idea (although it did a miserable job implementing it). Below is an example of the code you provided using JavaScript:
function BaseResponse(success, errorMessage) {
this.success = success;
this.errorMessage = errorMessage;
}
function MovieResponse(success, errorMessage, movieId, movieName) {
BaseResponse.call(this, success, errorMessage); // Call the base class's constructor (if necessary)
this.movieId = movieId;
this.movieName = movieName;
}
MovieResponse.prototype = Object.create(BaseResponse);
MovieResponse.prototype.constructor = MovieResponse;
/**
* This is an example of an instance method.
*/
MovieResponse.prototype.instanceMethod = function(data) { /*...*/ };
/**
* This is an example of a static method. Notice the lack of prototype.
*/
MovieResponse.staticMethod = function(data) {/* ... */ };
// Instantiate a MovieResponse
var movieResInstance = new MovieResponse();
Mozilla has really good documentation on JavaScript and classes. In the code above, you are creating two functions BaseResponse and MovieResponse. Both of these functions act as constructors for an object with the appropriate "class" when you use the new keyword. You specify that MovieResponse inherits from BaseMovie with MovieResponse.prototype =Object.create(BaseResponse). This effectively sets MovieResponse's prototype chain equal to BaseResponse's prototype chain. You'll notice that immediately after setting MovieResponse's prototype chain I have to set its constructor to point to MovieResponse. If I didn't do this, every time you tried to initialize a MovieResponse, JavaScript would try to instead instantiate a BaseResponse (I told you they did a horrible job).
The rest of the code should be relatively straightforward. You can create instance methods on your brand new, shiny class by defining them on the prototype chain. If you define a function on BaseResponse that is not defined on MovieResponse but call the function on an instance of MovieResponse, JavaScript will "crawl" the prototype chain until it finds the function. Static methods are defined directly on the constructor itself (another weird feature).
Notice there is no concept of types or access modifiers (public/private). There are runtime tricks that you can implement to enforce types, but it's usually unnecessary in JavaScript and more prone to errors and inflexibility than adding such checks may justify.
You can implement the concept of private and protected members of a class in a more straightforward method than types. Using Node's require(), and assuming you wanted a private function called privateMethod you could implement it as:
function privateMethod() { /* privateMethod definition */ }
// Definition for MovieResponse's constructor
function MovieResponse() { /*...*/ }
module.exports = MovieResponse;
I will add a somewhat required commentary that I do not agree with: it is unnecessary to use inheritance in JavaScript. JavaScript uses a notion coined "duck typing" (if it looks like a duck and sounds like a duck, its a duck). Since JavaScript is weakly typed, it doesn't care if the object is a BaseResponse or MovieResponse, you can call any method or try to access any field you want on it. The result is usually an error or erroneous/error-prone code. I mention this here because you may come across the notion and its supporters. Know that such programming is dangerous and results in just bad programming practices.

claimsprincipalpermission is not verified for parent class if child class has already attribute

I have a base base and derived classes like
[ClaimsPrincipalPermission(SecurityAction.Demand, Resource = "Base",
Operation = "Create")]
public abstract class Base
{
}
[ClaimsPrincipalPermission(SecurityAction.Demand, Resource = "Derived",
Operation = "Create")]
public class Derived : Base
{
}
It never comes to authorization manager to check for base class if I am creating a derived class object.
public class AuthorisationManager : ClaimsAuthorizationManager
{
public override bool CheckAccess(AuthorizationContext context)
{
var resource = context.Resource.First().Value;
var action = context.Action.First().Value;
return context.Principal.HasClaim(resource, action);
}
}
Any idea how can I implement that it should come to check for derived and base class both? Actually I want that if any one of them has permission, object should be allowed to create.
Is that your real scenario? Or do you want to use that in the context of some app framework like ASP.NET?
But IIRC this is the behavior of CAS permissions - you could try the same with good old PrincipalPermission to see if the behavior wrt derivation is the same.

C# 4, COM interop and UPnP: A trying triumvirate

I'm trying to write a bit of code (just for home use) that uses UPnP for NAT traversal, using C# 4 and Microsoft's COM-based NAT traversal API (Hnetcfg.dll).
Unfortunately (or perhaps fortunately) the last time I had to do COM interop in .NET was sometime around the last ice age, and I seem to be fundamentally confused about C#'s use of dynamic types for interop and how to write a callback (so that the COM server calls my managed code).
Here's an exciting few lines of code:
// Referencing COM NATUPNPLib ("NATUPnP 1.0 Type Library")
using System;
using NATUPNPLib;
class NATUPnPExample
{
public delegate void NewNumberOfEntriesDelegate(int lNewNumberOfEntries);
public static void NewNumberOfEntries(int lNewNumberOfEntries)
{
Console.WriteLine("New number of entries: {0}", lNewNumberOfEntries);
}
public static void Main(string[] args)
{
UPnPNAT nat = new UPnPNAT();
NewNumberOfEntriesDelegate numberOfEntriesCallback = NewNumberOfEntries;
nat.NATEventManager.NumberOfEntriesCallback = numberOfEntriesCallback;
nat.StaticPortMappingCollection.Add(4555, "TCP", 4555, "192.168.0.1", true, "UPnPNAT Test");
// Presumably my NewNumberOfEntries() method should be called by the COM component about now
nat.StaticPortMappingCollection.Remove(4555, "TCP");
}
}
In the above code, the Add and Remove calls work absolutely fine. Terrific.
The trouble is, I would also like to know when the number of port mapping entries have changed, and to do so I need to register a callback interface (INATEventManager::put_NumberOfEntriesCallback), which must support the INATNumberOfEntriesCallback or IDispatch interfaces. VS2012's object browser describes INATEventManager::put_NumberOfEntriesCallback thusly:
dynamic NumberOfEntriesCallback { set; }
Right, so I was under the impression that in C# 4 I shouldn't have to decorate anything with fancy attributes and that I can register my callback simply by jamming a delegate into INATEventManager::put_NumberOfEntriesCallback in a vulgar manner and leaving .NET to worry about IDispatch and clear up the mess; but it appears that I'm terribly wrong.
So, er... What should I do to ensure my NewNumberOfEntries method is called?
I'm also slightly concerned that I can write nat.NATEventManager.NumberOfEntriesCallback = 1; or nat.NATEventManager.NumberOfEntriesCallback = "Sausages"; without an exception being thrown.
It seems that I was able to make it work. Two options - with a custom interface "INATNumberOfEntriesCallback" (which does not seem to be declared in the type library btw, you need to declare it yourself) and using plain dispatch with DispId(0). The conversion to the IDispatch/IUnknown is preformed by the framework automatically. So:
Option 1.
Declare the INATNumberOfEntriesCallback and make a callback class which implements that interface (the tricky part is Guid - it comes from the "Natupnp.h" file, and does not seem to appear to be in the type library).
// declare INATNumberOfEntriesCallback interface
[ComVisible(true)]
[Guid("C83A0A74-91EE-41B6-B67A-67E0F00BBD78")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface INATNumberOfEntriesCallback
{
void NewNumberOfEntries(int val);
};
// implement callback object
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class CallbackNewNumberOfEntries : INATNumberOfEntriesCallback
{
public void NewNumberOfEntries(int val)
{
Console.WriteLine("Number of entries changed: {0}", val);
}
}
class NATUPnPExample
{
public static void Main(string[] args)
{
var nat = new UPnPNAT();
nat.NATEventManager.NumberOfEntriesCallback = new CallbackNewNumberOfEntries();
nat.StaticPortMappingCollection.Add(4555, "TCP", 4555, "192.168.0.1", true, "UPnPNAT Test");
// Presumably my NewNumberOfEntries() method should be called by the COM component about now
nat.StaticPortMappingCollection.Remove(4555, "TCP");
}
}
Option 2.
Use plain dispatch. The documentation says that you can use dispid(0) and it should be called, with 4 (!) parameters (see the remarks section in docs). So basically the following construction seems to work in "dispatch" way:
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class CallbackDisp
{
[DispId(0)]
public void OnChange(string updateType, object obj, object name, object val)
{
Console.WriteLine("{0}: {1} = {2}", updateType, name, val);
}
}
class NATUPnPExample
{
public static void Main(string[] args)
{
var nat = new UPnPNAT();
nat.NATEventManager.NumberOfEntriesCallback = new CallbackDisp();
nat.StaticPortMappingCollection.Add(4555, "TCP", 4555, "192.168.0.1", true, "UPnPNAT Test");
// Presumably my NewNumberOfEntries() method should be called by the COM component about now
nat.StaticPortMappingCollection.Remove(4555, "TCP");
}
}
I had the same problem you had, and since there isn't much help on the topic your posting helped tremendously! It wouldn't let me comment on your answer because I don't have enough points or whatever but your answer is the best, but doesn't quite work how I thought it would.
nat.NATEventManager.ExternalIPAddressCallback = new CallbackDisp();
Works, using the same dispatch, and will tell you when the external IP changes. HOWEVER,
nat.NATEventManager.NumberOfEntriesCallback = new CallbackDisp();
only reports UPnP map changes from these conditions: A.) It was added/removed by the NATUPnP instance.. In this case:
nat.StaticPortMappingCollection.Add();
OR B.) it was already mapped when the instance was created:
var nat = new UPnPNAT();
As an example, if Utorrent was running when you started your program and you you had something to block the program from exiting(Console.WriteLine();) for example.. When you exit Utorrent the callback would fire, and notify you of the map changes. Which is exactly what I wanted in the first place. However, if you re-open Utorrent, or any other app that uses UPnP it will NOT fire the callback, and will not notify you of the change.
Needless to say it has been very frustrating. If you figure it out please share! I know I can easily implement the functionality by polling the StaticPortMappingCollection at a given interval, but it seems a little 'hacky' to me.

How to force the order of Installer Execution

I have been building a new .NET solu­tion with Cas­tle per­form­ing my DI.
Its now at the stage where i would like to con­trol the order in which my installers run. I have built indi­vid­ual classes which implement IWind­sorIn­staller to han­dle my core types — eg IRepos­i­tory, IMap­per and ISer­vice to name a few.
I see that its suggested i implement my own Installer­Fac­tory (guessing i just override Select) in this class.
Then use this new factory in my call to:
FromAssembly.InDirectory(new AssemblyFilter("bin loca­tion"));
My ques­tion — when over­rid­ing the save method — what is the best way to force the order of my installers.
I know its already solved but I couldn't find any example on how to actually implement the InstallerFactory so here's a solution if anyone is googling for it.
How to use:
[InstallerPriority(0)]
public class ImportantInstallerToRunFirst : IWindsorInstaller
{
public void Install(IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
{
// do registrations
}
}
Just add the InstallerPriority attribute with a priority to your "install-order-sensitive" classes. Installers will be sorted by ascending. Installers without priority will default to 100.
How to implement:
public class WindsorBootstrap : InstallerFactory
{
public override IEnumerable<Type> Select(IEnumerable<Type> installerTypes)
{
var retval = installerTypes.OrderBy(x => this.GetPriority(x));
return retval;
}
private int GetPriority(Type type)
{
var attribute = type.GetCustomAttributes(typeof(InstallerPriorityAttribute), false).FirstOrDefault() as InstallerPriorityAttribute;
return attribute != null ? attribute.Priority : InstallerPriorityAttribute.DefaultPriority;
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class InstallerPriorityAttribute : Attribute
{
public const int DefaultPriority = 100;
public int Priority { get; private set; }
public InstallerPriorityAttribute(int priority)
{
this.Priority = priority;
}
}
When starting application, global.asax etc:
container.Install(FromAssembly.This(new WindsorBootstrap()));
You can call your installers in the order they need to be instantiated in Global.asax.cs or e.g. in a Bootstrapper class, which is called from Global.asax.cs.
IWindsorContainer container = new WindsorContainer()
.Install(
new LoggerInstaller() // No dependencies
, new PersistenceInstaller() // --""--
, new RepositoriesInstaller() // Depends on Persistence
, new ServicesInstaller() // Depends on Repositories
, new ControllersInstaller() // Depends on Services
);
They are instantiated in this order, and you can add a breakpoint after and check the container for "Potentially misconfigured components".
If there are any, check their Status->details, if not, it's the correct order.
This solution is quick and easy, the documentation mentions using a InstallerFactory Class for tighter control over your installers so if you have a ton of installers the other solution may fit better. (Using code as convention should not require tons of installers?)
http://docs.castleproject.org/Windsor.Installers.ashx#codeInstallerFactorycode_class_4
In the end i had to use InstallerFactory and implement the ordering rules as suggested previously by returning the IEnumerable<Type> with my specific order

Resources