Пример #1
0
        private void InvalidUpdateFile(AutoUpdateInfo aInfo)
        {
            MoveUpdateToTemporaryFile(aInfo);

            if (EventUpdateFailed != null)
            {
                EventUpdateFailed(this, EventArgs.Empty);
            }
        }
Пример #2
0
        private void DoCheckForUpdate()
        {
            Trace.WriteLine(Trace.kCore, ">AutoUpdate.OnCheckForUpdate");

            AutoUpdateInfo info = CheckForUpdate();

            if (info != null)
            {
                if (EventUpdateFound != null)
                {
                    EventUpdateFound(this, new EventArgsUpdateFound(info));
                }
            }
        }
Пример #3
0
        private void MoveUpdateToTemporaryFile(AutoUpdateInfo aInfo)
        {
            string tempFile = CreateTemporaryFilename();

            try
            {
                if (aInfo.FileName != null)
                {
                    File.Move(aInfo.FileName, tempFile);
                }
            }
            catch (IOException e)
            {
                UserLog.WriteLine(String.Format("Cannot move {0} to {1}", Path.GetFileName(aInfo.Uri.LocalPath), tempFile));
                UserLog.WriteLine(e.ToString());
            }
        }
Пример #4
0
        public bool ApplyUpdate(AutoUpdateInfo aInfo)
        {
            bool result = true;

            try
            {
                Assembly updateAssembly = Assembly.LoadFile(new FileInfo(aInfo.FileName).FullName);
                ExtractFiles(aInfo, updateAssembly);
            }
            catch (Exception e)
            {
                InvalidUpdateFile(aInfo);
                UserLog.WriteLine(String.Format("Error applying update: {0}", e));
                result = false;
            }

            CleanupTemporaryFiles();        // do some housekeeping

            return(result);
        }
Пример #5
0
        private void ExtractFiles(AutoUpdateInfo aInfo, Assembly aUpdateAssembly)
        {
            // Get resource names from update assembly
            string[] resources = aUpdateAssembly.GetManifestResourceNames();
            Dictionary <string, string> renameLog = new Dictionary <string, string>();

            try
            {
                foreach (string resource in resources)
                {
                    string path = Path.Combine(iUpdateFolder, resource);
                    // If a current file exists with the same name, rename it
                    if (File.Exists(path))
                    {
                        string tempName = CreateTemporaryFilename();
                        File.Move(path, tempName);
                        renameLog[tempName] = path;
                    }
                    // Copy the resource out into the new file
                    // this does not take into consideration file dates and other similar
                    // attributes (but probobly should).
                    FileInfo info = new FileInfo(path);
                    using (Stream res = aUpdateAssembly.GetManifestResourceStream(resource), file = new FileStream(path, FileMode.CreateNew))
                    {
                        Int32 pseudoByte;
                        while ((pseudoByte = res.ReadByte()) != -1)
                        {
                            file.WriteByte((Byte)pseudoByte);
                        }
                    }
                }
                // If we made it this far, it is safe to rename the update assembly
                MoveUpdateToTemporaryFile(aInfo);

                Type[] types = aUpdateAssembly.GetTypes();
                foreach (Type t in types)
                {
                    MethodInfo[] methods = t.GetMethods(BindingFlags.Public | BindingFlags.Static);
                    foreach (MethodInfo m in methods)
                    {
                        if (m.GetParameters().Length == 0 && m.ReturnType == typeof(void))
                        {
                            // Found one, lets call it
                            m.Invoke(null, null);
                        }
                    }
                }
            }
            catch
            {
                // Unwind failed operation
                foreach (KeyValuePair <string, string> rename in renameLog)
                {
                    string filename = rename.Value;
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                    File.Move(rename.Key, filename);
                }
                throw; // rethrow whatever went wrong
            }
        }
