Esempio n. 1
0
        public static AaBox BoundingBox(IEnumerable <Sphere> spheres)
        {
            var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
            var max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

            foreach (var sphere in spheres)
            {
                CodingHelper.UpdateIfLess(ref min.X, sphere.Center.X - sphere.Radius);
                CodingHelper.UpdateIfLess(ref min.Y, sphere.Center.Y - sphere.Radius);
                CodingHelper.UpdateIfLess(ref min.Z, sphere.Center.Z - sphere.Radius);
                CodingHelper.UpdateIfGreater(ref max.X, sphere.Center.X + sphere.Radius);
                CodingHelper.UpdateIfGreater(ref max.Y, sphere.Center.Y + sphere.Radius);
                CodingHelper.UpdateIfGreater(ref max.Z, sphere.Center.Z + sphere.Radius);
            }
            var halfSizeVec = (max - min) / 2;

            if (halfSizeVec.X < 0)
            {
                throw new ArgumentException("'spheres' parameter cannot be empty.");
            }
            return(new AaBox
            {
                Center = (min + max) / 2,
                HalfSize = new Size3(halfSizeVec)
            });
        }
        private void DoChildSwapping(int node)
        {
            var children    = sg.Children[node];
            var hasImpreved = true;

            while (hasImpreved)
            {
                hasImpreved = false;
                var energy = ChildEnergy(node);
                foreach (var childPair in children.AllPairs())
                {
                    var child1 = childPair.First;
                    var child2 = childPair.Second;

                    if (radii[child1] != radii[child2] ||
                        nodeExternalConnections.ContainsKey(child1) ||
                        nodeExternalConnections.ContainsKey(child2))
                    {
                        continue;
                    }

                    CodingHelper.Swap(ref positions[child1], ref positions[child2]);
                    var newEnergy = ChildEnergy(node);
                    if (newEnergy < energy)
                    {
                        energy      = newEnergy;
                        hasImpreved = true;
                    }
                    else
                    {
                        CodingHelper.Swap(ref positions[child1], ref positions[child2]);
                    }
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Кодирует заданную исходную последовательность символов с помощью указанных основания и словаря частот встречаемости символов.
        /// </summary>
        /// <exception cref="ArgumentNullException">Исключение, которое выдается если <paramref name="source"/> или <paramref name="occurrenceFrequencies"/> равен null.</exception>
        /// <exception cref="ArithmeticCodingException">Исключение, которое выдается при отсутствии символа из исходной последовательности в словаре частот встречаемости символов.</exception>
        /// <param name="source">Исходная последовательность символов.</param>
        /// <param name="occurrenceFrequencies">Словарь частот встречаемости символов.</param>
        /// <param name="radix">Основание.</param>
        /// <returns>Арифметическое значение.</returns>
        public static ArithmeticValue Encode(char[] source, IReadOnlyDictionary <char, int> occurrenceFrequencies, int radix)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (occurrenceFrequencies == null)
            {
                throw new ArgumentNullException(nameof(occurrenceFrequencies));
            }

            var cumulativeFrequencies = ArithmeticDictionary.GetEncodingCumulativeFrequencies(occurrenceFrequencies);
            var lower = new BigInteger(0);
            var pf    = new BigInteger(1);

            foreach (var symbol in source)
            {
                if (!occurrenceFrequencies.ContainsKey(symbol))
                {
                    throw new ArithmeticCodingException($"Символ '{symbol}' (код - {(int)symbol}) не найден в словаре частот символов.");
                }

                lower = lower * source.Length + cumulativeFrequencies[symbol] * pf;
                pf   *= occurrenceFrequencies[symbol];
            }

            var upper    = lower + pf;
            var power    = CodingHelper.GetPower(pf, radix);
            var mantissa = (upper - 1) / BigInteger.Pow(radix, power);

            return(new ArithmeticValue(occurrenceFrequencies, mantissa, radix, power));
        }
Esempio n. 4
0
        private void DoAntDeployProcess(string projectPath, ProjectParam param)
        {
            var md5             = CodingHelper.MD5(projectPath);
            var path            = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var projectPram     = JsonConvert.SerializeObject(param);
            var projectPramPath = Path.Combine(path, md5 + "_param.json");

            File.WriteAllText(projectPramPath, projectPram, Encoding.UTF8);

            var assembly          = Assembly.GetExecutingAssembly();
            var codeBase          = assembly.Location;
            var codeBaseDirectory = Path.GetDirectoryName(codeBase);
            var ant = Path.Combine(codeBaseDirectory, "AntDeployApp.exe");

            using (var process = new Process())
            {
                process.StartInfo.FileName        = ant;
                process.StartInfo.Arguments       = $"\"{projectPramPath}\"";
                process.StartInfo.CreateNoWindow  = false;
                process.StartInfo.WindowStyle     = ProcessWindowStyle.Normal;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.Verb            = "runas";

                process.Start();

                process.WaitForExit();
            }
        }
Esempio n. 5
0
        public static AaBox BoundingBox(IEnumerable <Vector3> points)
        {
            var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
            var max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

            foreach (var point in points)
            {
                CodingHelper.UpdateIfLess(ref min.X, point.X);
                CodingHelper.UpdateIfLess(ref min.Y, point.Y);
                CodingHelper.UpdateIfLess(ref min.Z, point.Z);
                CodingHelper.UpdateIfGreater(ref max.X, point.X);
                CodingHelper.UpdateIfGreater(ref max.Y, point.Y);
                CodingHelper.UpdateIfGreater(ref max.Z, point.Z);
            }
            var halfSizeVec = (max - min) / 2;

            if (halfSizeVec.X < 0)
            {
                throw new ArgumentException("'points' parameter cannot be empty.");
            }
            return(new AaBox
            {
                Center = (min + max) / 2,
                HalfSize = new Size3(halfSizeVec)
            });
        }
Esempio n. 6
0
 public bool TrySortSubscriptionsByDependencies(IServiceEventDependencyGraph dependencyGraph, out string contradictionString)
 {
     while (true)
     {
         var foundWrongOrder = false;
         for (var i = 0; i < Subscriptions.Count - 1; i++)
         {
             for (var j = i + 1; j < Subscriptions.Count; j++)
             {
                 var comparisonResult = CompareSubscriptions(Subscriptions[i], Subscriptions[j], dependencyGraph, out contradictionString);
                 if (comparisonResult == SubscriptionDependencyComparisonResult.Contradicting)
                 {
                     return(false);
                 }
                 if (comparisonResult != SubscriptionDependencyComparisonResult.FirstDependsOnSecond)
                 {
                     continue;
                 }
                 CodingHelper.Swap(subscriptions, i, j);
                 foundWrongOrder = true;
             }
         }
         if (!foundWrongOrder)
         {
             break;
         }
     }
     contradictionString = null;
     return(true);
 }
Esempio n. 7
0
        /// <summary>
        /// 根据user_role做内链接
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public DataTable GetUserAndRoleModel(string name, string password)
        {
            CodingHelper ch = new CodingHelper();

            //查询后解密返回
            return(ch.DataTableReCoding(dal.GetUserAndRoleModel(XYEEncoding.strCodeHex(name),
                                                                XYEEncoding.strCodeHex(password))));
        }
Esempio n. 8
0
        public void DropDown <TValue>(Expression <Func <T, TValue> > path, Dictionary <string, TValue> values)
        {
            var prop = CodingHelper.GetPropertyInfo(path);

            addControl(new FluentDropDown <T, TValue>(GetObject,
                                                      x => (TValue)prop.GetValue(x),
                                                      (x, v) => prop.SetValue(x, v), values));
        }
 private static LineSegment3 To3(Vector2 p1, Vector2 p2, Transform transform, bool swap)
 {
     if (swap)
     {
         CodingHelper.Swap(ref p1, ref p2);
     }
     return(new LineSegment3(To3(p1) * transform, To3(p2) * transform));
 }
Esempio n. 10
0
        public void ColorPicker(Expression <Func <T, Color4> > path)
        {
            var prop = CodingHelper.GetPropertyInfo(path);

            addControl(new FluentColorPicker <T>(GetObject,
                                                 x => (Color4)prop.GetValue(x),
                                                 (x, v) => prop.SetValue(x, v)));
        }
Esempio n. 11
0
        public void CheckBox(string text, Expression <Func <T, bool> > path)
        {
            var prop = CodingHelper.GetPropertyInfo(path);

            addControl(new FluentCheckBox <T>(text, GetObject,
                                              x => (bool?)prop.GetValue(x),
                                              (x, v) => prop.SetValue(x, v)));
        }
Esempio n. 12
0
        public void TextBox <TVal>(Expression <Func <T, TVal> > path, Func <TVal, string> valToStr, Func <string, TVal> strToVal)
        {
            var prop = CodingHelper.GetPropertyInfo(path);

            addControl(new FluentTextBox <T, TVal>(GetObject,
                                                   x => (TVal)prop.GetValue(x),
                                                   (x, v) => prop.SetValue(x, v),
                                                   valToStr, strToVal));
        }
Esempio n. 13
0
        public void Slider(Expression <Func <T, float> > path, float minValue, float maxValue, int numSteps)
        {
            var prop = CodingHelper.GetPropertyInfo(path);

            addControl(new FluentSlider <T>(GetObject,
                                            x => (float)prop.GetValue(x),
                                            (x, v) => prop.SetValue(x, v),
                                            minValue, maxValue, numSteps));
        }
Esempio n. 14
0
        public override IResource GetNew(IResourceSource resourceSource)
        {
            var cSource             = (Source)resourceSource;
            var verticalIndexOffset = 2 * cSource.HalfNumCircleSegments;
            var vertices            = new VertexPosTanNormTex[verticalIndexOffset * cSource.HalfNumCircleSegments];

            for (int i = 0; i < cSource.HalfNumCircleSegments; i++)
            {
                for (int j = 0; j < verticalIndexOffset; j++)
                {
                    var u   = (float)j / (verticalIndexOffset - 1);
                    var v   = (float)i / (cSource.HalfNumCircleSegments - 1);
                    var phi = MathHelper.TwoPi * u + MathHelper.Pi;
                    var psi = MathHelper.PiOver2 - MathHelper.Pi * v;
                    var z   = MathHelper.Cos(phi) * MathHelper.Cos(psi);
                    var x   = MathHelper.Sin(phi) * MathHelper.Cos(psi);
                    var y   = MathHelper.Sin(psi);

                    var normal   = new Vector3(x, y, z);
                    var position = normal;
                    var tangent  = Vector3.Cross(Vector3.UnitY, normal).Normalize();
                    var texcoord = new Vector2(u, v);
                    vertices[i * verticalIndexOffset + j] = new VertexPosTanNormTex(
                        position, tangent, normal, texcoord);
                }
            }
            var indexList = new List <int>();

            for (int i = 0; i < cSource.HalfNumCircleSegments - 1; i++)
            {
                for (int j = 0; j < verticalIndexOffset - 1; j++)
                {
                    var topLeftIndex = i * verticalIndexOffset + j;
                    indexList.Add(topLeftIndex);
                    indexList.Add(topLeftIndex + 1);
                    indexList.Add(topLeftIndex + 1 + verticalIndexOffset);
                    indexList.Add(topLeftIndex);
                    indexList.Add(topLeftIndex + 1 + verticalIndexOffset);
                    indexList.Add(topLeftIndex + verticalIndexOffset);
                }
            }
            var indices = indexList.ToArray();

            if (cSource.Inverse)
            {
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i].Normal = -vertices[i].Normal;
                }
                for (int i = 0; i < indices.Length; i += 3)
                {
                    CodingHelper.Swap(ref indices[i + 1], ref indices[i + 2]);
                }
            }
            return(ExplicitModel.FromVertices(vertices, indices, ExplicitModelPrimitiveTopology.TriangleList).WithSource(cSource));
        }
        public string Encode(MatrixCodeModel model)
        {
            int[] matrix = model.ConvertToDecMatrix();

            //var m = 3;
            //var n = 7;
            //var arrays = new int[] { 15, 51, 85 };

            return(CodingHelper.SpectreLinearCode(model.M, model.N, matrix));
        }
