示例#1
0
 public virtual void Restore()
 {
     CopyHelper.DirectoryCopy(this.args.RestorePath, this.args.AppFolder, true);
 }
示例#2
0
        public override string DeployExcutor(FormHandler.FormItem fileItem)
        {
            var projectPath = Path.Combine(Setting.PublishLinuxPathFolder, _serviceName);

            _projectPublishFolder = Path.Combine(projectPath,
                                                 !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss"));
            EnsureProjectFolder(projectPath);
            EnsureProjectFolder(_projectPublishFolder);
            var deployFolder = string.Empty;

            try
            {
                var _zipFile = Path.Combine(_projectPublishFolder, fileItem.FileName);
                using (var fs = new FileStream(_zipFile, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length);
                }


                if (!File.Exists(_zipFile))
                {
                    return("publish file save fail");
                }
#if NETCORE
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Log("linux agent version ==>" + Version.VERSION);
                }
                else
                {
                    Log("netcore agent version ==>" + Version.VERSION);
                }
#else
                Log("netframework agent version ==>" + Version.VERSION);
#endif
                Log("upload success ==>" + _zipFile);
                //解压
                try
                {
                    Log("start unzip file");
                    ZipFile.ExtractToDirectory(_zipFile, _projectPublishFolder);
                }
                catch (Exception ex)
                {
                    return("unzip publish file error:" + ex.Message);
                }

                Log("unzip success ==>" + _projectPublishFolder);

                deployFolder = findUploadFolder(_projectPublishFolder, true);

                if (!Directory.Exists(deployFolder))
                {
                    return("unzip publish file error,Path not found:" + deployFolder);
                }

                //查找  Service 里面是否存在该服务
                var service = LinuxServiceHelper.GetLinuxService(this._serviceName);
                if (!string.IsNullOrEmpty(service.Item1))
                {
                    //运行命令出错了
                    return(service.Item1);
                }

                if (string.IsNullOrEmpty(service.Item2)) //没有找到该服务的workingFolder 可能是service描述文件内容不对,可能是服务不存在
                {
                    Log($"systemctlService : {_serviceName} not found,start to create!");

                    //创建发布目录
                    var firstDeployFolder = string.IsNullOrEmpty(_physicalPath) ? Path.Combine(projectPath, "deploy") : _physicalPath;
                    EnsureProjectFolder(firstDeployFolder);
                    if (Directory.Exists(firstDeployFolder))
                    {
                        Log($"deploy folder create success : {firstDeployFolder} ");
                    }
                    else
                    {
                        return($"DeployFolder : {firstDeployFolder} create error!");
                    }

                    //复制文件到发布目录
                    CopyHelper.ProcessXcopy(deployFolder, firstDeployFolder, Log);

                    Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]");

                    //linux service
                    var execFullPath = Path.Combine(firstDeployFolder, _serviceExecName);
                    if (!File.Exists(execFullPath))
                    {
                        //try { Directory.Delete(firstDeployFolder, true); } catch (Exception) { }
                        return($"systemctl service exec file not found : {execFullPath}");
                    }

                    //安装服务
                    Log($"start to install systemctl service");
                    Log($"service name:{_serviceName}");
                    Log($"service path:{execFullPath}");
                    Log($"service description:{_serviceDescription ?? string.Empty}");

                    try
                    {
                        var err = LinuxServiceHelper.CreateServiceFileAndRun(this._serviceName, firstDeployFolder, _serviceExecName,
                                                                             (_serviceDescription ?? string.Empty), _env, execFullPath,
                                                                             string.IsNullOrEmpty(_serviceStartType) || _serviceStartType.Equals("Auto"), _notify, Log);
                        if (!string.IsNullOrEmpty(err))
                        {
                            return(err);
                        }

                        //检查是否成功了?
                        var runSuccess = false;

                        Thread.Sleep(5000);

                        CopyHelper.RunCommand($"sudo systemctl status {this._serviceName}", null, (msg) =>
                        {
                            if (!string.IsNullOrEmpty(msg))
                            {
                                this.Log(msg);
                                var msg1 = msg.ToLower();
                                if (msg1.Contains("activating (start)"))
                                {
                                    runSuccess = true;
                                }
                                else if (msg1.Contains("active:") && msg1.Contains("running"))
                                {
                                    runSuccess = true;
                                }
                            }
                        });

                        if (!runSuccess)
                        {
                            return($"install linux service fail");
                        }

                        Log($"install systemctl service success");
                        return(string.Empty);
                    }
                    catch (Exception e2)
                    {
                        return($"install linux service fail:" + e2.Message);
                    }
                }

                var projectLocationFolder = service.Item2;

                try
                {
                    if (!Directory.Exists(projectLocationFolder))
                    {
                        //如果目录不存在 那么就重新建立
                        EnsureProjectFolder(projectLocationFolder);
                    }
                }
                catch (Exception)
                {
                    return("ServiceFolder is not correct ===> " + projectLocationFolder);
                }

                if (string.IsNullOrEmpty(projectLocationFolder))
                {
                    return("ServiceFolder is not correct ===> " + projectLocationFolder);
                }

                var fullExcutePath = Path.Combine(projectLocationFolder, _serviceExecName);
                if (!File.Exists(fullExcutePath))
                {
                    return($"systemctl service exec file not found : {fullExcutePath}");
                }

                //保证有service描述文件 等后面实际要用到
                LinuxServiceHelper.CreateServiceFile(this._serviceName, projectLocationFolder, _serviceExecName,
                                                     (_serviceDescription ?? string.Empty), _env, this._notify, Log);

                Arguments args = new Arguments
                {
                    DeployType          = "Linux",
                    BackupFolder        = Setting.BackUpLinuxPathFolder,
                    AppName             = _serviceName,
                    AppFolder           = projectLocationFolder,
                    TempPhysicalPath    = Path.Combine(projectLocationFolder, $"{_serviceName}.service"), //服务文件描述
                    DeployFolder        = deployFolder,
                    ApplicationPoolName = fullExcutePath,
                    BackUpIgnoreList    = this._backUpIgnoreList,
                    UseOfflineHtm       = string.IsNullOrEmpty(_serviceStartType) || _serviceStartType.Equals("Auto"),
                    NoBackup            = !Setting.NeedBackUp,
                    Site1 = _env
                };

                Log("Start to deploy linux Service:");
                Log("ServiceName ===>" + _serviceName);
                Log("ServiceFolder ===> " + projectLocationFolder);

                if (_isNoStopWebSite)
                {
                    args.NoStop  = true;
                    args.NoStart = true;
                }

                var ops = new OperationsLinux(args, Log);

                try
                {
                    ops.Execute();

                    try
                    {
                        //如果是增量的话 要把复制过来
                        if (_isIncrement)
                        {
                            Log("Increment deploy start to backup...");
                            //projectLocation.Item1 转到 increment 的目录
                            var incrementFolder = Path.Combine(_projectPublishFolder, "increment");
                            EnsureProjectFolder(incrementFolder);

                            if (this._backUpIgnoreList != null && this._backUpIgnoreList.Any())
                            {
                                var excludFrom = Path.Combine(_projectPublishFolder, "exclude.log");
                                File.WriteAllLines(excludFrom, this._backUpIgnoreList);
                                //存到文件里面去 要指定排除
                                CopyHelper.ProcessXcopy(projectLocationFolder, incrementFolder, excludFrom, Log);
                            }
                            else
                            {
                                CopyHelper.ProcessXcopy(projectLocationFolder, incrementFolder, Log);
                            }

                            Log("Increment deploy backup success...");
                        }
                    }
                    catch (Exception ex3)
                    {
                        Log("Increment deploy folder backup fail:" + ex3.Message);
                    }

                    Log("Deploy linux service Execute Success");
                }
                catch (Exception ex)
                {
                    try
                    {
                        //ops.Rollback();

                        return($"publish to linux service err:{ex.Message}");
                    }
                    catch (Exception ex2)
                    {
                        return($"publish to linux service err:{ex.Message},rollback fail:{ex2.Message}");
                    }
                }

                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            finally
            {
                if (!string.IsNullOrEmpty(deployFolder) && Directory.Exists(deployFolder))
                {
                    new Task(() =>
                    {
                        try
                        {
                            Directory.Delete(deployFolder, true);
                        }
                        catch (Exception)
                        {
                            //ignore
                        }
                    }).Start();
                }
            }
        }
