Search This Blog

Thursday, November 20, 2014

Creating and installing Windows Service in a development enviroment.

I hadn't worked on a Windows Service in 4 years so I forgot some of the fun necessary to create a new Windows Service.

Useful References
SC.exe - http://technet.microsoft.com/en-us/library/cc754599.aspx

Using SC.exe 

Settings Description for Service:


Steps to create a new Windows service
(Using Windows 7 Pro and Visual Studio 2013 Ultimate)

  • Add new project to solution
  • Select C# Windows, Windows Service template
  • Name project SoftwareUpdaterService and create.
      Note: VS 2013 template creates the necessary service base code to be a functional service:

     public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }

   

  •  Build project and confirmed ..\SoftwareUpdaterService\bin\Debug\ SoftwareUpdaterService.exe
  • (I forgot this step) use SC to install the service
  • Open VS 2013 command prompt, switch to  bin\debug folder
  • Run this command:
SC create MergeSoftwareUpdater displayname= "Merge Healthcare Software Updater Service" binpath= "C:\CAP30\Tools\Software Updater Service\SoftwareUpdater\SoftwareUpdaterService\bin\Debug\SoftwareUpdaterService.exe" start= auto


  Creates registry entry for service:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services

MergeSoftwareUpdater <= service key.


  • Open Services manager and service should appear.
  • Added Installer class to service project (lifted it from an existing project)
  • Now InstallUtil.exe will install the project as a service.
     InstallUtil.exe SoftwareUpdaterService.exe
(Added) using System.Net;
              using System.ServiceProcess;
        private void InitializeComponent()
        {
            this.serviceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller = new System.ServiceProcess.ServiceInstaller();
            // 
            // deliveryServiceProcessInstaller
            // 
            this.serviceProcessInstaller.Password = null;
            this.serviceProcessInstaller.Username = null;
            // 
            // deliveryServiceInstaller
            // 
            this.serviceInstaller.ServiceName = "Merge Healthcare Software Updater Service";
            this.serviceInstaller.Description = "Allows software updates to be scheduled and run automatically.";
            this.serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
            // 
            // ProjectInstaller
            // 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
                                                                                      this.serviceProcessInstaller,
                                                                                      this.serviceInstaller});
        }

        public override void Install(IDictionary stateSaver) 
        {                    
            if (Context.Parameters["user"] != null && Context.Parameters["user"].Length != 0 && Context.Parameters["password"].Length != 0 && Context.Parameters["password"] != null) 
            {
                string user = Context.Parameters["user"];
                // if the user starts with . then we want to replace that with the local machine's actual hostname
                if (user.StartsWith(".")) 
                {
                    user = Dns.GetHostName() + user.Substring(1, user.Length - 1);
                }
                serviceProcessInstaller.Username = user;
                serviceProcessInstaller.Password = Context.Parameters["password"];
                serviceProcessInstaller.Account = ServiceAccount.User;
            } 
            else 
            {
                serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            }
            
            base.Install(stateSaver);
        }




Saturday, November 15, 2014

File sharing rant