Esempio n. 16
0
        public void NumericUpDown <TVal>(Expression <Func <T, TVal> > path, TVal minValue, TVal maxValue, Func <TVal, double> valToDouble, Func <double, TVal> doubleToVal)
        {
            var prop = CodingHelper.GetPropertyInfo(path);

            addControl(new FluentNumericUpDown <T, TVal>(GetObject,
                                                         x => (TVal)prop.GetValue(x),
                                                         (x, v) => prop.SetValue(x, v),
                                                         minValue, maxValue,
                                                         valToDouble, doubleToVal));
        }
Esempio n. 17
0
 private void SwapPlaces(ChildPlace place1, ChildPlace place2)
 {
     if (place1.Child.HasValue)
     {
         positions[place1.Child.Value] = place2.Position;
     }
     if (place2.Child.HasValue)
     {
         positions[place2.Child.Value] = place1.Position;
     }
     CodingHelper.Swap(ref place1.Child, ref place2.Child);
 }
Esempio n. 18
0
        /// <summary>
        /// 执行Api
        /// </summary>
        public ResultModel <object> Do()
        {
            string apiUrl = null, apiBody = null;

            using (StreamReader reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8))
            {
                var json = JsonHelper.Deserialize <JObject>(reader.ReadToEnd());
                apiUrl  = CodingHelper.UrlDecode(StringHelper.Get(json["action"]));
                apiBody = StringHelper.Get(json["content"]);
            }
            apiUrl.CheckEmpty();

            return(apiUrl.GetResult <object>(apiBody));
        }
