CreateGroup() public méthode

public CreateGroup ( string name, Budget, groupBudget ) : void
name string
groupBudget Budget,
Résultat void
Exemple #1
0
        public void AddTest()
        {
            FelBookDBEntities DBEntities  = new FelBookDBEntities();
            IWallService      wallService = null; // Snad ji zatím nepotřebuji
            GroupService      target      = new GroupService(DBEntities, wallService);

            User user = User.CreateUser(0, "group", "creator", DateTime.Now,
                                        "mail", "groupCreator", "1234");

            DBEntities.UserSet.AddObject(user);
            DBEntities.SaveChanges();

            Group group = Group.CreateGroup(0, "newGroup", "groupDescription");

            target.Add(user, group);

            Assert.IsTrue(DBEntities.GroupSet.ToList().Contains(group));
            Assert.AreEqual(user, group.Creator);
            Assert.IsTrue(group.Administrators.Contains(user));
            Assert.IsTrue(group.Users.Contains(user));

            Assert.IsTrue(user.AdminedGroups.Contains(group));
            Assert.IsTrue(user.CreatedGroups.Contains(group));
            Assert.IsTrue(user.JoinedGroups.Contains(group));

            DBEntities.GroupSet.DeleteObject(group);
            DBEntities.UserSet.DeleteObject(user);
            DBEntities.SaveChanges();
        }
Exemple #2
0
        public void EditTest()
        {
            FelBookDBEntities DBEntities  = new FelBookDBEntities();
            IWallService      wallService = null;
            GroupService      target      = new GroupService(DBEntities, wallService);

            User creator = User.CreateUser(0, "group", "creator", DateTime.Now,
                                           "mail", "groupCreator", "1234");

            DBEntities.UserSet.AddObject(creator);
            User member = User.CreateUser(0, "group", "member", DateTime.Now,
                                          "mail", "groupMember", "1234");

            DBEntities.UserSet.AddObject(member);

            Group group = Group.CreateGroup(0, "newGroup", "groupDescription");

            creator.CreatedGroups.Add(group);
            creator.AdminedGroups.Add(group);
            creator.JoinedGroups.Add(group);
            DBEntities.GroupSet.AddObject(group);
            DBEntities.SaveChanges();

            Assert.IsFalse(member.JoinedGroups.Contains(group));
            group.Users.Add(member);

            target.Edit(group);

            Assert.IsTrue(member.JoinedGroups.Contains(group));

            DBEntities.GroupSet.DeleteObject(group);
            DBEntities.UserSet.DeleteObject(member);
            DBEntities.UserSet.DeleteObject(creator);
            DBEntities.SaveChanges();
        }
Exemple #3
0
        private void HandleAddGroupClicked()
        {
            ChainView.NewNodePicker.Hide();

            UnbindFromNodePicker();

            Group.CreateGroup();
        }
Exemple #4
0
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        private void Initialize()
        {
            var sender     = CreateUser("TestMessageSender", "porkmuffins", "*****@*****.**", 10);
            var firstUser  = CreateUser("One", "1", "*****@*****.**", 20);
            var secondUser = CreateUser("Two", "2", "*****@*****.**", 30);
            var thirdUser  = CreateUser("Three", "3", "*****@*****.**", 40);
            var fourthUser = CreateUser("Four", "4", "*****@*****.**", 50);

            using (var db = new CSSDataContext())
            {
                Group.CreateGroup(db, "GroupA", false, "@GA");
                Group.CreateGroup(db, "GroupB", false, "@GB");

                var role = new GroupRole()
                {
                    Name  = "Member",
                    Token = null
                };

                db.GroupRoles.InsertOnSubmit(role);
                db.SubmitChanges();

                Group.AddAlias(db, "GroupA", "One");
                Group.AddAlias(db, "GroupA", "Two");
                Group.AddAlias(db, "GroupB", "Three");
                Group.AddAlias(db, "GroupB", "Four");
                db.SubmitChanges();

                GroupMessage.NewMessage(db, "SUBJECT", "THIS MESSAGE IS FOR GROUP A WHICH CONSISTS OF \"One\" AND \"Two\"",
                                        "GroupA", DateTime.Now, sender.Aliases.FirstOrDefault());
                GroupMessage.NewMessage(db, "SUBJECT", "THIS MESSAGE IS FOR GROUP A WHICH CONSISTS OF \"Three\" AND \"Four\"",
                                        "GroupB", DateTime.Now, sender.Aliases.FirstOrDefault());

                GroupMessage.NewMessage(db, "Global Message", "This message should go to all users.", null, DateTime.Now, sender.Aliases.FirstOrDefault());

                db.SubmitChanges();

                PersonalMessage.NewMessage(db, "SUBJECT", "THIS MESSAGE IS FOR \"One\"",
                                           firstUser.Aliases.First(), Login.FindLoginByUsernameOrCallsign(db, "One"), DateTime.Now);

                db.SubmitChanges();

                PersonalMessage.NewMessage(db, "SUBJECT", "THIS MESSAGE IS FOR \"Two\"",
                                           firstUser.Aliases.First(), Login.FindLoginByUsernameOrCallsign(db, "Two"), DateTime.Now);
                PersonalMessage.NewMessage(db, "SUBJECT", "THIS MESSAGE IS FOR \"Three\"",
                                           firstUser.Aliases.First(), Login.FindLoginByUsernameOrCallsign(db, "Three"), DateTime.Now);
                PersonalMessage.NewMessage(db, "SUBJECT", "THIS MESSAGE IS FOR \"Four\"",
                                           firstUser.Aliases.First(), Login.FindLoginByUsernameOrCallsign(db, "Four"), DateTime.Now);

                db.SubmitChanges();
            }
        }
Exemple #5
0
        public void GetUsersTest()
        {
            FelBookDBEntities DBEntities  = new FelBookDBEntities();
            IWallService      wallService = null;
            GroupService      target      = new GroupService(DBEntities, wallService);

            User creator = User.CreateUser(0, "group", "creator", DateTime.Now,
                                           "mail", "groupCreator", "1234");

            DBEntities.UserSet.AddObject(creator);
            User member = User.CreateUser(0, "group", "member", DateTime.Now,
                                          "mail", "groupMember", "1234");

            DBEntities.UserSet.AddObject(member);

            Group group = Group.CreateGroup(0, "newGroup", "groupDescription");

            creator.CreatedGroups.Add(group);
            creator.AdminedGroups.Add(group);
            creator.JoinedGroups.Add(group);
            DBEntities.GroupSet.AddObject(group);
            DBEntities.SaveChanges();

            List <User> actual = target.GetUsers(group).ToList();

            Assert.AreEqual(1, actual.Count);
            Assert.IsTrue(actual.Contains(creator));
            Assert.IsFalse(actual.Contains(member));

            group.Users.Add(member);
            DBEntities.SaveChanges();

            actual = target.GetUsers(group).ToList();
            Assert.AreEqual(2, actual.Count);
            Assert.IsTrue(actual.Contains(creator));
            Assert.IsTrue(actual.Contains(member));

            group.Users.Remove(member);
            group.Users.Remove(creator);
            DBEntities.SaveChanges();

            actual = target.GetUsers(group).ToList();
            Assert.AreEqual(0, actual.Count);
            Assert.IsFalse(actual.Contains(creator));
            Assert.IsFalse(actual.Contains(member));

            DBEntities.GroupSet.DeleteObject(group);
            DBEntities.UserSet.DeleteObject(member);
            DBEntities.UserSet.DeleteObject(creator);
            DBEntities.SaveChanges();
        }
        public void Place(Sheet sheet, Graphic graphic, E3Text text, Group group, Point placePosition)
        {
            E3Font     smallFont = new E3Font(height: smallFontHeight, alignment: Alignment.Left);
            E3Font     bigFont   = new E3Font(height: bigFontHeight, alignment: Alignment.Left);
            List <int> groupIds;

            if (orientation == Orientation.Horizontal)
            {
                groupIds = PlaceHorizontally(sheet, graphic, text, placePosition, smallFont, bigFont);
            }
            else
            {
                groupIds = PlaceVertically(sheet, graphic, text, placePosition, smallFont, bigFont);
            }
            group.CreateGroup(groupIds);
        }
