Window service Timers.Timer

Hi Guys Please help me.
Actully i create a window service. This window service has timer for update record once in a day at 5 pm.
I have write a code but it is not working fin
Here is my code.
App.Config File:-
<appSettings>  
    <add key="IsTrace" value="YES"/>
    <add key="SourceServerPath" value="Server=DATASERVER\SQL2008R2;database=WDSBHN;User ID=Wireless;pwd=chetu@123"/>
    <add key="ArchiveServerPath" value="Server=CHETUIWK091\SQL2008R2;database=Demo;User ID=sa;pwd=Chetu@123"/>
    <add key="ReportHour" value="22"/>
    <add key="ReportMinut" value="01"/>
    <add key="ReportSecond" value="20"/>
    <add key="ReportMilisecond" value="230"/>
    <add key="DailyTimer" value="tmrProductionDataTransfer"/>
    <add key="MonthlyTimer" value="tmrProductionCleanUp"/>
    <add key="ActionParameter" value="WDS-DataTransfer"/>
  </appSettings>   
Vb.Net Code:-
Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        Try
            LoggingTracing.WriteTrace("DataTransfer Service START " & Now.ToLongDateString & " " & Now.ToLongTimeString())
            '***Get the Time of service run
            Dim svcRunTime As System.DateTime = Configuration.ConfigurationManager.AppSettings("ServiceRunTime")
            '***differance of these two time
            Dim ts As TimeSpan = DateTime.Now.Subtract(svcRunTime)
            '***production data transfer
            tmrProductionDataTransfer.Enabled = True
            tmrProductionDataTransfer.Interval = 1000
            tmrProductionDataTransfer.Start()
        Catch ex As Exception
            LoggingTracing.WriteError(ex.ToString())
        End Try
    End Sub
Private Sub tmrProductionDataTransfer_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles tmrProductionDataTransfer.Elapsed
        Try
            Dim time As Date = Date.Now
            Dim currHour As Integer
            Dim currMinute As Integer
            Dim currnSecond As Integer
            Dim reportHour As Integer
            Dim reportMinute As Integer
            Dim reportSecond As Integer
            Dim reportMiliSecond As Integer
            Dim actionParameter As String = Configuration.ConfigurationManager.AppSettings("ActionParameter")
            Dim actionTimerName As String = Configuration.ConfigurationManager.AppSettings("DailyTimer")
            currHour = time.Hour
            currMinute = time.Minute
            currnSecond = time.Second
            reportHour = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportHour"))
            reportMinute = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportMinut"))
            reportSecond = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportSecond"))
            reportMiliSecond = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportMilisecond"))
            If currHour = reportHour AndAlso currMinute = reportMinute AndAlso currnSecond = reportSecond Then
                ObjProductionDataTransfer.CopyDataToArchiveServerDayWiseDL(Configuration.ConfigurationManager.AppSettings("SourceServerPath"), Configuration.ConfigurationManager.AppSettings("ArchiveServerPath"),
actionTimerName, time, actionParameter)
            End If
        Catch ex As Exception
            LoggingTracing.WriteError(ex.ToString())
        End Try
    End Sub
It is running at 5 pm , but run 3 times, for that records has updated 3 time 
How i can resolve it, If any problem in this code please give me the write direction or code. And this thing i have been searching for 3 days , but stile i didn't get any solution
sonesh

Sonesh,
Sorry but you have posted to a forum that deals exclusively with questions/issues about customizing and programming Microsoft Project, a planning and scheduling application. I suggest you delete this post and find a forum appropriate for your issue.
John