示例#3
0
        public override void Deploy()
        {
            if (args.UseTempPhysicalPath)
            {
                //先从iis站点 this.args.AppFolder 复制 到 当前 日期文件夹下的deploy文件夹  然后在 DeployFolder 复制到 日期文件夹下的deploy文件夹
                var isSuccess = CopyHelper.ProcessXcopy(this.args.AppFolder, this.args.TempPhysicalPath, logger);

                if (!isSuccess)
                {
                    logger($"【Error】Copy `{this.args.AppFolder}` to `{this.args.TempPhysicalPath}` fail");
                    throw new Exception($"Copy `{this.args.AppFolder}` to `{this.args.TempPhysicalPath}` fail");
                }

                isSuccess = CopyHelper.ProcessXcopy(this.args.DeployFolder, this.args.TempPhysicalPath, logger);

                if (!isSuccess)
                {
                    logger($"【Error】Copy `{this.args.DeployFolder}` to `{this.args.TempPhysicalPath}` fail");
                    throw new Exception($"Copy `{this.args.DeployFolder}` to `{this.args.TempPhysicalPath}` fail");
                }

                //修改物理路径
                var err = IISHelper.ChangePhysicalPath(this.args.Site1, this.args.Site2, this.args.TempPhysicalPath);
                if (!string.IsNullOrEmpty(err))
                {
                    logger($"【Error】Change `{this.args.SiteName}` physicalPath to `{this.args.TempPhysicalPath}` fail");
                    throw new Exception($"【Error】Change `{this.args.SiteName}` physicalPath to `{this.args.TempPhysicalPath}` fail");
                }

                //回收一下
                var r1 = ProcessHepler.RunAppCmd($"recycle apppool /apppool.name:\"{this.args.ApplicationPoolName}\"", logger);
                logger($"recycle apppool /apppool.name:{this.args.ApplicationPoolName} ===> {(r1 ? "Success" : "Fail")}");

                return;
            }


            try
            {
                if (args.UseOfflineHtm)
                {
                    try
                    {
                        var createErr = IISHelper.CreateAppOffineHtm(this.args.AppFolder);
                        if (!string.IsNullOrEmpty(createErr))
                        {
                            logger($"【Error】Create app_offline.htm to [{this.args.AppFolder}] Fail:[{createErr}]");
                            return;
                        }

                        logger($"create app_offline.htm to [{this.args.AppFolder}] Success");

                        //创建了app_offline.htm成功后 iis会解除占用

                        //执行copy

                        if (args.UseTempPhysicalPath)
                        {
                        }
                        else
                        {
                            base.Deploy();
                        }
                    }
                    finally
                    {
                        var deleteErr = IISHelper.DeleteAppOfflineHtm(this.args.AppFolder);
                        if (!string.IsNullOrEmpty(deleteErr))
                        {
                            logger($"【Error】delete app_offline.htm from [{this.args.AppFolder}] Fail:[{deleteErr}]");
                        }

                        logger($"delete app_offline.htm from [{this.args.AppFolder}] Success");
                    }
                }
                else
                {
                    base.Deploy();
                }
            }
            catch (Exception exception)
            {
                logger("Copy File Fail :" + exception.Message);
                retryTimes++;
                logger("Wait 5Senconds to Retry :" + retryTimes);
                Thread.Sleep(5000);
                if (retryTimes > 3)
                {
                    IISHelper.KillSiteProcess(args.SiteName);
                    killPool();
                    logger("Wait 5Senconds to Try deploy again");
                    Thread.Sleep(5000);
                    try
                    {
                        base.Deploy();
                        return;
                    }
                    catch (Exception)
                    {
                        logger("【Error】Retry Copy Limit ");
                        throw;
                    }
                }

                Deploy();
            }
        }
