Example #1
0
        /// <summary>
        /// Request a set of classes be published in bulk.
        /// </summary>
        /// <param name="user">requesting user</param>
        /// <param name="SectionIds">List of Section.id's</param>
        /// <param name="filename">file name given by the Server.MapPath() method.</param>
        /// <param name="TermId">default to the current term</param>
        public static void RequestByClass(ADUser user, List <int> SectionIds, String filename, int TermId = -1)
        {
            WebhostEventLog.Syslog.LogInformation("{0} has requested Comment Letters for {1} sections", user.Name, SectionIds.Count);
            if (TermId == -1)
            {
                TermId = DateRange.GetCurrentOrLastTerm();
            }

            LogEntry log = new LogEntry();

            XMLTree xml = new XMLTree()
            {
                TagName    = "publishrequest",
                Attributes = new Dictionary <string, string>()
                {
                    { "username", user.UserName },
                    { "name", XMLTree.MakeXMLAttributeValueSafe(user.Name) },
                    { "id", user.ID.ToString() },
                    { "type", "class" },
                    { "termid", TermId.ToString() },
                    { "timestamp", DateTime.Now.Ticks.ToString() }
                }
            };

            using (WebhostEntities db = new WebhostEntities())
            {
                foreach (int sectionId in SectionIds)
                {
                    Section section = db.Sections.Where(sec => sec.id == sectionId).Single();
                    if (section.CommentHeaders.Where(c => c.TermIndex == TermId).Count() != 1)
                    {
                        throw new WebhostException(String.Format("No comment header for Term id={0} of {1} ({2})", TermId, section.Course.Name, sectionId));
                    }

                    CommentHeader header = section.CommentHeaders.Where(c => c.TermIndex == TermId).Single();

                    XMLTree sectionTree = new XMLTree()
                    {
                        TagName    = "section",
                        Attributes = new Dictionary <string, string>()
                        {
                            { "headerid", header.id.ToString() }
                        }
                    };

                    foreach (int comid in header.StudentComments.Select(c => c.id).ToList())
                    {
                        sectionTree.ChildNodes.Add(new SimpleXMLTag()
                        {
                            TagName = "comment",
                            Value   = comid.ToString()
                        });
                    }

                    xml.ChildTrees.Add(sectionTree);
                }
            }

            xml.Save(filename + ".pubreq");
        }
Example #2
0
        protected XMLTree GET(String resource)
        {
            string  xml  = GETxml(resource);
            XMLTree tree = new XMLTree(xml);
            String  next = "";

            do
            {
                try
                {
                    next = tree.ChildTrees.Where(t => t.TagName.Equals("links")).Single().ChildNodes.Where(n => n.TagName.Equals("next")).Single().Value;
                    next = next.Replace("amp%3Blimit=20&amp;", "");
                    tree.ChildTrees.Remove(tree.ChildTrees.Where(t => t.TagName.Equals("links")).Single());
                    string nxml = "";
                    using (SchoologyAPICall newCall = new SchoologyAPICall())
                    {
                        string rscr = next.Substring(next.IndexOf("v1"));
                        nxml = newCall.GETxml(rscr);
                    }
                    tree = tree.MergeWith(new XMLTree(nxml));
                }
                catch
                {
                    next = "";
                }
            } while (!next.Equals(""));

            return(tree);
        }
Example #3
0
 public SchoologySectionResponse(XMLTree tree)
 {
     if (!tree.TagName.Equals("section"))
     {
         throw new XMLException("XMLTree is not a <section> tag.");
     }
     xml = tree;
 }
Example #4
0
 public SchoologyCourseResponse(XMLTree tree)
 {
     if (!tree.TagName.Equals("course"))
     {
         throw new FormatException("Xml is not a <course> tag.");
     }
     xml = tree;
 }