Exemple #7
0
 private void saveRule_Click(object sender, EventArgs e)
 {
     if (isedit && groupEditId != null)
     {
         int groupIndex = UserAdminUtilities.UserAdminUtility.groups.GetGroupIndexbyid(groupEditId);
         if (groupIndex >= 0)
         {
             if (!UserAdminUtilities.UserAdminUtility.groups.groupname.Contains(groupNameText.Text))
             {
                 if (!String.IsNullOrEmpty(groupNameText.Text))
                 {
                     UserAdminUtilities.UserAdminUtility.groups[groupIndex] = Group.CreateGroup(groupNameText.Text, UserAdminConstants.CompanyId);
                     this.Close();
                 }
                 else
                 {
                     MessageBox.Show("Group name cannot be null or empty");
                 }
             }
             else
             {
                 MessageBox.Show("Group with same name exists");
             }
         }
     }
     else
     {
         if (!UserAdminUtilities.UserAdminUtility.groups.groupname.Contains(groupNameText.Text))
         {
             if (!String.IsNullOrEmpty(groupNameText.Text))
             {
                 UserAdminUtilities.UserAdminUtility.groups.Add(Group.CreateGroup(groupNameText.Text, UserAdminConstants.CompanyName));
                 this.Close();
             }
             else
             {
                 MessageBox.Show("Group name cannot be null or empty");
             }
         }
         else
         {
             MessageBox.Show("Group with same name exists");
         }
     }
     //this.Close();
 }
Exemple #8
0
        public void Place(Point placePosition, Sheet sheet, Graphic graphic, Group group, E3Text text)
        {
            PlacedPosition = placePosition;
            double     width          = 0.2;
            List <int> ids            = new List <int>(5);
            double     halfBaseLength = triangleBaseLength / 2;
            Point      leftBottom     = new Point(sheet.MoveLeft(placePosition.X, halfBaseLength), placePosition.Y);
            Point      rightBottom    = new Point(sheet.MoveRight(placePosition.X, halfBaseLength), placePosition.Y);
            Point      top            = new Point(placePosition.X, sheet.MoveUp(placePosition.Y, triangleHeight));
            int        sheetId        = sheet.Id;

            ids.Add(graphic.CreateLine(sheetId, leftBottom.X, leftBottom.Y, rightBottom.X, rightBottom.Y, width));
            ids.Add(graphic.CreateLine(sheetId, leftBottom.X, leftBottom.Y, top.X, top.Y, width));
            ids.Add(graphic.CreateLine(sheetId, rightBottom.X, rightBottom.Y, top.X, top.Y, width));
            ids.Add(text.CreateText(sheetId, description, top.X, sheet.MoveUp(top.Y, descriptionVerticalMargin), font));
            ids.AddRange(CableLayoutById.Values.First().Place(sheet, graphic, placePosition));
            group.CreateGroup(ids);
        }
        /// <summary>
        /// Update all groups
        /// </summary>
        public void UpdateGroups()
        {
            var mPath = Path.Combine(Properties.Settings.Default.SaveLocation);

            AllGroups.Clear();

            try
            {
                string[] subdirectoryEntries = Directory.GetDirectories(mPath);
                foreach (string subdirectory in subdirectoryEntries)
                {
                    string[] group = subdirectory.Split('\\');
                    AllGroups.Add(Group.CreateGroup(group[group.Length - 1]));
                }
            }
            catch
            {
            }
        }
Exemple #10
0
        /// <summary>
        /// Reparse directory
        /// </summary>
        public void RefreshRepository()
        {
            AllGroups.Clear();

            var targetDirectory = Properties.Settings.Default.SaveLocation;

            try
            {
                string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
                foreach (string subdirectory in subdirectoryEntries)
                {
                    string[] group = subdirectory.Split('\\');
                    AllGroups.Add(Group.CreateGroup(group[group.Length - 1]));
                }
            }
            catch
            {
            }
        }
        void GroupMenu()
        {
            MenuGroup userChoice = 0;

            Console.Clear();
            Console.WriteLine("Vad vill du göra?");
            Console.WriteLine($"{Convert.ToInt32(MenuGroup.CreatGroup)}. Skapa grupp");
            Console.WriteLine($"{Convert.ToInt32(MenuGroup.JoinGroup)}. Gå med i grupp");
            Console.WriteLine($"{Convert.ToInt32(MenuGroup.LeaveGroup)}. Lämna grupp");
            Console.WriteLine($"{Convert.ToInt32(MenuGroup.Compete)}. Tävla");
            Console.Write("Ditt val: ");
            int input = error.TryInt();

            userChoice = (MenuGroup)input;

            switch (userChoice)
            {
            case MenuGroup.CreatGroup:
                Group.CreateGroup();
                break;

            case MenuGroup.JoinGroup:
                Group.AddMemberToGroup();
                break;

            case MenuGroup.LeaveGroup:
                Group.LeaveGroup();
                break;

            case MenuGroup.Compete:
                break;

            default:
                Console.Clear();
                error.ErrorMessage();
                Console.Write("\nTryck valfri tangent för att fortsätta.");
                Console.ReadKey();
                break;
            }
        }
        /// <summary>
        /// Default constructor
        /// </summary>
        public GroupRepository()
        {
            if (_groups == null)
            {
                _groups = new ObservableCollection <Group>();
            }

            var targetDirectory = Properties.Settings.Default.SaveLocation;

            try
            {
                var textFiles = Directory.EnumerateDirectories(targetDirectory);
                foreach (string currentDir in textFiles)
                {
                    string[] group = currentDir.Split('\\');
                    _groups.Add(Group.CreateGroup(group[group.Length - 1]));
                }
            }
            catch
            {
            }
        }
