Beispiel #1
0
        /// <summary>
        /// Distance between two points
        /// </summary>
        public override double Dist(double[] p1, double[] p2)
        {
            GeneralUtils.CheckDimensions(p1, p2);

            var dim = p1.Length;
            var max = double.MinValue;

            for (int i = 0; i < dim; i++)
            {
                var abs = Math.Abs(p1[i] - p2[i]);
                if (abs > max)
                {
                    max = abs;
                }
            }

            return(max);
        }
        private bool CompareValues(DataValue x, DataValue y)
        {
            Type xType = x.Value.GetType();

            if (xType == y.Value.GetType())
            {
                if (xType == typeof(byte[]))
                {
                    return(GeneralUtils.CompareBytes((byte[])x.Value, (byte[])y.Value));
                }
                else
                {
                    return(x.Value.Equals(y.Value));
                }
            }

            return(false);
        }
 public void calculateSuggestionsByReducingDaysFromEnd(DateTime start, DateTime end, int numDaysMaxReduced)
 {
     // suggestions from end date, decreasing days from start date
     for (int i = 1; i <= numDaysMaxReduced; i++)
     {
         start = GeneralUtils.simplifyStartDate(start);
         if (suggestions.Count > GeneralUtils.MAX_SUGGESTIONS_COUNT)
         {
             break;
         }
         constraintChecking.changeCurrentlyVerifiedHolidayRequest(new DateRange(start, end));
         if (!constraintChecking.isItBreakingConstraints())
         {
             suggestions.Add(new DateRange(start, end));
         }
         start = start.AddDays(1);
     }
 }
Beispiel #4
0
    private GameObject FindNearest(float x, float y, float z, ref double shortestDistance)
    {
        GameObject closest = null;

        //Reached a root node, check its objects
        if (childNodes == null)
        {
            searched = true;
            //We're a root node, check the objects we have
            foreach (GameObject obj in objects)
            {
                double distance = Mathf.Sqrt(
                    Mathf.Pow(x - obj.transform.position.x, 2.0f) +
                    Mathf.Pow(y - obj.transform.position.y, 2.0f) +
                    Mathf.Pow(z - obj.transform.position.z, 2.0f));

                if ((distance > shortestDistance))
                {
                    continue;
                }

                shortestDistance = distance;
                closest          = obj;
            }
            return(closest);
        }

        //Keep stepping into the children until we reach a root (above)
        foreach (QuadTree child in childNodes)
        {
            double childDistance = GeneralUtils.DistanceToRectEdge(child.nodeBounds, x, y);
            if (childDistance > shortestDistance)
            {
                continue;
            }

            GameObject tmpObject = child.FindNearest(x, y, z, ref shortestDistance);
            if (tmpObject != null)
            {
                closest = tmpObject;
            }
        }
        return(closest);
    }
    private void Load()
    {
        this.m_isInitialized = true;
        string str = Options.Get().GetString(Option.CHANGED_CARDS_DATA);

        if (!string.IsNullOrEmpty(str))
        {
            char[] separator = new char[] { '-' };
            foreach (string str2 in str.Split(separator))
            {
                if (!string.IsNullOrEmpty(str2))
                {
                    char[]   chArray2  = new char[] { ',' };
                    string[] strArray3 = str2.Split(chArray2);
                    if (strArray3.Length == 3)
                    {
                        int num3;
                        int num4;
                        int num5;
                        for (int i = 0; i < 3; i++)
                        {
                            if (string.IsNullOrEmpty(strArray3[i]))
                            {
                            }
                        }
                        if ((GeneralUtils.TryParseInt(strArray3[0], out num3) && GeneralUtils.TryParseInt(strArray3[1], out num4)) && GeneralUtils.TryParseInt(strArray3[2], out num5))
                        {
                            TrackedCard card = new TrackedCard {
                                Index = num3,
                                DbId  = num4,
                                Count = num5
                            };
                            this.AddCard(card);
                            if (card.Index > this.m_currentCardNerfIndex)
                            {
                                this.m_currentCardNerfIndex = card.Index;
                            }
                        }
                    }
                }
            }
            this.Save();
        }
    }