Example #5
0
        /// <summary>
        /// Request a batch of Student's comments.
        /// </summary>
        /// <param name="user"></param>
        /// <param name="StudentIds"></param>
        /// <param name="filename">file name given by the Server.MapPath() method.</param>
        /// <param name="TermId">default to the current term</param>
        public static void RequestByStudent(ADUser user, List <int> StudentIds, String filename, int TermId = -1)
        {
            if (TermId == -1)
            {
                TermId = DateRange.GetCurrentOrLastTerm();
            }
            XMLTree xml = new XMLTree()
            {
                TagName    = "publishrequest",
                Attributes = new Dictionary <string, string>()
                {
                    { "username", user.UserName },
                    { "name", XMLTree.MakeXMLAttributeValueSafe(user.Name) },
                    { "id", user.ID.ToString() },
                    { "type", "student" },
                    { "termid", TermId.ToString() },
                    { "timestamp", DateTime.Now.Ticks.ToString() }
                }
            };

            using (WebhostEntities db = new WebhostEntities())
            {
                foreach (int sid in StudentIds)
                {
                    Student student = db.Students.Where(s => s.ID == sid).Single();
                    if (student.StudentComments.Where(com => com.CommentHeader.TermIndex == TermId).Count() <= 0)
                    {
                        throw new WebhostException(String.Format("No Comments for {0} {1} in term id={2}", student.FirstName, student.LastName, TermId));
                    }

                    XMLTree studentTree = new XMLTree()
                    {
                        TagName    = "student",
                        Attributes = new Dictionary <string, string>()
                        {
                            { "studentid", sid.ToString() }
                        }
                    };

                    foreach (int comid in student.StudentComments.Select(c => c.id).ToList())
                    {
                        studentTree.ChildNodes.Add(new SimpleXMLTag()
                        {
                            TagName = "comment",
                            Value   = comid.ToString()
                        });
                    }

                    xml.ChildTrees.Add(studentTree);
                }
            }
            xml.Save(filename + ".pubreq");
        }
        public void BuildLesson()
        {
            XMLTree lroot = HUB.root.children.ElementAt(0);

            GridCanvas.Children.Clear();
            GridCanvas.RowDefinitions.Clear();
            rowNum = 0;

            if (lroot.children.Count >= HUB.config)   // make sure that if there isn't a lesson for this tab then don't print anything and crash

            {
                lroot = lroot.children.ElementAt(HUB.config - 1);
                BuildFromTree(lroot);
            }
        }
        private void BuildFromTree(XMLTree node)
        {
            if (node.tagName.Equals("Title"))
            {
                BuildTextBox(true, node.content, 0);
                return;
            }

            else if (node.tagName.Equals("Content"))
            {
                int i = 1;
                foreach (XMLTree n in node.children)
                {
                    BuildTextBox(false, n.content, i);
                }
                return;
            }

            else if (node.tagName.Equals("SimulationData"))
            {
                foreach (XMLTree n in node.children)
                {
                    HUB.simRoot = n.Duplicate(); // give duplicate to make sure that there isn't funny business where I edit node in another class but use it again here assuming it wasn't changed elsewhere

                    Frame sim = new Frame();
                    sim.Navigate(typeof(SimulationPage));

                    GridCanvas.RowDefinitions.Add(new RowDefinition());
                    GridCanvas.RowDefinitions.ElementAt(rowNum).Height = new GridLength(350);


                    GridCanvas.Children.Add(sim);
                    sim.SetValue(Grid.RowProperty, rowNum);
                    sim.SetValue(Grid.ColumnProperty, 0);

                    rowNum++;
                }
            }

            else
            {
                foreach (XMLTree n in node.children)
                {
                    BuildFromTree(n);
                }
            }
        }
        /// <summary>
        /// Parse Data from the <attendance>...</attendance> tag of Attendance Data.
        /// </summary>
        public SchoologyAttendance(int section_id, XMLTree tree)
        {
            XMLTree AttendanceTree = tree;

            schoology_section_id = section_id;
            AttendanceXMLData rawData = new AttendanceXMLData()
            {
                enrollment_id = AttendanceTree.ChildNodes.Where(node => node.TagName.Equals("enrollment_id")).Single().Value,
                date          = AttendanceTree.ChildNodes.Where(node => node.TagName.Equals("date")).Single().Value,
                status        = AttendanceTree.ChildNodes.Where(node => node.TagName.Equals("status")).Single().Value,
                comment       = AttendanceTree.ChildNodes.Where(node => node.TagName.Equals("comment")).Single().Value
            };

            enrollment = new SchoologyEnrollment(section_id, Convert.ToInt32(rawData.enrollment_id));
            String[] date_parts = rawData.date.Split('-');
            date = new DateTime(Convert.ToInt32(date_parts[0]), Convert.ToInt32(date_parts[1]), Convert.ToInt32(date_parts[2]));
            AttendanceMarking = StatusCodes[rawData.status];
            Notes             = rawData.comment;
        }
Example #9
0
        protected static void ExecuteStudentRequest(XMLTree xml, String saveDir)
        {
            int termId = Convert.ToInt32(xml.Attributes["termid"]);

            List <int> studentIds = new List <int>();

            foreach (XMLTree studentTree in xml.ChildTrees.Where(tree => tree.TagName.Equals("student")).ToList())
            {
                int studentId = Convert.ToInt32(studentTree.Attributes["studentid"]);
                studentIds.Add(studentId);
            }

            String fileName = CommentLetter.PublishTermByStudent(termId, studentIds, saveDir);

            MailControler.MailToUser("Comments Published Successfully",
                                     String.Format("Click the Link to download the comments you requested:{0}{1}",
                                                   Environment.NewLine,
                                                   fileName.Replace("W:", "https://webhost.dublinschool.org").Replace("\\", "/")),
                                     String.Format("{0}@dublinschool.org", xml.Attributes["username"]),
                                     xml.Attributes["name"],
                                     "*****@*****.**", "Comment Bot");
        }
Example #10
0
        protected static void ExecuteClassRequest(XMLTree xml, String saveDir)
        {
            int termId = Convert.ToInt32(xml.Attributes["termid"]);

            List <int>    studentIds = new List <int>();
            List <String> filenames  = new List <string>();

            foreach (XMLTree studentTree in xml.ChildTrees.Where(tree => tree.TagName.Equals("section")).ToList())
            {
                int headerId = Convert.ToInt32(studentTree.Attributes["headerid"]);
                filenames.Add(CommentLetter.PublishClass(headerId, saveDir));
            }

            String zipFile = MailControler.PackForDownloading(filenames, String.Format("{0}\\classes_{1}.zip", saveDir, DateTime.Now.Ticks));

            MailControler.MailToUser("Comments Published Successfully",
                                     String.Format("Click the Link to download the comments you requested:{0}{1}",
                                                   Environment.NewLine,
                                                   zipFile.Replace("W:", "https://webhost.dublinschool.org").Replace("\\", "/")),
                                     String.Format("{0}@dublinschool.org", xml.Attributes["username"]),
                                     xml.Attributes["name"].Replace('_', ' '),
                                     "*****@*****.**", "Comment Bot");
        }