Similar Messages

  • This window service has timer for update record once in a day at 5 pm.

    Hi Guys Please help me.
    Actully i create a window service. This window service has timer for update record once in a day at 5 pm.
    I have write a code but it is not working fin
    Here is my code.
    App.Config File:-
    <appSettings>  
        <add key="IsTrace" value="YES"/>
        <add key="SourceServerPath" value="Server=DATASERVER\SQL2008R2;database=WDSBHN;User ID=Wireless;pwd=chetu@123"/>
        <add key="ArchiveServerPath" value="Server=CHETUIWK091\SQL2008R2;database=Demo;User ID=sa;pwd=Chetu@123"/>
        <add key="ReportHour" value="22"/>
        <add key="ReportMinut" value="01"/>
        <add key="ReportSecond" value="20"/>
        <add key="ReportMilisecond" value="230"/>
        <add key="DailyTimer" value="tmrProductionDataTransfer"/>
        <add key="MonthlyTimer" value="tmrProductionCleanUp"/>
        <add key="ActionParameter" value="WDS-DataTransfer"/>
      </appSettings>   
    Vb.Net Code:-
    Protected Overrides Sub OnStart(ByVal args() As String)
            ' Add code here to start your service. This method should set things
            ' in motion so your service can do its work.
            Try
                LoggingTracing.WriteTrace("DataTransfer Service START " & Now.ToLongDateString & " " & Now.ToLongTimeString())
                '***Get the Time of service run
                Dim svcRunTime As System.DateTime = Configuration.ConfigurationManager.AppSettings("ServiceRunTime")
                '***differance of these two time
                Dim ts As TimeSpan = DateTime.Now.Subtract(svcRunTime)
                '***production data transfer
                tmrProductionDataTransfer.Enabled = True
                tmrProductionDataTransfer.Interval = 1000
                tmrProductionDataTransfer.Start()
            Catch ex As Exception
                LoggingTracing.WriteError(ex.ToString())
            End Try
        End Sub
    Private Sub tmrProductionDataTransfer_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles tmrProductionDataTransfer.Elapsed
            Try
                Dim time As Date = Date.Now
                Dim currHour As Integer
                Dim currMinute As Integer
                Dim currnSecond As Integer
                Dim reportHour As Integer
                Dim reportMinute As Integer
                Dim reportSecond As Integer
                Dim reportMiliSecond As Integer
                Dim actionParameter As String = Configuration.ConfigurationManager.AppSettings("ActionParameter")
                Dim actionTimerName As String = Configuration.ConfigurationManager.AppSettings("DailyTimer")
                currHour = time.Hour
                currMinute = time.Minute
                currnSecond = time.Second
                reportHour = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportHour"))
                reportMinute = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportMinut"))
                reportSecond = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportSecond"))
                reportMiliSecond = Convert.ToInt32(Configuration.ConfigurationManager.AppSettings("ReportMilisecond"))
                If currHour = reportHour AndAlso currMinute = reportMinute AndAlso currnSecond = reportSecond Then
                    ObjProductionDataTransfer.CopyDataToArchiveServerDayWiseDL(Configuration.ConfigurationManager.AppSettings("SourceServerPath"), Configuration.ConfigurationManager.AppSettings("ArchiveServerPath"),
    actionTimerName, time, actionParameter)
                End If
            Catch ex As Exception
                LoggingTracing.WriteError(ex.ToString())
            End Try
        End Sub
    It is running at 5 pm , but run 3 times, for that records has updated 3 time 
    How i can resolve it, If any problem in this code please give me the write direction or code. And this thing i have been searching for 3 days , but stile i didn't get any solution
    sonesh

    Sonesh,
    Sorry but you have posted to a forum that deals exclusively with questions/issues about customizing and programming Microsoft Project, a planning and scheduling application. I suggest you delete this post and find a more appropriate forum.
    John

  • Must restart windows services each time I cycle power.

    Each time I cycle the power on my wireless laptop computer, I must restart my wireless services following this procedure:
    Start->Run->"services.msc"
      Select:  "wireless zero configuration"
      Start or Restart service
      Close window
    Right-Click on wireless icon in lower right corner:
      Select “View available wireless networks”
      Click on “Change advanced settings” (in Related Tasks box at right)
      Select “Wireless Networks” tab at top of window:
      View “Use Windows to configure my wireless network settings”
      If no check mark, click on box to right to mark it
      Select “View wireless networks” (in Available networks:” box)
      Select (my network) if not already connected
      When connected close window
    It continues to work until I power off my computer.
    How can I make it start automatically?
    Thank you for your assistance.
    Richard
    Richard Vore

    I have now been able to get the "Wireless Zero Configuration" started automatically but I must still open the wireless "properties" window and check the "Use windows to configure..." box to get a list of wireless connections.  My wireless network will then connect automatically after that.  Still a hassle but much better.
    Richard
    Richard Vore

  • Windows Services, Timers & Threading

    I have a self hosted WCF service. I have 2 methods that need to run periodically so the Host Service has 2 System.Threading.Timers. 
    Timer1 has a long running process.  May take up to a minute to run.
    Timer2 has a method that is quick but MUST run every 10 seconds.
    My first thought was that each timer would run on a separate thread and I should be able to get this right out of the box.  I was incorrect.  I can't get Timer2 to be consistent because there seems to be a dependency between the two timers
    and/or the server load.  Timer2 doesn't give me a clean execution pattern.
    In trying to fix this, I put a System.Threading.Tasks.Task around the method call on Timer1.  I expected this to release resources so that Timer2 can run cleanly.  Still, no luck.
    This has me stumped.  Any idea why Timer2 doesn't fire on a consistent pattern?
    Thanks for your help, Joel.
    Application Developer Manufacturing

    Timer2 has a method that is quick but MUST run every 10 seconds.
    Timer2 doesn't give me a clean execution pattern.
    Hi Joel. What doe you mean by clean execution pattern? Is the timer taking longer than 10 seconds to execute the callback or is it random when the call back happens based on server load?
    What I can tell you is that any thread execution is always dependent on the O/S. If the O/S is busy with a process dubbed as high priority which takes up all the resources then your application would also suffer as would any other application running on
    that server. This could be seen in the  form of threads not being allocated to run your application, timers not being fired, longer wait times than usual for resource requests etc.
    As stated above if thread 1 is doing some heavy lifting and using up more CPU cycles/resources on the O/S is willing to allocate to your process then thread 1 (example of processing started on timer1) could affect thread 2 (example of processing
    started on timer 2).
    As far as timers go the timer is System.Threading namespace will always execute independent of each other unless you have added syncronization logic or thread 1 (example of processing started on timer1) blocks on a resource thread 2 (example
    of processing started on timer 2) is requesting.
    Let me know if I am way off on what I think you are asking here.
    Mark as answer or vote as helpful if you find it useful | Igor

  • Deploying Windows Service Fails Every Other Time

    I'm using Release Management 2013 to deploy a Windows service.  I go through the steps listed below to deploy it.  It fails on the first step (Delete Service) every other time.  When I run it again, it works.  It seems like it's saying
    it failed, but is somehow actually succeeding.  After it fails, I don't see the service in the Services list anymore.  Then when I run the deployment again, it succeeds. 
    I have found that if I manually stop the service before deploying again, it will always succeed.  There doesn't seem to be a good way of doing that in Release Management though, since the Stop Service action will error out if the service doesn't exist.
    Any help would be appreciated!
    ==============
    Delete Service
    Create Folder
    XCopy Site Deployment (deploys from drop folder)
    Copy Config Files from Drop folder (copies config files folder from drop folder)
    Delete File(s) or Folder (deletes existing config)
    Rename File or Folder (renames appropriate copied config to the name of the previously deleted config file)
    Delete File(s) or Folder (deletes other config files)
    Delete File(s) or Folder (deletes config folder)
    Create Service
    Start Service

    Hi,
    You may have solved this by now, but for the record, I had the exact same issue. The problem is in this section of ManageWindowsServices.ps1
    elseif ($Action -eq "delete")
    #If the service exists, we first stop it to avoid "Marked for deletion" problems
    $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
    if ($service -ne $null)
    #Stop the service
    $status = & "sc.exe" "$ServerName" stop "$ServiceName"
    "Stop status : $status"
    $status = & "sc.exe" "$ServerName" $Action "$ServiceName"
    "Delete status : $status"
    #Ensure the service was deleted successfully
    $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
    if ($service -ne $null)
    $(throw "The deletion of the service failed.")
    else
    $exitCode = 0
    and is due to the fact that the second Get-Service call does actually return the service, even though it's after the call to delete it. Presumably this is some kind of race condition, where the call to delete the service returns before it's finished all
    it's work.
    In any case, the solution I went for was to rewrite this section as:
    elseif ($Action -eq "delete")
    [int]$returnCode = 0
    #If the service exists, we first stop it to avoid "Marked for deletion" problems
    $service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'"
    if ($service -ne $null)
    #Stop the service
    $status = & "sc.exe" "$ServerName" stop "$ServiceName"
    "Stop status : $status"
    "Deleting Service..."
    $returnCode = $service.delete().ReturnValue
    "Return code was : $returnCode"
    if ($returnCode -ne 0)
    $(throw "The deletion of the service failed: Return code was $returnCode")
    #Ensure the service was deleted successfully
    $service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'"
    if ($service -ne $null)
    $(throw "The deletion of the service failed.")
    else
    $exitCode = 0
    The above code works in all cases that I've run it for. You can either edit the existing ManageWindowsServices script, or simply create a new one. I opted for the latter.
    Note: This is my first attempt at using Powershell, so there may well be a better way of doing the above.

  • Does any windows service affects the device driver wake up time?

    Is it possible for a windows service running on Win 8.1 (64 bit) to delay the wake up time of any device driver?
    One possibility could be where the driver has any dependency on any other driver/service.
    In this case, I checked the driver's INF file and there is no dependency section.
    The driver start up type is service_demand_start and driver type is kernel driver.
    Any help on this is greatly appreciated.

    Are you asking if a service can impact when the driver is started or when it is woken up after hibernation?  For a demand start driver they start when they are needed so depending on the driver yes it could only be started after the service does an
    action.  You have eliminated the dependency section, but is the driver for actual hardware?  If yes then it is highly unlikely the service can impact it.  If no, then the service could be the starting it with StartService, or forcing its enumeration
    and starting.
    If you are talking the hibernation case, no there is impact.
    Don Burn Windows Driver Consulting Website: http://www.windrvr.com

  • Memory Cap for a Windows Service to run in the background all the time on Windows 8.1 Device

    I have a Windows Store app that would run on a 2GB windows 8.1 Pro tablet. I want to create a service that would run in the background and more than one store app can utilize that service. The question I have is , is there any memory usage limit for the
    service to run on a 2 GB RAM tablet?
    I am expecting that the service might use 900 MB of RAM when its operational .
    Kindly help 

    Hi,
    For this situation, it seems that you create a wcf service and host the service on windows service which is running on the 2GB windows 8.1 Pro tablet. And other store app in the tablet can utilize that service.
    If you want to limit the memory usage for the service, it's recommended that you could host the wcf service on other machine, such as a computer. You just call the service from the store application if you want to invoke the service.
    Regards

  • Every time I try to install windows service pack 2 I get error message WindowsUpd​ate_800040​05

    When I try to install windows service pack 2 I get error message WindowsUpdate_80004005, has anyone else had this problem and how do you fix it

    If you have an external drive (USB thumbdrive or hard disk) connected, disconnect it and try the service pack installation again. 
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • Windows service write to event log

    Have strange conduct of code within my application. I've created windows service the same as according to MSDN default instruction:
    https://msdn.microso...=vs.110%29.aspx
    its working and logging to event log correctly. After that i copied that project and based on it i started to create second one almost similar one. my issue is within below part of code belongs to ProjectInstaller.vb when i installed it and tried to Start i
    get message that Windows service started and stoped imedietly.
    Imports System.ComponentModel
    Imports System.Configuration.Install
    Public Class ProjectInstaller
    Public Sub New()
    MyBase.New()
    'This call is required by the Component Designer.
    InitializeComponent()
    'Add initialization code after the call to InitializeComponent
    End Sub
    Protected Overrides Sub OnBeforeInstall(ByVal savedState As IDictionary)
    Dim parameter As String = "MySvcDeon2"" ""MyLogFileSvcDeon2"
    Context.Parameters("assemblypath") = """" + Context.Parameters("assemblypath") + """ """ + parameter + """"
    MyBase.OnBeforeInstall(savedState)
    End Sub
    End Class
    Within this line: Dim parameter As String = "MySvcDeon2"" ""MyLogFileSvcDeon2"
    When i change it to this form then service its starting correctly without any error meassage:
    Dim parameter As String = "MySvcDeon1"" ""MyLogFileSvcDeon1"
    its working. But Deon2 is already created by my first windows service. Whats wrong?

    i also tried from official msdn site  but same error, anyhow, see my code below:
    ProjectInstaller.vb:
    Imports System.ComponentModelImports System.Configuration.InstallPublic Class ProjectInstaller    Public Sub New()        MyBase.New()        'This call is required by the Component Designer.        InitializeComponent()        'Add initialization code after the call to InitializeComponent    End SubEnd Class
    ProjectInstaller.Designer.vb
    <System.ComponentModel.RunInstaller(True)> Partial Class ProjectInstaller    Inherits System.Configuration.Install.Installer    'Installer overrides dispose to clean up the component list.    <System.Diagnostics.DebuggerNonUserCode()> _    Protected Overrides Sub Dispose(ByVal disposing As Boolean)        Try            If disposing AndAlso components IsNot Nothing Then                components.Dispose()            End If        Finally            MyBase.Dispose(disposing)        End Try    End Sub    'Required by the Component Designer    Private components As System.ComponentModel.IContainer    'NOTE: The following procedure is required by the Component Designer    'It can be modified using the Component Designer.      'Do not modify it using the code editor.    <System.Diagnostics.DebuggerStepThrough()> _    Private Sub InitializeComponent()        Me.ServiceProcessInstaller1 = New System.ServiceProcess.ServiceProcessInstaller()        Me.ServiceInstaller1 = New System.ServiceProcess.ServiceInstaller()        '        'ServiceProcessInstaller1        '        Me.ServiceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem        Me.ServiceProcessInstaller1.Password = Nothing        Me.ServiceProcessInstaller1.Username = Nothing        '        'ServiceInstaller1        '        Me.ServiceInstaller1.Description = "Chorus windows service collector"        Me.ServiceInstaller1.DisplayName = "SvcChorusCollector"        Me.ServiceInstaller1.ServiceName = "SvcChorusCollector"        Me.ServiceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic        '        'ProjectInstaller        '        Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceProcessInstaller1, Me.ServiceInstaller1})    End Sub    Friend WithEvents ServiceProcessInstaller1 As System.ServiceProcess.ServiceProcessInstaller    Friend WithEvents ServiceInstaller1 As System.ServiceProcess.ServiceInstallerEnd Class
    SvcChorusCollector.vb:
    Public Class SvcChorusCollector
        Private Const EvtLogSource As String = "MySourceSvcChorusCollector"
        Private Const EvtLogName As String = "MyLogSvcChorusCollector"
        Private syncRoot As New Object
        Dim timer As System.Timers.Timer = New System.Timers.Timer()
        Sub New()
            ' This call is required by the designer.
            InitializeComponent()
            ' Add any initialization after the InitializeComponent() call.
            If Not System.Diagnostics.EventLog.SourceExists(EvtLogSource) Then
                System.Diagnostics.EventLog.CreateEventSource(EvtLogSource, EvtLogName)
            End If
            EventLog1.Source = EvtLogSource
        End Sub
        Protected Overrides Sub OnStart(ByVal args() As String)
            ' Add code here to start your service. This method should set things
            ' in motion so your service can do its work.
            EventLog1.WriteEntry("In OnStart")
            ' Set up a timer to trigger every minute.
            timer.Interval = 1000 ' 1 seconds
            'unfortunetly OnTimer event handler will be executed even already one is running if Interval is riched by default.
            'This is because it will go multiple threading and not in main thread unless a SynchronizingObject is supplied. (Which it wasn't.) below :
            'timer.SynchronizingObject = Me
            'this is solving problem. OTher way is to make lock within OnTimer event handler as its done right now.
            AddHandler timer.Elapsed, AddressOf Me.OnTimer
            timer.Start()
        End Sub
        Protected Overrides Sub OnStop()
            ' Add code here to perform any tear-down necessary to stop your service.
            EventLog1.WriteEntry("In OnStop")
        End Sub
        Protected Overrides Sub OnContinue()
            EventLog1.WriteEntry("In OnContinue.")
        End Sub
        Private Sub OnTimer(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
        End Sub
    End Class
    SvcChorusCollector.Designer.vb
    Imports System.ServiceProcess<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _Partial Class SvcChorusCollector    Inherits System.ServiceProcess.ServiceBase    'UserService overrides dispose to clean up the component list.    <System.Diagnostics.DebuggerNonUserCode()> _    Protected Overrides Sub Dispose(ByVal disposing As Boolean)        Try            If disposing AndAlso components IsNot Nothing Then                components.Dispose()            End If        Finally            MyBase.Dispose(disposing)        End Try    End Sub    ' The main entry point for the process    <MTAThread()> _    <System.Diagnostics.DebuggerNonUserCode()> _    Shared Sub Main()        Dim ServicesToRun() As System.ServiceProcess.ServiceBase        ' More than one NT Service may run within the same process. To add        ' another service to this process, change the following line to        ' create a second service object. For example,        '        '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}        '        ServicesToRun = New System.ServiceProcess.ServiceBase() {New SvcChorusCollector}        System.ServiceProcess.ServiceBase.Run(ServicesToRun)    End Sub    'Required by the Component Designer    Private components As System.ComponentModel.IContainer    ' NOTE: The following procedure is required by the Component Designer    ' It can be modified using the Component Designer.      ' Do not modify it using the code editor.    <System.Diagnostics.DebuggerStepThrough()> _    Private Sub InitializeComponent()        Me.EventLog1 = New System.Diagnostics.EventLog()        CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).BeginInit()        '        'EventLog1        '        '        'SvcChorusCollector        '        Me.ServiceName = "SvcChorusCollector"        Me.CanStop = True                   'if this is not set to true then will be not possible to stop service manually from service window services.msc !!!        Me.AutoLog = True        CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).EndInit()    End Sub    Friend WithEvents EventLog1 As System.Diagnostics.EventLogEnd Class
    The second service is on same basis, of course service names, source,logname are diffrent. What i do wrong? Error message appearing really fast after ~8 sec

  • Call a program via windows service

    Hi! I have write a windows service,and it works. I want to call a .exe file,and my .exe file is signature. The program can not work when I call it through my service. How can I solve my problem? Thanks!

    Hi Hassan,
    Thank you for sharing the code with us! 
    As I understand it, your code handles the situation of an user that is already logged on to an interactive window station (those of you, who need to create a UI-process of a user not yet logged on, could use
    CreateProcessWithLogon, or
    LogonUser to get the token). Because calling CreateProcessAsUser() requires advanced privileges (such as "Replace a process token level", or "Act as part of the operating system", privileges usually not held by a user unless specified so by the security
    policy), the code also implies a service running in the local system account (or equivalent).
    To make it easier to read, I'll post here the C#-version of your code:
    using System;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    namespace WindowsServiceLaunchingExe
    class NativeMethods
    [StructLayout(LayoutKind.Sequential)]
    public struct PROCESS_INFORMATION {
    public IntPtr hProcess;
    public IntPtr hThread;
    public System.UInt32 dwProcessId;
    public System.UInt32 dwThreadId;
    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_ATTRIBUTES {
    public System.UInt32 nLength;
    public IntPtr lpSecurityDescriptor;
    public bool bInheritHandle;
    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO {
    public System.UInt32 cb;
    public string lpReserved;
    public string lpDesktop;
    public string lpTitle;
    public System.UInt32 dwX;
    public System.UInt32 dwY;
    public System.UInt32 dwXSize;
    public System.UInt32 dwYSize;
    public System.UInt32 dwXCountChars;
    public System.UInt32 dwYCountChars;
    public System.UInt32 dwFillAttribute;
    public System.UInt32 dwFlags;
    public short wShowWindow;
    public short cbReserved2;
    public IntPtr lpReserved2;
    public IntPtr hStdInput;
    public IntPtr hStdOutput;
    public IntPtr hStdError;
    [StructLayout(LayoutKind.Sequential)]
    public struct PROFILEINFO {
    public int dwSize;
    public int dwFlags;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpUserName;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpProfilePath;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpDefaultPath;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpServerName;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpPolicyPath;
    public IntPtr hProfile;
    internal enum SECURITY_IMPERSONATION_LEVEL {
    SecurityAnonymous = 0,
    SecurityIdentification = 1,
    SecurityImpersonation = 2,
    SecurityDelegation = 3
    internal enum TOKEN_TYPE {
    TokenPrimary = 1,
    TokenImpersonation = 2
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation);
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, ref IntPtr phNewToken);
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);
    [DllImport("userenv.dll", SetLastError = true)]
    private static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
    [DllImport("userenv.dll", SetLastError = true)]
    private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);
    private const short SW_SHOW = 1;
    private const short SW_SHOWMAXIMIZED = 7;
    private const int TOKEN_QUERY = 8;
    private const int TOKEN_DUPLICATE = 2;
    private const int TOKEN_ASSIGN_PRIMARY = 1;
    private const int GENERIC_ALL_ACCESS = 268435456;
    private const int STARTF_USESHOWWINDOW = 1;
    private const int STARTF_FORCEONFEEDBACK = 64;
    private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
    private const string gs_EXPLORER = "explorer";
    public static void LaunchProcess(string Ps_CmdLine)
    IntPtr li_Token = default(IntPtr);
    IntPtr li_EnvBlock = default(IntPtr);
    Process[] lObj_Processes = Process.GetProcessesByName(gs_EXPLORER);
    // Get explorer.exe id
    // If process not found
    if (lObj_Processes.Length == 0)
    // Exit routine
    return;
    // Get primary token for the user currently logged in
    li_Token = GetPrimaryToken(lObj_Processes[0].Id);
    // If token is nothing
    if (li_Token.Equals(IntPtr.Zero))
    // Exit routine
    return;
    // Get environment block
    li_EnvBlock = GetEnvironmentBlock(li_Token);
    // Launch the process using the environment block and primary token
    LaunchProcessAsUser(Ps_CmdLine, li_Token, li_EnvBlock);
    // If no valid enviroment block found
    if (li_EnvBlock.Equals(IntPtr.Zero))
    // Exit routine
    return;
    // Destroy environment block. Free environment variables created by the
    // CreateEnvironmentBlock function.
    DestroyEnvironmentBlock(li_EnvBlock);
    private static IntPtr GetPrimaryToken(int Pi_ProcessId) {
    IntPtr li_Token = IntPtr.Zero;
    IntPtr li_PrimaryToken = IntPtr.Zero;
    bool lb_ReturnValue = false;
    Process lObj_Process = Process.GetProcessById(Pi_ProcessId);
    SECURITY_ATTRIBUTES lObj_SecurityAttributes = default(SECURITY_ATTRIBUTES);
    // Get process by id
    // Open a handle to the access token associated with a process. The access token
    // is a runtime object that represents a user account.
    lb_ReturnValue = OpenProcessToken(lObj_Process.Handle, TOKEN_DUPLICATE, ref li_Token);
    // If successfull in opening handle to token associated with process
    if (lb_ReturnValue) {
    // Create security attributes to pass to the DuplicateTokenEx function
    lObj_SecurityAttributes = new SECURITY_ATTRIBUTES();
    lObj_SecurityAttributes.nLength = Convert.ToUInt32(Marshal.SizeOf(lObj_SecurityAttributes));
    // Create a new access token that duplicates an existing token. This function
    // can create either a primary token or an impersonation token.
    lb_ReturnValue = DuplicateTokenEx(li_Token, Convert.ToUInt32(TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY), ref lObj_SecurityAttributes, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, ref li_PrimaryToken);
    // If un-successful in duplication of the token
    if (!lb_ReturnValue) {
    // Throw exception
    throw new Exception(string.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error()));
    else {
    // If un-successful in opening handle for token then throw exception
    throw new Exception(string.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error()));
    // Return primary token
    return li_PrimaryToken;
    private static IntPtr GetEnvironmentBlock(IntPtr Pi_Token) {
    IntPtr li_EnvBlock = IntPtr.Zero;
    bool lb_ReturnValue = CreateEnvironmentBlock(ref li_EnvBlock, Pi_Token, false);
    // Retrieve the environment variables for the specified user.
    // This block can then be passed to the CreateProcessAsUser function.
    // If not successful in creation of environment block then
    if (!lb_ReturnValue) {
    // Throw exception
    throw new Exception(string.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error()));
    // Return the retrieved environment block
    return li_EnvBlock;
    private static void LaunchProcessAsUser(string Ps_CmdLine, IntPtr Pi_Token, IntPtr Pi_EnvBlock) {
    bool lb_Result = false;
    PROCESS_INFORMATION lObj_ProcessInformation = default(PROCESS_INFORMATION);
    SECURITY_ATTRIBUTES lObj_ProcessAttributes = default(SECURITY_ATTRIBUTES);
    SECURITY_ATTRIBUTES lObj_ThreadAttributes = default(SECURITY_ATTRIBUTES);
    STARTUPINFO lObj_StartupInfo = default(STARTUPINFO);
    // Information about the newly created process and its primary thread.
    lObj_ProcessInformation = new PROCESS_INFORMATION();
    // Create security attributes to pass to the CreateProcessAsUser function
    lObj_ProcessAttributes = new SECURITY_ATTRIBUTES();
    lObj_ProcessAttributes.nLength = Convert.ToUInt32(Marshal.SizeOf(lObj_ProcessAttributes));
    lObj_ThreadAttributes = new SECURITY_ATTRIBUTES();
    lObj_ThreadAttributes.nLength = Convert.ToUInt32(Marshal.SizeOf(lObj_ThreadAttributes));
    // To specify the window station, desktop, standard handles, and appearance of the
    // main window for the new process.
    lObj_StartupInfo = new STARTUPINFO();
    lObj_StartupInfo.cb = Convert.ToUInt32(Marshal.SizeOf(lObj_StartupInfo));
    lObj_StartupInfo.lpDesktop = null;
    lObj_StartupInfo.dwFlags = Convert.ToUInt32(STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK);
    lObj_StartupInfo.wShowWindow = SW_SHOW;
    // Creates a new process and its primary thread. The new process runs in the
    // security context of the user represented by the specified token.
    lb_Result = CreateProcessAsUser(Pi_Token, null, Ps_CmdLine, ref lObj_ProcessAttributes, ref lObj_ThreadAttributes, true, CREATE_UNICODE_ENVIRONMENT, Pi_EnvBlock, null, ref lObj_StartupInfo, ref lObj_ProcessInformation);
    // If create process return false then
    if (!lb_Result) {
    // Throw exception
    throw new Exception(string.Format("CreateProcessAsUser Error: {0}", Marshal.GetLastWin32Error()));
    To use the code, create a new windows service project, and add code like the following one:
    using System;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Timers;
    namespace WindowsServiceLaunchingExe
    public partial class ExeLauncherSvc : ServiceBase
    public ExeLauncherSvc() {
    InitializeComponent();
    Timer timer;
    protected override void OnStart(string[] args) {
    timer = new Timer(5000);
    timer.Elapsed += (sender, e) => {
    try {
    timer.Stop();
    EventLog.WriteEntry("WindowsServiceLaunchingExe", "Launching process...");
    NativeMethods.LaunchProcess(@"C:\Windows\notepad.exe");
    } catch (Exception ex) {
    EventLog.WriteEntry("WindowsServiceLaunchingExe", ex.Message);
    timer.Start();
    protected override void OnStop() {
    Because NativeMethods.LaunchProcess() throws exceptions on errors, be sure to enclose calling code in a try/catch-block.
    I also would recommend reading this:
    Stephen Martin - The Perils and Pitfalls of Launching a Process Under New Credentials
    http://asprosys.blogspot.com/2009/03/perils-and-pitfalls-of-launching.html
    Stephen Martin - Launch Process From Service (code download)
    http://www.asprosys.com/Downloads/LaunchProcessFromService.zip
    Marcel

  • How create Windows Services in Azure using Visual Studio 2012

    Hi,
    I have a need to write a Windows Service (Batch Job), which would execute everyday at a specified time, say 4:00AM. This job will do some processing and will send out an email to predefined users. I am using Visual Studio 2012 for the development.
    Based on some research, it looks like that Azure doesn't have a concept of Windows Service. Rather, we need to create WorkerRole to achieve the same.
    I wrote the code to implement the WorkerRole. The problem, I am facing is that
    1. How to prevent the continuous looping of the code below? I want the task to be executed only once a day at 4:00AM
    2. How do I schedule this functionality in Azure?
    Any help will be highly appreciated. I have provided the code sample below.
    Thanks.
       public class WorkerRole : RoleEntryPoint
            public override void Run()
                while (true)
                    SendNewsEmail();
                    Thread.Sleep(10000);
           private void SendNewsEmail()
                /*Email Logic Goes Here*/
            public override bool OnStart()
                // Set the maximum number of concurrent connections
                ServicePointManager.DefaultConnectionLimit = 12;
                return base.OnStart();

    HI
    I think JuneT's answer is what you want.
    However it's for Azure website.
    If you still want to use a workerRole, you need much harder work.
    You can use Timers Class to do such things:
    http://stick2basic.wordpress.com/2013/02/22/how-to-schedule-a-c-windows-service-to-run-a-method-daily/
    How do I schedule this functionality in Azure
    I suggest you save the settings file in a cloud table, and notify your webrole using WCF service to let the service get the new settings when your changed it.
    My Blog
    Please use Make as Answer if my post solved your problem and use
    Vote As Helpful if a post was useful.

  • Windows service to diapi

    Is it possible to create a windows service that connects to the diapi?
    If so- if there something that I'm missing?
    I can create a service that performs a subroutine based on a timer.
    I add in the connection to the diapi and then seconds after connecting successfully my service aborts.

    Hi John,
    I've created a Windows Service that uses the DI API so I know it can be done. The only issue I found was the usual problem of memory consumption. I just used the standard .NET project template for a service and added the DI API. This was in C# and I'm using timers to poll a separate database which then imports and exports SBO data using the DI API. Apart from the aforementioned memory issues, it's always worked fine.
    (A bit off-topic maybe but) if I was to approach the same project again, I think I'd go for the DI Server with a web service wrapper as this seems to have better memory management.
    Kind Regards,
    Owen

  • Help, which windows Service msut be on to run Adobe Bridge CS3?

    hi all,
    I'm having trouble opening Adobe Bridge CS3, theres a windows popup that says "Adobe Bridge has encountered a problem and needs to close" error message when i try to start.
    I can run the other Adobe Cs3 applications fine, i've been playing around with the disabling of windows services to increase bootup time. i'm afraid i may have accidentally disabled something necessary
    pls advice on how to get it working.. i'm on win xp pro sp2
    thanks

    When you get the "Bridge has encountered an error" popup box, check the technical info hyperlink to see what's the problem. It may point to a DLL that had an error.
    From there, check the web to see what that DLL relates to, which may or may not give you a lead. Maybe something that needs to be running in WinXP, maybe a 3rd party product that needs to be fixed/removed/re-installed.
    Why do I say this? I had the same issue on Bridge after getting the trial version. Worked for a while, then suddenly stopped working with the same startup dialog box and a quick shutdown. Digging a bit as above pointed to a DLL that was related to Quicktime. I went to the Apple site and downloaded/installed the latest version of Quicktime, and the Brige problem was cured.

  • TNS-12560 error when running as Windows Service

    Hello,
    I created a VB.NET application that connects to a Oracle database using DbProviderFactory and ODP.NET for .Net Framework 2.0. This application runs on XP, I need it to run as Windows Service, but every time it try to connect to the database throw the Oracle exception TNS-12560: TNS:protocol adapter error, the weird thing is the same application running as a Console Application it works (Same code, same connection string, same query). It was using ODP.NET 10 I updated the provider to 11 still got the same error. The service is running user Local System account, and it has the same problem running under other adm account.
    Following is error in the sqlnet.log (PS: The file was under the system32 folder, probably because was running as a service):
    Fatal NI connect error 12560, connecting to:
    +(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XX.XX.XX.XX)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XXX)(CID=(PROGRAM=C:\Program Files\MyApp\MyApp.exe)(HOST=MYCOMPUTER)(USER=MYUSER))))+
    VERSION INFORMATION:
    +     TNS for 32-bit Windows: Version 10.2.0.1.0 - Production+
    +     Windows NT TCP/IP NT Protocol Adapter for 32-bit Windows: Version 10.2.0.1.0 - Production+
    Time: 28-AUG-2009 02:20:19
    Tracing not turned on.
    Tns error struct:
    ns main err code: 12560
    TNS-12560: TNS:protocol adapter error
    ns secondary err code: 0
    nt main err code: 530
    TNS-00530: Protocol adapter error
    nt secondary err code: 56
    nt OS err code: 0
    Does anyone have any thoughts as to why I'm getting this error ??
    Thanks

    I don't know :^(
    There could be many reasons: differences in the environment, missing permissions, virus scanners, you name it.
    Is it running under the same user as on the console?
    I suspect that the error code will give a hint where the problem is, but I could not find any documentation what this code means.
    You could try to run an Orace Net trace - maybe you get an idea if you see where in the connection process the problem occurs.
    Yours,
    Laurenz Albe

  • Setting up OIM to start as a Windows Service running under Weblogic 10.3.2

    Hi,
    On recommendation from our Oracle Rep. we have begun migrating our existing OIM installation on Oracle AS to a Weblogic Application Server. As such we are looking for a way to get the OIM application to run as a service in windows - so we dont have to start it manually after a reboot and so that system monitoring can alert us if/when the application crashes for some reason.
    I have asked Oracle support - which basically said that no such howto/documentation exists and that "One needs to debug on their own when face any issue." (whatever the h*** that means).
    I was thinking that we werent the first customers trying to get the OIM webapplication to start automatically under weblogic and that someone must have figured out a way to accomplish this ?
    Any advice on how to do this will be greatly appreciated.
    Thank you in advance.
    /Jacob

    Hi Jacob,
    See this post that I answered few time ago. Re: Keeping Remote Manager running - Windows
    Our OIM is running as a Windows Service.
    REnato

Maybe you are looking for

  • Object Services  attachement list

    From FB03, I am able to view archived images from Environment==>additional assignments==>object links==>attachment list. However, when I am using the Object Services==>attachment list the images does not display. Any ideas why? I have the following a

  • Multiple Priority Queues?

    All, I have read that one may configure up to 4 priority queues, not using the Modular QOS CLI (e.g. "priority-list" command, etc). For the Modular QOS CLI, PQs are implemented using LLQ ("priority" command), and for this one can only specify a singl

  • One interview question in BDC

    there r 10,000 records in a flatfile and first record contains error, if i upload to the bdc pgm,and run in session method what will happen.

  • Partitioning Questions (Measure twice, cut once.)

    I'm currently reinstalling the OS on my computer after swapping out most of the parts. It was an XP gaming machine but I plan on dualbooting with Arch as the primary OS and Windows 7 for gaming. My old XP setup had a 32GB 10k RPM HD as C: and then a

  • Mediaplayer streaming device

    I tried to produce HD file out of AVCHD clips but colud not find a way to produce compatible file type. The file types upported by most mdeiaplayers are: mkv/avi/m2ts etc. The only file type Premiere Elements 7 allows are m2t. Can any body help me.