示例#4
0
 public void OnInitialize(DeviceContextHolder holder)
 {
     _effect        = holder.GetEffect <EffectPpDof>();
     _copyHelper    = holder.GetHelper <CopyHelper>();
     _bokehBaseView = ShaderResourceView.FromMemory(holder.Device, Resources.Bokeh);
 }
        public override string DeployExcutor(FormHandler.FormItem fileItem)
        {
            var projectPath = Path.Combine(Setting.PublishWindowServicePathFolder, _serviceName);

            _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss"));
            EnsureProjectFolder(projectPath);
            EnsureProjectFolder(_projectPublishFolder);

            try
            {
                var filePath = Path.Combine(_projectPublishFolder, fileItem.FileName);
                using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length);
                }


                if (!File.Exists(filePath))
                {
                    return("publish file save fail");
                }
                Log("agent version ==>" + AntDeployAgentWindows.Version.VERSION);
                Log("upload success ==>" + filePath);
                //解压
                try
                {
                    ZipFile.ExtractToDirectory(filePath, _projectPublishFolder);
                }
                catch (Exception ex)
                {
                    return("unzip publish file error:" + ex.Message);
                }

                Log("unzip success ==>" + _projectPublishFolder);

                var deployFolder = Path.Combine(_projectPublishFolder, "publish");

                if (!Directory.Exists(deployFolder))
                {
                    return("unzip publish file error,Path not found:" + deployFolder);
                }

                //查找 Windows Service 里面是否存在该服务
                var service = WindowServiceHelper.GetWindowServiceByName(this._serviceName);
                if (service == null)
                {
                    //if (!_isProjectInstallService)
                    //{
                    //    return $"windowService : {_serviceName} not found";
                    //}

                    Log($"windowService : {_serviceName} not found,start to create!");

                    //创建发布目录
                    var firstDeployFolder = Path.Combine(projectPath, "deploy");
                    EnsureProjectFolder(firstDeployFolder);

                    Log($"deploy folder create success : {firstDeployFolder} ");

                    //复制文件到发布目录
                    CopyHelper.DirectoryCopy(deployFolder, firstDeployFolder, true);

                    Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]");

                    //部署windows service
                    var execFullPath = Path.Combine(firstDeployFolder, _serviceExecName);
                    if (!File.Exists(execFullPath))
                    {
                        try { Directory.Delete(firstDeployFolder, true); } catch (Exception) { }
                        return($"windows service exec file not found : {execFullPath} ");
                    }

                    //安装服务
                    Log($"start to install windows service");
                    Log($"service name:{_serviceName}");
                    Log($"service path:{execFullPath}");
                    try
                    {
                        ServiceInstaller.InstallAndStart(_serviceName, _serviceName, execFullPath);
                        Log($"install windows service success");
                        Log($"start windows service success");
                        return(string.Empty);
                    }
                    catch (Exception e2)
                    {
                        return($"install windows service fail:" + e2.Message);
                    }

                    //var installResult = WindowServiceHelper.InstallWindowsService(execFullPath);
                    //if (!string.IsNullOrEmpty(installResult))
                    //{
                    //    try{ Directory.Delete(firstDeployFolder, true);}catch (Exception) {}
                    //    return installResult;
                    //}


                    ////部署成功 启动服务
                    //Log($"start windows service : " + _serviceName);
                    //var startResult = WindowServiceHelper.StartService(_serviceName,120);
                    //if (!string.IsNullOrEmpty(startResult))
                    //{
                    //    try{ Directory.Delete(firstDeployFolder, true);}catch (Exception) {}
                    //    return startResult;
                    //}
                    //Log($"start windows service success");
                    //return string.Empty;
                }

                var projectLocationFolder = string.Empty;
                var projectLocation       = WindowServiceHelper.GetWindowServiceLocation(this._serviceName);
                if (string.IsNullOrEmpty(projectLocation))
                {
                    return($"can not find executable path of service:{_serviceName}");
                }

                try
                {
                    projectLocation       = projectLocation.Replace("\"", "");
                    projectLocationFolder = new FileInfo(projectLocation).DirectoryName;
                    if (!Directory.Exists(projectLocationFolder))
                    {
                        //如果目录不存在 那么就重新建立
                        EnsureProjectFolder(projectLocationFolder);
                    }
                }
                catch (Exception)
                {
                    return("ServiceFolder is not correct ===> " + projectLocationFolder);
                }

                Log("Start to deploy Windows Service:");
                Log("ServiceName ===>" + _serviceName);
                Log("ServiceFolder ===> " + projectLocationFolder);

                Arguments args = new Arguments
                {
                    DeployType   = "WindowsService",
                    BackupFolder = Setting.BackUpWindowServicePathFolder,
                    AppName      = _serviceName,
                    AppFolder    = projectLocationFolder,
                    DeployFolder = deployFolder,
                    WaitForWindowsServiceStopTimeOut = _waitForServiceStopTimeOut,
                    BackUpIgnoreList = this._backUpIgnoreList
                };

                var ops = new OperationsWINDOWSSERVICE(args, Log);

                try
                {
                    ops.Execute();

                    try
                    {
                        //如果是增量的话 要把复制过来
                        if (_isIncrement)
                        {
                            Log("Increment deploy start to backup...");
                            //projectLocation.Item1 转到 increment 的目录
                            var incrementFolder = Path.Combine(_projectPublishFolder, "increment");
                            EnsureProjectFolder(incrementFolder);
                            DirectoryInfo directoryInfo = new DirectoryInfo(projectLocationFolder);
                            string        fullName      = directoryInfo.FullName;
                            if (directoryInfo.Parent != null)
                            {
                                fullName = directoryInfo.Parent.FullName;
                            }
                            CopyHelper.DirectoryCopy(projectLocationFolder, incrementFolder, true, fullName, this._backUpIgnoreList);
                            Log("Increment deploy backup success...");
                        }
                    }
                    catch (Exception ex3)
                    {
                        Log("Increment deploy folder backup fail:" + ex3.Message);
                    }

                    Log("Deploy WindowsService Execute Success");
                }
                catch (Exception ex)
                {
                    try
                    {
                        //ops.Rollback();

                        return($"publish to WindowsService err:{ex.Message}");
                    }
                    catch (Exception ex2)
                    {
                        return($"publish to WindowsService err:{ex.Message},rollback fail:{ex2.Message}");
                    }
                }
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#6
0
        /// <summary>
        ///   Reads one entry from the zip directory structure in the zip file.
        /// </summary>
        ///
        /// <param name="zf">
        ///   The zipfile for which a directory entry will be read.  From this param, the
        ///   method gets the ReadStream and the expected text encoding
        ///   (ProvisionalAlternateEncoding) which is used if the entry is not marked
        ///   UTF-8.
        /// </param>
        ///
        /// <param name="previouslySeen">
        ///   a list of previously seen entry names; used to prevent duplicates.
        /// </param>
        ///
        /// <returns>the entry read from the archive.</returns>
        internal static ZipEntry ReadDirEntry(ZipFile zf,
                                              Dictionary <String, Object> previouslySeen)
        {
            System.IO.Stream     s = zf.ReadStream;
            System.Text.Encoding expectedEncoding = (zf.AlternateEncodingUsage == ZipOption.Always)
                ? zf.AlternateEncoding
                : ZipFile.DefaultEncoding;

            while (true)
            {
                int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
                // return null if this is not a local file header signature
                if (IsNotValidZipDirEntrySig(signature))
                {
                    s.Seek(-4, System.IO.SeekOrigin.Current);

                    // Getting "not a ZipDirEntry signature" here is not always wrong or an
                    // error.  This can happen when walking through a zipfile.  After the
                    // last ZipDirEntry, we expect to read an
                    // EndOfCentralDirectorySignature.  When we get this is how we know
                    // we've reached the end of the central directory.
                    if (signature != ZipConstants.EndOfCentralDirectorySignature &&
                        signature != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature &&
                        signature != ZipConstants.ZipEntrySignature  // workitem 8299
                        )
                    {
                        throw new BadReadException(String.Format("  Bad signature (0x{0:X8}) at position 0x{1:X8}", signature, s.Position));
                    }
                    return(null);
                }

                int    bytesRead = 42 + 4;
                byte[] block     = new byte[42];
                int    n         = s.Read(block, 0, block.Length);
                if (n != block.Length)
                {
                    return(null);
                }

                int      i   = 0;
                ZipEntry zde = new ZipEntry();
                zde.AlternateEncoding = expectedEncoding;
                zde._Source           = ZipEntrySource.ZipFile;
                zde._container        = new ZipContainer(zf);

                unchecked
                {
                    zde._VersionMadeBy     = (short)(block[i++] + block[i++] * 256);
                    zde._VersionNeeded     = (short)(block[i++] + block[i++] * 256);
                    zde._BitField          = (short)(block[i++] + block[i++] * 256);
                    zde._CompressionMethod = (Int16)(block[i++] + block[i++] * 256);
                    zde._TimeBlob          = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                    zde._LastModified      = Ionic.Zip.SharedUtilities.PackedToDateTime(zde._TimeBlob);
                    zde._timestamp        |= ZipEntryTimestamp.DOS;

                    zde._Crc32            = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
                    zde._CompressedSize   = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                    zde._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                }

                // preserve
                zde._CompressionMethod_FromZipFile = zde._CompressionMethod;

                zde._filenameLength   = (short)(block[i++] + block[i++] * 256);
                zde._extraFieldLength = (short)(block[i++] + block[i++] * 256);
                zde._commentLength    = (short)(block[i++] + block[i++] * 256);
                zde._diskNumber       = (UInt32)(block[i++] + block[i++] * 256);

                zde._InternalFileAttrs = (short)(block[i++] + block[i++] * 256);
                zde._ExternalFileAttrs = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;

                zde._RelativeOffsetOfLocalHeader = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);

                // workitem 7801
                zde.IsText = ((zde._InternalFileAttrs & 0x01) == 0x01);

                block      = new byte[zde._filenameLength];
                n          = s.Read(block, 0, block.Length);
                bytesRead += n;
                if ((zde._BitField & 0x0800) == 0x0800)
                {
                    // UTF-8 is in use
                    zde._FileNameInArchive = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
                }
                else
                {
                    zde._FileNameInArchive = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
                }

                // workitem 10330
                // insure unique entry names
                while (!zf.IgnoreDuplicateFiles && previouslySeen.ContainsKey(zde._FileNameInArchive))
                {
                    zde._FileNameInArchive = CopyHelper.AppendCopyToFileName(zde._FileNameInArchive);
                    zde._metadataChanged   = true;
                }

                if (zde.AttributesIndicateDirectory)
                {
                    zde.MarkAsDirectory();  // may append a slash to filename if nec.
                }
                // workitem 6898
                else if (zde._FileNameInArchive.EndsWith("/"))
                {
                    zde.MarkAsDirectory();
                }

                zde._CompressedFileDataSize = zde._CompressedSize;
                if ((zde._BitField & 0x01) == 0x01)
                {
                    // this may change after processing the Extra field
                    zde._Encryption_FromZipFile = zde._Encryption =
                        EncryptionAlgorithm.PkzipWeak;
                    zde._sourceIsEncrypted = true;
                }

                if (zde._extraFieldLength > 0)
                {
                    zde._InputUsesZip64 = (zde._CompressedSize == 0xFFFFFFFF ||
                                           zde._UncompressedSize == 0xFFFFFFFF ||
                                           zde._RelativeOffsetOfLocalHeader == 0xFFFFFFFF);

                    // Console.WriteLine("  Input uses Z64?:      {0}", zde._InputUsesZip64);

                    bytesRead += zde.ProcessExtraField(s, zde._extraFieldLength);
                    zde._CompressedFileDataSize = zde._CompressedSize;
                }

                // we've processed the extra field, so we know the encryption method is set now.
                if (zde._Encryption == EncryptionAlgorithm.PkzipWeak)
                {
                    // the "encryption header" of 12 bytes precedes the file data
                    zde._CompressedFileDataSize -= 12;
                }
#if AESCRYPTO
                else if (zde.Encryption == EncryptionAlgorithm.WinZipAes128 ||
                         zde.Encryption == EncryptionAlgorithm.WinZipAes256)
                {
                    zde._CompressedFileDataSize = zde.CompressedSize -
                                                  (ZipEntry.GetLengthOfCryptoHeaderBytes(zde.Encryption) + 10);
                    zde._LengthOfTrailer = 10;
                }
#endif

                // tally the trailing descriptor
                if ((zde._BitField & 0x0008) == 0x0008)
                {
                    // sig, CRC, Comp and Uncomp sizes
                    if (zde._InputUsesZip64)
                    {
                        zde._LengthOfTrailer += 24;
                    }
                    else
                    {
                        zde._LengthOfTrailer += 16;
                    }
                }

                // workitem 12744
                zde.AlternateEncoding = ((zde._BitField & 0x0800) == 0x0800)
                    ? System.Text.Encoding.UTF8
                    :expectedEncoding;

                zde.AlternateEncodingUsage = ZipOption.Always;

                if (zde._commentLength > 0)
                {
                    block      = new byte[zde._commentLength];
                    n          = s.Read(block, 0, block.Length);
                    bytesRead += n;
                    if ((zde._BitField & 0x0800) == 0x0800)
                    {
                        // UTF-8 is in use
                        zde._Comment = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
                    }
                    else
                    {
                        zde._Comment = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
                    }
                }
                //zde._LengthOfDirEntry = bytesRead;
                if (zf.IgnoreDuplicateFiles && previouslySeen.ContainsKey(zde._FileNameInArchive))
                {
                    continue;
                }
                return(zde);
            }
        }