Example #11
0
        public static void ExecuteRequest(String fileName)
        {
            StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open));
            String       xmlstr = reader.ReadToEnd();

            reader.Close();
            XMLTree xml = new XMLTree(xmlstr);

            String dir = Directory.GetParent(fileName).FullName;

            dir += String.Format("\\{0}", xml.Attributes["username"]);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (!xml.Attributes.ContainsKey("type"))
            {
                throw new XMLException("File root tag does not contain a type attribute.");
            }

            if (xml.Attributes["type"].Equals("class"))
            {
                ExecuteClassRequest(xml, dir);
            }
            else if (xml.Attributes["type"].Equals("student"))
            {
                ExecuteStudentRequest(xml, dir);
            }
            else
            {
                throw new XMLException("File has an invalid type attribute.");
            }

            File.Delete(fileName);
        }
Example #12
0
        private void SaveProject(string path)
        {
            XMLTree tree   = new XMLTree("1.0", System.Text.Encoding.UTF8);
            XMLTag  tgProj = tree.MainTag.AddChild("Project");

            tgProj.AddChild("namespace").Body = GlobalData.GlobalProject.ProjectName;
            XMLTag tgClasses = tgProj.AddChild("Classes");

            foreach (SmartB1tCSClass cs in GlobalData.GlobalProject.Classes)
            {
                XMLTag tgCS = tgClasses.AddChild("Class");
                tgCS.AddChild("name").Body = cs.ClassName;
                XMLTag tgVars = tgCS.AddChild("Vars");
                foreach (SmartB1tCSVar csv in cs.Fields)
                {
                    XMLTag tgVarData = tgVars.AddChild("Var");
                    tgVarData.AddChild("name").Body        = csv.VarName;
                    tgVarData.AddChild("custom_type").Body = csv.IsCustomType.ToString();
                    tgVarData.AddChild("data_type").Body   = csv.DataType;
                }
            }
            tree.SaveTo(path);
            MessageBox.Show("Project saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Example #13
0
        private void ParseNodeSecondPass(XmlTextReader reader, XMLTree parentNode, String curTypeName)
        {
            if (curTypeName != "xmi:XMI") // happens on/if first node is xmi:XMI
            {
                HandleAttributes(reader, curTypeName, parentNode.elementNode);
            }

            int index = 0;

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    break;
                }
                if (reader.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                bool   emptyElem = reader.IsEmptyElement; // retard API designer
                String tagName   = reader.Name;

                XMLTree child = null;
                if (parentNode != null)
                {
                    if (parentNode.children == null)
                    {
                        ++index;
                        continue;
                    }
                    child = parentNode.children[index];
                }

                String typeName;
                if (curTypeName == "xmi:XMI")
                {
                    typeName = tagName;
                }
                else if (reader.MoveToAttribute("xsi:type"))
                {
                    typeName = reader.Value;
                }
                else if (reader.MoveToAttribute("xmi:type"))
                {
                    typeName = reader.Value;
                }
                else
                {
                    typeName = FindRefTypeName(curTypeName, tagName);
                }

                if (!emptyElem)
                {
                    ParseNodeSecondPass(reader, child, typeName);
                }
                else
                {
                    HandleAttributes(reader, typeName, child.elementNode);
                }
                ++index;
            }
        }
Example #14
0
        private void ParseNodeFirstPass(XmlTextReader reader, XMLTree parentNode, String parentTypeName)
        {
            INodeModel nodeModel = graph.Model.NodeModel;
            IEdgeModel edgeModel = graph.Model.EdgeModel;

            Dictionary <String, int> tagNameToNextIndex = new Dictionary <String, int>();

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    break; // reached end of current nesting level
                }
                if (reader.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                bool   emptyElem = reader.IsEmptyElement; // retard API designer
                String tagName   = reader.Name;
                String id        = null;
                if (reader.MoveToAttribute("xmi:id"))
                {
                    id = reader.Value;
                }
                String elementName = null;
                if (reader.MoveToAttribute("name"))
                {
                    elementName = reader.Value;
                }
                String typeName = null;
                if (reader.MoveToAttribute("xsi:type"))
                {
                    typeName = reader.Value;
                }
                else if (reader.MoveToAttribute("xmi:type"))
                {
                    typeName = reader.Value;
                }
                else
                {
                    typeName = FindRefTypeName(parentTypeName, tagName);

                    if (typeName == null)
                    {
                        // Treat it as an attribute
                        AssignAttribute(parentNode.elementNode, tagName, reader.ReadInnerXml());

                        XMLTree attributeChild = new XMLTree();
                        attributeChild.elementNode = null;
                        attributeChild.elementName = elementName;
                        attributeChild.element     = tagName;
                        attributeChild.children    = null;
                        parentNode.children.Add(attributeChild);
                        continue;
                    }
                }

                INode   gnode = graph.AddNode(nodeModel.GetType(GrGenTypeNameFromXmi(typeName)));
                XMLTree child = new XMLTree();
                child.elementNode = gnode;
                child.elementName = elementName;
                child.element     = tagName;
                child.children    = new List <XMLTree>();
                parentNode.children.Add(child);
                if (id != null)
                {
                    nodeMap[id] = gnode;
                }

                String edgeTypeName      = FindContainingTypeName(parentTypeName, tagName);
                String grgenEdgeTypeName = GrGenTypeNameFromXmi(edgeTypeName) + "_" + tagName;
                IEdge  parentEdge        = graph.AddEdge(edgeModel.GetType(grgenEdgeTypeName), parentNode.elementNode, gnode);
                if (IsRefOrdered(parentTypeName, tagName))
                {
                    int nextIndex = 0;
                    tagNameToNextIndex.TryGetValue(tagName, out nextIndex);
                    parentEdge.SetAttribute("ordering", nextIndex);
                    tagNameToNextIndex[tagName] = nextIndex + 1;
                }

                if (!emptyElem)
                {
                    ParseNodeFirstPass(reader, child, typeName);
                }
            }
        }
