Guest User

UpdateHelper.cs

a guest
Dec 12th, 2012
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.58 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. using System.Windows.Forms;
  9. using wyUpdate.Common;
  10.  
  11.  
  12. namespace wyDay.Controls
  13. {
  14.     internal class UpdateHelper : IDisposable
  15.     {
  16.         /// <summary>
  17.         /// lock access to this for thread safety
  18.         /// </summary>
  19.         private object _lock = new object();
  20.         // Constants
  21.         const int MaxSendRetries = 20;
  22.         const int MilliSecsBetweenRetry = 250;
  23.  
  24.         // 20 * 250 = 5000 ms = 5 seconds for an error to show
  25.  
  26.         Process ClientProcess;
  27.  
  28.         string m_CompleteWULoc;
  29.         string m_wyUpdateLocation = "wyUpdate.exe";
  30.  
  31.         public string wyUpdateLocation
  32.         {
  33.             get { return m_wyUpdateLocation; }
  34.             set
  35.             {
  36.                 lock (_lock)
  37.                 {
  38.                     if (isDisposed) return;
  39.  
  40.                     m_wyUpdateLocation = value;
  41.  
  42.                     // Try to create the complete wyUpdate path (expanding relative paths, etc.) . If it fails,
  43.                     // we'll be notifying the user later. (Hence the empty "catch" block).
  44.                     try
  45.                     {
  46.                         m_CompleteWULoc = Path.GetFullPath(Path.IsPathRooted(value)
  47.                                                   ? value
  48.                                                   : Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), value)
  49.                                                 );
  50.                     }
  51.                     catch { }
  52.                 }
  53.             }
  54.         }
  55.  
  56.         // extra arguments for wyUpdate
  57.         public string ExtraArguments;
  58.  
  59.         PipeClient pipeClient;
  60.  
  61.  
  62.         BackgroundWorker bw;
  63.  
  64.         public event UpdateStepMismatchHandler UpdateStepMismatch;
  65.         public event ResponseHandler ProgressChanged;
  66.         public event ResponseHandler PipeServerDisconnected;
  67.         public event EventHandler ResendRestartInfo;
  68.  
  69.         public UpdateStep UpdateStep = UpdateStep.CheckForUpdate;
  70.  
  71.         [DllImport("user32.dll")]
  72.         static extern int ShowWindow(int hwnd, int nCmdShow);
  73.  
  74.         [DllImport("user32.dll")]
  75.         static extern bool SetForegroundWindow(int hWnd);
  76.  
  77.         readonly Stack<UpdateHelperData> sendBuffer = new Stack<UpdateHelperData>(1);
  78.         readonly List<UpdateHelperData> receivedBuffer = new List<UpdateHelperData>();
  79.         public bool BufferResponse;
  80.  
  81.         #region Dispose
  82.  
  83.         /// <summary>Indicates whether this instance is disposed.</summary>
  84.         private bool isDisposed;
  85.  
  86.         /// <summary>
  87.         /// Finalizes an instance of the <see cref="UpdateHelper"/> class.
  88.         /// Releases unmanaged resources and performs other cleanup operations before the
  89.         /// <see cref="UpdateHelper"/> is reclaimed by garbage collection.
  90.         /// </summary>
  91.         ~UpdateHelper()
  92.         {
  93.             Dispose(false);
  94.         }
  95.  
  96.         /// <summary>
  97.         /// Releases unmanaged and - optionally - managed resources.
  98.         /// </summary>
  99.         /// <param name="isManaged">Result: <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  100.         protected virtual void Dispose(bool isManaged)
  101.         {
  102.  
  103.  
  104.  
  105.             // true if not invoked by the GC
  106.             if (isManaged)
  107.             {
  108.                 lock (_lock)
  109.                 {
  110.                     if (!isDisposed)
  111.                     {
  112.                         // dispose managed resources
  113.                         // Not already disposed ?
  114.                         if (pipeClient != null)
  115.                         {
  116.                             pipeClient.Dispose(); // Dispose it
  117.                             pipeClient = null; // Its now inaccessible
  118.                         }
  119.                         if (bw != null)
  120.                         {
  121.                             bw.Dispose(); // Dispose it
  122.                             bw = null; // Its now inaccessible
  123.                         }
  124.                         // Instance is disposed
  125.                         isDisposed = true;
  126.                     }
  127.                 }
  128.             }
  129.  
  130.             // free unmanaged resources
  131.             // Set large fields to null.
  132.  
  133.             // Instance is disposed
  134.             isDisposed = true;
  135.  
  136.  
  137.         }
  138.  
  139.         /// <summary>
  140.         /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  141.         /// </summary>
  142.         public void Dispose()
  143.         {
  144.             Dispose(true);
  145.             GC.SuppressFinalize(this);
  146.         }
  147.  
  148.         #endregion
  149.  
  150.         public void FlushResponses()
  151.         {
  152.             lock (_lock)
  153.             {
  154.                 if (isDisposed) return;
  155.  
  156.                 lock (receivedBuffer)
  157.                 {
  158.                     foreach (var resp in receivedBuffer)
  159.                     {
  160.                         // process the response
  161.                         ProcessReceivedMessage(resp);
  162.                     }
  163.  
  164.                     receivedBuffer.Clear();
  165.                     BufferResponse = false;
  166.                 }
  167.             }
  168.         }
  169.  
  170.         public UpdateHelper()
  171.         {
  172.             // Try to create the complete wyUpdate path. If it fails,
  173.             // we'll be notifying the user later. (Hence the empty "catch" block).
  174.             try
  175.             {
  176.                 m_CompleteWULoc = Path.GetFullPath(Path.IsPathRooted(m_wyUpdateLocation)
  177.                                           ? m_wyUpdateLocation
  178.                                           : Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), m_wyUpdateLocation)
  179.                                         );
  180.             }
  181.             catch { }
  182.  
  183.             CreateNewPipeClient();
  184.         }
  185.  
  186.         void CreateNewPipeClient()
  187.         {
  188.             lock (_lock)
  189.             {
  190.                 if (isDisposed) return;
  191.  
  192.                 if (pipeClient != null)
  193.                 {
  194.                     pipeClient.MessageReceived -= SafeProcessReceivedMessage;
  195.                     pipeClient.ServerDisconnected -= ServerDisconnected;
  196.                 }
  197.  
  198.                 pipeClient = new PipeClient();
  199.  
  200.                 pipeClient.MessageReceived += SafeProcessReceivedMessage;
  201.                 pipeClient.ServerDisconnected += ServerDisconnected;
  202.             }
  203.         }
  204.  
  205.         bool StartClient()
  206.         {
  207.             lock (_lock)
  208.             {
  209.                 if (isDisposed) return false;
  210.  
  211.                 if (string.IsNullOrEmpty(m_CompleteWULoc))
  212.                     throw new Exception("The wyUpdate executable path supplied is not valid. Make sure wyUpdate exists on disk.");
  213.  
  214.                 // get the unique pipe name (the last 246 chars of the complete path)
  215.                 string pipeName = UpdateHelperData.PipenameFromFilename(m_CompleteWULoc);
  216.  
  217.                 // first try to connect to the pipe
  218.                 if (!pipeClient.Connected)
  219.                     pipeClient.Connect(pipeName);
  220.  
  221.                 if (pipeClient.Connected)
  222.                 {
  223.                     // request the processId
  224.                     if (!RetrySend((new UpdateHelperData(UpdateAction.GetwyUpdateProcessID)).GetByteArray()))
  225.                         throw new Exception("Failed to get the wyUpdate Process ID.");
  226.  
  227.                     return true;
  228.                 }
  229.  
  230.                 if (!File.Exists(m_CompleteWULoc))
  231.                     throw new Exception("The wyUpdate executable was not found: " + m_CompleteWULoc);
  232.  
  233.                 ClientProcess = new Process
  234.                                           {
  235.                                               StartInfo =
  236.                                                     {
  237.                                                         FileName = m_CompleteWULoc,
  238.  
  239.                                                         // start the client in automatic update mode (a.k.a. wait mode)
  240.                                                         Arguments = "/autoupdate",
  241.  
  242.                                                         WindowStyle = ProcessWindowStyle.Hidden
  243.                                                     }
  244.                                           };
  245.  
  246.                 if (!string.IsNullOrEmpty(ExtraArguments))
  247.                     ClientProcess.StartInfo.Arguments += " " + ExtraArguments;
  248.  
  249.                 ClientProcess.Start();
  250.  
  251.                 TryToConnectToPipe(pipeName);
  252.  
  253.                 return pipeClient.Connected;
  254.             }
  255.         }
  256.  
  257.         void TryToConnectToPipe(string pipename)
  258.         {
  259.             lock (_lock)
  260.             {
  261.                 if (isDisposed) return;
  262.                 // try to connect to the pipe - bail out if it takes longer than 30 seconds
  263.                 for (int retries = 0; !pipeClient.Connected && retries < 120; retries++)
  264.                 {
  265.                     pipeClient.Connect(pipename);
  266.  
  267.                     // wait half a second
  268.                     if (!pipeClient.Connected)
  269.                     {
  270.                         if (ClientProcess == null || ClientProcess.HasExited)
  271.                         {
  272.                             ClientProcess = null;
  273.                             break;
  274.                         }
  275.  
  276.                         Thread.Sleep(250);
  277.                     }
  278.                 }
  279.  
  280.                 if (!pipeClient.Connected && ClientProcess != null)
  281.                 {
  282.                     // try to kill the process without throwing any exceptions
  283.                     try
  284.                     {
  285.                         ClientProcess.Kill();
  286.                     }
  287.                     catch { }
  288.  
  289.                     ClientProcess = null;
  290.                 }
  291.             }
  292.         }
  293.  
  294.         void ServerDisconnected()
  295.         {
  296.             lock (_lock)
  297.             {
  298.                 if (isDisposed) return;
  299.                 ClientProcess = null;
  300.  
  301.                 if (PipeServerDisconnected != null)
  302.                     PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, AUTranslation.C_PrematureExitMessage));
  303.             }
  304.         }
  305.  
  306.         void bw_DoWork(object sender, DoWorkEventArgs e)
  307.         {
  308.             lock (_lock)
  309.             {
  310.                 if (isDisposed) return;
  311.  
  312.                 // start the client if it's not already running.
  313.                 if (ClientProcess == null)
  314.                 {
  315.                     if (!StartClient())
  316.                         throw new Exception("wyUpdate failed to start.");
  317.                 }
  318.  
  319.                 if (!RetrySend(((UpdateHelperData)e.Argument).GetByteArray()))
  320.                     throw new Exception("Message failed to send message to pipe server");
  321.             }
  322.         }
  323.  
  324.         /// <summary>Tries to send a message MaxSendRetries waiting MilliSecsBetweenRetry.</summary>
  325.         /// <param name="message">Message to send.</param>
  326.         /// <returns>True if success.</returns>
  327.         bool RetrySend(byte[] message)
  328.         {
  329.             lock (_lock)
  330.             {
  331.                 if (isDisposed) return false;
  332.  
  333.                 bool messageFailedToSend;
  334.  
  335.                 for (int retries = 0;
  336.  
  337.                      // try to send the message
  338.                      (messageFailedToSend = !pipeClient.SendMessage(message))
  339.                           && retries < MaxSendRetries
  340.                           && pipeClient.Connected;
  341.  
  342.                      retries++)
  343.                 {
  344.                     // wait between retries
  345.                     Thread.Sleep(MilliSecsBetweenRetry);
  346.                 }
  347.  
  348.                 // if the client process has already exited, just say the send succeeded
  349.                 // otherwise return whether the send actually succeeded
  350.                 return pipeClient.Connected ? !messageFailedToSend : true;
  351.             }
  352.         }
  353.  
  354.         void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  355.         {
  356.             lock (_lock)
  357.             {
  358.                 if (isDisposed) return;
  359.  
  360.                 bw.DoWork -= bw_DoWork;
  361.                 bw.RunWorkerCompleted -= bw_RunWorkerCompleted;
  362.                 bw.Dispose();
  363.                 bw = null;
  364.  
  365.                 // error occurs when a message fails to send or wyUpdate fails to start
  366.                 if (e.Error != null)
  367.                 {
  368.                     // if the process is running - try to kill it
  369.                     try
  370.                     {
  371.                         if (ClientProcess != null && !ClientProcess.HasExited)
  372.                             ClientProcess.Kill();
  373.                     }
  374.                     catch { }
  375.  
  376.                     // set the client process to null so it can be restarted
  377.                     // when the user retries.
  378.                     ClientProcess = null;
  379.  
  380.                     // clear the to-send stack
  381.                     sendBuffer.Clear();
  382.  
  383.                     // inform the AutomaticUpdater that wyUpdate is no longer running
  384.                     if (PipeServerDisconnected != null)
  385.                         PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, e.Error.Message));
  386.                 }
  387.                 else
  388.                 {
  389.                     // process the next in stack
  390.                     if (sendBuffer.Count > 0)
  391.                     {
  392.                         RecreateBackgroundWorker();
  393.  
  394.                         UpdateHelperData uhd = sendBuffer.Pop();
  395.                         UpdateStep = uhd.UpdateStep;
  396.  
  397.                         // begin sending to the client
  398.                         bw.RunWorkerAsync(uhd);
  399.                     }
  400.                 }
  401.             }
  402.         }
  403.  
  404.         public void ForceRecheckForUpdate()
  405.         {
  406.             SendAsync(new UpdateHelperData(UpdateStep.ForceRecheckForUpdate));
  407.         }
  408.  
  409.         public void CheckForUpdate()
  410.         {
  411.             SendAsync(new UpdateHelperData(UpdateStep.CheckForUpdate));
  412.         }
  413.  
  414.         public void DownloadUpdate()
  415.         {
  416.             SendAsync(new UpdateHelperData(UpdateStep.DownloadUpdate));
  417.         }
  418.  
  419.         public void BeginExtraction()
  420.         {
  421.             SendAsync(new UpdateHelperData(UpdateStep.BeginExtraction));
  422.         }
  423.  
  424.         public void RestartInfo(string fileToExecute, string autoUpdateID, string argumentsForFiles, bool isAService)
  425.         {
  426.             lock (_lock)
  427.             {
  428.                 if (isDisposed) return;
  429.  
  430.                 UpdateHelperData uhd = new UpdateHelperData(UpdateStep.RestartInfo);
  431.  
  432.                 uhd.ExtraData.Add(fileToExecute);
  433.                 uhd.ExtraDataIsRTF.Add(isAService);
  434.  
  435.                 if (!string.IsNullOrEmpty(autoUpdateID))
  436.                 {
  437.                     uhd.ExtraData.Add(autoUpdateID);
  438.                     uhd.ExtraDataIsRTF.Add(false);
  439.  
  440.                     if (!string.IsNullOrEmpty(argumentsForFiles))
  441.                     {
  442.                         uhd.ExtraData.Add(argumentsForFiles);
  443.                         uhd.ExtraDataIsRTF.Add(false);
  444.                     }
  445.                 }
  446.  
  447.                 SendAsync(uhd);
  448.             }
  449.         }
  450.  
  451.         int ClientWindowHandleToShow;
  452.  
  453.         public void InstallNow()
  454.         {
  455.             lock (_lock)
  456.             {
  457.                 // show & set as foreground window ( SW_RESTORE = 9)
  458.                 ShowWindow(ClientWindowHandleToShow, 9);
  459.                 SetForegroundWindow(ClientWindowHandleToShow);
  460.  
  461.                 //begin installing the update
  462.                 SendAsync(new UpdateHelperData(UpdateStep.Install));
  463.             }
  464.         }
  465.  
  466.         public void Cancel()
  467.         {
  468.             SendAsync(new UpdateHelperData(UpdateAction.Cancel));
  469.         }
  470.  
  471.         void RecreateBackgroundWorker()
  472.         {
  473.             lock (_lock)
  474.             {
  475.                 // Fixes windows service bugs: http://wyday.com/forum/viewtopic.php?f=1&t=2949
  476.                 //Application.DoEvents();
  477.                 bw = new BackgroundWorker();
  478.                 bw.DoWork += bw_DoWork;
  479.                 bw.RunWorkerCompleted += bw_RunWorkerCompleted;
  480.             }
  481.         }
  482.  
  483.         void SendAsync(UpdateHelperData uhd)
  484.         {
  485.             lock (_lock)
  486.             {
  487.                 if (isDisposed) return;
  488.  
  489.                 // if currently working, add the new message to the stack
  490.                 if (bw != null)
  491.                 {
  492.                     sendBuffer.Push(uhd);
  493.                 }
  494.                 else
  495.                 {
  496.                     RecreateBackgroundWorker();
  497.  
  498.                     // process immediately
  499.                     UpdateStep = uhd.UpdateStep == UpdateStep.ForceRecheckForUpdate ? UpdateStep.CheckForUpdate : uhd.UpdateStep;
  500.  
  501.                     // begin sending to the client
  502.                     bw.RunWorkerAsync(uhd);
  503.                 }
  504.             }
  505.         }
  506.  
  507.         void SafeProcessReceivedMessage(byte[] message)
  508.         {
  509.             lock (_lock)
  510.             {
  511.                 if (isDisposed) return;
  512.                 // Cast the data to the type of object we sent:
  513.                 UpdateHelperData data = UpdateHelperData.FromByteArray(message);
  514.  
  515.                 if (BufferResponse)
  516.                 {
  517.                     lock (receivedBuffer)
  518.                     {
  519.                         // only buffer important messages
  520.                         if (data.ResponseType != Response.Progress)
  521.                             receivedBuffer.Add(data);
  522.                     }
  523.  
  524.                     // checks if we're still buffering responses, if so don't process it now
  525.                     if (BufferResponse)
  526.                         return;
  527.                 }
  528.  
  529.                 ProcessReceivedMessage(data);
  530.             }
  531.         }
  532.  
  533.         void ProcessReceivedMessage(UpdateHelperData data)
  534.         {
  535.             lock (_lock)
  536.             {
  537.                 if (isDisposed) return;
  538.  
  539.                 if (data.Action == UpdateAction.GetwyUpdateProcessID)
  540.                 {
  541.                     ClientProcess = Process.GetProcessById(data.ProcessID);
  542.                     return;
  543.                 }
  544.  
  545.                 if (data.Action == UpdateAction.NewWyUpdateProcess)
  546.                 {
  547.                     // disconnect from the existing pipeclient
  548.                     pipeClient.Disconnect();
  549.  
  550.                     CreateNewPipeClient();
  551.  
  552.                     try
  553.                     {
  554.                         ClientProcess = Process.GetProcessById(data.ProcessID);
  555.                     }
  556.                     catch (Exception)
  557.                     {
  558.                         // inform the AutomaticUpdater that wyUpdate is no longer running
  559.                         if (PipeServerDisconnected != null)
  560.                             PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, "Failed to connect to the new version of wyUpdate.exe"));
  561.                     }
  562.  
  563.                     TryToConnectToPipe(data.ExtraData[0]);
  564.  
  565.                     // if the process is running - try to kill it
  566.                     if (!pipeClient.Connected)
  567.                     {
  568.                         // inform the AutomaticUpdater that wyUpdate is no longer running
  569.                         if (PipeServerDisconnected != null)
  570.                             PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, "Failed to connect to the new version of wyUpdate.exe"));
  571.                     }
  572.  
  573.                     // begin where we left off
  574.                     // if update step == RestartInfo, we need to send the restart info as well
  575.                     if (ResendRestartInfo != null && UpdateStep == UpdateStep.RestartInfo)
  576.                         ResendRestartInfo(this, EventArgs.Empty);
  577.                     else
  578.                         SendAsync(new UpdateHelperData(UpdateStep));
  579.  
  580.                     return;
  581.                 }
  582.  
  583.                 if (data.UpdateStep != UpdateStep)
  584.                 {
  585.                     // this occurs when wyUpdate is on a separate step from the AutoUpdater
  586.  
  587.                     UpdateStep prev = UpdateStep;
  588.  
  589.                     // set new update step
  590.                     UpdateStep = data.UpdateStep;
  591.  
  592.                     // tell AutoUpdater that the message we sent didn't respond in kind
  593.                     // e.g. we sent RestartInfo, and wyUpdate responded with DownloadUpdate
  594.                     // meaning we can't update yet, we're just begginning downloading the update
  595.                     if (UpdateStepMismatch != null)
  596.                         UpdateStepMismatch(this, data.ResponseType, prev);
  597.                 }
  598.  
  599.                 // wyUpdate will give us its main Window Handle so we can pass focus to it
  600.                 if (data.Action == UpdateAction.UpdateStep && data.UpdateStep == UpdateStep.RestartInfo)
  601.                     ClientWindowHandleToShow = data.ProcessID;
  602.  
  603.                 if (data.ResponseType != Response.Nothing && ProgressChanged != null)
  604.                     ProgressChanged(this, data);
  605.             }
  606.         }
  607.     }
  608.  
  609.     internal delegate void ResponseHandler(object sender, UpdateHelperData e);
  610.     internal delegate void UpdateStepMismatchHandler(object sender, Response respType, UpdateStep previousStep);
  611. }
Advertisement
Add Comment
Please, Sign In to add comment