Beispiel #6
0
        public void MergeAndRemoveDuplicatesTest()
        {
            List <int> list1 = null;
            List <int> list2 = null;

            try
            {
                GeneralUtils.MergeAndRemoveDuplicates(list1, list2);
                Assert.Fail("Should have thrown a NullReferenceException.");
            }
            catch (Exception)
            {
                //ignore
            }

            list1 = new List <int>();
            var list3 = GeneralUtils.MergeAndRemoveDuplicates(list1, list2).ToList();

            Assert.IsNotNull(list3);
            Assert.AreEqual(0, list3.Count);

            list2 = new List <int>();
            list3 = GeneralUtils.MergeAndRemoveDuplicates(list1, list2).ToList();
            Assert.IsNotNull(list3);
            Assert.AreEqual(0, list3.Count);

            list1.Add(1);
            list2.Add(1);
            list3 = GeneralUtils.MergeAndRemoveDuplicates(list1, list2).ToList();
            Assert.IsNotNull(list3);
            Assert.AreEqual(1, list3.Count);

            list1.Add(2);
            list2.Add(3);
            list3 = GeneralUtils.MergeAndRemoveDuplicates(list1, list2).ToList();
            Assert.IsNotNull(list3);
            CollectionAssert.AreEqual(new List <int>(new[]
            {
                1,
                2,
                3
            }),
                                      list3);
        }
Beispiel #7
0
        public override void OnRender(int id)
        {
            var style = new GUIStyle(GUI.skin.box);

            if (GUILayout.Button(CustomColorHTML("red", "Annoy All"), style))
            {
                GeneralUtils.AnnoyAll();
            }

            if (GUILayout.Button(CustomColorHTML("#90ee90", "Delete Portals"), style))
            {
                GeneralUtils.DeleteAllPortals();
            }

            if (GUILayout.Button(CustomColorHTML("white", "Utils"), style))
            {
                Enabled = false;
                GeneralUtils.UIHelper.UIMenu[1].Enabled = true; //UI Menu
            }

            if (GUILayout.Button(CustomColorHTML("white", "Settings"), style))
            {
                Enabled = false;
                GeneralUtils.UIHelper.UIMenu[2].Enabled = true; //Settings Menu
            }

            if (GUILayout.Button(CustomColorHTML("white", "Players"), style))
            {
                Enabled = false;
                GeneralUtils.UIHelper.UIMenu[3].Enabled = true; //Players Menu
            }

            if (GUILayout.Button(CustomColorHTML("white", "Lobby"), style))
            {
                Enabled = false;
                GeneralUtils.UIHelper.UIMenu[5].Enabled = true; //Lobby Menu
            }

            if (GUILayout.Button(CustomColorHTML("white", "Fun"), style))
            {
                Enabled = false;
                GeneralUtils.UIHelper.UIMenu[6].Enabled = true; //Fun Menu
            }
        }
Beispiel #8
0
        /// <summary>
        /// Back up to file
        /// </summary>
        /// <param name="folderPath">folder will contain backup file</param>
        /// <returns></returns>
        public string BackupToFile(string folderPath)
        {
            using (var entityConntext = new GeoViewerEntities())
            {
                SecurityBLL.Current.CheckPermissionThrowException(SecurityBLL.ROLE_DATA_MANAGE);
                // Make backup folder name
                string backupFolder = folderPath + @"\GeoViewer_" + DateTime.Now.ToString("ddMMyyyy-hhmm") + "_" +
                                      GeneralUtils.GenerateRandomString(4);
                // Create temp folder
                Directory.CreateDirectory(backupFolder);

                // Copy files data
                foreach (var obj in entityConntext.Loggers)
                {
                    // Copy data files
                    FileInfo file = new FileInfo(obj.DataPath);
                    if (file.Exists)
                    {
                        File.Copy(obj.DataPath, backupFolder + @"\" + obj.LoggerID + file.Extension, true);
                    }
                    else
                    {
                        CopyFolder(obj.DataPath, backupFolder + @"\" + obj.LoggerID);
                    }
                }
                // Back up database
                entityConntext.ExecuteStoreCommand(
                    "backup database " + databaseName + "  to disk = '" + backupFolder + @"\database.bak'",
                    null);

                // Copy Pictures folder
                CopyFolder("Pictures", backupFolder + @"\Pictures");

                // Zip to file
                ZipFile zip = new ZipFile();
                zip.AddDirectory(backupFolder);
                zip.Save(backupFolder + ".zip");

                // Delete file after zipped
                DeleteFolder(backupFolder);

                return(backupFolder + ".zip");
            }
        }
        public async Task <dynamic> LikeById(string postId, string commentId)
        {
            var postCollection = MongoWrapper.Database.GetCollection <Models.Post>(nameof(Models.Post));

            var commentFilterBuilder = new FilterDefinitionBuilder <Models.Comment>();
            var commentFilter        = commentFilterBuilder.Eq(c => c._id, new ObjectId(commentId));

            var postFilterBuilder = new FilterDefinitionBuilder <Models.Post>();
            var postFilter        = postFilterBuilder.And
                                    (
                postFilterBuilder.Eq(u => u._id, new ObjectId(postId)),
                GeneralUtils.NotDeactivated(postFilterBuilder),
                postFilterBuilder.ElemMatch(u => u.Comments, commentFilter),
                GeneralUtils.NotDeactivated(postFilterBuilder, p => p.Comments)
                                    );

            ObjectId currentUserId = new ObjectId(this.GetCurrentUserId());

            var commentUpdateBuilder = new UpdateDefinitionBuilder <Models.Post>();
            var commentUpdate        = commentUpdateBuilder.AddToSet(p => p.Comments[-1].Likes, currentUserId);

            var updateResult = await postCollection.UpdateOneAsync(
                postFilter,
                commentUpdate
                );

            if (updateResult.MatchedCount == 0)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Comentário não encontrado!",
                });
            }

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Comentário Likeado com sucesso!",
            });
        }
        public override void Transform(Engine engine, Package package)
        {
            GeneralUtils.TimedLog("started Transform");
            Package = package;
            Engine  = engine;
            Dynamic.Page page;
            bool         hasOutput = HasPackageValue(package, "Output");

            if (hasOutput)
            {
                String inputValue = package.GetValue("Output");
                page = (Dynamic.Page)SerializerService.Deserialize <Dynamic.Page>(inputValue);
            }
            else
            {
                page = GetDynamicPage();
            }

            try
            {
                TransformPage(page);
            }
            catch (StopChainException)
            {
                Log.Debug("caught stopchainexception, will not write current page back to the package");
                return;
            }

            string outputValue = SerializerService.Serialize <Dynamic.Page>(page);

            if (hasOutput)
            {
                Item outputItem = package.GetByName("Output");
                outputItem.SetAsString(outputValue);
                //package.Remove(outputItem);
                //package.PushItem(Package.OutputName, package.CreateStringItem(SerializerService is XmlSerializerService ? ContentType.Xml : ContentType.Text, outputValue));
            }
            else
            {
                package.PushItem(Package.OutputName, package.CreateStringItem(SerializerService is XmlSerializerService ? ContentType.Xml : ContentType.Text, outputValue));
            }

            GeneralUtils.TimedLog("finished Transform");
        }