Exemple #13
0
        public void AddSubGroupTest()
        {
            FelBookDBEntities DBEntities  = new FelBookDBEntities();
            IWallService      wallService = null;
            GroupService      target      = new GroupService(DBEntities, wallService);

            User user = User.CreateUser(0, "group", "creator", DateTime.Now,
                                        "mail", "groupCreator", "1234");

            DBEntities.UserSet.AddObject(user);

            Group parentGroup = Group.CreateGroup(0, "parentGroup", "parentGroupDescription");

            user.CreatedGroups.Add(parentGroup);
            user.AdminedGroups.Add(parentGroup);
            user.JoinedGroups.Add(parentGroup);
            DBEntities.GroupSet.AddObject(parentGroup);
            DBEntities.SaveChanges();

            Group childGroup = Group.CreateGroup(1, "childGroup", "childGroupDescription");

            target.AddSubGroup(user, parentGroup, childGroup);

            Assert.AreEqual(user, childGroup.Creator);
            Assert.IsTrue(childGroup.Administrators.Contains(user));
            Assert.IsTrue(childGroup.Users.Contains(user));

            Assert.IsTrue(user.AdminedGroups.Contains(childGroup));
            Assert.IsTrue(user.CreatedGroups.Contains(childGroup));
            Assert.IsTrue(user.JoinedGroups.Contains(childGroup));

            Assert.AreEqual(parentGroup, childGroup.Parent);
            Assert.IsTrue(parentGroup.Children.Contains(childGroup));

            DBEntities.GroupSet.DeleteObject(childGroup);
            DBEntities.GroupSet.DeleteObject(parentGroup);
            DBEntities.UserSet.DeleteObject(user);
            DBEntities.SaveChanges();
        }
        public void Place(Point placePosition, Sheet sheet, Graphic graphic, Group group, E3Text text)
        {
            PlacedPosition = placePosition;
            List <int> ids = new List <int>();

            ids.AddRange(PlaceAssignmentFrame(placePosition, sheet, graphic, text));
            foreach (CableLayout cableLayout in cableLayoutById.Values)
            {
                if (cableLayout.Level == Level.Bottom)
                {
                    ids.AddRange(cableLayout.Place(sheet, graphic, placePosition));
                }
                else
                {
                    ids.AddRange(cableLayout.Place(sheet, graphic, placePosition));
                }
            }
            foreach (DeviceSymbol symbol in deviceSymbols)
            {
                ids.AddRange(symbol.Place(sheet, graphic, text, placePosition));
                placePosition.X = sheet.MoveRight(placePosition.X, symbol.Size.Width);
            }
            group.CreateGroup(ids);
        }
Exemple #15
0
        public void FindByNameTest()
        {
            FelBookDBEntities DBEntities  = new FelBookDBEntities();
            IWallService      wallService = null;
            GroupService      target      = new GroupService(DBEntities, wallService);

            Group actual;

            try
            {
                actual = target.FindByName(null);
                Assert.Fail();
            }
            catch (InvalidOperationException)
            { }

            User user = User.CreateUser(0, "group", "creator", DateTime.Now,
                                        "mail", "groupCreator", "1234");

            DBEntities.UserSet.AddObject(user);

            Group expected = Group.CreateGroup(0, "newGroup", "groupDescription");

            user.CreatedGroups.Add(expected);
            user.AdminedGroups.Add(expected);
            user.JoinedGroups.Add(expected);
            DBEntities.GroupSet.AddObject(expected);
            DBEntities.SaveChanges();

            actual = target.FindByName(expected.Name);
            Assert.AreEqual(expected, actual);

            DBEntities.GroupSet.DeleteObject(expected);
            DBEntities.UserSet.DeleteObject(user);
            DBEntities.SaveChanges();
        }
Exemple #16
0
    /// <summary>
    /// Creates the shapes in Groups.
    /// </summary>
    private IEnumerator CreateShapes()
    {
        yield return(0);

        //Clear current shapes list
        shapes.Clear();

        //The ID of the shape
        int ID = 0;

        //The scale ratio for the shape
        float ratio = Mathf.Max(Screen.width, Screen.height) / 1000.0f;

        //The group of the shape
        GameObject shapesGroup = null;

        //The index of the group
        int groupIndex = 0;

        pointersParent.gameObject.SetActive(false);
        groupsParent.gameObject.SetActive(false);

        //Create Shapes inside groups
        for (int i = 0; i < shapesManager.shapes.Count; i++)
        {
            if (i % shapesPerGroup == 0)
            {
                groupIndex  = (i / shapesPerGroup);
                shapesGroup = Group.CreateGroup(shapesGroupPrefab, groupsParent, groupIndex, columnsPerGroup);
                if (!EnableGroupGridLayout)
                {
                    shapesGroup.GetComponent <GridLayoutGroup> ().enabled = false;
                }
                if (createGroupsPointers)
                {
                    Pointer.CreatePointer(groupIndex, shapesGroup, pointerPrefab, pointersParent);
                }
            }

            //Create Shape
            ID = (i + 1);                                                                       //the id of the shape
            GameObject tableShapeGameObject = Instantiate(shapePrefab, Vector3.zero, Quaternion.identity) as GameObject;
            tableShapeGameObject.transform.SetParent(shapesGroup.transform);                    //setting up the shape's parent
            TableShape tableShapeComponent = tableShapeGameObject.GetComponent <TableShape> (); //get TableShape Component
            tableShapeComponent.ID    = ID;                                                     //setting up shape ID
            tableShapeGameObject.name = "Shape-" + ID;                                          //shape name
            tableShapeGameObject.transform.localScale = Vector3.one;
            tableShapeGameObject.GetComponent <RectTransform> ().offsetMax = Vector2.zero;
            tableShapeGameObject.GetComponent <RectTransform> ().offsetMin = Vector2.zero;

            GameObject uiShape = Instantiate(shapesManager.shapes [i].gamePrefab, Vector3.zero, Quaternion.identity) as GameObject;

            uiShape.transform.SetParent(tableShapeGameObject.transform.Find("Content"));

            RectTransform rectTransform = tableShapeGameObject.transform.Find("Content").GetComponent <RectTransform> ();

            uiShape.transform.localScale = new Vector3(ratio * shapeScaleFactor, ratio * shapeScaleFactor);
            uiShape.GetComponent <RectTransform> ().anchoredPosition3D = Vector3.zero;

            List <Shape> shapeComponents = new List <Shape> ();
            if (uiShape.GetComponent <CompoundShape> () != null)
            {
                Shape[] tempS = uiShape.GetComponentsInChildren <Shape> ();
                foreach (Shape s in tempS)
                {
                    shapeComponents.Add(s);
                }
            }
            else
            {
                shapeComponents.Add(uiShape.GetComponent <Shape> ());
            }

            int compoundID;
            for (int s = 0; s < shapeComponents.Count; s++)
            {
                CompoundShape compundShape = shapeComponents [s].transform.parent.GetComponent <CompoundShape> ();
                compoundID = 0;
                if (compundShape != null)
                {
                    compoundID = compundShape.GetShapeIndexByInstanceID(shapeComponents[s].GetInstanceID());
                }

                shapeComponents[s].enabled = false;
                //release unwanted resources
                shapeComponents[s].GetComponent <Animator> ().enabled = false;
                shapeComponents[s].transform.Find("TracingHand").gameObject.SetActive(false);
                shapeComponents[s].transform.Find("Collider").gameObject.SetActive(false);

                Animator[] animators = shapeComponents[s].transform.GetComponentsInChildren <Animator> ();
                foreach (Animator a in animators)
                {
                    a.enabled = false;
                }

                int              from, to;
                string[]         slices;
                List <Transform> paths = CommonUtil.FindChildrenByTag(shapeComponents[s].transform.Find("Paths"), "Path");
                foreach (Transform p in paths)
                {
                    slices = p.name.Split('-');
                    from   = int.Parse(slices [1]);
                    to     = int.Parse(slices [2]);

                    p.Find("Start").gameObject.SetActive(false);
                    Image img = CommonUtil.FindChildByTag(p, "Fill").GetComponent <Image> ();

                    if (PlayerPrefs.HasKey(DataManager.GetPathStrKey(ID, compoundID, from, to, shapesManager)))
                    {
                        List <Transform> numbers = CommonUtil.FindChildrenByTag(p.transform.Find("Numbers"), "Number");
                        foreach (Transform n in numbers)
                        {
                            n.gameObject.SetActive(false);
                        }
                        img.fillAmount = 1;
                        img.color      = DataManager.GetShapePathColor(ID, compoundID, from, to, shapesManager);
                    }
                }
            }
            tableShapeGameObject.GetComponent <Button> ().onClick.AddListener(() => GameObject.FindObjectOfType <UIEvents> ().AlbumShapeEvent(tableShapeGameObject.GetComponent <TableShape> ()));

            SettingUpShape(tableShapeComponent, ID, groupIndex); //setting up the shape contents (stars number ,islocked,...)
            shapes.Add(tableShapeComponent);                     //add table shape component to the list
        }

        collectedStarsText.text = collectedStars + "/" + (3 * shapesManager.shapes.Count);
        if (shapesManager.shapes.Count == 0)
        {
            Debug.Log("There are no Shapes found");
        }
        else
        {
            Debug.Log("New shapes have been created");
        }

        GameObject.Find("Loading").SetActive(false);

        pointersParent.gameObject.SetActive(true);
        groupsParent.gameObject.SetActive(true);

        GameObject.FindObjectOfType <ScrollSlider> ().Init();
    }