Пример #6
0
        public void DownloadUpdate(AutoUpdateInfo aInfo)
        {
            iUpdateProgress = 0;
            if (EventUpdateProgress != null)
            {
                EventUpdateProgress(this, EventArgs.Empty);
            }

            int    startingPoint = 0;
            string tempFile      = string.Format("{0}{2}{1}", aInfo.Name, aInfo.Version, ".part");

            tempFile = Path.Combine(iUpdateFolder, tempFile);
            if (File.Exists(tempFile))
            {
                startingPoint = (int)(new FileInfo(tempFile).Length);
            }

            try
            {
                HttpWebRequest headRequest = (HttpWebRequest)WebRequest.Create(aInfo.Uri);
                headRequest.Method = "HEAD";
                HttpWebResponse headResponse  = (HttpWebResponse)headRequest.GetResponse();
                int             contentLength = Int32.Parse(headResponse.Headers[HttpResponseHeader.ContentLength]);

                if (contentLength > startingPoint)
                {
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(aInfo.Uri);
                    request.Credentials = CredentialCache.DefaultCredentials;
                    if (request.Proxy != null)
                    {
                        request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    }
                    request.AddRange(startingPoint);
                    HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
                    Stream          responseSteam = response.GetResponseStream();
                    FileStream      fileStream    = null;
                    if (startingPoint == 0 || response.StatusCode != HttpStatusCode.PartialContent)
                    {
                        fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    }
                    else
                    {
                        fileStream = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    }

                    int  bytesSize;
                    long fileSize = response.ContentLength;
                    Trace.WriteLine(Trace.kCore, "fileSize=" + fileSize);
                    byte[] downloadBuffer = new byte[kPacketLength];
                    int    total          = startingPoint;

                    iUpdateProgress = (int)((total / (float)fileSize) * 100.0f);
                    if (EventUpdateProgress != null)
                    {
                        EventUpdateProgress(this, EventArgs.Empty);
                    }

                    while ((bytesSize = responseSteam.Read(downloadBuffer, 0, downloadBuffer.Length)) > 0)
                    {
                        fileStream.Write(downloadBuffer, 0, bytesSize);

                        total          += bytesSize;
                        iUpdateProgress = (int)((total / (float)fileSize) * 100.0f);

                        if (EventUpdateProgress != null)
                        {
                            EventUpdateProgress(this, EventArgs.Empty);
                        }
                    }

                    if (fileStream != null)
                    {
                        fileStream.Close();
                        fileStream.Dispose();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                string fileName = Path.Combine(iUpdateFolder, Guid.NewGuid().ToString() + ".dll");
                File.Move(tempFile, fileName);
                aInfo.FileName = fileName;
            }
            catch (Exception e)
            {
                UserLog.WriteLine(String.Format("Error downloading update: {0}", e));
                InvalidUpdateFile(aInfo);
            }
        }
Пример #7
0
 public EventArgsUpdateFound(AutoUpdateInfo aInfo)
 {
     Info = aInfo;
 }
Пример #8
0
        public AutoUpdateInfo CheckForUpdate()
        {
            WebResponse response = null;
            Stream      stream   = null;

            try
            {
                WebRequest request = WebRequest.Create(iUpdateFeedLocation);
                request.Credentials = CredentialCache.DefaultCredentials;
                if (request.Proxy != null)
                {
                    request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                }
                response = request.GetResponse();
                stream   = response.GetResponseStream();

                XmlDocument       document = new XmlDocument();
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.XmlResolver = null;
                settings.ProhibitDtd = true;
                XmlReader xmlReader = XmlTextReader.Create(stream, settings);
                document.Load(xmlReader);

                XmlNamespaceManager xmlNsMan = new XmlNamespaceManager(document.NameTable);
                xmlNsMan.AddNamespace("ns", "urn:linn-co-uk/autoupdate");

                string latestVersion = iHelper.Version;
                string product       = iHelper.Product;

                AutoUpdateInfo result = null;

                KeyValuePair <EUpdateType, string>[] versionTypeNodeNames = new KeyValuePair <EUpdateType, string>[]
                {
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Stable, "stable"),
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Beta, "beta"),
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Development, "development"),
                    new KeyValuePair <EUpdateType, string>(EUpdateType.Nightly, "nightly")
                };

                foreach (XmlNode applicationNode in document.SelectNodes(string.Format("/ns:autoupdate/ns:updateinfo[@version='{0}']/ns:application[@name='{1}']", iUpdateVersion, iApplicationName), xmlNsMan))
                {
                    Uri historyUri = new Uri(applicationNode.SelectSingleNode("ns:history", xmlNsMan).FirstChild.Value);

                    foreach (KeyValuePair <EUpdateType, string> versionType in versionTypeNodeNames)
                    {
                        if ((UpdateTypes & versionType.Key) == versionType.Key)
                        {
                            foreach (XmlNode versionNode in applicationNode.SelectNodes(string.Format("ns:{0}", versionType.Value), xmlNsMan))
                            {
                                string version = versionNode.Attributes["version"].Value;

                                if (VersionSupport.CompareVersions(version, latestVersion) > 0 ||
                                    (VersionSupport.CompareVersions(version, latestVersion) == 0 && versionType.Key > iApplicationBuildType))
                                {
                                    XmlNode uriNode = versionNode.SelectSingleNode(String.Format("ns:url[@target='{0}']", iApplicationTarget), xmlNsMan);
                                    if (uriNode != null)
                                    {
                                        UserLog.WriteLine(String.Format("{0} update available: {1}", versionType.Value, version));
                                        Uri uri = new Uri(uriNode.InnerText);
                                        result        = new AutoUpdateInfo(iApplicationName, version, historyUri, uri, versionType.Key, VersionSupport.Family(iHelper.Version) != VersionSupport.Family(version));
                                        latestVersion = version;
                                    }
                                }
                            }
                        }
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                UserLog.WriteLine(String.Format("Error caught checking for updates: {0}", ex.ToString()));
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
            }

            return(null);
        }
Пример #9
0
        /// <summary>
        /// 检查更新
        /// </summary>
        public static void CheckUpdateStatus()
        {
            string CurrentVersion = ConfigurationManager.AppSettings["CurrentVersion"]; //当前程序的version版本
            string AppId          = ConfigurationManager.AppSettings["AppId"];          //当前程序的AppId,唯一标示

            Bll.AppVersion appVersion = new AppVersion();
            string         tempVal    = appVersion.GetAppVersion();
            //MessageBox.Show(str);
            JObject jo = (JObject)JsonConvert.DeserializeObject(tempVal);

            if (JObjectHelper.GetStrNum(jo["code"].ToString()) == 200)  //请求成功
            {
                int[] _currentVersion = Array.ConvertAll <string, int>(CurrentVersion.Split('.'), int.Parse);
                int[] _updateVersion  = Array.ConvertAll <string, int>(jo["dataList"]["VersionNo"].ToString().Split('.'), int.Parse);
                int   len             = _currentVersion.Length >= _updateVersion.Length
                    ? _updateVersion.Length
                    : _currentVersion.Length;
                //判断是否需要更新
                bool bo = false;
                for (int i = 0; i < len; i++)
                {
                    if (!bo)
                    {
                        bo = _currentVersion[i] < _updateVersion[i];
                    }
                    else
                    {
                        break;
                    }
                }
                //bo=true可以更新,false不用更新
                if (bo)
                {
                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        AutoUpdateInfo autoUpdate = new AutoUpdateInfo();
                        bool?update_bo            = autoUpdate.ShowDialog();
                        if (update_bo == null || update_bo == false)
                        {
                            return;
                        }
                        string appDir        = Path.Combine(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.LastIndexOf(Path.DirectorySeparatorChar)));
                        string updateFileDir = Path.Combine(Path.Combine(appDir.Substring(0, appDir.LastIndexOf(Path.DirectorySeparatorChar))), "temporary");
                        if (!Directory.Exists(updateFileDir))
                        {
                            Directory.CreateDirectory(updateFileDir);
                        }

                        string exePath = Path.Combine(updateFileDir, "Update");

                        if (!Directory.Exists(exePath))
                        {
                            Directory.CreateDirectory(exePath);
                        }
                        //File.Copy(Path.Combine(appDir,"Update"),exePath,true);
                        FileOperationHelper.FileCopy(Path.Combine(appDir, "Update"), exePath, true);
                        //string str= "{\"CurrentVersion\":\"" + CurrentVersion + "\",\"AppId\":\"" + AppId + "\"}";
                        ProcessStartInfo psi      = new ProcessStartInfo();
                        Process ps                = new Process();
                        psi.FileName              = Path.Combine(exePath, "IntoApp.AutoUpdate.exe");
                        psi.Arguments             = tempVal.Replace(" ", "").Replace("\"", "*") + " " + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IntoApp.exe");
                        psi.UseShellExecute       = false;
                        psi.RedirectStandardError = true;
                        //Process.Start(psi);
                        //ProcessHelper.OpenAdminProcess(psi, ps, "自动更新失败,稍后请手动更新!");
                        ShellExecute(IntPtr.Zero, "runas", @Path.Combine(exePath, "IntoApp.AutoUpdate.exe"), tempVal.Replace(" ", "").Replace("\"", "*") + " " + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IntoApp.exe"), "", 5);
                        Application.Current.Shutdown();
                    });
                }
            }
            else    //请求失败
            {
            }
        }