Any links to a good template for a windows service? (looking for C# code)
Something that has the basic functionality that I could extend.
It is a little clear what you are looking for. The Windows Service project type in Visual Studio creates a project with the templates you need to get going with a basic windows service.
You can also look at this article from C# Online. It goes over a few ideas and has a few parts to the article. (Note; the page seems to loads a little slow so be patient)
I use VS2005 and I like to start with the basic template.
Modify the Service class to this
using System;
using System.ServiceProcess;
using System.Timers;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
//better is to read from settings or config file
private readonly Double _interval = (new TimeSpan(1, 0, 0, 0)).TotalMilliseconds;
private Timer m_Timer;
public Service1()
{
InitializeComponent();
Init();
}
private void Init()
{
m_Timer = new Timer();
m_Timer.BeginInit();
m_Timer.AutoReset = false;
m_Timer.Enabled = true;
m_Timer.Interval = 1000.0;
m_Timer.Elapsed += m_Timer_Elapsed;
m_Timer.EndInit();
}
private void m_Timer_Elapsed(object sender, ElapsedEventArgs e)
{
//TODO WORK WORK WORK
RestartTimer();
}
private void RestartTimer()
{
m_Timer.Interval = _interval;
m_Timer.Start();
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
Start();
}
protected override void OnStop()
{
Stop();
base.OnStop();
}
public void Start()
{
m_Timer.Start();
}
public new void Stop()
{
m_Timer.Stop();
}
}
}
Install using InstallUtil.exe, after you have added an installer : http://msdn.microsoft.com/en-us/library/ddhy0byf(VS.80).aspx
Keep the Init function small and fast, otherwise your service will not start with an error that the service did not respond in a timely fashion
Hope this helps
Related
I have an MvvmCross application, and I am using the MvvmCross ViewModel Lifecycle functions to realize
certain actions when the view appears, moves to background, and moves to foreground:
public override async void ViewAppeared()
public override async void ViewAppearing()
public override void ViewDisappearing()
public override void ViewDisappeared()
public override void ViewDestroy(bool viewFinishing)
Those functions work great in my Android device.
But for iOS they do not get fired when the application moves to background or to foreground
(although, except for ViewDestroy, they fire when navigating between the screens in the app in iOS)
1)Is that the intended behavior, or I am missing something?
2)If so, what is the approach we have to follow, when there are actions that we need to do when the app moves to foreground/background (like stopping timers)?
Should we maybe have two implementations one for android, and one for ios? I also tried the ViewDidDisappear method in the MvxBaseViewController,
still it is not activated when the app moves to background. There is a way in Xamarin/MvvmCross to hook into the native ios applicationDidEnterBackground?
Edit:
I have tried Ranjit´s answer, but it seems to be a problem subscribing to the message. Here is my test code:
AppDelegate.cs:
public override void DidEnterBackground(UIApplication application)
{
base.DidEnterBackground(application);
var message = new LocationMessage(
this,
34
);
_messenger = Mvx.IoCProvider.Resolve<IMvxMessenger>();
_messenger.Publish(message);
}
Base class:
public abstract class GenericMvxViewModel : MvxViewModel
{
private IMvxMessenger _messenger;
protected GenericMvxViewModel()
{
// other stuff
_messenger = Mvx.IoCProvider.Resolve<IMvxMessenger>();
_messenger.Subscribe<LocationMessage>(OnLocationMessage);
}
protected virtual void OnLocationMessage(LocationMessage locationMessage){}
}
ViewModel:
public class MyClassViewModel : GenericMvxViewModel
{
protected override void OnLocationMessage(LocationMessage locationMessage)
{
Debug.WriteLine(locationMessage.Lat);
}
}
The message is published in the AppDelegate.cs, but the OnLocationMessage method in the viewmodel is never executed.
Also I was wondering how to unsubscribe properly the message. ViewDestroy seems the most natural place, but as mentioned before it is never called on iOS
Your code should work. I am using same kind of function in my app it was working fine
GenericMvxViewModel Code
private MvxSubscriptionToken _locationEventToken;
public override void ViewAppeared()
{
SubscribeBaseLocationEvent();
base.ViewAppeared();
}
public override void ViewDisappeared()
{
if (StaticStorage.IsApplicationInForeground)
{
UnSubscribeBaseLocationEvent();
}
base.ViewDisappeared();
}
public void SubscribeBaseLocationEvent()
{
if (_locationEventToken == null)
{
_locationEventToken = Messenger.Subscribe<LocationMessage>(OnLocationMessage);
}
}
public void UnSubscribeBaseLocationEvent()
{
if (_locationEventToken != null)
{
Messenger.Unsubscribe<LocationMessage>(_locationEventToken);
_locationEventToken = null;
}
}
AppDelegate Code
public override void DidEnterBackground(UIApplication application)
{
base.DidEnterBackground(application);
StaticStorage.IsApplicationInForeground = false;
_messenger.Publish(new LocationMessage( this, 34 ));
}
public override void WillEnterForeground(UIApplication application)
{
StaticStorage.IsApplicationInForeground = true;
}
Android
protected override void OnResume()
{
StaticStorage.IsApplicationInForeground = true;
base.OnResume();
}
protected override void OnStop()
{
StaticStorage.IsApplicationInForeground = false;
base.OnStart();
}
When application is moving from one view to other view, we need to unsubscribe the event. But not when application moves to background. So, IsApplicationInForeground flag will help to solve this issue for android. Because for android when application goes to background ViewDisappeared will be called.
In my case. I have one common activity which holds remaining all views of fragment. So, I have added this code in common activity. Not sure in your case how you are using. But implementation will be similar.
Little background: I am working on a topology using Apache Storm, I thought why not use dependency injection in it, but I was not sure how it will behave on cluster environment when topology deployed to cluster. I started looking for answers on if DI is good option to use in Storm topologies, I came across some threads about Apache Spark where it was mentioned serialization is going to be problem and saw some responses for apache storm along the same lines. So finally I decided to write a sample topology with google guice to see what happens.
I wrote a sample topology with two bolts, and used google guice to injects dependencies. First bolt emits a tick tuple, then first bolt creates message, bolt prints the message on log and call some classes which does the same. Then this message is emitted to second bolt and same printing logic there as well.
First Bolt
public class FirstBolt extends BaseRichBolt {
private OutputCollector collector;
private static int count = 0;
private FirstInjectClass firstInjectClass;
#Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
collector = outputCollector;
Injector injector = Guice.createInjector(new Module());
firstInjectClass = injector.getInstance(FirstInjectClass.class);
}
#Override
public void execute(Tuple tuple) {
count++;
String message = "Message count "+count;
firstInjectClass.printMessage(message);
log.error(message);
collector.emit("TO_SECOND_BOLT", new Values(message));
collector.ack(tuple);
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declareStream("TO_SECOND_BOLT", new Fields("MESSAGE"));
}
#Override
public Map<String, Object> getComponentConfiguration() {
Config conf = new Config();
conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, 10);
return conf;
}
}
Second Bolt
public class SecondBolt extends BaseRichBolt {
private OutputCollector collector;
private SecondInjectClass secondInjectClass;
#Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
collector = outputCollector;
Injector injector = Guice.createInjector(new Module());
secondInjectClass = injector.getInstance(SecondInjectClass.class);
}
#Override
public void execute(Tuple tuple) {
String message = (String) tuple.getValue(0);
secondInjectClass.printMessage(message);
log.error("SecondBolt {}",message);
collector.ack(tuple);
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
}
Class in which dependencies are injected
public class FirstInjectClass {
FirstInterface firstInterface;
private final String prepend = "FirstInjectClass";
#Inject
public FirstInjectClass(FirstInterface firstInterface) {
this.firstInterface = firstInterface;
}
public void printMessage(String message){
log.error("{} {}", prepend, message);
firstInterface.printMethod(message);
}
}
Interface used for binding
public interface FirstInterface {
void printMethod(String message);
}
Implementation of interface
public class FirstInterfaceImpl implements FirstInterface{
private final String prepend = "FirstInterfaceImpl";
public void printMethod(String message){
log.error("{} {}", prepend, message);
}
}
Same way another class that receives dependency via DI
public class SecondInjectClass {
SecondInterface secondInterface;
private final String prepend = "SecondInjectClass";
#Inject
public SecondInjectClass(SecondInterface secondInterface) {
this.secondInterface = secondInterface;
}
public void printMessage(String message){
log.error("{} {}", prepend, message);
secondInterface.printMethod(message);
}
}
another interface for binding
public interface SecondInterface {
void printMethod(String message);
}
implementation of second interface
public class SecondInterfaceImpl implements SecondInterface{
private final String prepend = "SecondInterfaceImpl";
public void printMethod(String message){
log.error("{} {}", prepend, message);
}
}
Module Class
public class Module extends AbstractModule {
#Override
protected void configure() {
bind(FirstInterface.class).to(FirstInterfaceImpl.class);
bind(SecondInterface.class).to(SecondInterfaceImpl.class);
}
}
Nothing fancy here, just two bolts and couple of classes for DI. I deployed it on server and it works just fine. The catch/problem though is that I have to initialize Injector in each bolt which makes me question what is side effect of it going to be?
This implementation is simple, just 2 bolts.. what if I have more bolts? what impact it would create on topology if I have to initialize Injector in all bolts?
If I try to initialize Injector outside prepare method I get error for serialization.
In a microservice environment I need to construct a framework for Contract based testing.
I'm currently investigatingh how to isolate a single service from it's external dependencies inorder to execute the Provider tests.
What I need to do is:
Keep the WebApi project intact
Start an instance of the WepApi with some config-differences
Mock out selected dependencies
My Solution structure is this:
Case-Solution/
├── src/
| ├──Case.Api
| └──Case.Application
├── test/
| ├──Case.Api.Unittest
| ├──(other tests)
| ├──Case.Pact.CunsumerTest
| └──Case.Pact.ProviderTest
I've read this guide about Pact Tests in dotnet.
Focusing on Case.Pace.ProviderTest, I need to start Case.Api programmatically from Case.Pact.ProviderTest (and another WebHost for Pact it self) and substitute some of it dependencies.
So far I got this:
public class ProviderApiTests : IDisposable
{
private string ProviderUri { get; }
private string PactServiceUri { get; }
private IWebHost PactServiceWebHost { get; }
private IWebHost CasesWebHost { get; }
private ITestOutputHelper OutputHelper { get; }
public static IConfiguration CaseConfiguration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT" ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
public ProviderApiTests(ITestOutputHelper output)
{
OutputHelper = output;
ProviderUri = "http://localhost:9000";
PactServiceUri = "http://localhost:9001";
CasesWebHost = WebHost.CreateDefaultBuilder()
.UseUrls(ProviderUri)
.UseStartup<CaseStartup>()
.UseConfiguration(CaseConfiguration)
.Build();
CasesWebHost.Start();
PactServiceWebHost = WebHost.CreateDefaultBuilder()
.UseUrls(PactServiceUri)
.UseStartup<ProviderServerStartup>()
.Build();
PactServiceWebHost.Start();
}
[Fact]
public void EnsureProviderApiHonoursPactWithConsumer()
{
//Arrange
var config = new PactVerifierConfig
{
Outputters = new List<IOutput>
{
new XUnitOutput(OutputHelper)
},
Verbose = true,
CustomHeader = new KeyValuePair<string, string>("X-apikey", "XXX")
};
//Act //Assert
IPactVerifier pactVerifier = new PactVerifier(config);
pactVerifier.ProviderState($"{PactServiceUri}/provider-states")
.ServiceProvider("CaseProvider", ProviderUri)
.HonoursPactWith("CaseConsumer")
.PactUri(#"..\..\..\..\..\pacts\caseconsumer-caseprovider.json")
.Verify();
}
#region IDisposable Support
//IDisposable code
#endregion
}
In the line containing .UseStartup<CaseStartup>() I've simply copied Startup.cs from Case.Api and changed the needed dependencies, which works fine.
But I want a more generic solution. It's doesn't feel right to just copy code and call it a day :) because it is not generic and reusable for the other services.
So I kept digging, and came up with the following.
Add Controllers from other assembly
I realised, that starting a IWebhost, using StartUp from a different assembly, doesn't automagically add controller from that assembly. This needs to be done explicitly. So I did this:
public void ConfigureServices(IServiceCollection services)
{
var assembly = Assembly.Load("Case.Api");
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddApplicationPart(assembly)
.AddControllersAsServices();
......
}
Awesome!!! So far so good.
Next issue:
Replace dependencies:
Reding this article, I created the extension method for replacing dependencies:
public static void Replace<TRegisteredType>(this IServiceCollection services, TRegisteredType replcement)
{
for (var i = 0; i < services.Count; i++)
{
if (services[i].ServiceType == typeof(TRegisteredType))
{
services[i] = new ServiceDescriptor(typeof(TRegisteredType), replcement);
}
}
}
So I'm able to replace the dependencies I want like so: (in this case a QueryHandler)
public void ConfigureServices(IServiceCollection services)
{
.....
var queryHandler = Substitute.For<IQueryHandler<Query, QueryResult>>();
queryHandler.Handle(Arg.Any<Query>()).Returns(new QueryResult(...));
services.Replace(queryHandler);
......
}
But this doesn't solve my issue with copied code.
My wet dream is to be able to use Startup.cs from Case.Api and somehow tweak the DI to replace the dependencies, without having all the redundant code.
Any input would be highly appriciated.
Thanks :)
I had a similar situation also using Pact.net. But I wanted to use TestServer, unfortunately Pact.net does not have support for httpClient ( Verifying pact with in-memory API ). At the end I use a combination of two libraries, probably not the best to validate all scenarios. I took the consumer part of Pact.net to generate the contract and the Verifier part of Pactify to verify if the provider is honoring the contract. The Verifier requires code modification to be compatible with the Pact.net contract though.
I also used your code example to replace dependencies for mocks using moq.
[TestClass]
public class EndpointShouldHonorContract
{
private HttpClient httpClient;
private ApiWebApplicationFactory<Startup> testServerFactory;
Mock<IRepository> repositoryMock =
new Mock<IRepository>();
public EndpointShouldHonorContract()
{
//omitting code... Creation of mock Data Set https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking?redirectedfrom=MSDN#testing-query-scenarios
repositoryMock.Setup(s => s.GetQueryable()).Returns(mockDataSet.Object);
testServerFactory = new ApiWebApplicationFactory<Startup>(services =>
{
services.Replace<IRepository>(repositoryMock.Object);
});
httpClient = testServerFactory.CreateClient();
}
[TestMethod]
public async Task HonorContract()
{
// this is my modified Pactify Verifier
await MyModifiedPactify
.VerifyPact
.PactVerifier
.Create(httpClient)
.Between("consumer", "provider")
//location of contract, there is also an option where you can get contracts from a http location
.RetrievedFromFile(#"\Pacts")
.VerifyAsync();
}
}
Web Api Factory : here I use your extension to replace dependencies
public class ApiWebApplicationFactory<TStartUp>
: WebApplicationFactory<TStartUp> where TStartUp: class
{
Action<IServiceCollection> serviceConfiguration { get; }
public ApiWebApplicationFactory(Action<IServiceCollection> serviceConfiguration) : base()
{
this.serviceConfiguration = serviceConfiguration;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
if (this.serviceConfiguration != null)
{
builder.ConfigureServices(this.serviceConfiguration);
}
}
}
internal static class ServiceCollectionExtensions
{
public static void Replace<TRegisteredType>(this IServiceCollection services, TRegisteredType replacement)
{
for (var i = 0; i < services.Count; i++)
{
if (services[i].ServiceType == typeof(TRegisteredType))
{
services[i] = new ServiceDescriptor(typeof(TRegisteredType), replacement);
}
}
}
}
I am trying to view a hosted PDF file with the default Android pdf viewer in my App with the following code
var intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Uri.Parse("http://sample/url.pdf"), "application/pdf");
intent.SetFlags(ActivityFlags.ClearTop);
Android.Content.Context.StartActivity(intent);
I have used this code in a Native project, so I know that it works within an Android activity. For Xamarin Forms, is there a way for me to start an Android activity from a content page, and vice versa?
You can use DependencyService to implement this function:
INativePages in PCL:
public interface INativePages
{
void StartActivityInAndroid();
}
Implement the interface in Xamarin.Android:
[assembly: Xamarin.Forms.Dependency(typeof(NativePages))]
namespace PivotView.Droid
{
public class NativePages : INativePages
{
public NativePages()
{
}
public void StartAc()
{
var intent = new Intent(Forms.Context, typeof(YourActivity));
Forms.Context.StartActivity(intent);
}
}
}
Start an Android Activity in PCL :
private void Button_Clicked(object sender, EventArgs e)
{
Xamarin.Forms.DependencyService.Register<INativePages>();
DependencyService.Get<INativePages>().StartAc();
}
Forms.Context is obsolete now.
The workaround is to instantiate the current context in Main activity class of Android project as under:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static Xamarin.Forms.Platform.Android.FormsAppCompatActivity Instance { get; private set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
Instance = this;
}
And retrieve the local context in your NativePages StartAc() method as under:
public void StartAc()
{
var intent = new Intent(MainActivity.Instance, typeof(YourActivity));
MainActivity.Instance.StartActivity(intent);
}
Create an class for this function in an android project:
public class PdfLauncher : IPdfLauncher
{
public void LaunchPdf(string url)
{
//implementation
}
}
Create an interface in a portable project
public interface IPdfLauncher
{
void LaunchPdf(string url);
}
Add a property to your viewmodel so you can call the function from your portable project
public IPdfLauncher PdfLauncher {get;set;}
Add the interface to your viewmodel constructor and pass in an instance that you create in your android main activity. You can now call android code from your xforms commands and, if you ever add iOS or UWP you can simply implement that interface in those projects and pass them in at runtime. I use an injection framework from MVVM to automate creating these platform specific implementations, and I'd recommend you look into it if you find yourself doing these often.
Anyone knows how to develop an add-in for PowerDesigner? I was reading the document of PowerDesigner about how to create an ActiveX Add-in, it says "The ActiveX must implement a specific interface called IPDAddIn to become a PowerDesigner add-in.". But I don't know where the interface IPDAddIn is, and how to implement it ?
Here is the online document
I have this old example, which could give some ideas, even if not everything it up-to-date.
using PdAddInTypLib;
namespace MineSpace
{
[ComVisible(true)]
[Guid("A6FA0D26-77E8-4DD3-B27E-F4050C3D5188")]
public class Launcher : IPdAddIn {
// Main() manages the console or GUI interface
// the PdAddIn interface is managed by an instance of Launcher
[ComVisible(false)]
[STAThread]
public static void Main(String[] args) {
}
public Launcher() {
_app = null;
}
// IPdAddIn implementation
public void Initialize(Object anApplication) {
try {
_app = (PdCommon.Application)anApplication;
}
catch (Exception e) {
// process
}
}
public void Uninitialize() {
}
public String ProvideMenuItems(String aMenu, Object anObj) {
return "";
}
public int IsCommandSupported(String aMenu, Object anObj, String aCommand) {
return 0;
}
public void DoCommand(String aMenu, Object anObj, String aCommand) {
}
private PdCommon.Application _app;
}
}
with the corresponding part in the class declaration:
[HKEY_CLASSES_ROOT\MyPlugin.Launcher]
#="MyPlugin.Launcher"
[HKEY_CLASSES_ROOT\MyPlugin.Launcher\CLSID]
#="{13749EFC-1ADA-4451-8C47-FF0B545FF172}"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}]
#="MyPlugin.Launcher"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}\InprocServer32]
#="C:\windows\System32\mscoree.dll"
"ThreadingModel"="Both"
"Class"="MyPlugin.Launcher"
"Assembly"="MyPlugin, Version=1.0.1402.33688, Culture=neutral, PublicKeyToken=null"
"RuntimeVersion"="v1.0.3705"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}\ProgId]
#="MyPlugin.Launcher"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}\Implemented Categories\{62C8FE65-4EBB-45E7-B440-6E39B2CDBF29}]
And the corresponding code to declare the add-in in PowerDesigner. If the File value is present, PowerDesigner could call DllRegisterServer on it, if the component is not yet registered.
[HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerDesigner 10\Addins\MyPlugin Launcher]
"Enable"="No"
"Class"="MyPlugin.Launcher"
"Type"="ActiveX"
"File"="d:\\myplugin\\myplugin.exe"