示例#7
0
        private void GA_Button_Click(object sender, EventArgs e)
        {
            messageBox.Text = string.Empty;
            Stopwatch sw = new Stopwatch();

            sw.Start();
            var uri     = string.Format($"{Environment.CurrentDirectory}");
            var fullUri = string.Empty;

            if (string.IsNullOrWhiteSpace(PathBox.Text))
            {
                fullUri = string.Format($"{Environment.CurrentDirectory}\\Data\\OD.xlsx");
            }
            else
            {
                fullUri = PathBox.Text;
            }
            var groups = new List <Group>();

            Varias.GroupNo = 0;
            ReadExcel.Excel2Json(fullUri);
            var nodesOrigin = ReadExcel.Nodes(fullUri);
            var odsOrigin   = ReadExcel.OD(fullUri);
            var result      = ReadExcel.LuDuan(fullUri);

            result = result.OrderBy(l => l.No).ToList();
            var luduansOrigin = ReadExcel.LuduanAndPoint(result, fullUri);

            messageBox.Text += string.Format($"数据读入成功!\r\n{nameof(nodesOrigin)}:{nodesOrigin.Count}\r\n");
            messageBox.Text += string.Format($"{nameof(odsOrigin)}:{odsOrigin.Count}\r\n");
            messageBox.Text += string.Format($"{nameof(luduansOrigin)}:{luduansOrigin.Count}\r\n");
            #region 产生种群
            for (int i = 0; i < Varias.M; i++)
            {
                var luduans = CopyHelper.DeepClone(luduansOrigin);
                var ods     = CopyHelper.DeepClone(odsOrigin);
                var nodes   = CopyHelper.DeepClone(nodesOrigin);
                foreach (var od in ods)
                {
                    od.LuJings = GenarateLuJing.GetAllPath(od, luduans, nodes);
                    foreach (var lujing in od.LuJings) //添加路段所在路径信息
                    {
                        foreach (var luduan in lujing.LuDuans)
                        {
                            if (luduan.No != 0)
                            {
                                if (luduans.NumOf(luduan.No).At == null)
                                {
                                    luduans.NumOf(luduan.No).At = new List <LuJing>();
                                }

                                if (!luduans.NumOf(luduan.No).At.Any(l => l.start.No == lujing.Nodes.First().No&& l.end.No == lujing.Nodes.Last().No))
                                {
                                    luduans.NumOf(luduan.No).At.Add(lujing);
                                }
                            }
                        }
                    }
                }
                var group = new Group
                {
                    No      = Varias.GroupNo,
                    Luduans = luduans,
                    Ods     = ods
                };
                foreach (var ld in group.Luduans)
                {
                    ld.F = Randam.F;
                }
                groups.Add(group);
                Varias.GroupNo += 1;
            }
            messageBox.Text += string.Format($"产生种群:{groups.Count}\r\n");
            #endregion
            sw.Stop();
            messageBox.Text += string.Format(($"数据读取完成,耗时{sw.ElapsedMilliseconds / 1000}秒,开始数据初始化\r\n"));
            #region 循环
            sw.Restart();
            Varias.IsGA = true;
            foreach (var group in groups)
            {
                group.Result = Iteration.Run(group.Ods, group.Luduans, ReadExcel.Nodes(fullUri), uri);
            }
            sw.Stop();
            messageBox.Text += string.Format(($"数据初始化完成,{groups.Count}个种群共耗时{sw.ElapsedMilliseconds / 1000}秒,开始遗传算法迭代\r\n"));
            var minResults = new List <double>();
            var minFs      = new List <List <int> >();
            sw.Restart();
            var results = new Dictionary <int, List <double> >();
            for (int i = 0; i < Varias.T; i++)
            {
                var sw2 = new Stopwatch();
                sw2.Start();
                var chosenGroup = CopyHelper.DeepClone(Randam.Roulette(groups));
                var children    = GeneticAlgorithm.Children(chosenGroup, CopyHelper.DeepClone(odsOrigin), CopyHelper.DeepClone(luduansOrigin), CopyHelper.DeepClone(nodesOrigin));
                #region 原有串行代码
                //foreach (var child in children)
                //{
                //    child.Result = Iteration.Run(child.Ods, child.Luduans, ReadExcel.Nodes(fullUri), uri);
                //}
                #endregion
                #region 并行
                Parallel.ForEach <Group>(children, child =>
                {
                    child.Result = Iteration.Run(child.Ods, child.Luduans, ReadExcel.Nodes(fullUri), uri);
                });
                #endregion
                var minGroup = groups.OrderBy(g => g.Result).Take(Varias.M - (int)Math.Round(Varias.M * Varias.Pc)).ToList();
                children.AddRange(minGroup);
                children = GeneticAlgorithm.CalculateFitness(children);
                var minResult = children.Min(c => c.Result);
                minResults.Add(minResult);
                minFs.Add(CopyHelper.DeepClone(children.FirstOrDefault(g => g.Result == minResult).Fs));
                results.Add(i, children.Select(c => c.Result).ToList());
                sw2.Stop();
                groups           = children;
                messageBox.Text += string.Format(($"第{i + 1}次迭代完成,耗时{sw2.ElapsedMilliseconds / 1000}秒\r\n"));
            }

            sw.Stop();
            messageBox.Text += string.Format(($"遗传算法完成,{Varias.T}次迭代共耗时{sw.ElapsedMilliseconds / 1000}秒"));
            #endregion
            #region 输出到Excel
            IWorkbook workbook = new XSSFWorkbook();
            ISheet    sheet1   = workbook.CreateSheet("ResultFs");
            IRow      row0     = sheet1.CreateRow(0);
            row0.CreateCell(0).SetCellValue("Result");
            row0.CreateCell(1).SetCellValue("Fs");
            row0.CreateCell(1).SetCellValue(Varias.MaxResult);
            var rowCount = 0;
            foreach (var Fs in minFs)
            {
                rowCount = rowCount + 1;
                IRow row = sheet1.CreateRow(rowCount);
                row.CreateCell(0).SetCellValue(minResults[rowCount - 1]);
                for (int i = 0; i < Fs.Count; i++)
                {
                    row.CreateCell(i + 1).SetCellValue(Fs[i]);
                }
            }
            ISheet sheet2 = workbook.CreateSheet("AllResult");
            IRow   row1   = sheet2.CreateRow(0);
            row1.CreateCell(0).SetCellValue("No");
            row1.CreateCell(1).SetCellValue("Result");
            rowCount = 0;
            foreach (var list in results)
            {
                rowCount = rowCount + 1;
                IRow row = sheet2.CreateRow(rowCount);
                row1.CreateCell(0).SetCellValue(string.Format($"{list.Key}"));
                for (int i = 0; i < list.Value.Count; i++)
                {
                    row.CreateCell(i + 1).SetCellValue(list.Value[i]);
                }
            }
            ISheet sheet3 = workbook.CreateSheet("AllGroups");
            IRow   row3   = sheet3.CreateRow(0);
            rowCount = 0;
            foreach (var list in groups)
            {
                rowCount = rowCount + 1;
                IRow row = sheet3.CreateRow(rowCount);
                row.CreateCell(0).SetCellValue(string.Format($"{list.Fitness}"));
                for (int i = 0; i < list.Fs.Count; i++)
                {
                    row.CreateCell(i + 1).SetCellValue(list.Fs[i]);
                }
            }


            var        newFile = string.Format($"{uri}\\Data\\{DateTime.Now.Day}-{DateTime.Now.Hour}-{DateTime.Now.Minute}-{DateTime.Now.Second}-遗传算法结果.xlsx");
            FileStream sw1     = File.Create(newFile);
            workbook.Write(sw1);
            workbook.Close();
            sw1.Close();
            #endregion
        }
示例#8
0
        public override string DeployExcutor(FormHandler.FormItem fileItem)
        {
            var projectPath = Path.Combine(Setting.PublishIIsPathFolder, _projectName);

            _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss"));
            EnsureProjectFolder(projectPath);
            EnsureProjectFolder(_projectPublishFolder);

            try
            {
                var isNetcore = _sdkTypeName.ToLower().Equals("netcore");
                var filePath  = Path.Combine(_projectPublishFolder, fileItem.FileName);
                using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length);
                }


                if (!File.Exists(filePath))
                {
                    return("publish file save fail");
                }
#if NETCORE
                Log("netcore agent version ==>" + AntDeployAgentWindows.Version.VERSION);