Example #15
0
        INode GetNode(String name)
        {
            if (nodeMap.ContainsKey(name))
            {
                return(nodeMap[name]);
            }

            XMLTree curPos = root;

            String[] addressParts = name.Split('/');
            for (int i = 1; i < addressParts.Length; ++i) // first is ignored
            {
                XMLTree oldCurPos = curPos;
                String  part      = addressParts[i];
                int     index;
                if (part.Length == 0)
                {
                    continue;
                }
                else if (part.StartsWith("@"))
                {
                    String element = part.Substring(1);
                    index = 0;

                    if (part.LastIndexOf('.') != -1)
                    {
                        element = part.Substring(1, part.LastIndexOf('.') - 1);
                        index   = int.Parse(part.Substring(part.LastIndexOf('.') + 1));
                    }

                    int counter = -1;
                    foreach (XMLTree child in curPos.children)
                    {
                        if (child.element == element)
                        {
                            ++counter;
                            if (counter == index)
                            {
                                curPos = child;
                                break;
                            }
                        }
                    }
                }
                else if (int.TryParse(part, out index))
                {
                    curPos = curPos.children[index];
                }
                else
                {
                    foreach (XMLTree child in curPos.children)
                    {
                        if (child.elementName == part)
                        {
                            curPos = child;
                            break;
                        }
                    }
                }
                if (oldCurPos == curPos)
                {
                    throw new Exception("Can't find address " + name + ", stop at part " + part);
                }
            }

            return(curPos.elementNode);
        }