Beispiel #11
0
        /// <summary>
        /// Update the display with the localise text
        /// </summary>
        void Localise()
        {
            // added by YouLocal team, 27.08.2017
            _textComponent.font = GeneralUtils.FontForCurrentLanguage(_textComponent.fontStyle);

            // If we don't have a key then don't change the value
            if (string.IsNullOrEmpty(Key))
            {
                return;
            }

            PreLocaliseValue = Localisation.LocaliseText.Get(Key);

            // Run any callback to modify the term.
            OnPreLocalise.Invoke(this);

            // apply any modifier
            if (!string.IsNullOrEmpty(PreLocaliseValue))
            {
                switch (Modifier)
                {
                case ModifierType.LowerCase:
                    PreLocaliseValue = PreLocaliseValue.ToLower();
                    break;

                case ModifierType.UpperCase:
                    PreLocaliseValue = PreLocaliseValue.ToUpper();
                    break;

                case ModifierType.Title:
                    CultureInfo.CurrentCulture.TextInfo.ToTitleCase(PreLocaliseValue);
                    break;

                case ModifierType.FirstCapital:
                    var characters = PreLocaliseValue.ToLower().ToCharArray();
                    characters[0]    = char.ToUpper(PreLocaliseValue[0]);
                    PreLocaliseValue = new string(characters);
                    break;
                }
            }

            // set the value
            Value = PreLocaliseValue;
        }