#else
                Log("netframework agent version ==>" + AntDeployAgentWindows.Version.VERSION);
#endif


                Log("upload success ==>" + filePath);
                //解压
                try
                {
                    Log("start unzip file");
                    ZipFile.ExtractToDirectory(filePath, _projectPublishFolder);
                }
                catch (Exception ex)
                {
                    return("unzip publish file error:" + ex.Message);
                }

                Log("unzip success ==>" + _projectPublishFolder);

                var deployFolder = Path.Combine(_projectPublishFolder, "publish");

                if (!Directory.Exists(deployFolder))
                {
                    if (Directory.Exists(_projectPublishFolder))
                    {
                        var temp           = new DirectoryInfo(_projectPublishFolder);
                        var tempFolderList = temp.GetDirectories();
                        if (tempFolderList.Length == 1)
                        {
                            deployFolder = tempFolderList.First().FullName;
                        }
                    }
                }

                if (!Directory.Exists(deployFolder))
                {
                    return("unzip publish file error,Path not found:" + deployFolder);
                }

                //查找 IIS 里面是否存在
                var siteArr = _webSiteName.Split('/');
                if (siteArr.Length > 2)
                {
                    return($"website level limit is 2!");
                }

                var level1 = siteArr[0];
                var level2 = siteArr.Length == 2 ? siteArr[1] : string.Empty;

                var isSiteExistResult = IISHelper.IsSiteExist(level1, level2);
                if (!string.IsNullOrEmpty(isSiteExistResult.Item3))
                {
                    return($"【Error】 : {isSiteExistResult.Item3}");
                }

                var iisVersion = IISHelper.GetIISVersion();
                if (iisVersion > 0)
                {
                    Log($"IIS_Version : {iisVersion} ");
                }
                if (!isSiteExistResult.Item1)//一级都不存在
                {
                    if (iisVersion <= 6)
                    {
                        return($"website : {_webSiteName} not found,start to create,but iis verison is too low!");
                    }

                    //准备好目录
                    if (string.IsNullOrEmpty(_port))
                    {
                        if (IISHelper.IsDefaultWebSite(level1))
                        {
                            _port = "80";
                        }
                        else
                        {
                            return($"website : {_webSiteName} not found,start to create,but port is required!");
                        }
                    }

                    Log($"website : {_webSiteName} not found,start to create!");

                    //创建发布目录
                    var firstDeployFolder = string.IsNullOrEmpty(_physicalPath)? Path.Combine(projectPath, "deploy"):_physicalPath;
                    EnsureProjectFolder(firstDeployFolder);
                    if (Directory.Exists(firstDeployFolder))
                    {
                        Log($"deploy folder create success : {firstDeployFolder} ");
                    }
                    else
                    {
                        return($"DeployFolder : {firstDeployFolder} create error!");
                    }


                    var rt = IISHelper.InstallSite(level1, firstDeployFolder, _port, (string.IsNullOrEmpty(_poolName) ? _projectName : _poolName), isNetcore);
                    if (string.IsNullOrEmpty(rt))
                    {
                        Log($"create website : {level1} success ");
                    }
                    else
                    {
                        return($"create website : {level1} error: {rt} ");
                    }

                    if (!string.IsNullOrEmpty(level2))
                    {
                        //创建一级 但是一级需要一个空的目录
                        //创建二级虚拟目录 二级的目录才是正常程序所在目录
                        var level2Folder = Path.Combine(firstDeployFolder, level2);
                        EnsureProjectFolder(level2Folder);

                        var rt2 = IISHelper.InstallVirtualSite(level1, level2, level2Folder, (string.IsNullOrEmpty(_poolName) ? _projectName : _poolName), isNetcore);
                        if (string.IsNullOrEmpty(rt2))
                        {
                            Log($"create virtualSite :{level2} Of Website : {level1} success ");
                        }
                        else
                        {
                            return($"create virtualSite :{level2} website : {level1} error: {rt2} ");
                        }

                        //复制文件到发布目录
                        CopyHelper.ProcessXcopy(deployFolder, level2Folder, Log);

                        Log($"copy files success from [{deployFolder}] to [{level2Folder}]");
                        return(String.Empty);
                    }
                    else
                    {
                        //只需要一级 就是程序所在目录
                        //复制文件到发布目录
                        CopyHelper.ProcessXcopy(deployFolder, firstDeployFolder, Log);

                        Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]");
                        return(String.Empty);
                    }
                }
                else if (isSiteExistResult.Item1 && !isSiteExistResult.Item2 && !string.IsNullOrEmpty(level2))
                {
                    if (IISHelper.GetIISVersion() <= 6)
                    {
                        return($"website : {_webSiteName} not found,start to create,but iis verison is too low!");
                    }

                    //有一级 但是需要创建二级

                    Log($"website : {_webSiteName} not found,start to create!");
                    //创建发布目录
                    var firstDeployFolder = string.IsNullOrEmpty(_physicalPath)? Path.Combine(projectPath, "deploy"):_physicalPath;
                    EnsureProjectFolder(firstDeployFolder);
                    Log($"deploy folder create success : {firstDeployFolder} ");

                    var level2Folder = Path.Combine(firstDeployFolder, level2);
                    EnsureProjectFolder(level2Folder);

                    var rt2 = IISHelper.InstallVirtualSite(level1, level2, level2Folder, (string.IsNullOrEmpty(_poolName) ? _projectName : _poolName), isNetcore);
                    if (string.IsNullOrEmpty(rt2))
                    {
                        Log($"create virtualSite :{level2} Of Website : {level1} success ");
                    }
                    else
                    {
                        return($"create virtualSite :{level2} website : {level1} error: {rt2} ");
                    }

                    //复制文件到发布目录
                    CopyHelper.ProcessXcopy(deployFolder, level2Folder, Log);

                    Log($"copy files success from [{deployFolder}] to [{level2Folder}]");
                    return(String.Empty);
                }



                var projectLocation = IISHelper.GetWebSiteLocationInIIS(level1, level2, Log);
                if (projectLocation == null)
                {
                    return($"read info from iis error");
                }

                if (string.IsNullOrEmpty(projectLocation.Item1))
                {
                    return($"website : {_webSiteName} not found in iis");
                }

                if (!Directory.Exists(projectLocation.Item1))
                {
                    //如果目录不存在 那么就重新建立
                    EnsureProjectFolder(projectLocation.Item1);
                }

                Log("Start to deploy IIS:");
                Log("SiteName ===>" + _webSiteName);
                Log("SiteFolder ===> " + projectLocation.Item1);
                Log("SiteApplicationPoolName ===> " + projectLocation.Item3);

                Arguments args = new Arguments
                {
                    DeployType          = "IIS",
                    BackupFolder        = Setting.BackUpIIsPathFolder,
                    AppName             = _projectName,
                    ApplicationPoolName = projectLocation.Item3,
                    AppFolder           = projectLocation.Item1,
                    DeployFolder        = deployFolder,
                    SiteName            = projectLocation.Item2,
                    BackUpIgnoreList    = this._backUpIgnoreList,
                    NoBackup            = !Setting.NeedBackUp
                };

                if (_useOfflineHtm)
                {
                    args.NoStop        = true;
                    args.NoStart       = true;
                    args.UseOfflineHtm = true;
                }
                else if (_isNoStopWebSite)
                {
                    args.NoStop  = true;
                    args.NoStart = true;
                }
                var ops = new OperationsIIS(args, Log);

                try
                {
                    ops.Execute();
                    try
                    {
                        //如果是增量的话 要把复制过来
                        if (_isIncrement)
                        {
                            Log("Increment deploy start to backup...");
                            //projectLocation.Item1 转到 increment 的目录
                            var incrementFolder = Path.Combine(_projectPublishFolder, "increment");
                            EnsureProjectFolder(incrementFolder);
                            DirectoryInfo directoryInfo = new DirectoryInfo(projectLocation.Item1);
                            string        fullName      = directoryInfo.FullName;
                            if (directoryInfo.Parent != null)
                            {
                                fullName = directoryInfo.Parent.FullName;
                            }
                            CopyHelper.DirectoryCopy(projectLocation.Item1, incrementFolder, true, fullName, directoryInfo.Name, this._backUpIgnoreList);
                            Log("Increment deploy backup success...");
                        }
                    }
                    catch (Exception ex3)
                    {
                        Log("Increment deploy folder backup fail:" + ex3.Message);
                    }

                    Log("Deploy IIS Execute Success");
                }
                catch (Exception ex)
                {
                    try
                    {
                        //ops.Rollback();

                        return($"publish to iis err:{ex.Message}");
                    }
                    catch (Exception ex2)
                    {
                        return($"publish to iis err:{ex.Message},rollback fail:{ex2.Message}");
                    }
                }
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#9
0
 public virtual void Restore()
 {
     logger("Start to Restore");
     CopyHelper.DirectoryCopy(this.args.RestorePath, this.args.AppFolder, true);
     logger("Success Restore from folder:[" + this.args.RestorePath + "] to folder:[" + this.args.AppFolder + "]");
 }