Example #16
0
        private void ImportGraph(String importFilename)
        {
            // First pass: build the nodes and the parent edges given by nesting
            using (XmlTextReader reader = new XmlTextReader(importFilename))
            {
                while (reader.Read()) // handle root node
                {
                    if (reader.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    root = new XMLTree();
                    if (reader.Name == "xmi:XMI") // if root node is the xmi node we've to read the first level of nodes so we got real graph nodes we can hand down
                    {
                        // relevant for hierarchy but not a real graph node to be created from it
                        root.element     = reader.Name;
                        root.elementName = null;
                        root.elementNode = null;
                        root.children    = new List <XMLTree>();

                        while (reader.Read())
                        {
                            if (reader.NodeType != XmlNodeType.Element)
                            {
                                continue;
                            }

                            // create real graph node from it
                            bool    emptyElem = reader.IsEmptyElement; // retard API designer
                            XMLTree rootChild = new XMLTree();
                            String  tagName   = reader.Name;
                            rootChild.element = tagName;
                            if (reader.MoveToAttribute("name"))
                            {
                                rootChild.elementName = reader.Value;
                            }
                            INode gnode = graph.AddNode(graph.Model.NodeModel.GetType(GrGenTypeNameFromXmi(tagName)));
                            rootChild.elementNode = gnode;
                            rootChild.children    = new List <XMLTree>();
                            root.children.Add(rootChild);

                            if (reader.MoveToAttribute("xmi:id"))
                            {
                                nodeMap[reader.Value] = gnode;
                            }

                            if (!emptyElem)
                            {
                                ParseNodeFirstPass(reader, rootChild, tagName); // descend and munch subtree
                            }
                        }
                    }
                    else
                    {
                        // create real graph node from it
                        String tagName = reader.Name;
                        root.element = tagName;
                        if (reader.MoveToAttribute("name"))
                        {
                            root.elementName = reader.Value;
                        }
                        INode gnode = graph.AddNode(graph.Model.NodeModel.GetType(GrGenTypeNameFromXmi(tagName)));
                        root.elementNode = gnode;
                        root.children    = new List <XMLTree>();

                        if (reader.MoveToAttribute("xmi:id"))
                        {
                            nodeMap[reader.Value] = gnode;
                        }

                        ParseNodeFirstPass(reader, root, tagName); // descend and munch subtree
                    }
                }
            }

            // Second pass: assign the attributes and edges given by reference attributes
            using (XmlTextReader reader = new XmlTextReader(importFilename))
            {
                while (reader.Read())
                {
                    if (reader.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    ParseNodeSecondPass(reader, root, reader.Name);
                }
            }
        }
Example #17
0
 public SchoologySectionResponse(String xmlstr)
 {
     xml = new XMLTree(xmlstr);
 }
Example #18
0
        private void ParseNodeFirstPass(XmlTextReader reader, XMLTree parentNode, String parentTypeName)
        {
            INodeModel nodeModel = graph.Model.NodeModel;
            IEdgeModel edgeModel = graph.Model.EdgeModel;

            Dictionary<String, int> tagNameToNextIndex = new Dictionary<String, int>();

            while(reader.Read())
            {
                if(reader.NodeType == XmlNodeType.EndElement) break; // reached end of current nesting level
                if(reader.NodeType != XmlNodeType.Element) continue;

                bool emptyElem = reader.IsEmptyElement; // retard API designer
                String tagName = reader.Name;
                String id = null;
                if(reader.MoveToAttribute("xmi:id"))
                    id = reader.Value;
                String elementName = null;
                if(reader.MoveToAttribute("name"))
                    elementName = reader.Value;
                String typeName = null;
                if(reader.MoveToAttribute("xsi:type"))
                    typeName = reader.Value;
                else if(reader.MoveToAttribute("xmi:type"))
                    typeName = reader.Value;
                else
                {
                    typeName = FindRefTypeName(parentTypeName, tagName);

                    if(typeName == null)
                    {
                        // Treat it as an attribute
                        AssignAttribute(parentNode.elementNode, tagName, reader.ReadInnerXml());

                        XMLTree attributeChild = new XMLTree();
                        attributeChild.elementNode = null;
                        attributeChild.elementName = elementName;
                        attributeChild.element = tagName;
                        attributeChild.children = null;
                        parentNode.children.Add(attributeChild);
                        continue;
                    }
                }

                INode gnode = graph.AddNode(nodeModel.GetType(GrGenTypeNameFromXmi(typeName)));
                XMLTree child = new XMLTree();
                child.elementNode = gnode;
                child.elementName = elementName;
                child.element = tagName;
                child.children = new List<XMLTree>();
                parentNode.children.Add(child);
                if(id != null)
                    nodeMap[id] = gnode;

                String edgeTypeName = FindContainingTypeName(parentTypeName, tagName);
                String grgenEdgeTypeName = GrGenTypeNameFromXmi(edgeTypeName) + "_" + tagName;
                IEdge parentEdge = graph.AddEdge(edgeModel.GetType(grgenEdgeTypeName), parentNode.elementNode, gnode);
                if(IsRefOrdered(parentTypeName, tagName))
                {
                    int nextIndex = 0;
                    tagNameToNextIndex.TryGetValue(tagName, out nextIndex);
                    parentEdge.SetAttribute("ordering", nextIndex);
                    tagNameToNextIndex[tagName] = nextIndex + 1;
                }

                if(!emptyElem)
                    ParseNodeFirstPass(reader, child, typeName);
            }
        }
Example #19
0
        static void PullSchoologyUserIds()
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                using (SchoologyAPICall call = new SchoologyAPICall())
                {
                    XMLTree userList = call.ListUsers();

                    foreach (XMLTree userTree in userList.ChildTrees.Where(u => u.TagName.Equals("user")).ToList())
                    {
                        int webhost_id;
                        try
                        {
                            webhost_id = Convert.ToInt32(userTree.ChildNodes.Where(t => t.TagName.Equals("school_uid")).Single().Value);
                        }
                        catch
                        {
                            WebhostEventLog.SchoologyLog.LogWarning("Skipping user with no school_uid. schoology id = {0}", userTree.ChildNodes.Where(t => t.TagName.Equals("id")).Single().Value);
                            Console.WriteLine("Skipping user with no school_uid. email: {0}", userTree.ChildNodes.Where(t => t.TagName.Equals("primary_email")).Single().Value);
                            continue;
                        }

                        int     schoology_id = Convert.ToInt32(userTree.ChildNodes.Where(t => t.TagName.Equals("id")).Single().Value);
                        Faculty faculty      = db.Faculties.Find(webhost_id);
                        if (faculty != null)
                        {
                            if (faculty.SchoologyId != schoology_id)
                            {
                                WebhostEventLog.SchoologyLog.LogInformation("Updating Schoology User Id for {0} {1} [{2}, {3}]", faculty.FirstName, faculty.LastName, faculty.ID, schoology_id);
                                Console.WriteLine("Updating Schoology User Id for {0} {1} [{2}, {3}]", faculty.FirstName, faculty.LastName, faculty.ID, schoology_id);
                                faculty.SchoologyId = schoology_id;
                            }
                            else
                            {
                                Console.WriteLine("{0} {1} has their correct Schoology Id already.  schoology id:  {2}", faculty.FirstName, faculty.LastName, schoology_id);
                            }
                        }
                        else
                        {
                            Student student = db.Students.Find(webhost_id);
                            if (student == null) // unknown webhost_id?
                            {
                                WebhostEventLog.SchoologyLog.LogWarning("No Webhost user corresponds to email: {0}", userTree.ChildNodes.Where(t => t.TagName.Equals("primary_email")).Single().Value);
                                Console.WriteLine("No Webhost user corresponds to email: {0}", userTree.ChildNodes.Where(t => t.TagName.Equals("primary_email")).Single().Value);
                                continue;
                            }

                            if (student.SchoologyId != schoology_id)
                            {
                                WebhostEventLog.SchoologyLog.LogInformation("Updating Schoology User Id for {0} {1} [{2}, {3}]", student.FirstName, student.LastName, student.ID, schoology_id);
                                student.SchoologyId = schoology_id;
                            }
                            else
                            {
                                Console.WriteLine("{0} {1} already has their correct schoology id:  {2}", student.FirstName, student.LastName, schoology_id);
                            }
                        }

                        //Thread.Sleep(250);
                    }

                    db.SaveChanges();
                }
            }
        }