Beispiel #12
0
        private void RefreshData()
        {
            OptionsList.Items.Add(Option_CoreInfo);
            OptionsList.Items.Add(Option_FarmServers);
            OptionsList.Items.Add(Option_Services);
            OptionsList.Items.Add(Option_ServiceApplications);
            OptionsList.Items.Add(Option_ContentDatabases);
            OptionsList.Items.Add(Option_FarmSolutions);
            OptionsList.Items.Add(Option_UserSolutions);
            OptionsList.Items.Add(Option_ManagedPaths);
            OptionsList.Items.Add(Option_WebApplications);
            OptionsList.Items.Add(Option_SiteCollections);
            OptionsList.Items.Add(Option_Sites);
            OptionsList.Items.Add(Option_Lists);
            OptionsList.Items.Add(Option_Items);

            GeneralUtils.CheckAll(OptionsList);
            OptionsList.SetItemChecked(OptionsList.Items.IndexOf(Option_Items), false);
        }
        public static void Select(string[] args)
        {
            ArrayManipulators <string> arrman = new ArrayManipulators <string>();

            string[] selectargs = arrman.RemoveEmptyEntries(args);
            Logger.TalkyLog(args[0]);
            switch (selectargs[0])
            {
            case "ilasm":
                Logger.Log(string.Format("ILasm wrapper v{0}.{1}", ApiVersion.ILasmMajor, ApiVersion.ILasmMinor));
                Logger.TalkyLog(args.Skip(1).ToArray().JoinToString(" "));
                ILasmCompiler.ILasmCommand(args.Skip(1).ToArray().JoinToString(" "));
                break;

            case "al":
                Logger.Log(string.Format("AssemblyLinker wrapper v{0}.{1}", ApiVersion.ALMajor, ApiVersion.ALMinor));
                Logger.TalkyLog(args.Skip(1).ToArray().JoinToString(" "));
                AssemblyLinkerProgram.AssemblyLinkerCommand(args.Skip(1).ToArray().JoinToString(" "));
                break;

            case "ildasm":
                Logger.Log(string.Format("ILdasm wrapper v{0}.{1}", ApiVersion.ILdasmMajor, ApiVersion.ILdasmMinor));
                Logger.TalkyLog(args.Skip(1).ToArray().JoinToString(" "));
                ILdasmProgram.ILdasmCommand(args.Skip(1).ToArray().JoinToString(" "));
                break;

            case "ngen":
                Logger.Log(string.Format("Native Image Generator (ngen) wrapper v{0}.{1}", ApiVersion.NGENMajor, ApiVersion.NGENMinor));
                Logger.TalkyLog(args.Skip(1).ToArray().JoinToString(" "));
                NGENProgram.NGENCommand(args.Skip(1).ToArray().JoinToString(" "));
                break;

            case "lc":
                Logger.Log(string.Format("LicenseCompiler wrapper v{0}.{1}", ApiVersion.LCMajor, ApiVersion.LCMinor));
                Logger.TalkyLog(args.Skip(1).ToArray().JoinToString(" "));
                LicenseCompilerProgram.LicenseCompilerCommand(args.Skip(1).ToArray().JoinToString(" "));
                break;

            case "help":
                GeneralUtils.printExecHelp();
                break;
            }
        }
Beispiel #14
0
        /// <summary>Initialize the datastructures.</summary>
        protected override void InitClass()
        {
            TableName              = "AlphabeticalListOfProduct";
            _columnProductId       = GeneralUtils.CreateTypedDataTableColumn("ProductId", @"ProductId", typeof(System.Int32), this.Columns);
            _columnProductName     = GeneralUtils.CreateTypedDataTableColumn("ProductName", @"ProductName", typeof(System.String), this.Columns);
            _columnSupplierId      = GeneralUtils.CreateTypedDataTableColumn("SupplierId", @"SupplierId", typeof(System.Int32), this.Columns);
            _columnCategoryId      = GeneralUtils.CreateTypedDataTableColumn("CategoryId", @"CategoryId", typeof(System.Int32), this.Columns);
            _columnQuantityPerUnit = GeneralUtils.CreateTypedDataTableColumn("QuantityPerUnit", @"QuantityPerUnit", typeof(System.String), this.Columns);
            _columnUnitPrice       = GeneralUtils.CreateTypedDataTableColumn("UnitPrice", @"UnitPrice", typeof(System.Decimal), this.Columns);
            _columnUnitsInStock    = GeneralUtils.CreateTypedDataTableColumn("UnitsInStock", @"UnitsInStock", typeof(System.Int16), this.Columns);
            _columnUnitsOnOrder    = GeneralUtils.CreateTypedDataTableColumn("UnitsOnOrder", @"UnitsOnOrder", typeof(System.Int16), this.Columns);
            _columnReorderLevel    = GeneralUtils.CreateTypedDataTableColumn("ReorderLevel", @"ReorderLevel", typeof(System.Int16), this.Columns);
            _columnDiscontinued    = GeneralUtils.CreateTypedDataTableColumn("Discontinued", @"Discontinued", typeof(System.Boolean), this.Columns);
            _columnCategoryName    = GeneralUtils.CreateTypedDataTableColumn("CategoryName", @"CategoryName", typeof(System.String), this.Columns);

            // __LLBLGENPRO_USER_CODE_REGION_START InitClass
            // __LLBLGENPRO_USER_CODE_REGION_END
            OnInitialized();
        }