Recently, I solved file sharing dilemma for (DRC 3.0)
I started a write up that included a short review/rant of file sharing which I am re-posting here.

  • DropBox - Limits free shares to a daily download limit.  Very poor security from the get go and I am still not convinced they have solved all of their security woes.  I would never use DropBox for any extremely important. 
  • OneDrive (SkyDrive); Microsoft has really grown this product well except they seem to want to exclude normal application developers from using these shares. Size limits, poorly published API which is only convenient for mobile device developers.  It has a very cool integration for Windows 8+ which I make good use of but it makes a very poor direct download file share.
  • Google Drive: Google also provides a decent online file share.  Microsoft has caught up and passed Google though.  Typical Google launch a really good idea then cut back the development staff supporting it unless it is essential to this quarter's earnings.  Google needs a new mission statement... Don't be evil was a good start (although they have strayed from this). Better mission would be support what you create and people actually use and don't be stupid.  iGoogle, Blogger, Web Search API are just 3 things that jump mind.  Google Drive makes it difficult to do direct downloads.
  • NetGear - The fine people that brings us the routers, DSL and cable modems most of us use. Even they have a file sharing solution.  Problem here is using the latest router, I can't share using SSL because THESE GENIUSES WON'T FIX THE ROOT CERTIFICATE ISSUES WITH MYNETGEAR.COM.  Very cool USB device shares would be a very cool way of sharing files on the down-low only works with https but I could not get a proper certificate through NetGear.  Not sure what the issue: just stupid (don't discount this just look into you uPnP feature on your router; btw  DO NOT USE UPNP  the feature) or unwilling to provider the correct solution.  Either I use Netgear, I do not trust netgear.

Thursday, October 23, 2014

Send To Toys: Copy File names from selected files in Windows Explorer

I found a cool solution for this problem

Send To Toys: http://www.gabrieleponti.com/software/index.html#sendtotoys

From Site:
Description

Send To Toys is an enhancement of the Send To system menu.

- Send To Toys Control Panel Applet allows you to manage the Send To system menu content, and configure the various Send To Toys settings.

- "Add to Send To menu" and "Remove from Send To menu" allows you to personalize the Send To system menu for drives, folders, and programs.

- Send To "Clipboard (as content)" copies the content of the file to the clipboard. Supports the most common text and image file formats.

- Send To "Clipboard (as name)" copies the name of the file or files to the clipboard. Hold down the CTRL key to change the settings for this extension.

- Send To "Clipboard" command line utility copies the output of a command to the clipboard. Type SENDTOCLIP /? at the command prompt for more information.

- Send To "Command Prompt" opens a DOS console window, setting the current directory to the selected folder. If the selection was a file, the folder containing the file will be the active directory and the name of the file will be typed for you at the prompt. Hold down the CTRL key to change the active directory to a different folder. Hold down the SHIFT key to force the use of the COMMAND.COM regardless of the Windows version.

- Send To "Default Mail Recipient" creates a new e-mail with attachments and predefined defaults for the recipients, subject, and message. Hold down the CTRL key to change the settings for this extension.

- Send To "Favorites" adds a shortcut to your Favorites list. Hold down the CTRL key for the "Add Favorite" dialog.

- Send To "Folder..." sends a file or files to another folder, you will be shown a dialog box that lets you choose where the files should be copied, moved, or have a shortcut created. To move the files press and hold down the SHIFT key. To create a shortcut hold down the SHIFT and CTRL keys.

- Send To "Quick Launch" adds a shortcut to the Quick Launch toolbar.

- Send To "Recycle Bin" sends a file or files to the Recycle Bin. Hold down the CTRL key to perform a file shredding.

- Send To "Run..." sends a file or files to the Run command dialog.

Freeware. For Windows XP, 2003 Server, Vista, Windows 7, and 2008 Server. 

Monday, September 29, 2014

Microsoft.WebApplication.targets" was not found error when building VS 2012 solution on Jenkins build server


Encountered an odd error in an automated build.
One solution was failing with this error:

Here is the error:
The imported project "E:\Build\RXS\external\microsoft\Microsoft.WebApplication.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk. E:\Build\RXS\DirectAdministrativeApplication\service\config.service.VS2012.csproj


Open the solution locally (not on the build server) no problem.
Open the solution on the build server, one project failed to load....
Ah, a missing reference perhaps....

Based on this link:


I copied the project file
And changed the following V9.0 to V11.0
These are the imports in the .proj file:
 
  v9.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

  v9.0\WebApplications\Microsoft.WebApplication.targets')" Project="..\..\external\microsoft\Microsoft.WebApplication.targets" />

The build machine never had VS 2008 installed on it but the reference in the project came off a dev machine and was only missing off.

Lucky blind guess worked....
Solution opens and builds now.

Saturday, August 16, 2014

Virtual Router for Windows 8


I tried several attempts to setup my win8.1 laptop as a wifi hotspot.
None of the straight forward ways worked for me.

Here is what I found that worked:

http://virtualrouterplus.com/

http://virtualrouterplus.com/submit/virtualrouterplussetup.exe

Saturday, August 2, 2014

Mouse not working correctly in Chrome in a Windows 8 laptop

Here is the oddest mouse I've seen in years....

Open Chrome, search google, open URL in new tab.
Left click on tab and it closes !!!?

Found this issue: Cause low battery in wireless mouse except I'm not using a wireless mouse.
https://productforums.google.com/forum/#!topic/chrome/Op4Zema2hyo

Unplug the mouse and plugged it back in and everything is good.

Very Odd.

Tuesday, June 24, 2014

ApplicationPoolIdentity ran web service cannot write to the Event log


http://support.thycotic.com/KB/a220/giving-application-pool-access-to-event-log.aspx

(From Article) states giving NETWORK SERVICE permission to eventLog

1. Determine the account that is running Secret Server. This can be done by logging in to Secret Server, clicking on "Administration", and then on "Diagnostics". Look for any of the "Thread Identity" labels. These will contain the identity of Secret Server (often NT AUTHORITY\NETWORK SERVICE).

You can also determine the identity by logging in and navigating to http://yoursecretserverurl/Installer.aspx

The first step of this installer/updater page will tell you the application pool identity.

2. Open the Registry Editor on the machine running Secret Server (start->run-regedit)

3. On the left, navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog

4. Right click on the "eventlog" folder in your registry editor and select "Permissions"

5. Give the account running Secret Server Full Control to this folder

Saturday, May 10, 2014

AutoMapper


AutoMapper:
(from automapper.org)

AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another.

https://github.com/AutoMapper/AutoMapper
http://automapper.org/

Another essential open source library...

For Microsoft Visual Studio 2013, you can install Automapper from the nuget manager.

Amazing little code needed to convert one class into another.
Typically, DTOs deserialized from data source are often less then ideal to use display data in UI or databind.
Automapper saved me 4-5hrs today and I have my code working in under 30 mins.


    public class LegoCategory : INotifyPropertyChanged
    // ReSharper restore InconsistentNaming
    {
        private bool _inUse;

        [Column]
        public Int32 CatID { get; set; }

        [Column]
        public string CatDesc { get; set; }

        [Column]
        public bool InUse
        {
            get { return _inUse; }
            set
            {
                if (value == _inUse) return;
                _inUse = value;
                OnPropertyChanged("InUse");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }


    public class LegoCategoryDto 
    // ReSharper restore InconsistentNaming
    {

        [DataMember,Column]
        public object CatID { get; set; }

        [DataMember, Column]
        public string CatDesc { get; set; }

        [DataMember, Column]
        public object InUse { get; set; }
        

    }

//Code fragment...
//fetches data from SQLite => LegoCategoryDTO converts to LegoCategory using
//AUTOMAPPER

 var cmd = new SQLiteCommand(sql);
 var list = cmd.Deserialize<LegoCategoryDto>(Database.SQLITE);
 Mapper.CreateMap<LegoCategoryDto, LegoCategory>();
 return list.Select(Mapper.Map<LegoCategory>).ToList();





Wednesday, May 7, 2014

Friday, April 18, 2014

Few Resources I find useful...



http://directshownet.sourceforge.net/
Summary: (from link)

DirectShowNET Library

The purpose of this library is to allow access to Microsoft's DirectShow functionality from within .NET applications. This library supports both Visual Basic .NET and C#, and theoretically, should work with any .NET language.

NLog:nlog-project.org

NLog is a free logging platform for .NET, Silverlight and Windows Phone with rich log routing and management capabilities.

SharpBox - Store everything



Ionic.Zip


a library for handling zip archives. http://www.codeplex.com/DotNetZip (Flavor=Retail)

SharpMap

https://sharpmap.codeplex.com/

SharpMap is an easy-to-use mapping library for use in web and desktop applications. 

DotSpatial.Projections

http://dotspatial.codeplex.com/

The DotSpatial.Projections library is a port of the popular proj4 c++ library to C# .Net. 


NetTopologySuite

A .NET library for GIS operations, direct porting of JTS Topology Suite 1.10 library

Google.GData


BruTile

BruTile is a C# open source library to access tile services like OpenStreetMap and Bing. BruTile has few dependencies, is platform independent and has a limited scope. It is intended for reuse by other more sophisticated libraries


Tuesday, March 4, 2014

Frustrating Windows sockets error 10106: ProviderFailed to initialize.

I lost the ability to connect to svn servers on my workstation either through tortoise of SVN commandline. Happens with coporate SVN server and my local SVN server, my home svn server, and other public svn servers.

I can however reach a coporate SVN repository in a web Browser.  I can also do the same with my local svn server repo.

Not sure if this has happened at the same time, but i can't get fiddler2 or fiddler4 to work anymore.  I need Unable to bind to port 8888 Error code 10106.  Seems like I have a proxy issue.


Windows sockets error 10106: ProviderFailed to initialize.

Today, I could not get asp net state service to start up.  Error:  requested provider could not be loaded or intialized.

Found the solution to my problem:
http://www.pcreview.co.uk/forums/asp-net-state-service-wont-start-t3422497.html

This sounds like a Winsock problem, not a problem with ASP.NET itself. You
can reset your Winsock installation to setup defaults by following the
instructions from this KB article:

http://support.microsoft.com/kb/811259

(The short version of this is to use "netsh winsock reset" from a command
prompt.)

I reset my winsock installation and rebooted.

Problem solved.

Wednesday, February 5, 2014

Helpful ASP.NET forms authenication and session timeout article


From Adam Tuliper's Development Tips

What happens when user session timeouts before Form authenication does?

http://completedevelopment.blogspot.com/2009/12/caution-with-using-sessiontimeout-and.html

Modifield code from Adam's article:

Add the following code to global.asax to reroute request to login if session has expired:

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            //Only access session state if it is available
            if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
            {
                //If we are authenticated AND we dont have a session here.. redirect to login page.
                HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authenticationCookie != null)
                {
                    FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value);
                    if (authenticationTicket != null && !authenticationTicket.Expired)
                    {
                        if (Session["username"] == null)
                        {
                            //This means for some reason the session expired before the authentication ticket. Force a login.
                            FormsAuthentication.SignOut();
                            Response.Redirect(FormsAuthentication.LoginUrl, true);
                            return;
                        }
                    }
                }
            }
        }