Exemple #17
0
        public void SearchGroupsTest()
        {
            FelBookDBEntities DBEntities  = new FelBookDBEntities();
            IWallService      wallService = null;
            GroupService      target      = new GroupService(DBEntities, wallService);

            User user = User.CreateUser(0, "group", "creator", DateTime.Now,
                                        "mail", "groupCreator", "1234");

            DBEntities.UserSet.AddObject(user);

            Group group1 = Group.CreateGroup(0, "foo", "description");

            user.CreatedGroups.Add(group1);
            user.AdminedGroups.Add(group1);
            user.JoinedGroups.Add(group1);
            DBEntities.GroupSet.AddObject(group1);

            Group group2 = Group.CreateGroup(0, "foo2", "description");

            user.CreatedGroups.Add(group2);
            user.AdminedGroups.Add(group2);
            user.JoinedGroups.Add(group2);
            DBEntities.GroupSet.AddObject(group2);

            Group group3 = Group.CreateGroup(0, "moo", "description");

            user.CreatedGroups.Add(group3);
            user.AdminedGroups.Add(group3);
            user.JoinedGroups.Add(group3);
            DBEntities.GroupSet.AddObject(group3);

            DBEntities.SaveChanges();

            List <Group> actual = target.SearchGroups("2").ToList();

            Assert.IsFalse(actual.Contains(group1));
            Assert.IsTrue(actual.Contains(group2));
            Assert.IsFalse(actual.Contains(group3));

            actual = target.SearchGroups("foo").ToList();
            Assert.IsTrue(actual.Contains(group1));
            Assert.IsTrue(actual.Contains(group2));
            Assert.IsFalse(actual.Contains(group3));

            actual = target.SearchGroups("moo").ToList();
            Assert.IsFalse(actual.Contains(group1));
            Assert.IsFalse(actual.Contains(group2));
            Assert.IsTrue(actual.Contains(group3));

            actual = target.SearchGroups("abcdef").ToList();
            Assert.IsFalse(actual.Contains(group1));
            Assert.IsFalse(actual.Contains(group2));
            Assert.IsFalse(actual.Contains(group3));

            actual = target.SearchGroups("oo").ToList();
            Assert.IsTrue(actual.Contains(group1));
            Assert.IsTrue(actual.Contains(group2));
            Assert.IsTrue(actual.Contains(group3));

            DBEntities.GroupSet.DeleteObject(group1);
            DBEntities.GroupSet.DeleteObject(group2);
            DBEntities.GroupSet.DeleteObject(group3);
            DBEntities.UserSet.DeleteObject(user);
            DBEntities.SaveChanges();
        }