Esempio n. 19
0
        public static void Intersect(Circle2 c1, Circle2 c2, out Circle2?circle2Result, out Vector2?pointRes1, out Vector2?pointRes2)
        {
            circle2Result = null;
            pointRes1     = null;
            pointRes2     = null;
            if (c1.Center == c2.Center)
            {
                if (c1.Radius == c2.Radius)
                {
                    circle2Result = c1;
                }
                return;
            }
            if (c1.Radius < c2.Radius)
            {
                CodingHelper.Swap(ref c1, ref c2);
            }
            var firstToSecond = c2.Center - c1.Center;
            var distance      = firstToSecond.Length();
            var dir           = firstToSecond / distance;
            var radiusSum     = c1.Radius + c2.Radius;

            if (radiusSum < distance)
            {
                return;
            }
            if (radiusSum == distance)
            {
                pointRes1 = c1.Center + dir * c1.Radius;
                return;
            }
            if (distance + c2.Radius > c1.Radius)
            {
                var offset = (distance.Sq() + c1.Radius.Sq() - c2.Radius.Sq()) / (2 * distance);
                var center = c1.Center + dir * offset;
                var radius = MathHelper.Sqrt(c1.Radius.Sq() - offset.Sq());
                var ortho  = new Vector2(dir.Y, -dir.X).Normalize();
                pointRes1 = center + ortho * radius;
                pointRes2 = center - ortho * radius;
                return;
            }
            if (distance + c2.Radius == c1.Radius)
            {
                pointRes1 = c1.Center + dir * c1.Radius;
                return;
            }
        }