示例#10
0
 /// <summary>
 /// A primitive inverse CopyTo implementation that scrapes public fields and properties and
 /// copies them to the target object. Will not target private fields/properties.
 /// </summary>
 /// <typeparam name="T">
 /// </typeparam>
 /// <param name="ťhis">
 /// </param>
 /// <param name="that">
 /// </param>
 public static void PrimitiveCopyFrom <T>(this T ťhis, T that, bool copyPrivate = false)
 {
     CopyHelper.CopyProperties(that, ťhis, copyPrivate);
     CopyHelper.CopyFields(that, ťhis, copyPrivate);
 }
示例#11
0
        /// <summary>
        /// Handles the SaveChanges event of the EditSaveControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void EditSaveControl_SaveChanges(object sender, SaveControl.SaveEventArgs e)
        {
            // Validate form
            if (!this.Page.IsValid)
            {
                e.RunScript = false;
                return;
            }

            try
            {
                // Always load, since we need application data
                SiteDto dto = (SiteDto)Session[_SiteEditSessionKey];

                if (dto == null && SiteId != Guid.Empty)
                {
                    if (NeedCopy)
                    {
                        dto = new SiteDto();
                    }
                    else
                    {
                        dto = CMSContext.Current.GetSiteDto(SiteId, true);
                    }
                }
                else if (dto == null && SiteId == Guid.Empty)
                {
                    dto = new SiteDto();
                }

                // Put a dictionary key that can be used by other tabs
                IDictionary dic = new ListDictionary();
                dic.Add(_SiteDtoDestinationString, dto);

                dto.EnforceConstraints = false;

                ViewControl.SaveChanges(dic);

                // get saveddto from the dictionary
                dto = (SiteDto)dic[_SiteDtoDestinationString];

                // Save modifications
                if (dto.HasChanges())
                {
                    if (dto.Site.Count > 0)
                    {
                        // update siteId for the GlobalVariable rows that have just been addded
                        SiteDto.main_GlobalVariablesRow[] variableRows = (SiteDto.main_GlobalVariablesRow[])dto.main_GlobalVariables.Select("", "", DataViewRowState.Added);
                        if (variableRows != null && variableRows.Length > 0)
                        {
                            foreach (SiteDto.main_GlobalVariablesRow row in variableRows)
                            {
                                row.SiteId = dto.Site[0].SiteId;
                            }
                        }
                    }

                    dto.EnforceConstraints = true;

                    CMSContext.Current.SaveSite(dto);

                    if (NeedCopy && SiteId != Guid.Empty)
                    {
                        CopyHelper helper = new CopyHelper();

                        //Menu copy
                        helper.CopySiteMenu(SiteId, dto.Site[0].SiteId);

                        //Folders and pages copy
                        helper.CopySiteContent(SiteId, dto.Site[0].SiteId);
                    }
                }

                // Call commit changes
                ViewControl.CommitChanges(dic);
            }
            catch (SiteImportExportException ex)
            {
                e.RunScript = false;
                DisplayErrorMessage(ex.Message);
            }
            finally
            {
                // we don't need to store Dto in session any more
                Session.Remove(_SiteEditSessionKey);
            }
        }
示例#12
0
 public static bool PrimitiveEquals <T>(this T ťhis, T that, bool comparePrivate = false)
 {
     return(CopyHelper.EqualsProperties(ťhis, that, comparePrivate) && CopyHelper.EqualsFields(ťhis, that, comparePrivate));
 }
示例#13
0
        /// <summary>
        /// 部署
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filePath">所属单页面的根目录文件夹</param>
        /// <param name="saveFile">保存到单页面根目录文件夹下的zip的委托</param>
        /// <param name="backupAction">备份委托</param>
        /// <returns></returns>
        private static async Task Deploy(HttpContext context, string filePath, Action <string> saveFile, Action backupAction)
        {
            //保存到的目的文件
            var guidFile = Path.Combine(filePath, "new.zip");

            //解压后的文件夹
            var destFolder = Path.Combine(filePath, "new");

            try
            {
                //看是否有人在处理了?
                if (File.Exists(guidFile))
                {
                    //查看是否创建了超过1分钟了
                    if ((DateTime.Now - new FileInfo(guidFile).CreationTime).TotalMinutes > 1)
                    {
                        File.Delete(guidFile);
                    }
                    else
                    {
                        //说明有人正在处理
                        await context.Response.WriteAsync("please wait 5 sencods and retry");

                        return;
                    }
                }

                //真是处理前就先删除
                if (Directory.Exists(destFolder))
                {
                    Directory.Delete(destFolder, true);
                }

                //保存到guidFile文件
                saveFile(guidFile);

                //解压zip
                ZipFile.ExtractToDirectory(guidFile, destFolder);

                var copyFromFolder = destFolder;
                var indexFile      = Path.Combine(destFolder, "index.html");

                //查看是否有index.html
                if (!File.Exists(indexFile))
                {
                    //可能是有二级目录 找到哪个里面存在
                    var subFolders = Directory.GetFiles(destFolder, "index.html", SearchOption.AllDirectories);
                    if (subFolders.Length == 1)
                    {
                        // ReSharper disable once PossibleNullReferenceException
                        copyFromFolder = new FileInfo(subFolders.First()).Directory.FullName;
                    }
                    else
                    {
                        await context.Response.WriteAsync("can not found index.html in zip file");

                        return;
                    }
                }

                //替换文件
                CopyHelper.DirectoryCopy(copyFromFolder, filePath, true);

                //备份为了能快速回滚
                backupAction();

                await context.Response.WriteAsync("success");
            }
            finally
            {
                File.Delete(guidFile);
                Directory.Delete(destFolder, true);
            }
        }
示例#14
0
        public async Task <RenderResult> RenderAsync(string path, object model, dynamic viewBag, RouteValueDictionary routevalues, string area,
                                                     ViewType viewType)
        {
            var re = new RenderResult
            {
                Html   = "",
                Status = 200
            };

            if (string.IsNullOrEmpty(path) || path.Equals("/"))
            {
                return(re);
            }
            var nomarlPath = path;

            try
            {
                if (routevalues != null && routevalues.ContainsKey("url"))
                {
                    path = routevalues["url"].ToString();
                }

                //只拿第一层路径
                var entryPointName = path.Split('/').FirstOrDefault();
                if (string.IsNullOrEmpty(entryPointName))
                {
                    return(re);
                }

                entryPointName = entryPointName.ToLowerInvariant();
                var indexHtml = new FileModel(_hostingEnvironment, entryPointName, "index.html");
                if (!indexHtml.IsExist)
                {
                    return(re);
                }

                var jsonFile = new FileInfo(Path.Combine(_hostingEnvironment.WebRootPath, "appsettings.json"));
                if (jsonFile.Exists && (_appJsonLastWriteTime == null || _appJsonLastWriteTime != jsonFile.LastWriteTime))
                {
                    _appJsonLastWriteTime = jsonFile.LastWriteTime;
                    try
                    {
                        this._appsettingsJson = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(CopyHelper.ReadAllText(jsonFile.FullName));
                    }
                    catch (Exception e)
                    {
                        logger.Info(e.ToString());
                    }
                }

                var html = indexHtml.GetContent();
                re.Html = html;

                var cacheKey = entryPointName + "_" + indexHtml.LastModifyTime.ToString("yyyMMddHHmmss");

                var     jsFileContent  = new FileModel(_hostingEnvironment, entryPointName, "server.js");
                dynamic serverJsResult = null;
                if (jsFileContent.IsExist)
                {
                    var exports = engine
                                  .CommonJS()
                                  .RegisterInternalModule("server", typeof(Server))
                                  .RunMain(jsFileContent.FilePath);

                    try
                    {
                        var jsValue = exports.AsObject().Get("main").Invoke(new JsValue(nomarlPath)).ToString();
                        if (!string.IsNullOrEmpty(jsValue) && jsValue != "null" && jsValue != "undefined")
                        {
                            serverJsResult = JObject.Parse(jsValue);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e.ToString());
                    }
                }

                if (serverJsResult == null)
                {
                    serverJsResult = new JObject();
                }

                serverJsResult.Env = new JObject();
                if (_appsettingsJson != null)
                {
                    foreach (var jsonItem in _appsettingsJson)
                    {
                        serverJsResult.Env[jsonItem.Key] = jsonItem.Value;
                    }
                }

                try
                {
                    var cacheResult = _engine.Handler.Cache.RetrieveTemplate(cacheKey);
                    if (cacheResult.Success)
                    {
                        var itemple = cacheResult.Template.TemplatePageFactory();
                        itemple.DisableEncoding = true;
                        string result2 = await _engine.RenderTemplateAsync(itemple, serverJsResult);

                        re.Html = result2;
                        return(re);
                    }

                    string result = await _engine.CompileRenderStringAsync(cacheKey, html, serverJsResult);

                    if (!cacheList.TryGetValue(entryPointName, out var oldCache))
                    {
                        cacheList.TryAdd(entryPointName, cacheKey);
                    }
                    else
                    {
                        //之前有缓存了 就清掉
                        _engine.Handler.Cache.Remove(oldCache);
                        cacheList[entryPointName] = cacheKey;
                    }

                    re.Html = result;
                }
                catch (Exception e)
                {
                    logger.Error(e.ToString());
                }
            }
            catch (Exception e1)
            {
                //ignore
                logger.Error(e1.ToString());
            }

            return(re);
        }