Exemple #18
0
        public static void Main(string[] args)
        {
            #if NETCOREAPP3_1
            Console.Write("CoFlows CE - NetCoreApp 3.1... ");
            #endif

            #if NET461
            Console.Write("CoFlows CE - Net Framework 461... ");
            #endif

            Console.Write("Python starting... ");
            PythonEngine.Initialize();

            Code.InitializeCodeTypes(new Type[] {
                typeof(QuantApp.Engine.Workflow),
                typeof(Jint.Native.Array.ArrayConstructor)
            });

            var config_env  = Environment.GetEnvironmentVariable("coflows_config");
            var config_file = Environment.GetEnvironmentVariable("config_file");

            if (string.IsNullOrEmpty(config_file))
            {
                config_file = "coflows_config.json";
            }

            JObject config = string.IsNullOrEmpty(config_env) ? (JObject)JToken.ReadFrom(new JsonTextReader(File.OpenText(@"mnt/" + config_file))) : (JObject)JToken.Parse(config_env);
            workflow_name = config["Workflow"].ToString();
            hostName      = config["Server"]["Host"].ToString();
            var secretKey = config["Server"]["SecretKey"].ToString();

            letsEncryptEmail   = config["Server"]["LetsEncrypt"]["Email"].ToString();
            letsEncryptStaging = config["Server"]["LetsEncrypt"]["Staging"].ToString().ToLower() == "true";

            var sslFlag = hostName.ToLower() != "localhost" && !string.IsNullOrWhiteSpace(letsEncryptEmail);

            useJupyter = config["Jupyter"].ToString().ToLower() == "true";

            // var connectionString = config["Database"].ToString();

            var cloudHost = config["Cloud"]["Host"].ToString();
            var cloudKey  = config["Cloud"]["SecretKey"].ToString();
            var cloudSSL  = config["Cloud"]["SSL"].ToString();

            if (args != null && args.Length > 0 && args[0] == "lab")
            {
                Connection.Client.Init(hostName, sslFlag);

                if (!Connection.Client.Login(secretKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                var pargs = new string[] { "-m", "ipykernel_launcher.py", "-f", args[1] };
                Console.Write("Starting lab... ");

                Python.Runtime.Runtime.Py_Main(pargs.Length, pargs);
                Console.WriteLine("started lab... ");
            }
            //Cloud
            else if (args != null && args.Length > 1 && args[0] == "cloud" && args[1] == "deploy")
            {
                Console.WriteLine("Cloud Host: " + cloudHost);
                Console.WriteLine("Cloud SSL: " + cloudSSL);
                Connection.Client.Init(cloudHost, cloudSSL.ToLower() == "true");

                if (!Connection.Client.Login(cloudKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.Write("Starting cloud deployment... ");

                Code.UpdatePackageFile(workflow_name);
                var t0 = DateTime.Now;
                Console.WriteLine("Started: " + t0);
                var res = Connection.Client.PublishPackage(workflow_name);
                var t1  = DateTime.Now;
                Console.WriteLine("Ended: " + t1 + " taking " + (t1 - t0));
                Console.Write("Result: " + res);
            }
            else if (args != null && args.Length > 1 && args[0] == "cloud" && args[1] == "build")
            {
                Console.WriteLine("Cloud Host: " + cloudHost);
                Console.WriteLine("Cloud SSL: " + cloudSSL);
                Connection.Client.Init(cloudHost, cloudSSL.ToLower() == "true");

                if (!Connection.Client.Login(cloudKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.Write("CoFlows Cloud build... ");

                Code.UpdatePackageFile(workflow_name);
                var t0 = DateTime.Now;
                Console.WriteLine("Started: " + t0);
                var res = Connection.Client.BuildPackage(workflow_name);
                var t1  = DateTime.Now;
                Console.WriteLine("Ended: " + t1 + " taking " + (t1 - t0));
                Console.Write("Result: " + res);
            }
            else if (args != null && args.Length > 2 && args[0] == "cloud" && args[1] == "query")
            {
                Console.WriteLine("Cloud Host: " + cloudHost);
                Console.WriteLine("Cloud SSL: " + cloudSSL);
                Connection.Client.Init(cloudHost, cloudSSL.ToLower() == "true");

                if (!Connection.Client.Login(cloudKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.WriteLine("CoFlows Cloud query... ");

                var queryID    = args[2];
                var funcName   = args.Length > 3 ? args[3] : null;
                var parameters = args.Length > 4 ? args.Skip(4).ToArray() : null;

                var pkg = Code.ProcessPackageFile(workflow_name, true);
                Console.WriteLine("Workflow: " + pkg.Name);

                Console.WriteLine("Query ID: " + queryID);
                Console.WriteLine("Function Name: " + funcName);

                if (parameters != null)
                {
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        Console.WriteLine("Parameter[" + i + "]: " + parameters[i]);
                    }
                }


                var(code_name, code) = pkg.Queries.Where(entry => entry.ID == queryID).Select(entry => (entry.Name as string, entry.Content as string)).FirstOrDefault();

                var t0 = DateTime.Now;
                Console.WriteLine("Started: " + t0);
                var result = Connection.Client.Execute(code, code_name, pkg.ID, queryID, funcName, parameters);
                var t1     = DateTime.Now;
                Console.WriteLine("Ended: " + t1 + " taking " + (t1 - t0));

                Console.WriteLine("Result: ");
                Console.WriteLine(result);
            }
            else if (args != null && args.Length > 1 && args[0] == "cloud" && args[1] == "log")
            {
                Console.WriteLine("Cloud Host: " + cloudHost);
                Console.WriteLine("Cloud SSL: " + cloudSSL);
                Connection.Client.Init(cloudHost, cloudSSL.ToLower() == "true");

                if (!Connection.Client.Login(cloudKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.Write("CoFlows Cloud log... ");

                var res = Connection.Client.RemoteLog(workflow_name);
                Console.WriteLine("Result: ");
                Console.WriteLine(res);
            }
            else if (args != null && args.Length > 1 && args[0] == "cloud" && args[1] == "remove")
            {
                Console.WriteLine("Cloud Host: " + cloudHost);
                Console.WriteLine("Cloud SSL: " + cloudSSL);
                Connection.Client.Init(cloudHost, cloudSSL.ToLower() == "true");

                if (!Connection.Client.Login(cloudKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.Write("CoFlows Cloud log... ");

                var res = Connection.Client.RemoteRemove(workflow_name);
                Console.WriteLine("Result: ");
                Console.WriteLine(res);
            }
            else if (args != null && args.Length > 1 && args[0] == "cloud" && args[1] == "restart")
            {
                Console.WriteLine("Cloud Host: " + cloudHost);
                Console.WriteLine("Cloud SSL: " + cloudSSL);
                Connection.Client.Init(cloudHost, cloudSSL.ToLower() == "true");

                if (!Connection.Client.Login(cloudKey))
                {
                    throw new Exception("CoFlows Not connected!");
                }

                Connection.Client.Connect();
                Console.Write("server connected! ");

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.Write("CoFlows Cloud log... ");

                var res = Connection.Client.RemoteRestart(workflow_name);
                Console.WriteLine("Result: ");
                Console.WriteLine(res);
            }
            else if (args != null && args.Length > 0 && args[0] == "server")
            {
                PythonEngine.BeginAllowThreads();

                // Databases(connectionString);
                var connectionString = config["Database"]["Connection"].ToString();
                var type             = config["Database"]["Type"].ToString();
                if (type.ToLower() == "mssql" || type.ToLower() == "postgres")
                {
                    DatabasesDB(connectionString);
                }
                else
                {
                    DatabasesSqlite(connectionString);
                }

                Console.WriteLine("QuantApp Server " + DateTime.Now);
                Console.WriteLine("DB Connected");

                Console.WriteLine("Local deployment");

                if (string.IsNullOrEmpty(config_env))
                {
                    var pkg = Code.ProcessPackageFile(workflow_name, true);
                    Code.ProcessPackageJSON(pkg);
                    SetDefaultWorkflows(new string[] { pkg.ID }, false, config["Jupter"] != null && config["Jupter"].ToString().ToLower() == "true");
                    Console.WriteLine(pkg.Name + " started");

                    var _g = Group.FindGroup(pkg.ID);
                    if (_g == null)
                    {
                        _g = Group.CreateGroup(pkg.ID, pkg.ID);
                    }

                    foreach (var _p in pkg.Permissions)
                    {
                        string _id    = "QuantAppSecure_" + _p.ID.ToLower().Replace('@', '.').Replace(':', '.');
                        var    _quser = QuantApp.Kernel.User.FindUser(_id);
                        if (_quser != null)
                        {
                            _g.Add(_quser, typeof(QuantApp.Kernel.User), _p.Permission);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Empty server...");
                    var workflow_ids = QuantApp.Kernel.M.Base("--CoFlows--Workflows")[xe => true];
                    foreach (var wsp in workflow_ids)
                    {
                        SetDefaultWorkflows(new string[] { wsp.ToString() }, true, config["Jupter"] != null && config["Jupter"].ToString().ToLower() == "true");
                        Console.WriteLine(wsp + " started");
                    }
                }


                if (!sslFlag)
                {
                    Init(new string[] { "--urls", "http://*:80" }, new Realtime.WebSocketListner(), typeof(Startup <CoFlows.Server.Realtime.RTDSocketMiddleware>));
                }
                else
                {
                    Init(args, new Realtime.WebSocketListner(), typeof(Startup <CoFlows.Server.Realtime.RTDSocketMiddleware>));
                }

                Task.Factory.StartNew(() => {
                    while (true)
                    {
                        // Console.WriteLine(DateTime.Now.ToString());
                        System.Threading.Thread.Sleep(1000);
                    }
                });
                Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
                _closing.WaitOne();
            }
            //Local
            else if (args != null && args.Length > 1 && args[0] == "local" && args[1] == "build")
            {
                PythonEngine.BeginAllowThreads();

                // Databases(connectionString);
                var connectionString = config["Database"]["Connection"].ToString();
                var type             = config["Database"]["Type"].ToString();
                if (type.ToLower() == "mssql" || type.ToLower() == "postgres")
                {
                    DatabasesDB(connectionString);
                }
                else
                {
                    DatabasesSqlite(connectionString);
                }

                Console.WriteLine("DB Connected");

                Console.WriteLine("Local build");

                var pkg = Code.ProcessPackageFile(Code.UpdatePackageFile(workflow_name), true);
                var res = Code.BuildRegisterPackage(pkg);
                if (string.IsNullOrEmpty(res))
                {
                    Console.WriteLine("Success!!!");
                }
                else
                {
                    Console.WriteLine(res);
                }
            }
            else if (args != null && args.Length > 2 && args[0] == "local" && args[1] == "query")
            {
                PythonEngine.BeginAllowThreads();

                // Databases(connectionString);
                var connectionString = config["Database"]["Connection"].ToString();
                var type             = config["Database"]["Type"].ToString();
                if (type.ToLower() == "mssql" || type.ToLower() == "postgres")
                {
                    DatabasesDB(connectionString);
                }
                else
                {
                    DatabasesSqlite(connectionString);
                }

                Console.WriteLine("Local Query " + DateTime.Now);
                Console.WriteLine("DB Connected");

                Console.WriteLine("CoFlows Local query... ");

                var queryID    = args[2];
                var funcName   = args.Length > 3 ? args[3] : null;
                var parameters = args.Length > 4 ? args.Skip(4).ToArray() : null;

                Console.WriteLine("QueryID: " + queryID);
                Console.WriteLine("FuncName: " + funcName);
                Console.WriteLine("Parameters: " + parameters);


                var pkg = Code.ProcessPackageFile(Code.UpdatePackageFile(workflow_name), true);
                Code.ProcessPackageJSON(pkg);

                var _g = Group.FindGroup(pkg.ID);
                if (_g == null)
                {
                    _g = Group.CreateGroup(pkg.ID, pkg.ID);
                }

                foreach (var _p in pkg.Permissions)
                {
                    string _id    = "QuantAppSecure_" + _p.ID.ToLower().Replace('@', '.').Replace(':', '.');
                    var    _quser = QuantApp.Kernel.User.FindUser(_id);
                    if (_quser != null)
                    {
                        _g.Add(_quser, typeof(QuantApp.Kernel.User), _p.Permission);
                    }
                }



                if (parameters != null)
                {
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        Console.WriteLine("Parameter[" + i + "]: " + parameters[i]);
                    }
                }


                var(code_name, code) = pkg.Queries.Where(entry => entry.ID == queryID).Select(entry => (entry.Name as string, entry.Content as string)).FirstOrDefault();
                var t0 = DateTime.Now;
                Console.WriteLine("Started: " + t0);

                // var wb = wb_res.FirstOrDefault() as CodeData;
                var codes = new List <Tuple <string, string> >();
                codes.Add(new Tuple <string, string>(code_name, code));

                var result = QuantApp.Engine.Utils.ExecuteCodeFunction(false, codes, funcName, parameters);
                //var result = Connection.Client.Execute(code, code_name, pkg.ID, queryID, funcName, parameters);
                var t1 = DateTime.Now;
                Console.WriteLine("Ended: " + t1 + " taking " + (t1 - t0));

                Console.WriteLine("Result: ");
                Console.WriteLine(result);
            }
            //Azure Container Instance
            else if (args != null && args.Length > 1 && args[0] == "aci" && args[1] == "deploy")
            {
                PythonEngine.BeginAllowThreads();

                Console.WriteLine();
                Console.WriteLine("Azure Container Instance start...");
                var t0 = DateTime.Now;
                Console.WriteLine("Started: " + t0);


                var pkg = Code.ProcessPackageFile(Code.UpdatePackageFile(workflow_name), true);
                var res = Code.BuildRegisterPackage(pkg);

                if (string.IsNullOrEmpty(res))
                {
                    Console.WriteLine("Build Success!!!");
                }
                else
                {
                    Console.WriteLine(res);
                }

                AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(config["AzureContainerInstance"]["AuthFile"].ToString());

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                string rgName             = pkg.ID.ToLower() + "-rg";
                string aciName            = pkg.Name.ToLower();
                string containerImageName = "coflows/ce";

                Console.WriteLine("Container Name: " + aciName);
                Console.WriteLine("Resource Group Name: " + rgName);

                try
                {
                    Console.WriteLine("Cleaning Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);


                    IResourceGroup resGroup = azure.ResourceGroups.GetByName(rgName);
                    while (resGroup != null)
                    {
                        resGroup = azure.ResourceGroups.GetByName(rgName);

                        Console.Write(".");

                        SdkContext.DelayProvider.Delay(1000);
                    }
                    Console.WriteLine();

                    Console.WriteLine("Cleaned Resource Group: " + rgName);
                }
                catch (Exception e)
                {
                    Console.WriteLine();
                    Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                }

                Region region = Region.Create(config["AzureContainerInstance"]["Region"].ToString());
                Console.WriteLine("Region: " + region);



                if (config["AzureContainerInstance"]["Gpu"] != null && config["AzureContainerInstance"]["Gpu"]["Cores"].ToString() != "" && config["AzureContainerInstance"]["Gpu"]["Cores"].ToString() != "0" && config["AzureContainerInstance"]["Gpu"]["SKU"].ToString() != "")
                {
                    Console.WriteLine("Creating a GPU container...");
                    Task.Run(() =>
                             azure.ContainerGroups.Define(aciName)
                             .WithRegion(region)
                             .WithNewResourceGroup(rgName)
                             .WithLinux()
                             .WithPublicImageRegistryOnly()
                             // .WithNewAzureFileShareVolume(volumeMountName, shareName)
                             .WithoutVolume()
                             .DefineContainerInstance(aciName)
                             .WithImage(containerImageName)
                             .WithExternalTcpPorts(new int[] { 80, 443 })
                             // .WithVolumeMountSetting(volumeMountName, "/aci/logs/")
                             .WithCpuCoreCount(Int32.Parse(config["AzureContainerInstance"]["Cores"].ToString()))
                             .WithMemorySizeInGB(Int32.Parse(config["AzureContainerInstance"]["Mem"].ToString()))
                             .WithGpuResource(
                                 Int32.Parse(config["AzureContainerInstance"]["Gpu"]["Cores"].ToString()),
                                 config["AzureContainerInstance"]["Gpu"]["SKU"].ToString().ToLower() == "k80" ? GpuSku.K80 : config["AzureContainerInstance"]["Gpu"]["SKU"].ToString().ToLower() == "p100" ? GpuSku.P100 : GpuSku.V100
                                 )
                             .WithEnvironmentVariables(new Dictionary <string, string>()
                    {
                        { "coflows_config", File.ReadAllText(@"mnt/" + config_file) },
                    })
                             .WithStartingCommandLine("dotnet", "CoFlows.Server.lnx.dll", "server")
                             .Attach()
                             .WithDnsPrefix(config["AzureContainerInstance"]["Dns"].ToString())
                             .CreateAsync()
                             );
                }
                else
                {
                    Console.WriteLine("Creating a standard container...");
                    Task.Run(() =>
                             azure.ContainerGroups.Define(aciName)
                             .WithRegion(region)
                             .WithNewResourceGroup(rgName)
                             .WithLinux()
                             .WithPublicImageRegistryOnly()
                             // .WithNewAzureFileShareVolume(volumeMountName, shareName)
                             .WithoutVolume()
                             .DefineContainerInstance(aciName)
                             .WithImage(containerImageName)
                             .WithExternalTcpPorts(new int[] { 80, 443 })
                             // .WithExternalTcpPort(sslFlag ? 443 : 80)
                             // .WithVolumeMountSetting(volumeMountName, "/aci/logs/")
                             .WithCpuCoreCount(Int32.Parse(config["AzureContainerInstance"]["Cores"].ToString()))
                             .WithMemorySizeInGB(Int32.Parse(config["AzureContainerInstance"]["Mem"].ToString()))
                             .WithEnvironmentVariables(new Dictionary <string, string>()
                    {
                        { "coflows_config", File.ReadAllText(@"mnt/" + config_file) },
                    })
                             .WithStartingCommandLine("dotnet", "CoFlows.Server.lnx.dll", "server")
                             .Attach()
                             .WithDnsPrefix(config["AzureContainerInstance"]["Dns"].ToString())
                             .CreateAsync()
                             );
                }


                // Poll for the container group
                IContainerGroup containerGroup = null;
                while (containerGroup == null)
                {
                    containerGroup = azure.ContainerGroups.GetByResourceGroup(rgName, aciName);

                    Console.Write(".");

                    SdkContext.DelayProvider.Delay(1000);
                }

                var lastContainerGroupState = containerGroup.Refresh().State;

                Console.WriteLine();
                Console.WriteLine($"Container group state: {containerGroup.Refresh().State}");
                // Poll until the container group is running
                while (containerGroup.State != "Running")
                {
                    var containerGroupState = containerGroup.Refresh().State;
                    if (containerGroupState != lastContainerGroupState)
                    {
                        Console.WriteLine();
                        Console.WriteLine(containerGroupState);
                        lastContainerGroupState = containerGroupState;
                    }
                    Console.Write(".");

                    System.Threading.Thread.Sleep(1000);
                }
                Console.WriteLine();
                Console.WriteLine("Container instance IP address: " + containerGroup.IPAddress);
                Console.WriteLine("Container instance Ports: " + string.Join(",", containerGroup.ExternalTcpPorts));

                string serverUrl = config["AzureContainerInstance"]["Dns"].ToString() + "." + config["AzureContainerInstance"]["Region"].ToString().ToLower() + ".azurecontainer.io";
                Console.WriteLine("Container instance DNS Prefix: " + serverUrl);
                SdkContext.DelayProvider.Delay(10000);

                Connection.Client.Init(serverUrl, sslFlag);

                for (int i = 0; i < 50; i++)
                {
                    try
                    {
                        SdkContext.DelayProvider.Delay(10000);
                        // Console.WriteLine("Connecting to Cluster(" + i + "): " + CoFlows.Server.Program.hostName + " with SSL " + sslFlag + " " + config["Server"]["SecretKey"].ToString());
                        if (!Connection.Client.Login(config["Server"]["SecretKey"].ToString()))
                        {
                            throw new Exception("CoFlows Not connected!");
                        }

                        Connection.Client.Connect();
                        Console.WriteLine("Container connected! " + i);
                        break;
                    }
                    catch {}
                }

                QuantApp.Kernel.M.Factory = new MFactory();

                Console.Write("Starting azure deployment... ");

                Code.UpdatePackageFile(workflow_name);
                var resDeploy = Connection.Client.PublishPackage(workflow_name);
                var t1        = DateTime.Now;
                Console.WriteLine("Ended: " + t1 + " taking " + (t1 - t0));
                Console.Write("Result: " + resDeploy);
            }
            else if (args != null && args.Length > 1 && args[0] == "aci" && args[1] == "remove")
            {
                PythonEngine.BeginAllowThreads();

                Console.WriteLine("Azure Container Instance remove start");

                var pkg = Code.ProcessPackageFile(Code.UpdatePackageFile(workflow_name), true);
                var res = Code.BuildRegisterPackage(pkg);

                if (!string.IsNullOrEmpty(res))
                {
                    Console.WriteLine(res);
                }

                AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(config["AzureContainerInstance"]["AuthFile"].ToString());

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                string rgName = pkg.ID.ToLower() + "-rg";

                try
                {
                    Console.WriteLine("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);


                    IResourceGroup resGroup = azure.ResourceGroups.GetByName(rgName);
                    while (resGroup != null)
                    {
                        resGroup = azure.ResourceGroups.GetByName(rgName);

                        Console.Write(".");

                        SdkContext.DelayProvider.Delay(1000);
                    }
                    Console.WriteLine();

                    Console.WriteLine("Deleted Resource Group: " + rgName);
                }
                catch (Exception)
                {
                    Console.WriteLine("Did not create any resources in Azure. No clean up is necessary");
                }
            }
            else
            {
                Console.WriteLine("Wrong argument");
            }
        }
Exemple #19
0
    private void CreateShapes()
    {
        if (ShapesManager.instance == null)
        {
            return;
        }
        //Clear current shapes list
        shapes.Clear();

        //The ID of the shape
        int ID = 0;

        GameObject shapesGroup = null;

        float contentScale = (Screen.width * 1.0f / Screen.height) * contentScaleRatio;//content scale

        //Create Shapes inside groups
        for (int i = 0; i < ShapesManager.instance.shapes.Count; i++)
        {
            if (i % shapesPerGroup == 0)
            {
                int groupIndex = (i / shapesPerGroup);
                shapesGroup = Group.CreateGroup(shapesGroupPrefab, groupsParent, groupIndex, columnsPerGroup);
            }

            ID = (i + 1);                                                                      //the ID of the shape
                                                                                               //Create a Shape
            GameObject tableShapeGameObject = Instantiate(shapePrefab, Vector3.zero, Quaternion.identity) as GameObject;
            tableShapeGameObject.transform.SetParent(shapesGroup.transform);                   //setting up the shape's parent
            TableShape tableShapeComponent = tableShapeGameObject.GetComponent <TableShape>(); //get TableShape Component
            tableShapeComponent.ID    = ID;                                                    //setting up shape ID
            tableShapeGameObject.name = "Shape-" + ID;                                         //shape name
            tableShapeGameObject.transform.localScale = Vector3.one;
            tableShapeGameObject.GetComponent <RectTransform>().offsetMax = Vector2.zero;
            tableShapeGameObject.GetComponent <RectTransform>().offsetMin = Vector2.zero;

            GameObject content = Instantiate(ShapesManager.instance.shapes[i].gamePrefab, Vector3.zero, Quaternion.identity) as GameObject;

            //release unwanted resources
            Destroy(content.GetComponent <EventTrigger>());
            Destroy(content.GetComponent <UIEvents>());
            if (content.transform.Find("Parts") != null)
            {
                Destroy(content.transform.Find("Parts").gameObject);
            }

            content.transform.SetParent(tableShapeGameObject.transform.Find("Content"));

            RectTransform rectTransform = tableShapeGameObject.transform.Find("Content").GetComponent <RectTransform>();

            //set up the scale
            content.transform.localScale = new Vector3(contentScale, contentScale);
            //set up the anchor
            content.GetComponent <RectTransform>().anchorMin = Vector2.zero;
            content.GetComponent <RectTransform>().anchorMax = Vector2.one;
            //set up the offset
            content.GetComponent <RectTransform>().offsetMax = Vector2.zero;
            content.GetComponent <RectTransform>().offsetMin = Vector2.zero;
            //enable image component
            content.GetComponent <Image>().enabled = true;
            //add click listener
            tableShapeGameObject.GetComponent <Button>().onClick.AddListener(() => GameObject.FindObjectOfType <UIEvents>().AlbumShapeEvent(tableShapeGameObject.GetComponent <TableShape>()));
            content.gameObject.SetActive(true);
            shapes.Add(tableShapeComponent);//add table shape component to the list
        }

        if (ShapesManager.instance.shapes.Count == 0)
        {
            Debug.Log("There are no Shapes found");
        }
        else
        {
            Debug.Log("New shapes have been created");
        }
    }
    /// <summary>
    /// Creates the shapes in Groups.
    /// </summary>
    private void CreateShapes()
    {
        //Clear current shapes list
        shapes.Clear();

        //The ID of the shape
        int ID = 0;

        GameObject shapesGroup = null;

        //Create Shapes inside groups
        for (int i = 0; i < ShapesManager.instance.shapes.Count; i++)
        {
            if (i % shapesPerGroup == 0)
            {
                int groupIndex = (i / shapesPerGroup);
                shapesGroup = Group.CreateGroup(shapesGroupPrefab, groupsParent, groupIndex, columnsPerGroup);
                if (!EnableGroupGridLayout)
                {
                    shapesGroup.GetComponent <GridLayoutGroup>().enabled = false;
                }
                if (createGroupsPointers)
                {
                    Pointer.CreatePointer(groupIndex, shapesGroup, pointerPrefab, pointersParent);
                }
            }

            //Create Shape
            ID = (i + 1);                                                                       //the id of the shape
            GameObject tableShapeGameObject = Instantiate(shapePrefab, Vector3.zero, Quaternion.identity) as GameObject;
            tableShapeGameObject.transform.SetParent(shapesGroup.transform);                    //setting up the shape's parent
            TableShape tableShapeComponent = tableShapeGameObject.GetComponent <TableShape> (); //get TableShape Component
            tableShapeComponent.ID    = ID;                                                     //setting up shape ID
            tableShapeGameObject.name = "Shape-" + ID;                                          //shape name
            tableShapeGameObject.transform.localScale = Vector3.one;
            tableShapeGameObject.GetComponent <RectTransform> ().offsetMax = Vector2.zero;
            tableShapeGameObject.GetComponent <RectTransform> ().offsetMin = Vector2.zero;

            GameObject content = Instantiate(ShapesManager.instance.shapes[i].gamePrefab, Vector3.zero, Quaternion.identity) as GameObject;

            content.transform.SetParent(tableShapeGameObject.transform.Find("Content"));

            RectTransform rectTransform = tableShapeGameObject.transform.Find("Content").GetComponent <RectTransform>();

            float ratio = Mathf.Max(Screen.width, Screen.height) / 1000.0f;

            //set up the scale
            content.transform.localScale = new Vector3(ratio * 0.7f, ratio * 0.7f);

            //release unwanted resources
            content.GetComponent <Shape>().enabled    = false;
            content.GetComponent <Animator>().enabled = false;
            content.transform.Find("TracingHand").gameObject.SetActive(false);
            content.transform.Find("Collider").gameObject.SetActive(false);

            Animator [] animators = content.transform.GetComponentsInChildren <Animator>();
            foreach (Animator a in animators)
            {
                a.enabled = false;
            }

            int              from, to;
            string []        slices;
            List <Transform> paths = CommonUtil.FindChildrenByTag(content.transform.Find("Paths"), "Path");
            foreach (Transform p in paths)
            {
                slices = p.name.Split('-');
                from   = int.Parse(slices [1]);
                to     = int.Parse(slices [2]);

                p.Find("Start").gameObject.SetActive(false);
                Image img = CommonUtil.FindChildByTag(p, "Fill").GetComponent <Image>();
                if (PlayerPrefs.HasKey("Shape-" + ID + "-Path-" + from + "-" + to))
                {
                    List <Transform> numbers = CommonUtil.FindChildrenByTag(p.transform.Find("Numbers"), "Number");
                    foreach (Transform n in numbers)
                    {
                        n.gameObject.SetActive(false);
                    }
                    img.fillAmount = 1;
                    img.color      = DataManager.GetShapePathColor(ID, from, to);
                }
            }
            tableShapeGameObject.GetComponent <Button> ().onClick.AddListener(() => GameObject.FindObjectOfType <UIEvents> ().AlbumShapeEvent(tableShapeGameObject.GetComponent <TableShape> ()));

            SettingUpShape(tableShapeComponent, ID);                             //setting up the shape contents (stars number ,islocked,...)
            shapes.Add(tableShapeComponent);                                     //add table shape component to the list
        }


        collectedStarsText.text = collectedStars + "/" + (3 * ShapesManager.instance.shapes.Count);
        if (ShapesManager.instance.shapes.Count == 0)
        {
            Debug.Log("There are no Shapes found");
        }
        else
        {
            Debug.Log("New shapes have been created");
        }
    }
        public void VerifyThatOblectIsNullWhenPropertyIsNull(string value, string value2)
        {
            Group createdGroup = Group.CreateGroup(value, value2, out string error);

            Assert.IsNull(createdGroup);
        }