Esempio n. 20
0
        public static AaRectangle2 BoundingRect(IEnumerable <Vector2> points)
        {
            var minX = float.MaxValue;
            var minY = float.MaxValue;
            var maxX = float.MinValue;
            var maxY = float.MinValue;

            foreach (var point in points)
            {
                CodingHelper.UpdateIfLess(ref minX, point.X);
                CodingHelper.UpdateIfLess(ref minY, point.Y);
                CodingHelper.UpdateIfGreater(ref maxX, point.X);
                CodingHelper.UpdateIfGreater(ref maxY, point.Y);
            }

            return(minX != float.MaxValue ? FromBounds(minX, maxX, minY, maxY) : new AaRectangle2());
        }
Esempio n. 21
0
        public static AaRectangle2 BoundingRect(IEnumerable <AaRectangle2> rects)
        {
            var minX = float.MaxValue;
            var minY = float.MaxValue;
            var maxX = float.MinValue;
            var maxY = float.MinValue;

            foreach (var rect in rects)
            {
                CodingHelper.UpdateIfLess(ref minX, rect.MinX);
                CodingHelper.UpdateIfLess(ref minY, rect.MinY);
                CodingHelper.UpdateIfGreater(ref maxX, rect.MaxX);
                CodingHelper.UpdateIfGreater(ref maxY, rect.MaxY);
            }

            return(minX != float.MaxValue ? FromBounds(minX, maxX, minY, maxY) : new AaRectangle2());
        }