Beispiel #15
0
 /// <summary>Initialize the datastructures.</summary>
 protected override void InitClass()
 {
     TableName               = "Channel1";
     _columnChannelId        = GeneralUtils.CreateTypedDataTableColumn("ChannelId", @"ChannelId", typeof(System.Int32), this.Columns);
     _columnCampaignId       = GeneralUtils.CreateTypedDataTableColumn("CampaignId", @"CampaignId", typeof(System.Int32), this.Columns);
     _columnChannelName      = GeneralUtils.CreateTypedDataTableColumn("ChannelName", @"ChannelName", typeof(System.String), this.Columns);
     _columnChannelTypeId    = GeneralUtils.CreateTypedDataTableColumn("ChannelTypeId", @"ChannelTypeId", typeof(System.Int32), this.Columns);
     _columnDescription      = GeneralUtils.CreateTypedDataTableColumn("Description", @"Description", typeof(System.String), this.Columns);
     _columnStartDate        = GeneralUtils.CreateTypedDataTableColumn("StartDate", @"StartDate", typeof(System.DateTime), this.Columns);
     _columnEndDate          = GeneralUtils.CreateTypedDataTableColumn("EndDate", @"EndDate", typeof(System.DateTime), this.Columns);
     _columnChannelCode      = GeneralUtils.CreateTypedDataTableColumn("ChannelCode", @"ChannelCode", typeof(System.String), this.Columns);
     _columnRedemptionCodeId = GeneralUtils.CreateTypedDataTableColumn("RedemptionCodeId", @"RedemptionCodeId", typeof(System.Int32), this.Columns);
     _columnIsLocked         = GeneralUtils.CreateTypedDataTableColumn("IsLocked", @"IsLocked", typeof(System.Int32), this.Columns);
     _columnCreatedBy        = GeneralUtils.CreateTypedDataTableColumn("CreatedBy", @"CreatedBy", typeof(System.String), this.Columns);
     _columnStoreOptionId    = GeneralUtils.CreateTypedDataTableColumn("StoreOptionId", @"StoreOptionId", typeof(System.Int32), this.Columns);
     // __LLBLGENPRO_USER_CODE_REGION_START InitClass
     // __LLBLGENPRO_USER_CODE_REGION_END
     OnInitialized();
 }
Beispiel #16
0
        public async Task <dynamic> Get([FromQuery] string search)
        {
            var userCollection = MongoWrapper.Database.GetCollection <Models.User>(nameof(Models.User));

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var userProjection        = userProjectionBuilder
                                        .MetaTextScore("MetaScore".WithLowercaseFirstCharacter())
                                        .Include(user => user._id)
                                        .Include(user => user.FullName)
                                        .Include(user => user.Avatar)
                                        .Include(user => user.About)
                                        .Include("_t");

            var userFilterBuilder = new FilterDefinitionBuilder <Models.User>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Text(search, new TextSearchOptions
            {
                CaseSensitive      = false,
                DiacriticSensitive = false,
            }),
                GeneralUtils.NotDeactivated(userFilterBuilder)
                                    );

            var userSortBuilder = new SortDefinitionBuilder <Models.User>();
            var userSort        = userSortBuilder.MetaTextScore("MetaScore".WithLowercaseFirstCharacter());

            var users = (await userCollection.FindAsync(userFilter, new FindOptions <Models.User>
            {
                Sort = userSort,
                Limit = 50,
                AllowPartialResults = true,
                Projection = userProjection,
            }));

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Data = users.ToEnumerable().Select(u => u.BuildUserResponse()),
                Message = "Usuários encontrados com sucesso!",
            });
        }
Beispiel #17
0
    public static bool CallbackIsValid(Delegate callback)
    {
        bool flag = true;

        if (callback == null)
        {
            flag = false;
        }
        else if (!callback.Method.IsStatic)
        {
            object target = callback.Target;
            flag = GeneralUtils.IsObjectAlive(target);
            if (!flag)
            {
                Console.WriteLine(string.Format("Target for callback {0} is null.", callback.Method.Name));
            }
        }
        return(flag);
    }