Wednesday, January 22, 2014

Freeware SMTP server software for Windows

Found a useful SMTP server in case the version of Windows you have does not include SMTP server features. I needed a quick to setup SMTP server for testing.

http://www.softstack.com/freesmtp.html


Setting up Windows SMTP server:

http://support.microsoft.com/kb/2600912/en-us

http://www.vsysad.com/2012/04/setup-and-configure-smtp-server-on-windows-server-2008-r2/

Friday, January 17, 2014

Opening Firewall for SQL Server allowing TCP access

From Microsoft TechNext

When you can't access a remote sql server, always change the firewall 1st.
the confirm what the sa / user password.

To open a port in the Windows firewall for TCP access

  1. On the Start menu, click Run, type WF.msc, and then click OK.
  2. In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then click New Rule in the action pane.
  3. In the Rule Type dialog box, select Port, and then click Next.
  4. In the Protocol and Ports dialog box, select TCP. Select Specific local ports, and then type the port number of the instance of the Database Engine, such as 1433 for the default instance. Click Next.
  5. In the Action dialog box, select Allow the connection, and then click Next.
  6. In the Profile dialog box, select any profiles that describe the computer connection environment when you want to connect to the Database Engine, and then click Next.
  7. In the Name dialog box, type a name and description for this rule, and then click Finish.