Esempio n. 22
0
        public static void Intersect(Sphere s1, Sphere s2, out Sphere?sphereResult, out Circle3?circleResult, out Vector3?pointResult)
        {
            sphereResult = null;
            circleResult = null;
            pointResult  = null;
            if (s1.Center == s2.Center)
            {
                if (s1.Radius == s2.Radius)
                {
                    sphereResult = s1;
                }
                return;
            }
            if (s1.Radius < s2.Radius)
            {
                CodingHelper.Swap(ref s1, ref s2);
            }
            var firstToSecond = s2.Center - s1.Center;
            var distance      = firstToSecond.Length();
            var dir           = firstToSecond / distance;
            var radiusSum     = s1.Radius + s2.Radius;

            if (radiusSum < distance)
            {
                return;
            }
            if (radiusSum == distance)
            {
                pointResult = s1.Center + dir * s1.Radius;
                return;
            }
            if (distance + s2.Radius > s1.Radius)
            {
                var offset = (distance.Sq() + s1.Radius.Sq() - s2.Radius.Sq()) / (2 * distance);
                var center = s1.Center + dir * offset;
                var radius = MathHelper.Sqrt(s1.Radius * s1.Radius - offset * offset);
                circleResult = new Circle3(center, dir, radius);
                return;
            }
            if (distance + s2.Radius == s1.Radius)
            {
                pointResult = s1.Center + dir * s1.Radius;
                return;
            }
        }