Beispiel #18
0
        protected override void TransformPage(Dynamic.Page page)
        {
            GeneralUtils.TimedLog("start TransformPage with id " + page.Id);

            Page           tcmPage        = this.GetTcmPage();
            StructureGroup tcmSG          = (StructureGroup)tcmPage.OrganizationalItem;
            String         mergeActionStr = Package.GetValue("MergeAction");

            while (tcmSG != null)
            {
                if (tcmSG.MetadataSchema != null)
                {
                    TCM.Fields.ItemFields tcmFields = new TCM.Fields.ItemFields(tcmSG.Metadata, tcmSG.MetadataSchema);
                    FieldsBuilder.AddFields(page.MetadataFields, tcmFields, Manager);
                }
                tcmSG = tcmSG.OrganizationalItem as StructureGroup;
            }
            GeneralUtils.TimedLog("finished TransformPage");
        }
        public bool MatchedVersion()
        {
            Version curr = GeneralUtils.GetCanapeVersion();

            if (curr.CompareTo(_minimum) < 0)
            {
                return(false);
            }

            if (_maximum != null)
            {
                if (curr.CompareTo(_maximum) > 0)
                {
                    return(false);
                }
            }

            return(true);
        }
        protected void CategoriesRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (GeneralUtils.ValueIsInList(e.Item.ItemType, ListItemType.Item, ListItemType.AlternatingItem))
            {
                // Get the category
                Category category = (Category)e.Item.DataItem;

                // Get the link button
                LinkButton categoryLinkButton = (LinkButton)e.Item.FindControl("CategoryLinkButton");

                if (!category.ParentCategory.IsNull)
                {
                    categoryLinkButton.CommandArgument = category.CategoryId.ToString();
                    categoryLinkButton.Text            = category.Name;
                    categoryLinkButton.ToolTip         = SiteUtils.GetFullCategoryName(category);
                    categoryLinkButton.Visible         = true;
                }
            }
        }
        private void RenderDropDownMenuItems(DropDownMenuItemCollection items, HtmlTextWriter writer)
        {
            foreach (DropDownMenuItem item in items.FindAll(item => item.Visible))
            {
                string url = GeneralUtils.GetNonEmptyString(item.NavigateUrl, "#");

                if (url != "#" && !url.EndsWith("/") && !url.Contains("?"))
                {
                    string path = HttpContext.Current.Server.MapPath(url);
                    url = (File.Exists(path)) ? ResolveUrl(url) : "#";
                }
                else if (url.Contains("?"))
                {
                    url = ResolveUrl(url);
                }

                writer.WriteBeginTag("li");
                if (!string.IsNullOrEmpty(item.CssClass))
                {
                    writer.WriteAttribute("class", item.CssClass);
                }
                writer.Write(HtmlTextWriter.TagRightChar);

                writer.WriteBeginTag("a");
                writer.WriteAttribute("href", url);
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Write(item.Text);
                writer.WriteEndTag("a");

                if (item.Items.Count > 0)
                {
                    writer.WriteBeginTag("ul");
                    writer.WriteAttribute("class", "sub_menu");
                    writer.Write(HtmlTextWriter.TagRightChar);

                    RenderDropDownMenuItems(item.Items, writer);

                    writer.WriteEndTag("ul");
                }

                writer.WriteEndTag("li");
            }
        }
Beispiel #22
0
        /// <inheritdoc />
        protected override void HandleMain(CodeEntryPointMethod obj, Context ctx)
        {
            ctx.Writer.Write("Public ");
            if (ctx.VisualBasic.CurrentBlockType != BlockType.Module)
            {
                ctx.Writer.Write("Shared ");
            }
            bool isSub = GeneralUtils.IsNullOrVoidType(obj.ReturnType);

            ctx.Writer.Write((isSub ? "Sub" : "Function") + " Main(ByVal cmdArgs() As String)");

            if (!isSub)
            {
                ctx.Writer.Write(" As ");
                ctx.HandlerProvider.TypeReferenceHandler.Handle(obj.ReturnType, ctx);
            }

            HandleMethodStatements(obj, ctx, isSub);
        }
        private Dynamic.Component GetDynamicComponent(BuildManager manager)
        {
            GeneralUtils.TimedLog("start getting component from package");
            Item item = Package.GetByName(Package.ComponentName);

            GeneralUtils.TimedLog("finished getting component from package");
            if (item == null)
            {
                Log.Error("no component found (is this a page template?)");
                return(null);
            }
            Component tcmComponent = (Component)Engine.GetObject(item.GetAsSource().GetValue("ID"));
            int       linkLevels;

            if (HasPackageValue(Package, "LinkLevels"))
            {
                linkLevels = Convert.ToInt32(Package.GetValue("LinkLevels"));
            }
            else
            {
                GeneralUtils.TimedLog("no link levels configured, using default level " + this.DefaultLinkLevels);
                linkLevels = this.DefaultLinkLevels;
            }
            bool resolveWidthAndHeight;

            if (HasPackageValue(Package, "ResolveWidthAndHeight"))
            {
                resolveWidthAndHeight = Package.GetValue("ResolveWidthAndHeight").ToLower().Equals("yes");
            }
            else
            {
                GeneralUtils.TimedLog("no ResolveWidthAndHeight configured, using default value " + this.DefaultResolveWidthAndHeight);
                resolveWidthAndHeight = this.DefaultResolveWidthAndHeight;
            }

            GeneralUtils.TimedLog("found component with title " + tcmComponent.Title + " and id " + tcmComponent.Id);
            GeneralUtils.TimedLog("constructing dynamic component, links are followed to level " + linkLevels + ", width and height are " + (resolveWidthAndHeight ? "" : "not ") + "resolved");

            GeneralUtils.TimedLog("start building dynamic component");
            Dynamic.Component component = manager.BuildComponent(tcmComponent, linkLevels, resolveWidthAndHeight);
            GeneralUtils.TimedLog("finished building dynamic component");
            return(component);
        }