示例#15
0
 public virtual void Deploy()
 {
     CopyHelper.DirectoryCopy(this.args.DeployFolder, this.args.AppFolder, true);
 }
示例#16
0
 public virtual void Deploy()
 {
     logger("Start to Deploy");
     CopyHelper.DirectoryCopy(this.args.DeployFolder, this.args.AppFolder, true);
     logger("Success Deploy from folder:[" + this.args.DeployFolder + "] to folder [" + this.args.AppFolder + "]");
 }
示例#17
0
        public override string DeployExcutor(FormHandler.FormItem fileItem)
        {
            var projectPath = Path.Combine(Setting.PublishWindowServicePathFolder, _serviceName);

            _projectPublishFolder = Path.Combine(projectPath, !string.IsNullOrEmpty(_dateTimeFolderName) ? _dateTimeFolderName : DateTime.Now.ToString("yyyyMMddHHmmss"));
            EnsureProjectFolder(projectPath);
            EnsureProjectFolder(_projectPublishFolder);

            try
            {
                var filePath = Path.Combine(_projectPublishFolder, fileItem.FileName);
                using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(fileItem.FileBody, 0, fileItem.FileBody.Length);
                }


                if (!File.Exists(filePath))
                {
                    return("publish file save fail");
                }
#if NETCORE
                Log("netcore agent version ==>" + AntDeployAgentWindows.Version.VERSION);
#else
                Log("netframework agent version ==>" + AntDeployAgentWindows.Version.VERSION);
#endif
                Log("upload success ==>" + filePath);
                //解压
                try
                {
                    Log("start unzip file");
                    ZipFile.ExtractToDirectory(filePath, _projectPublishFolder);
                }
                catch (Exception ex)
                {
                    return("unzip publish file error:" + ex.Message);
                }

                Log("unzip success ==>" + _projectPublishFolder);

                var deployFolder = Path.Combine(_projectPublishFolder, "publish");

                if (!Directory.Exists(deployFolder))
                {
                    if (Directory.Exists(_projectPublishFolder))
                    {
                        var temp           = new DirectoryInfo(_projectPublishFolder);
                        var tempFolderList = temp.GetDirectories();
                        if (tempFolderList.Length == 1)
                        {
                            deployFolder = tempFolderList.First().FullName;
                        }
                    }
                }

                if (!Directory.Exists(deployFolder))
                {
                    return("unzip publish file error,Path not found:" + deployFolder);
                }

                //查找 Windows Service 里面是否存在该服务
                var service = WindowServiceHelper.GetWindowServiceByName(this._serviceName);
                if (!string.IsNullOrEmpty(service.Item2))
                {
                    return(service.Item2);
                }
                if (service.Item1 == null)
                {
                    Log($"windowService : {_serviceName} not found,start to create!");

                    //创建发布目录
                    var firstDeployFolder = string.IsNullOrEmpty(_physicalPath)? Path.Combine(projectPath, "deploy"):_physicalPath;
                    EnsureProjectFolder(firstDeployFolder);
                    if (Directory.Exists(firstDeployFolder))
                    {
                        Log($"deploy folder create success : {firstDeployFolder} ");
                    }
                    else
                    {
                        return($"DeployFolder : {firstDeployFolder} create error!");
                    }


                    //复制文件到发布目录
                    CopyHelper.ProcessXcopy(deployFolder, firstDeployFolder, Log);

                    Log($"copy files success from [{deployFolder}] to [{firstDeployFolder}]");

                    //部署windows service
                    var execFullPath = Path.Combine(firstDeployFolder, _serviceExecName);
                    if (!File.Exists(execFullPath))
                    {
                        try { Directory.Delete(firstDeployFolder, true); } catch (Exception) { }
                        return($"windows service exec file not found : {execFullPath} ");
                    }

                    //安装服务
                    Log($"start to install windows service");
                    Log($"service name:{_serviceName}");
                    Log($"service path:{execFullPath}");
                    Log($"service startType:{(!string.IsNullOrEmpty(_serviceStartType)?_serviceStartType:"Auto")}");
                    Log($"service description:{_serviceDescription??string.Empty}");


                    try
                    {
                        ServiceInstaller.InstallAndStart(_serviceName, _serviceName, execFullPath, _serviceStartType, _serviceDescription);
                        Log($"install windows service success");
                        Log($"start windows service success");
                        return(string.Empty);
                    }
                    catch (Exception e2)
                    {
                        Thread.Sleep(5000);
                        var isStart = WindowServiceHelper.IsStart(_serviceName);
                        if (isStart)
                        {
                            Log($"install windows service success");
                            Log($"start windows service success");
                            return(string.Empty);
                        }
                        return($"install windows service fail:" + e2.Message);
                    }
                }

                var projectLocationFolder = string.Empty;
                var projectLocation       = WindowServiceHelper.GetWindowServiceLocation(this._serviceName);
                if (string.IsNullOrEmpty(projectLocation))
                {
                    return($"can not find executable path of service:{_serviceName}");
                }

                try
                {
                    projectLocation       = projectLocation.Replace("\"", "");
                    projectLocationFolder = new FileInfo(projectLocation).DirectoryName;
                    if (!Directory.Exists(projectLocationFolder))
                    {
                        //如果目录不存在 那么就重新建立
                        EnsureProjectFolder(projectLocationFolder);
                    }
                }
                catch (Exception)
                {
                    return("ServiceFolder is not correct ===> " + projectLocationFolder);
                }

                Arguments args = new Arguments
                {
                    DeployType   = "WindowsService",
                    BackupFolder = Setting.BackUpWindowServicePathFolder,
                    AppName      = _serviceName,
                    AppFolder    = projectLocationFolder,
                    DeployFolder = deployFolder,
                    WaitForWindowsServiceStopTimeOut = _waitForServiceStopTimeOut,
                    BackUpIgnoreList = this._backUpIgnoreList,
                    NoBackup         = !Setting.NeedBackUp
                };

                if (_serviceName.ToLower().Equals("antdeployagentwindowsservice"))
                {
                    return(UpdateSelft(args));
                }


                Log("Start to deploy Windows Service:");
                Log("ServiceName ===>" + _serviceName);
                Log("ServiceFolder ===> " + projectLocationFolder);

                if (_isNoStopWebSite)
                {
                    args.NoStop  = true;
                    args.NoStart = true;
                }

                var ops = new OperationsWINDOWSSERVICE(args, Log);

                try
                {
                    ops.Execute();

                    try
                    {
                        //如果是增量的话 要把复制过来
                        if (_isIncrement)
                        {
                            Log("Increment deploy start to backup...");
                            //projectLocation.Item1 转到 increment 的目录
                            var incrementFolder = Path.Combine(_projectPublishFolder, "increment");
                            EnsureProjectFolder(incrementFolder);
                            DirectoryInfo directoryInfo = new DirectoryInfo(projectLocationFolder);
                            string        fullName      = directoryInfo.FullName;
                            if (directoryInfo.Parent != null)
                            {
                                fullName = directoryInfo.Parent.FullName;
                            }
                            CopyHelper.DirectoryCopy(projectLocationFolder, incrementFolder, true, fullName, directoryInfo.Name, this._backUpIgnoreList);
                            Log("Increment deploy backup success...");
                        }
                    }
                    catch (Exception ex3)
                    {
                        Log("Increment deploy folder backup fail:" + ex3.Message);
                    }

                    Log("Deploy WindowsService Execute Success");
                }
                catch (Exception ex)
                {
                    try
                    {
                        //ops.Rollback();

                        return($"publish to WindowsService err:{ex.Message}");
                    }
                    catch (Exception ex2)
                    {
                        return($"publish to WindowsService err:{ex.Message},rollback fail:{ex2.Message}");
                    }
                }
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#18
0
        private void SimulationThread()
        {
            try
            {
                DiceBet NewBet = SimulatedBet(DiceStrategy.RunReset());
                this.Balance += (decimal)NewBet.Profit;
                Profit       += (decimal)NewBet.Profit;
                while (TotalBetsPlaced < Bets && !Stop && Running)
                {
                    if (log)
                    {
                        bets.Add(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}"
                                               , TotalBetsPlaced, NewBet.Roll, NewBet.Chance, (NewBet.High ? ">" : "<"), NewBet.GetWin(Site) ? "win" : "lose", NewBet.TotalAmount, NewBet.Profit, this.Balance, Profit));
                    }

                    if (TotalBetsPlaced % 10000 == 0)
                    {
                        OnSimulationWriting?.Invoke(this, new EventArgs());
                        if (log)
                        {
                            using (StreamWriter sw = File.AppendText(TmpFileName))
                            {
                                foreach (string tmpbet in bets)
                                {
                                    sw.WriteLine(tmpbet);
                                }
                            }
                            bets.Clear();
                        }
                    }

                    TotalBetsPlaced++;
                    BetsWithSeed++;
                    bool         Reset        = false;
                    PlaceDiceBet NewBetObject = null;
                    bool         win          = NewBet.GetWin(Site);
                    string       Response     = "";
                    if (BetSettings.CheckResetPreStats(NewBet, NewBet.GetWin(Site), Stats, SiteStats))
                    {
                        Reset        = true;
                        NewBetObject = DiceStrategy.RunReset();
                    }
                    if (BetSettings.CheckStopPreStats(NewBet, NewBet.GetWin(Site), Stats, out Response, SiteStats))
                    {
                        this.Stop = (true);
                    }
                    Stats.UpdateStats(NewBet, win);
                    if (DiceStrategy is ProgrammerMode)
                    {
                        (DiceStrategy as ProgrammerMode).UpdateSessionStats(CopyHelper.CreateCopy <SessionStats>(Stats));
                        (DiceStrategy as ProgrammerMode).UpdateSiteStats(CopyHelper.CreateCopy <SiteStats>(SiteStats));
                        (DiceStrategy as ProgrammerMode).UpdateSite(CopyHelper.CreateCopy <SiteDetails>(Site.SiteDetails));
                    }
                    if (BetSettings.CheckResetPostStats(NewBet, NewBet.GetWin(Site), Stats, SiteStats))
                    {
                        Reset        = true;
                        NewBetObject = DiceStrategy.RunReset();
                    }
                    if (BetSettings.CheckStopPOstStats(NewBet, NewBet.GetWin(Site), Stats, out Response, SiteStats))
                    {
                        Stop = true;
                    }
                    decimal withdrawamount = 0;
                    if (BetSettings.CheckWithdraw(NewBet, NewBet.GetWin(Site), Stats, out withdrawamount, SiteStats))
                    {
                        this.Balance -= withdrawamount;
                    }
                    if (BetSettings.CheckBank(NewBet, NewBet.GetWin(Site), Stats, out withdrawamount, SiteStats))
                    {
                        this.Balance -= withdrawamount;
                    }
                    if (BetSettings.CheckTips(NewBet, NewBet.GetWin(Site), Stats, out withdrawamount, SiteStats))
                    {
                        this.Balance -= withdrawamount;
                    }
                    bool NewHigh = false;
                    if (BetSettings.CheckResetSeed(NewBet, NewBet.GetWin(Site), Stats, SiteStats))
                    {
                        GenerateSeeds();
                    }
                    if (BetSettings.CheckHighLow(NewBet, NewBet.GetWin(Site), Stats, out NewHigh, SiteStats))
                    {
                        (DiceStrategy as iDiceStrategy).High = NewHigh;
                    }
                    if (!Reset)
                    {
                        NewBetObject = (DiceStrategy as iDiceStrategy).CalculateNextDiceBet(NewBet, win);
                    }
                    if (Running && !Stop && TotalBetsPlaced <= Bets)
                    {
                        if (this.Balance < (decimal)NewBetObject.Amount)
                        {
                            break;
                        }
                        NewBet        = SimulatedBet(NewBetObject);
                        this.Balance += (decimal)NewBet.Profit;
                        Profit       += (decimal)NewBet.Profit;
                        //save to file
                    }
                }

                using (StreamWriter sw = File.AppendText(TmpFileName))
                {
                    foreach (string tmpbet in bets)
                    {
                        sw.WriteLine(tmpbet);
                    }
                }
                bets.Clear();
                OnSimulationComplete?.Invoke(this, new EventArgs());
            }
            catch (Exception e)
            {
                Logger.DumpLog(e);
            }
        }