Esempio n. 23
0
        public static ef.Keys ToEto(Key key, KeyModifiers modifiers)
        {
            var result = key.ToEto();

            if (CodingHelper.HasFlag((int)modifiers, (int)KeyModifiers.Control))
            {
                result |= ef.Keys.Control;
            }
            if (CodingHelper.HasFlag((int)modifiers, (int)KeyModifiers.Shift))
            {
                result |= ef.Keys.Shift;
            }
            if (CodingHelper.HasFlag((int)modifiers, (int)KeyModifiers.Alt))
            {
                result |= ef.Keys.Alt;
            }
            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// Handles the Click event of the btnPreview control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnPreview_Click(object sender, EventArgs e)
        {
            // Clean-up UI
            gPreview.Visible     = true;
            ltImportResults.Text = string.Empty;

            RockContext rockContext         = new RockContext();
            var         workflowTypeService = new WorkflowTypeService(rockContext);
            var         workflowType        = workflowTypeService.Get(wtpExport.SelectedValueAsId().Value);
            var         coder    = new EntityCoder(new RockContext());
            var         exporter = new WorkflowTypeExporter();

            coder.EnqueueEntity(workflowType, exporter);

            List <PreviewEntity> previewEntities = new List <PreviewEntity>();

            foreach (var qe in coder.Entities)
            {
                string shortType = CodingHelper.GetEntityType(qe.Entity).Name;

                if (shortType == "Attribute" || shortType == "AttributeValue" || shortType == "AttributeQualifier" || shortType == "WorkflowActionFormAttribute")
                {
                    continue;
                }

                var preview = new PreviewEntity
                {
                    Guid       = qe.Entity.Guid,
                    Name       = EntityFriendlyName(qe.Entity),
                    ShortType  = shortType,
                    IsCritical = qe.IsCritical,
                    IsNewGuid  = qe.RequiresNewGuid,
                    Paths      = qe.ReferencePaths.Select(p => p.ToString()).ToList()
                };

                previewEntities.Add(preview);
            }

            ViewState["PreviewEntities"] = previewEntities;

            BindPreviewGrid();
        }
        public string Encode(string value)
        {
            StringBuilder str = new StringBuilder();

            try
            {
                int key = CodingSQLHelper.SetKey(value);

                var result = CodingHelper.ShannonFanoEncode(value);
                str.Append(result);
                str.Append(Environment.NewLine);
                str.Append(CodingHelper.ShannonFanoShowTable(value));
                str.AppendFormat("${0}", key);
            }
            catch (Exception exc)
            {
            }

            return(str.ToString());
        }
Esempio n. 26
0
            public async Task <Response> Handle(Request request, CancellationToken token)
            {
                string connectionString = "Server=LAPTOP-RD9P71LP\\SQLEXPRESS;Database=TEST1;UID=sa;PWD=1234;";

                DbSchema.Table tableSchema = CodingHelper.GetDbTableSchema(connectionString, "Article");
                CsSchema.Class csClass     = mapper.Map <CsSchema.Class>(tableSchema);

                CsSchema.Unit      unit       = new CsSchema.Unit();
                CsSchema.Namespace @namespace = new CsSchema.Namespace();
                @namespace.Name    = "QQ";
                @namespace.Classes = new CsSchema.Class[] { csClass };
                unit.Namespaces    = new CsSchema.Namespace[] { @namespace };
                var syntax = mapper.Map <CompilationUnitSyntax>(unit);

                return(new Response
                {
                    Code = syntax
                           .NormalizeWhitespace()
                           .ToFullString()
                });
            }
Esempio n. 27
0
        /// <summary>
        /// 将DataSet里的第一个table解密后绑定到控件上
        /// </summary>
        /// <param name="ds"></param>
        private void bindingDGVByDataTable(DataSet ds)
        {
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    CodingHelper codingHelper = new CodingHelper();

                    superGridControl1.PrimaryGrid.DataSource =
                        codingHelper.DataTableReCoding(ds.Tables[0]);
                }
                else
                {
                    DataTable dt = ds.Tables[0].Clone();

                    CodingHelper codingHelper = new CodingHelper();

                    superGridControl1.PrimaryGrid.DataSource =
                        codingHelper.DataTableReCoding(dt);
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 查询所有信息
        /// </summary>
        /// <param name="isflag">是否显示禁用:true显示所有禁用状态的信息,false仅显示未禁用状态的信息</param>
        /// <returns></returns>
        public DataTable SelEmpolyee(bool isflag)
        {
            CodingHelper ch  = new CodingHelper();
            string       sql = @"select Emp_Code as 员工工号,
            Emp_Name as 姓名,
            r.Role_Name as 角色,
            Emp_Area as 地址,
            Emp_CardCode as 卡号,
            dep.Dt_Name as 所属部门,
            Emp_Sex as 性别,
            Emp_Card as 身份证号,
            Emp_Phone as 联系电话,
            Emp_Bank as 银行卡号,
            Emp_OpenBank as 开户行,
            Emp_Birthday 出生年月,
            Emp_Email as 邮箱,
            Emp_Education as 最高学历,
            Emp_School as 毕业院校,
            Emp_Entry as 入职时间,
            Emp_State as 就职状态,
            Emp_Enable as 禁用状态  
            from T_Empolyee emp,
            T_Role r,
            T_Department dep 
            where Emp_Clear=1 
            and emp.Emp_Depid=dep.Dt_Code 
            and emp.Emp_UserRole=r.Role_Code";

            if (isflag == false)
            {
                sql += " and Emp_Enable=1";
            }
            SqlDataAdapter adapter = new SqlDataAdapter(sql, DbHelperSQL.connectionString);
            DataSet        ds      = new DataSet();

            adapter.Fill(ds, "T_Empolyee");
            return(ch.DataTableReCoding(ds.Tables[0]));
        }
Esempio n. 29
0
        public static string GetPluginConfigPath(string projectName = null)
        {
            try
            {
                var path       = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                var folderName = Path.Combine(path, "AntDeploy");
                if (!string.IsNullOrEmpty(folderName))
                {
                    if (!Directory.Exists(folderName))
                    {
                        Directory.CreateDirectory(folderName);
                    }

                    return(Path.Combine(folderName, string.IsNullOrEmpty(projectName)? "AntDeploy.json": CodingHelper.MD5(projectName) + ".json"));
                }
                return(string.Empty);
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Esempio n. 30
0
        public override async Task <bool> Run()
        {
            byte[] zipBytes = File.ReadAllBytes(Arguments.PackageZipPath);
            if (zipBytes.Length < 1)
            {
                Error("package file is empty");
                return(await Task.FromResult(false));
            }

            this.Info($"Start Uppload,Host:{Arguments.Host}");

            HttpRequestClient httpRequestClient = new HttpRequestClient();

            httpRequestClient.SetFieldValue("publishType", "iis");
            httpRequestClient.SetFieldValue("isIncrement", (Arguments.IsSelectedDeploy || Arguments.IsIncrementDeploy)?"true":"false");
            httpRequestClient.SetFieldValue("useOfflineHtm", (Arguments.UseAppOffineHtm)?"true":"false");
            httpRequestClient.SetFieldValue("sdkType", "netcore");
            httpRequestClient.SetFieldValue("port", Arguments.Port);
            httpRequestClient.SetFieldValue("id", Arguments.LoggerId);
            httpRequestClient.SetFieldValue("remark", Arguments.Remark);
            httpRequestClient.SetFieldValue("mac", CodingHelper.GetMacAddress());
            httpRequestClient.SetFieldValue("pc", string.IsNullOrEmpty(Arguments.Email) ? System.Environment.MachineName : Arguments.Email);
            httpRequestClient.SetFieldValue("localIp", CodingHelper.GetLocalIPAddress());
            httpRequestClient.SetFieldValue("poolName", Arguments.PoolName);
            httpRequestClient.SetFieldValue("physicalPath", Arguments.PhysicalPath);
            httpRequestClient.SetFieldValue("webSiteName", Arguments.WebSiteName);
            httpRequestClient.SetFieldValue("deployFolderName", Arguments.DeployFolderName);
            httpRequestClient.SetFieldValue("Token", Arguments.Token);
            httpRequestClient.SetFieldValue("backUpIgnore", (Arguments.BackUpIgnore != null && Arguments.BackUpIgnore.Any()) ? string.Join("@_@", Arguments.BackUpIgnore) : "");
            httpRequestClient.SetFieldValue("publish", "publish.zip", "application/octet-stream", zipBytes);


            HttpLogger HttpLogger = new HttpLogger
            {
                Key = Arguments.LoggerId,
                Url = $"http://{Arguments.Host}/logger?key=" + Arguments.LoggerId
            };

            //IDisposable _subcribe = null;
            WebSocketClient webSocket = new WebSocketClient(this.Log, HttpLogger);
            var             isSuccess = true;

            try
            {
                var hostKey = await webSocket.Connect($"ws://{Arguments.Host}/socket");

                httpRequestClient.SetFieldValue("wsKey", hostKey);

                var uploadResult = await httpRequestClient.Upload($"http://{Arguments.Host}/publish", ClientOnUploadProgressChanged, GetProxy());

                if (ProgressPercentage == 0)
                {
                    isSuccess = false;
                }
                else
                {
                    webSocket.ReceiveHttpAction(true);
                    if (webSocket.HasError)
                    {
                        this.Error($"Host:{Arguments.Host},Deploy Fail,Skip to Next");
                        isSuccess = false;
                    }
                    else
                    {
                        if (uploadResult.Item1)
                        {
                            this.Info($"【deploy success】Host:{Arguments.Host},Response:{uploadResult.Item2}");
                        }
                        else
                        {
                            isSuccess = false;
                            this.Error($"Host:{Arguments.Host},Response:{uploadResult.Item2},Skip to Next");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                this.Error($"Fail Deploy,Host:{Arguments.Host},Response:{ex.Message},Skip to Next");
            }
            finally
            {
                await webSocket?.Dispose();

                //_subcribe?.Dispose();
            }

            return(await Task.FromResult(isSuccess));
        }