Beispiel #24
0
        /// <summary>
        /// Gets the absolute folder where files of the specified type should be saved for the specified asset
        /// </summary>
        internal static string GetFolder(AssetFilePath path, AssetFileType fileType)
        {
            if (GeneralUtils.ValueIsInList(fileType, AssetFileType.AssetFile, AssetFileType.AssetPreview, AssetFileType.AssetThumbnail))
            {
                return(Path.Combine(path.Path, fileType + "s"));
            }

            if (GeneralUtils.ValueIsInList(fileType, AssetFileType.AssetFileZipped))
            {
                return(Path.Combine(path.Path, "AssetFilesZipped"));
            }

            if (GeneralUtils.ValueIsInList(fileType, AssetFileType.AttachedFile))
            {
                throw new SystemException("Attached files are not stored on disk");
            }

            throw new SystemException("Unknown file type: " + fileType);
        }
Beispiel #25
0
        /// <inheritdoc/>
        public bool Handle(CodeTypeParameter obj, Context ctx)
        {
            if (ctx.CSharp.TypeParameterHandlerRequestedOperation == CSharpContext.TypeParameterHandlerOperations.Declaration)
            {
                //TODO struct and class type constraints, out and in
                if (obj.CustomAttributes.Count > 0)
                {
                    GeneralUtils.HandleCollection(obj.CustomAttributes.Cast <CodeAttributeDeclaration>(),
                                                  ctx.HandlerProvider.AttributeDeclarationHandler, ctx);
                    ctx.Writer.Write(" ");
                }
                ctx.Writer.Write(obj.Name.AsCsId());
            }
            else if (ctx.CSharp.TypeParameterHandlerRequestedOperation == CSharpContext.TypeParameterHandlerOperations.Constraint)
            {
                if (HasConstraints(obj))
                {
                    ctx.Writer.NewLine();
                    ctx.Writer.Indent(ctx);
                    ctx.Writer.Write($"where {obj.Name.AsCsId()} : ");

                    GeneralUtils.HandleCollectionCommaSeparated(obj.Constraints.Cast <CodeTypeReference>(),
                                                                ctx.HandlerProvider.TypeReferenceHandler, ctx);

                    if (obj.HasConstructorConstraint)
                    {
                        if (obj.Constraints.Count > 0)
                        {
                            ctx.Writer.Write(", ");
                        }

                        ctx.Writer.Write("new()");
                    }
                }
            }
            else
            {
                throw new InvalidOperationException();
            }

            return(true);
        }
Beispiel #26
0
        private string BuildReport(string templateName, List <Param> paramList, OutputPresentationType output)
        {
            var outputFileName = GetOutputFileName(templateName, output);

            GeneralUtils.ChangeCurrentCultrue("es-ES");
            var report     = GetReport(templateName, paramList);
            var paramsList = GetReportParams(paramList, ref report);

            report.RunGetData(paramsList);
            var pages = report.BuildPages();

            var sg = new OneFileStreamGen(outputFileName, true);


            switch (output)
            {
            case OutputPresentationType.Word:
                report.RunRender(sg, OutputPresentationType.HTML, pages);
                outputFileName = GetWordDocumentFromHtml(outputFileName);
                break;

            case OutputPresentationType.RenderPdf_iTextSharp:
            case OutputPresentationType.PDF:
                report.ItextPDF = true;
                report.RunRenderPdf(sg, pages);
                break;

            case OutputPresentationType.PDFOldStyle:
                report.ItextPDF = false;
                report.RunRenderPdf(sg, pages);
                break;

            default:
                report.RunRender(sg, output, pages);
                break;
            }

            sg.CloseMainStream();
            sg.Dispose();

            return(outputFileName);
        }