示例#19
0
 public static void CopyTo <T>(this T ťhis, T that, bool copyPrivate = false) where T : PrimitiveCopyable
 {
     CopyHelper.CopyProperties(ťhis, that, copyPrivate);
     CopyHelper.CopyFields(ťhis, that, copyPrivate);
 }
示例#20
0
        private void ProcessRequestCallback(IAsyncResult ar)
        {
            var context = httpListener.EndGetContext(ar);

            // Tell listener to stast the next connection simultaneously
            httpListener.BeginGetContext(ProcessRequestCallback, null);

            var request    = context.Request;
            var requestUrl = new Uri(request.Url.ToString().ToLower());

            // Check for double request
            if (requestUrl.AbsoluteUri.Contains("favicon"))
            {
                return;
            }

            if (request.HttpMethod == "OPTIONS")
            {
                context.Response.AddHeader("Access-Control-Allow-Origin", "*");
                context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Z-Key");
                context.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
                context.Response.Close();
                return;
            }

            var readingResource = request.HttpMethod == "GET";
            var pathList        = requestUrl.LocalPath.Split("/").Where(s => !string.IsNullOrEmpty(s)).Take(2).ToList();

            if (pathList.Count == 2)
            {
                if (!readingResource)
                {
                    var resource = pathList[0] + "/" + pathList[1];
                    RemoveCacheByPattern("*" + resource + "*");
                    Console.Out.WriteLineAsync($"[Thread {Thread.CurrentThread.ManagedThreadId}] Removing cache for " + resource + " because of method : " + request.HttpMethod);
                }
            }
            var redisKey = requestUrl.PathAndQuery;

            if (readingResource &&
                connectionMultiplexer.GetDatabase(0).KeyExists(redisKey))
            {
                Console.Out.WriteLineAsync($"[Thread {Thread.CurrentThread.ManagedThreadId}] Returning cached request.");
                var content        = connectionMultiplexer.GetDatabase(0).StringGet(redisKey);
                var cachedResponse = JsonConvert.DeserializeObject <CachedResponse>(content);

                CopyHelper.Headers(CopyHelper.ToNameValueCollection(cachedResponse.Headers), context.Response.Headers);
                CopyHelper.Response(context.Response, cachedResponse.Body, cachedResponse.Body.Length);
            }
            else
            {
                var uri = GetRedirectUri(request);

                Console.Out.WriteLineAsync($"[Thread {Thread.CurrentThread.ManagedThreadId}] Incoming {request.HttpMethod} request for: {uri}");

                var webRequest = WebRequest.Create(uri);
                CopyHelper.RequestDetails(webRequest, request);
                CopyHelper.Headers(request.Headers, webRequest.Headers);
                CopyHelper.InputStream(webRequest, request);
                var webResponse = webRequest.GetResponse();

                var buffer = new byte[CopyHelper.BufferSize];
                var read   = webResponse.GetResponseStream().Read(buffer, 0, buffer.Length);

                CopyHelper.Headers(webResponse.Headers, context.Response.Headers);
                CopyHelper.Response(context.Response, buffer, read);

                if (readingResource)
                {
                    var serializeObject = JsonConvert.SerializeObject(new CachedResponse
                    {
                        Body    = buffer.Take(read).ToArray(),
                        Headers = CopyHelper.ToDictionary(webResponse.Headers)
                    });
                    connectionMultiplexer.GetDatabase(0).StringSet(redisKey, serializeObject);
                }
            }
        }