Example #20
0
        static void CheckSectionRosters(int ay = 2017)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                foreach (Section section in db.Sections.Where(s => s.Course.AcademicYearID == ay && s.Course.goesToSchoology).ToList())
                {
                    Console.WriteLine("[{0}] {1}:", section.Block.LongName, section.Course.Name);

                    if (section.Course.SchoologyId <= 0)
                    {
                        // create course
                        using (SchoologyAPICall call = new SchoologyAPICall())
                        {
                            XMLTree response;
                            try
                            {
                                response = call.CreateItem(new SchoologyCourse(section.Course.id));
                            }
                            catch (XMLException e)
                            {
                                Console.WriteLine(e.Message);
                                continue;
                            }
                            section.Course.SchoologyId = Convert.ToInt32(response.ChildNodes.Where(n => n.TagName.Equals("id")).Single().Value);
                            WebhostEventLog.SchoologyLog.LogInformation("Created new Schoology Course {0} : {1}", section.Course.Name, section.Course.SchoologyId);
                            Console.WriteLine("Created new Schoology Course {0} : {1}", section.Course.Name, section.Course.SchoologyId);
                            db.SaveChanges();
                        }
                    }

                    if (section.SchoologyId <= 0)
                    {
                        if (section.Terms.Count == 0)
                        {
                            Console.WriteLine("This section has no Terms assigned.... I'm deleting it.");
                            WebhostEventLog.Syslog.LogInformation("Deleting section with no terms assigned [{0}] {1}", section.Block.LongName, section.Course.Name);
                            section.Students.Clear();
                            section.Teachers.Clear();
                            section.AttendanceSubmissionStatuses.Clear();
                            db.Sections.Remove(section);
                            try
                            {
                                db.SaveChanges();
                            }
                            catch (Exception e)
                            {
                                String message = e.Message;
                                while (e.InnerException != null)
                                {
                                    e       = e.InnerException;
                                    message = e.Message;
                                }
                                Console.WriteLine("Failed to save database changes. {0}", message);
                            }
                            continue;
                        }

                        using (SchoologyAPICall call = new SchoologyAPICall())
                        {
                            XMLTree response;
                            try
                            {
                                response = call.CreateItem(new SchoologySection(section.id));
                            }
                            catch (XMLException e)
                            {
                                Console.WriteLine(e.Message);
                                continue;
                            }
                            section.SchoologyId = Convert.ToInt32(response.ChildNodes.Where(n => n.TagName.Equals("id")).Single().Value);
                            WebhostEventLog.SchoologyLog.LogInformation("Created new Schoology Section [{0}] {1} : {2}", section.Block.LongName, section.Course.Name, section.SchoologyId);
                            Console.WriteLine("Created new Schoology Section [{0}] {1} : {2}", section.Block.LongName, section.Course.Name, section.SchoologyId);
                            db.SaveChanges();
                        }
                    }

                    if (section.Students.Count <= 0 || section.Teachers.Count <= 0)
                    {
                        Console.WriteLine("This section has no students or no teachers...");
                        section.Students.Clear();
                        section.Teachers.Clear();
                        section.Terms.Clear();
                        using (SchoologyAPICall call = new SchoologyAPICall())
                        {
                            call.DeleteSection(section.SchoologyId);
                            WebhostEventLog.SchoologyLog.LogInformation("Deleted superfluous section: [{0}] {1}", section.Block.LongName, section.Course.Name);
                            Console.WriteLine("Deleted Section from Schoology.");
                        }

                        section.SchoologyId = -1;

                        try
                        {
                            db.SaveChanges();
                        }
                        catch
                        {
                            Console.WriteLine("Failed to save changes to database.");
                        }
                        continue;
                    }

                    List <int> schoologyIds;
                    List <SchoologyEnrollment> enrollments;
                    try
                    {
                        using (SchoologyAPICall call = new SchoologyAPICall())
                            enrollments = call.GetSectionEnrollments(section.SchoologyId).ToList();

                        schoologyIds = enrollments.Select(u => u.user_id).ToList();
                    }
                    catch (SchoologyAPICall.SchoologyAPIException ex)
                    {
                        Console.WriteLine(ex.Message);
                        continue;
                    }

                    List <int> webhostIds = section.Students.Select(s => s.ID).ToList();
                    webhostIds.AddRange(section.Teachers.Select(t => t.ID).ToList());

                    foreach (int id in schoologyIds)
                    {
                        if (!webhostIds.Contains(id))
                        {
                            String  name;
                            Student student = db.Students.Find(id);
                            if (student == null)
                            {
                                Faculty teacher = db.Faculties.Find(id);
                                name = String.Format("{0} {1}", teacher.FirstName, teacher.LastName);
                            }
                            else
                            {
                                name = String.Format("{0} {1} [2]", student.FirstName, student.LastName);
                            }

                            Console.WriteLine("Schoology Section has extra enrollment for {0}.", name);
                            using (SchoologyAPICall call = new SchoologyAPICall())
                            {
                                call.DeleteEnrollment(section.SchoologyId, enrollments.Where(enr => enr.user_id == id).Select(enr => enr.enrollment_id).Single());
                            }
                        }
                    }

                    foreach (int id in webhostIds)
                    {
                        if (!schoologyIds.Contains(id))
                        {
                            String  name;
                            Student student     = db.Students.Find(id);
                            int     schoologyId = 0;
                            if (student == null)
                            {
                                Faculty teacher = db.Faculties.Find(id);
                                schoologyId = teacher.SchoologyId;
                                name        = String.Format("{0} {1}", teacher.FirstName, teacher.LastName);
                            }
                            else
                            {
                                name        = String.Format("{0} {1} [2]", student.FirstName, student.LastName, student.GraduationYear);
                                schoologyId = student.SchoologyId;
                            }
                            Console.WriteLine("Schoology Section is missing enrollment for {0}.", name);
                            using (SchoologyAPICall call = new SchoologyAPICall())
                            {
                                try
                                {
                                    XMLTree tree = call.CreateEnrollment(section.SchoologyId, schoologyId, student == null);
                                }
                                catch (XMLException e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #21
0
 public SchoologyCourseResponse(String xmlstr)
 {
     xml = new XMLTree(xmlstr);
 }
Example #22
0
        private void ImportGraph(String importFilename)
        {
            // First pass: build the nodes and the parent edges given by nesting
            using(XmlTextReader reader = new XmlTextReader(importFilename))
            {
                while(reader.Read()) // handle root node
                {
                    if(reader.NodeType != XmlNodeType.Element) continue;

                    root = new XMLTree();
                    if(reader.Name == "xmi:XMI") // if root node is the xmi node we've to read the first level of nodes so we got real graph nodes we can hand down
                    {
                        // relevant for hierarchy but not a real graph node to be created from it
                        root.element = reader.Name;
                        root.elementName = null;
                        root.elementNode = null;
                        root.children = new List<XMLTree>();

                        while(reader.Read())
                        {
                            if(reader.NodeType != XmlNodeType.Element)
                                continue;

                            // create real graph node from it
                            bool emptyElem = reader.IsEmptyElement; // retard API designer
                            XMLTree rootChild = new XMLTree();
                            String tagName = reader.Name;
                            rootChild.element = tagName;
                            if(reader.MoveToAttribute("name"))
                                rootChild.elementName = reader.Value;
                            INode gnode = graph.AddNode(graph.Model.NodeModel.GetType(GrGenTypeNameFromXmi(tagName)));
                            rootChild.elementNode = gnode;
                            rootChild.children = new List<XMLTree>();
                            root.children.Add(rootChild);

                            if(reader.MoveToAttribute("xmi:id"))
                                nodeMap[reader.Value] = gnode;

                            if(!emptyElem)
                                ParseNodeFirstPass(reader, rootChild, tagName); // descend and munch subtree
                        }
                    }
                    else
                    {
                        // create real graph node from it
                        String tagName = reader.Name;
                        root.element = tagName;
                        if(reader.MoveToAttribute("name"))
                            root.elementName = reader.Value;
                        INode gnode = graph.AddNode(graph.Model.NodeModel.GetType(GrGenTypeNameFromXmi(tagName)));
                        root.elementNode = gnode;
                        root.children = new List<XMLTree>();

                        if(reader.MoveToAttribute("xmi:id"))
                            nodeMap[reader.Value] = gnode;

                        ParseNodeFirstPass(reader, root, tagName); // descend and munch subtree
                    }
                }
            }

            // Second pass: assign the attributes and edges given by reference attributes
            using(XmlTextReader reader = new XmlTextReader(importFilename))
            {
                while(reader.Read())
                {
                    if(reader.NodeType != XmlNodeType.Element) continue;

                    ParseNodeSecondPass(reader, root, reader.Name);
                }
            }
        }
Example #23
0
        private void LoadProjectData()
        {
            XMLTree tree = XMLTree.LoadFrom(path);

            foreach (XMLTag tgProj in tree.MainTag.Children)
            {
                foreach (XMLTag tgProjCh in tgProj.Children)
                {
                    if (tgProjCh.TagName == "Classes")
                    {
                        foreach (XMLTag tgCS in tgProjCh.Children)
                        {
                            foreach (XMLTag tgCSCh in tgCS.Children)
                            {
                                if (tgCSCh.TagName == "Vars")
                                {
                                    foreach (XMLTag tgVar in tgCSCh.Children)
                                    {
                                        SmartB1tCSVar csv = new SmartB1tCSVar("", "", false);
                                        foreach (XMLTag tgVarData in tgVar.Children)
                                        {
                                            if (tgVarData.TagName == "name")
                                            {
                                                csv.VarName = tgVarData.Body;
                                            }
                                            else
                                            {
                                                if (tgVarData.TagName == "custom_type")
                                                {
                                                    csv.IsCustomType = bool.Parse(tgVarData.Body);
                                                }
                                                else
                                                {
                                                    if (tgVarData.TagName == "data_type")
                                                    {
                                                        csv.DataType = tgVarData.Body;
                                                    }
                                                }
                                            }
                                        }
                                        GlobalData.GlobalProject.Classes[GlobalData.GlobalProject.Classes.Count - 1].Fields.Add(csv);
                                    }
                                }
                                else
                                {
                                    if (tgCSCh.TagName == "name")
                                    {
                                        GlobalData.GlobalProject.Classes.Add(new SmartB1tCSClass(tgCSCh.Body));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (tgProjCh.TagName == "namespace")
                        {
                            GlobalData.GlobalProject.ProjectName = tgProjCh.Body;
                        }
                    }
                }
            }
        }
Example #24
0
        private void ParseNodeSecondPass(XmlTextReader reader, XMLTree parentNode, String curTypeName)
        {
            if(curTypeName != "xmi:XMI") // happens on/if first node is xmi:XMI
                HandleAttributes(reader, curTypeName, parentNode.elementNode);

            int index = 0;
            while(reader.Read())
            {
                if(reader.NodeType == XmlNodeType.EndElement) break;
                if(reader.NodeType != XmlNodeType.Element) continue;

                bool emptyElem = reader.IsEmptyElement; // retard API designer
                String tagName = reader.Name;

                XMLTree child = null;
                if(parentNode != null)
                {
                    if(parentNode.children == null)
                    {
                        ++index;
                        continue;
                    }
                    child = parentNode.children[index];
                }

                String typeName;
                if(curTypeName == "xmi:XMI")
                    typeName = tagName;
                else if(reader.MoveToAttribute("xsi:type"))
                    typeName = reader.Value;
                else if(reader.MoveToAttribute("xmi:type"))
                    typeName = reader.Value;
                else
                    typeName = FindRefTypeName(curTypeName, tagName);

                if(!emptyElem)
                    ParseNodeSecondPass(reader, child, typeName);
                else
                    HandleAttributes(reader, typeName, child.elementNode); 
                ++index;
            }
        }
Example #25
0
        public void SetupSim()
        {
            if (pLocalRoot == null)
            {
                pLocalRoot = HUB.simRoot.Duplicate();
            }
            XMLTree rn = pLocalRoot.Duplicate(); // sim node (not sim list but <Simulation>)

            // setup environment
            fps       = int.Parse(rn.children.ElementAt(0).content);
            g         = double.Parse(rn.children.ElementAt(1).content);
            gA        = double.Parse(rn.children.ElementAt(2).content);
            resetTime = int.Parse(rn.children.ElementAt(3).content);

            XMLTree o = rn.children.ElementAt(4); // object list

            // setup build ellipse
            int c = o.children.Count;

            UIObjects = new Ellipse[c];
            eObjects  = new EngineCircle[c];
            vectors   = new Vector[c];

            int i = 0;

            foreach (XMLTree n in o.children)   // foreach object in simulation, build ellipse

            {
                BuildEllipse(i,                                                                   // index
                             double.Parse(n.children.ElementAt(0).content),                       // xPos
                             double.Parse(n.children.ElementAt(1).content),                       // yPos
                             double.Parse(n.children.ElementAt(2).content),                       // radius
                             byte.Parse(n.children.ElementAt(5).children.ElementAt(0).content),   // a
                             byte.Parse(n.children.ElementAt(5).children.ElementAt(1).content),   // r
                             byte.Parse(n.children.ElementAt(5).children.ElementAt(2).content),   // g
                             byte.Parse(n.children.ElementAt(5).children.ElementAt(3).content),   // b
                             double.Parse(n.children.ElementAt(6).children.ElementAt(2).content), // mag
                             double.Parse(n.children.ElementAt(6).children.ElementAt(3).content), // angle
                             double.Parse(n.children.ElementAt(6).children.ElementAt(0).content), // xV
                             double.Parse(n.children.ElementAt(6).children.ElementAt(1).content), // yV
                             double.Parse(n.children.ElementAt(3).content),                       // mass
                             double.Parse(n.children.ElementAt(4).content));                      // e
                i++;
            }

            // UserEdits

            SimStackPanel.Children.Clear();

            if (rn.children.Count == 6)   // If simulation has UserEdits

            {
                o = rn.children.ElementAt(5);                                 // UserEdits list

                List <int[]> targetList = new List <int[]>(o.children.Count); // List of arrays that will be added to int[][] targets

                foreach (XMLTree n in o.children)                             // for each object available for edit

                {
                    int objectID; // ObjectID from xml

                    // If the ObjectID from the xml is not valid, then throw an exception
                    if ((!int.TryParse(n.children.ElementAt(0).content, out objectID)) || objectID >= eObjects.Length)
                    {
                        throw new InvalidDataException("XML format error: <objectID>" + n.children.ElementAt(0).content + "</objectID>. " + n.children.ElementAt(0).content + " is not a valid objectID.");
                    }

                    int[] tempArray = new int[n.children.Count]; // array to be added to targetList

                    tempArray[0] = objectID;

                    for (i = 1; i < n.children.Count; i++)   // goes through each target of object available for edit

                    {
                        int target; // targeted value ID of taret object from xml

                        // If the target tag's content from the xml is not valid then throw an exception
                        if ((!int.TryParse(n.children.ElementAt(i).content, out target)) || target > 8)
                        {
                            throw new InvalidDataException("XML format error: <target>" + n.children.ElementAt(i).content + "</target>. " + n.children.ElementAt(i).content + " is not a valid target.");
                        }

                        tempArray[i] = target; // add <target> value to array

                        // Setup the TextBox user will input values into
                        TextBox b = new TextBox();
                        b.Width              = 100;            // set width of box to 80 pixels
                        b.CharacterReceived += TextBoxHandler; // call handler when new character is received
                        // add objectID # to box access key, to the left of the '|' the integer is the objectID,
                        //to the right it is the target value, access key is like a name for the textbox
                        b.AccessKey += objectID + "|" + target;

                        switch (target)
                        {
                        case 0:
                            b.PlaceholderText = "x pos";
                            break;

                        case 1:
                            b.PlaceholderText = "y pos";
                            break;

                        case 2:
                            b.PlaceholderText = "radius";
                            break;

                        case 3:
                            b.PlaceholderText = "mass";
                            break;

                        case 4:
                            b.PlaceholderText = "elasticiy";
                            break;

                        case 5:
                            b.PlaceholderText = "x velocity";
                            break;

                        case 6:
                            b.PlaceholderText = "y velocity";
                            break;

                        case 7:
                            b.PlaceholderText = "velocity";
                            break;

                        case 8:
                            b.PlaceholderText = "direction";
                            break;
                        }

                        SimStackPanel.Children.Add(b);
                    }

                    targetList.Add(tempArray); // add array to list
                }

                targets = targetList.ToArray(); // targets = list
            }

            // Add a reset Button

            Button resetB = new Button();

            resetB.Content = "Reset";
            resetB.Width   = 100;
            resetB.Click  += Reset;
            SimStackPanel.Children.Add(resetB);
        }