Beispiel #27
0
    static void UploadApkFiles(string apkPath, WWWUtils.Environment env)
    {
        try
        {
            var tmpDir = "/tmp/apk";
            GeneralUtils.DeleteDirectory(tmpDir, true);               // mko: cleaning up build folder
            Directory.CreateDirectory(tmpDir);

            // unzip
            var res = CommandLineUtils.Run("/usr/bin/unzip", string.Format("-d {0} {1}", tmpDir, apkPath));
            Debug.Log(res);

            // generate the app.dll
            var files = new List <string>(Directory.GetFiles("/tmp/apk/assets/bin/Data/Managed", "*.dll", SearchOption.TopDirectoryOnly));
            files.Sort(System.StringComparer.OrdinalIgnoreCase);

            List <byte> bytes = new List <byte>();
            foreach (string filePath in files)
            {
                Debug.Log("Adding file " + filePath);
                bytes.AddRange(File.ReadAllBytes(filePath));
            }

            Debug.Log("MSIL size is " + EB.Localizer.FormatNumber(bytes.Count, true));

            WWWForm form = new WWWForm();
            form.AddBinaryData("data", bytes.ToArray(), "data");
            form.AddField("version", EB.Version.GetVersion());
            form.AddField("platform", "android");
            form.AddField("sha1", EB.Encoding.ToBase64String(EB.Digest.Sha1().Hash(bytes.ToArray())));

            var stoken  = WWWUtils.AdminLogin(env);
            var postUrl = WWWUtils.GetAdminUrl(env) + "/protect/upload?stoken=" + stoken;
            res = WWWUtils.Post(postUrl, form);
            Debug.Log("version: " + res);
        }
        catch (System.Exception e)
        {
            Debug.Log("Build Failed: exception: " + e.ToString());
            Failed(e);
        }
    }
Beispiel #28
0
        private void btn_password_Click(object sender, EventArgs e)
        {
            confirmPasswordErrorLabel.Visible = false;
            passwordErrorLabel.Visible        = false;
            bool noErrors = true;

            try
            {
                if (String.IsNullOrEmpty(_selectedUser.Username))
                {
                    throw new Exception("No User selected");
                }
                if (tb_password.Text != tb_repeat_password.Text)
                {
                    confirmPasswordErrorLabel.Visible = true;
                    noErrors = false;
                }
                if (!GeneralUtils.checkPasswordComplexity(tb_password.Text))
                {
                    passwordErrorLabel.Visible = true;
                    noErrors = false;
                }
                if (noErrors)
                {
                    using (HBSModel _entity = new HBSModel())
                    {
                        var    _user = _entity.Users.FirstOrDefault(user => user.Username == _selectedUser.Username);
                        byte[] passwordHash, passwordSalt;
                        GeneralUtils.CreatePasswordHash(tb_password.Text, out passwordHash, out passwordSalt);
                        _user.Pwd     = passwordHash;
                        _user.PwdSalt = passwordSalt;
                        _entity.SaveChanges();
                        MessageBox.Show("Password Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        initalizeUserInputs();
                    }
                }
            }
            catch (Exception ex)
            {
                DesktopAppUtils.popDefaultErrorMessageBox("Error:\n" + ex.Message);
            }
        }
Beispiel #29
0
        public void AppendByteArraysNullTest()
        {
            byte[] bytes1 = null;
            byte[] bytes2 = null;

            try
            {
                GeneralUtils.AppendByteArrays(bytes1, bytes2);
                Assert.Fail("Should have thrown ArgumentNullException.");
            }
            catch (Exception)
            {
                //ignore
            }

            bytes1 = new byte[]
            {
                1,
                2,
                3
            };

            bytes2 = new byte[]
            {
                4,
                5,
                6
            };

            var bytes3 = GeneralUtils.AppendByteArrays(bytes1, bytes2);

            CollectionAssert.AreEqual(new byte[]
            {
                1,
                2,
                3,
                4,
                5,
                6
            },
                                      bytes3);
        }
        protected void CopyNotesToAllButton_Click(object sender, EventArgs e)
        {
            bool found = false;

            DateTime?dt    = null;
            string   notes = string.Empty;

            Button btn = (Button)sender;

            foreach (RepeaterItem ri in CartRepeater.Items)
            {
                if (GeneralUtils.ValueIsInList(ri.ItemType, ListItemType.Item, ListItemType.AlternatingItem))
                {
                    Button CopyNotesToAllButton = (Button)ri.FindControl("CopyNotesToAllButton");

                    if (CopyNotesToAllButton.UniqueID == btn.UniqueID)
                    {
                        DatePicker DateRequiredPicker = (DatePicker)ri.FindControl("DateRequiredPicker");
                        TextArea   NotesTextBox       = (TextArea)ri.FindControl("NotesTextBox");

                        dt    = DateRequiredPicker.SelectedDate;
                        notes = NotesTextBox.Text;

                        found = true;

                        break;
                    }
                }
            }

            if (found)
            {
                foreach (Cart cart in ContextInfo.CartManager.CartList)
                {
                    cart.RequiredByDate = dt;
                    cart.Notes          = notes;
                    Cart.Update(cart);
                }
            }

            Bind(CurrentPage);
        }