I found some sample code posted at
https://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4/4519371a77ed4a74?hl=en&pli=1
for self installing a Windows Service. I am in C# on fx 4.0. Trying
to figure out where I went off the rails...
My questions:
I created a Win Service project. In program.cs / main() I pretty much
copied the code example. It appears most everything is working
except launching a console window if I am in DEBUG mode (passing in -
c of course). For some reason the console window never opens.
The other challenge I had was the call to StartUp() / ShutDown() in
the console portion would not compile. I ended up have to initialize
my service object and then call it.
I am getting the following error when the Console.ReadKey() method is called:
Cannot read keys when either
application does not have a console or
when console input has been redirected
from a file. Try Console.Read.
My code and stuff:
An image of my project structure:
NOTE: I was duplicating the startup sequence in the TestHarness when
in DEBUG mode. If/when I get this working I will be dropping that
from the solution. The Library project is where the majority of my
code lives.
PROGRAM.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ComponentModel;
using System.Configuration.Install;
using System.Collections;
using RivWorks.FeedHandler.Service;
namespace RivWorks.FeedHandler
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static int Main(string[] args)
{
bool install = false, uninstall = false, console = false, rethrow = false;
try
{
foreach (string arg in args)
{
switch (arg)
{
case "-i":
case "-install":
install = true; break;
case "-u":
case "-uninstall":
uninstall = true; break;
case "-c":
case "-console":
console = true; break;
default:
Console.Error.WriteLine("Argument not expected: " + arg);
break;
}
}
if (uninstall)
{
Install(true, args);
}
if (install)
{
Install(false, args);
}
if (console)
{
Console.WriteLine("Starting...");
FeedListener fl = new FeedListener();
fl.StartUp();
Console.WriteLine("System running; press any key to stop");
Console.ReadKey(true);
fl.ShutDown();
Console.WriteLine("System stopped");
}
else if (!(install || uninstall))
{
rethrow = true; // so that windows sees error...
ServiceBase[] services = { new Service.FeedListener() };
ServiceBase.Run(services);
rethrow = false;
}
return 0;
}
catch (Exception ex)
{
if (rethrow) throw;
Console.Error.WriteLine(ex.Message);
return -1;
}
}
static void Install(bool undo, string[] args)
{
try
{
Console.WriteLine(undo ? "uninstalling" : "installing");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
}
else
{
inst.Install(state);
inst.Commit(state);
}
}
catch
{
try
{
inst.Rollback(state);
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
}
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.NetworkService;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = "Provides a service to listen for, then import, feed files from various sources.";
this.DisplayName = "RIVWorks Feed Handler (.NET 4.0)";
this.ServiceName = "FeedListener";
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
}
}
}
FEEDLISTENER.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using sysIO = System.IO;
using RivWorks.FeedHandler;
using System.Collections;
using RivWorks.FeedHandler.Library;
using System.Threading;
namespace RivWorks.FeedHandler.Service
{
public partial class FeedListener : ServiceBase
{
#region Declarations
static private List<string> _keys = new List<string>();
static private System.Threading.Timer _clock = null;
static private FileSystemWatcher _watcher;
static private RivWorks.FeedHandler.Library.QueueHandler _qHandler = null;
static private bool _isDequeueing = false;
#endregion
#region Constructor
public FeedListener()
{
InitializeComponent();
}
#endregion
#region Internal Methods
internal void StartUp() {...}
internal void ShutDown() {...}
#endregion
#region Start/Stop
protected override void OnStart(string[] args)
{
StartUp();
}
protected override void OnStop()
{
ShutDown();
}
#endregion
#region Event Handlers
static void qHandler_QueuesGrew() {...}
static void qHandler_QueuesShrunk() {...}
static void qHandler_QueuesChanged() {...}
static void fileCreatedOrChanged(object sender, sysIO.FileSystemEventArgs e) {...}
#endregion
#region Private Methods
private static void Tick(object state) {...}
private static void WriteToEventLog(Exception ex, EventLogEntryType eventLogEntryType) {...}
private static void WriteToEventLog(string message, EventLogEntryType eventLogEntryType) {...}
#endregion
}
}
And I found my answer! My project properties were set to Windows App instead of Console App. DOH! (Project Properties > Application Tab > Output type:)
Also.. instead of using -console arg, you can identify its console by using Environment.UserInteractive, which will be false when running as service, but true when running the EXE directly.
You can also have a look at this: http://www.thedavejay.com/2012/04/self-installing-c-windows-service-safe.html
It allows you to debug as a console application, and install the same app as a windows service without having to change the project type.
Related
I have created new CustomView.xib file and associated to code-behind class. But when i try to initialise the view, the app getting crashed as below mentioned error.
MonoTouch: Could not install sigaction override, unexpected sigaction implementation.
NSBundle.MainBundle.LoadNib("CustomView", this, null); // App crashes here.
CS class file:
public partial class CustomView : UIView
{
public CustomView(IntPtr handle) : base(handle)
{
}
public override void AwakeFromNib()
{
base.AwakeFromNib();
}
}
Designer class:
[Register("CustomView")]
partial class CustomView
{
[Outlet]
UIKit.UIView contentView { get; set; }
void ReleaseDesignerOutlets ()
{
if (contentView != null) {
contentView.Dispose ();
contentView = null;
}
}
}
Note:
Build Action is set to interfaceDefinition.
File owner of the xib is set the class name "CustomView"
AwakeFromNib override method also implemented.
Thanks in advance.
Edited:
We came across with similar kind of issue after a long time but with different exceptions says "Object Null Reference" on "contentView" in the AwakeFromNib method. App crashes when you try to access the ContentView inside the AwakeFromNib method. This happened only on iOS 9.3.x. The following fix might help someone if they face the same kind of issue.
[Export("initWithFrame:")]
public SampleHeaderView(CGRect frame) : base(frame)
{
Initialize();
}
[Export("initWithCoder:")]
public SampleHeaderView(NSCoder coder) : base(coder)
{
Initialize();
}
public override void AwakeFromNib()
{
base.AwakeFromNib();
}
private void Initialize()
{
if (this.ContentView != null)
{
this.ContentView.BackgroundColor = UIColor.Red();
}
}
I've got the most simple windows store program. It just runs the white-color window till the Quit (as well as the most simple Win32 application would do).
ref class ApplicationViewSource sealed : IFrameworkViewSource {
public:
virtual IFrameworkView^ CreateView() {
return ref new WindowsStoreApp::MainView();
}
};
[MTAThread]
int main(Array<String^>^ args) {
CoreApplication::Run(ref new ApplicationViewSource());
return 0;
}
ref class MainView sealed : IFrameworkView {
public:
virtual void Initialize(CoreApplicationView^ AppView);
virtual void SetWindow(CoreWindow^ Window);
virtual void Load(String^ EntryPoint);
virtual void Run();
virtual void Uninitialize();
void OnActivated(CoreApplicationView^, IActivatedEventArgs^);
};
void MainView::Initialize(CoreApplicationView^ AppView) {
AppView->Activated += ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &MainView::OnActivated);
}
void MainView::SetWindow(CoreWindow^ window) {
window->PointerCursor = ref new CoreCursor(CoreCursorType::Hand, 0);
}
void MainView::Load(String^ EntryPoint) {
}
void MainView::Run() {
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
}
void MainView::Uninitialize() {
}
void MainView::OnActivated(CoreApplicationView^, IActivatedEventArgs^) {
CoreWindow::GetForCurrentThread()->Activate();
}
So... What I need to do next ? As for Win32 project I could create some graphical user interface components with CreateWindow(Ex) function as windows of the specific window-classes. With the windows store app API I can't figure out how to add any visuals.
Manual only gives hints about adding ones with code to existing XAML page, allready been connected to the window.
I am working with an application that will call OData Service. I tried the Simple.OData.Client but I can't get it working..
Here is the code that I try
var client = new ODataClient("http://packages.nuget.org/v1/FeedService.svc/");
var packages = await client.FindEntriesAsync("Packages?$filter=Title eq 'Simple.OData.Client'");
foreach (var package in packages)
{
Console.WriteLine(package["Title"]);
}
I get this error
Error 1 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
using System;
using Simple.OData.Client;
namespace ODataClient
{
class Program
{
static void Main(string[] args)
{
new Manager().GetData();
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ODataClient
{
public class Manager
{
private readonly Simple.OData.Client.ODataClient client;
public Manager()
{
client = new Simple.OData.Client.ODataClient("http://packages.nuget.org/v1/FeedService.svc/");
}
public void GetData()
{
try
{
IEnumerable<IDictionary<string, object>> response = GetPackages().Result;
foreach (var package in response)
{
Console.WriteLine(package["Title"]);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private async Task<IEnumerable<IDictionary<string, object>>> GetPackages()
{
var packages = await client.FindEntriesAsync("Packages?$filter=Title eq 'Simple.OData.Client'");
return packages;
}
}
}
This is even simpler. We need SimpleQuery method, since we cannot add the async keyword to the Main or any entry point methods.
static async void SimpleQuery()
{
var client = new ODataClient("http://blahb...lah.svc/");
try
{
var packages = await client.FindEntriesAsync("Products");
foreach (var package in packages)
{
Console.WriteLine(package);
}
} catch (Exception e)
{
Console.WriteLine("Simple Query " + e);
}
}
static void Main(string[] args)
{
Console.WriteLine("Press Enter when the job is completed");
SimpleQuery();
Console.ReadLine();
}
in my asp.net mvc projet, i tried to implement a membership provider to manage accounts and roles
i'm facing this stack
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.
acually i added this ligne to my Startup.Auth.cs
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); in order to allow
i tried to change my global.asax.cs as bellow
using decidata.mennilik.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebMatrix.WebData;
namespace decidata.mennilik
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
private static object _initializerLock = new object();
private static bool _isInitialized;
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<ApplicationDbContext>(null);
try
{
using (var context = new ApplicationDbContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
}
but i'm having a problem in
AuthConfig.RegisterAuth();
did i miss something ?
I am developing a small SMS server in C# and want to make an asynchronous listener that processes requests sent to an SMS object (username, message, etc.). I want to create the asynchronous listener as a class library. Here is the code:
using System;
using System.Net;
using System.Threading;
namespace AListener
{
public class CAListener
{
public CAListener()
{
Thread listener = new Thread(new ParameterizedThreadStart(RequestListener));
listener.Start(new string[] { "http://*:11600/" });
}
private ManualResetEvent stopListener = new ManualResetEvent(false);
private object lockListener = new object();
private bool newRequest = false;
public void StopListener()
{
stopListener.Set();
}
public void RequestListener(object parameter)
{
string[] prefixes = parameter as string[];
HttpListener listener = new HttpListener();
foreach (string prefix in prefixes)
{
listener.Prefixes.Add(prefix);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
while (!stopListener.WaitOne(10))
{
lock (lockListener)
{
if (newRequest)
{
result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
newRequest = false;
}
}
result.AsyncWaitHandle.WaitOne(10);
}
listener.Close();
}
public void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
lock (lockListener)
{
newRequest = true;
}
}
}
}
I have a UI form where I obtain AListener object and everything here is OK.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AListener;
namespace ZNSMS
{
public partial class ZNSMSServer : Form
{
public ZNSMSServer()
{
InitializeComponent();
}
CAListener ca = null;
private void button1_Click(object sender, EventArgs e)
{
ca.StopListener();
}
private void ZNSMSServer_Load(object sender, EventArgs e)
{
ca = new CAListener();
}
}
}
But when I press the Button (I just want to stop the listener) - for some reason listener.Stop() kills my main UI Form ZNSMSServer. When I comment listener.Stop() it's working, but I think that's not the proper way and I cannot understand why calling listener.Stop() can impact (in this case Close?) the calling object - in this case ZNSMSServer.
If anyone has dealt with this kind of issue before, I would really appreciate it.
Thanks in advance.