public static void Main()
        {
            using (var context = new ProductsDbContext())
            {
                //XML:


                //CREATE XML Element manually:
                var xmlDoc = new XDocument();

                var books = new XElement("books");

                xmlDoc.Add(books);

                var bookDescription = new XElement("Descritpion", "very good book!");
                var bookTitle       = new XElement("Title", "C#, Motha' Fuckkrs'");

                var book = new XElement("book", bookTitle, bookDescription);

                books.Add(book);

                xmlDoc.Save("demoXmlBooks.xml"); //to save it in a file!

                Console.WriteLine(books.Value.ToString());
                //string str =
                //    @"<?xml version=""1.0""?>
                //    <!-- comment at the root level -->
                //     <Root>
                //         <Child>Content</Child>
                //    </Root>";

                //XDocument doc = XDocument.Parse(str); //from string to XDoc

                //var xmlString = File.ReadAllText("someXmlFile.xml");

                //var xml = XDocument.Parse(xmlString);

                //var elements = xml.Root.Elements();

                //var windows = elements.Where(e => e.Element("Name")
                //.Value == "Window")
                //.Select(e => new
                //    {
                //        Name = e.Element("Name")?.Value,
                //        Description = e.Element("Desription")?.Value
                //    })
                //.ToArray();

                //foreach (var e in root)
                //{
                //    var name = e.Element("Name").Value; //case sensitive!

                //    Console.WriteLine(e.Name);

                //    e.SetElementValue("Name", "Niki"); //sets tne new value
                //}



                //var product = new Product
                //{
                //    Name = "Tyre",
                //    Description = "makes the car go forw/backw",
                //    Manufacturer = new Manufacturer()
                //    {
                //        Name = "Michelin"
                //    }
                //};



                /* Example for working with REST.Api + JSON
                 *
                 *
                 *
                 * Console.OutputEncoding = Encoding.UTF8;
                 *
                 * string json;
                 * using (var client = new WebClient())
                 * {
                 *  json = client.DownloadString("http://drone.sumc.bg/api/v1/metro/all");
                 * }
                 *
                 * var stations = JsonConvert.DeserializeObject<StationDto[]>(json);
                 *
                 * foreach (var station in stations)
                 * {
                 *  Console.WriteLine(station.Name);
                 *  Console.WriteLine(station.Code);
                 *  Console.WriteLine(station.RouteId);
                 * }
                 *
                 * //REMEMBER: For Cyrilic:
                 *
                 */



                //JSON:


                //var databaseInit = new DatabaseInitializer(context);

                //databaseInit.ResetDatabase();

                //var jsonObjDemo = JObject.Parse(@"{'products': [
                //{'name': 'Fruits', 'products': ['apple', 'banana']},
                //{'name': 'Vegetables', 'products': ['cucumber']}]}");

                //var products = jsonObjDemo["products"].Select(t =>
                //    string.Format("{0} ({1})",
                //        t["name"],
                //        string.Join(", ", t["products"])
                //    )).ToArray();

                //foreach (var p in products)
                //{
                //    Console.WriteLine(p);
                //}



                //JObject jsonArrayInside = JObject.Parse("{'Name': 'Pesho', 'Age': 15, 'RandomElements': [15, 2.3, 'Kiro']}");

                //var jObj = JObject.FromObject(product);
                ////you can:
                //jObj.ToString(Formatting.Indented);
                //how to read from a file:
                // var jObjFromFile = JObject.Parse(File.ReadAllText(@"c:\text.txt"));

                //foreach (var kvp in jsonArrayInside)
                //{
                //    var key = kvp.Key;
                //    var value = kvp.Value; //if you want to be only in specifit type:
                //           // = kvp.Value.ToObject<int>(); - ti will throw exept if value is string, etc.

                //    Console.WriteLine($"The key is: {key} and the value is: {value}");
                //}
                //you can index it like:
                //json["products"].Select(t => t.String.Format("{0} ({1})",
                //t["name"],
                //string.Join(", ", c["products"]));

                //var jsonString = JsonConvert.SerializeObject(product, Formatting.Indented /*or .None*/, new JsonSerializerSettings()
                //{
                //    NullValueHandling = NullValueHandling.Ignore, /*or*/
                //    DefaultValueHandling = DefaultValueHandling.Ignore
                //});

                //var json = JObject.Parse(jsonString);

                //Jtoken is one value from a json object

                //var jsonString = SerializeObject(product); //don't

                //var parsedProduct = DeserializeObject<Product>(jsonString); //don't

                //Console.WriteLine(jsonString);



                //Console.WriteLine(jsonString);

                //var objProduct = JsonConvert.DeserializeObject<Product>(jsonString);
            }

            //how to deserialize anonymousType:

            //var obj = new
            //{
            //    Name = "Pesho",
            //    Age = 20,
            //    Grades = new []
            //    {
            //        3.2,
            //        5.46,
            //        6.00
            //    }
            //};

            //var serializedObj = JsonConvert.SerializeObject(obj);

            //var template = new
            //{
            //    Name = string.Empty,
            //    Age = 0,
            //    Grades = new decimal[] {}
            //};

            // var deserilizedObj = JsonConvert.DeserializeAnonymousType(serializedObj, template);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            XDocument xdoc       = new XDocument();
            XElement  xcomputers = new XElement("computers");
            Computer  computer;

            Console.Write("Enter number of computer you want to write: ");
            int    comp_count = Convert.ToInt16(Console.ReadLine());
            string comp_name;
            double comp_price;
            double comp_power;

            string person_name;
            int    person_age;

            //entering computer info
            for (int i = 0; i < comp_count; i++)
            {
                Console.Write($"\nEnter name of {i+1} computer: ");
                comp_name = Console.ReadLine();
                Console.Write($"Enter price of {i + 1} computer: ");
                comp_price = Convert.ToDouble(Console.ReadLine());
                Console.Write($"Enter power of {i+1} computer: ");
                comp_power = Convert.ToDouble(Console.ReadLine());
                Console.Write("\tEnter name of client: ");
                person_name = Console.ReadLine();
                Console.Write($"\tEnter age of client: ");
                person_age = Convert.ToInt16(Console.ReadLine());
                Client client = new Client(1, person_name, person_age);
                computer = new Computer(i + 1, comp_name, comp_price, comp_power, client); //write computer info to computer object
                //====================Creating XElements for XDocument=========================//
                XElement xcomputer = new XElement("computer",
                                                  new XAttribute("name", computer.name),
                                                  new XElement("price", computer.price),
                                                  new XElement("power", computer.power));
                XElement xclient = new XElement("client",
                                                new XAttribute("name", client.name),
                                                new XElement("age", client.age));
                xcomputer.Add(xclient);    //adding list of clients to computer element
                xcomputers.Add(xcomputer); //adding computer element to list of computers
                //Console.WriteLine(computer.ToString()); //output computer info
            }
            xdoc.Add(xcomputers);
            //xdoc.Add(xcomputers); //adding list of computers to XDocument
            xdoc.Save("computers.xml"); //saving XDocument

            XmlSerializer formatter = new XmlSerializer(typeof(XMLComputer[]));

            using (FileStream fs = new FileStream("computers.xml", FileMode.OpenOrCreate))
            {
                XMLComputer[] new_comp = (XMLComputer[])formatter.Deserialize(fs);

                Console.WriteLine("Объект десериализован");
                foreach (XMLComputer c in new_comp)
                {
                    Console.WriteLine(c.name + " " + c.power.ToString() + " " + c.price.ToString() + " " + c.client.name);
                }
                //Console.WriteLine(new_comp.name + " " + new_comp.power.ToString() + " " + new_comp.price.ToString() + " " + new_comp.client.name);
            }
            Console.WriteLine("done");
        }
Beispiel #3
0
        public override bool Download()
        {
            if (null == this.DbReadData && this.DbReadData.Count() < 1)
            {
                return(false);
            }

            if (File.Exists(this.DownloadFile))
            {
                File.Delete(this.DownloadFile);
            }

            //创建XML对象
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));

            //创建一个根节点
            XElement root = new XElement("root");

            xdoc.Add(root);

            //获取一级分类
            var tops = this.DbReadData.Where(p => p.ParentID == 0).ToList();

            //遍历一级分类
            foreach (var top in tops)
            {
                //定义一级分类节点
                XElement first = new XElement("topcategory");

                first.SetAttributeValue("id", top.CategoryID);
                first.SetAttributeValue("name", top.Name);
                first.SetAttributeValue("icon", top.Ico);
                first.SetAttributeValue("disabled", top.Disabled);
                first.SetAttributeValue("description", top.Description);
                first.SetAttributeValue("depth", top.Depth);

                root.Add(first);

                //遍历子分类
                var childrens = this.DbReadData.Where(p => p.ParentID == top.CategoryID);

                foreach (var child in childrens)
                {
                    //定义子分类节点
                    XElement second = new XElement("category");

                    first.SetAttributeValue("id", top.CategoryID);
                    first.SetAttributeValue("name", top.Name);
                    first.SetAttributeValue("icon", top.Ico);
                    first.SetAttributeValue("disabled", top.Disabled);
                    first.SetAttributeValue("description", top.Description);
                    first.SetAttributeValue("depth", top.Depth);

                    first.Add(second);
                }
            }

            xdoc.Save(this.DownloadFile);

            return(true);
        }
 private static void AddElement(XDocument Document, string Name)
 {
     Document.Add(new XElement(Name));
 }
Beispiel #5
0
        public static void pract5()
        {
            XmlDocument xDoc = new XmlDocument();
            XDocument   xdoc = new XDocument();

            Console.WriteLine("Сколько пользователей нужно внести?");
            int      count = Convert.ToInt32(Console.ReadLine());
            XElement list  = new XElement("list");

            for (int i = 1; i <= count; i++)
            {
                XElement   people      = new XElement("people");
                XAttribute username    = new XAttribute("name", Console.ReadLine());
                XElement   userage     = new XElement("company", Console.ReadLine());
                XElement   usercompany = new XElement("age", Convert.ToInt32(Console.ReadLine()));
                people.Add(username);
                people.Add(userage);
                people.Add(usercompany);
                list.Add(people);
            }

            xdoc.Add(list);
            xdoc.Save("users.xml");
            Console.WriteLine("Прочитать только что записанный xml файл? y/n");
            switch (Console.ReadLine())
            {
            case "y":
                Console.WriteLine();
                xDoc.Load("users.xml");
                XmlElement xRoot = xDoc.DocumentElement;
                foreach (XmlNode xnode in xRoot)
                {
                    if (xnode.Attributes.Count > 0)
                    {
                        XmlNode attr = xnode.Attributes.GetNamedItem("name");
                        if (attr != null)
                        {
                            Console.WriteLine($"Имя: {attr.Value}");
                        }
                    }

                    foreach (XmlNode childnode in xnode.ChildNodes)
                    {
                        if (childnode.Name == "company")
                        {
                            Console.WriteLine($"Компания: {childnode.InnerText}");
                        }

                        if (childnode.Name == "age")
                        {
                            Console.WriteLine($"Возраст: {childnode.InnerText}");
                        }
                    }
                }
                Console.WriteLine();
                Console.WriteLine("Удалить созданный xml файл? y/n");
                switch (Console.ReadLine())
                {
                case "y":
                    FileInfo xmlfilecheck = new FileInfo("users.xml");
                    if (xmlfilecheck.Exists)
                    {
                        xmlfilecheck.Delete();
                    }
                    break;

                case "n":
                    break;

                default:
                    Console.WriteLine("Вы не выбрали значение");
                    break;
                }
                Console.WriteLine();
                break;

            case "n":
                Console.WriteLine("Удалить созданный xml файл? 1-да/2-нет");
                switch (Console.ReadLine())
                {
                case "1":
                    FileInfo xmlfilecheck = new FileInfo("users.xml");
                    if (xmlfilecheck.Exists)
                    {
                        xmlfilecheck.Delete();
                    }
                    break;

                case "2":
                    break;

                default:
                    Console.WriteLine("Вы не выбрали значение");
                    break;
                }
                break;

            default:
                Console.WriteLine("Вы не выбрали значение");
                break;
            }
        }
        /// <summary>
        /// Data is urls with protocol, host name, uri and parameters
        /// or with protocol, host name and uri
        /// or protocol and host name.
        /// URLs separated by \n or white spaces.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public XDocument Convert(string data)
        {
            XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));
            // Main tag.
            XElement urlAddresses = new XElement("urlAddresses");

            string[] everyUrl = data.Split();
            for (int i = 0; i < everyUrl.Length - 1; i++)
            {
                string url = everyUrl[i];
                if (string.IsNullOrWhiteSpace(url))
                {
                    continue;
                }

                // Construct <urlAddress>.
                XElement urlAddress = new XElement("urlAddress");
                string[] elements   = url.Split("//")[1].Split("/");

                // Add host name.
                urlAddress.Add(new XElement("host", new XAttribute("name", elements[0])));

                // If we dont have uri and parameters.
                if (elements.Length < 1)
                {
                    urlAddresses.Add(urlAddress);
                    continue;
                }

                XElement uri = new XElement("uri");
                // Add segments of uri.
                for (int j = 1; j < elements.Length; j++)
                {
                    if (elements[j].Contains("?"))
                    {
                        uri.Add(new XElement("segment", elements[j].Split("?")[0]));
                        break;
                    }

                    if (string.IsNullOrWhiteSpace(elements[j]))
                    {
                        continue;
                    }

                    uri.Add(new XElement("segment", elements[j]));
                }

                urlAddress.Add(uri);
                if (!url.Contains("?"))
                {
                    urlAddresses.Add(urlAddress);
                    continue;
                }

                // Contructing parameters.
                IEnumerable <string> parametersEnum = elements[elements.Length - 1].Split("?").Where(x => x.Contains("="));
                XElement             parameters     = new XElement("parameters");
                foreach (string parameter in parametersEnum)
                {
                    parameters.Add(new XElement("parametr", new XAttribute("value", parameter.Split("=")[1]), new XAttribute("key", parameter.Split("=")[0])));
                }

                urlAddress.Add(parameters);
                // Final adding for url which consist both uri and parameters.
                urlAddresses.Add(urlAddress);
            }

            doc.Add(urlAddresses);
            return(doc);
        }
Beispiel #7
0
        /// <summary>
        /// You can create a server farm by issuing an HTTP POST request. Only
        /// one server farm per webspace is permitted. You can retrieve server
        /// farm details by using HTTP GET, change server farm properties by
        /// using HTTP PUT, and delete a server farm by using HTTP DELETE. A
        /// request body is required for server farm creation (HTTP POST) and
        /// server farm update (HTTP PUT).  Warning: Creating a server farm
        /// changes your webspace’s Compute Mode from Shared to Dedicated. You
        /// will be charged from the moment the server farm is created, even
        /// if all your sites are still running in Free mode.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx
        /// for more information)
        /// </summary>
        /// <param name='webSpaceName'>
        /// The name of the web space.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Create Server Farm operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Create Server Farm operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.WebSites.Models.ServerFarmCreateResponse> CreateAsync(string webSpaceName, ServerFarmCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (webSpaceName == null)
            {
                throw new ArgumentNullException("webSpaceName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("webSpaceName", webSpaceName);
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/WebSpaces/" + webSpaceName + "/ServerFarms";

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2013-08-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string    requestContent = null;
                XDocument requestDoc     = new XDocument();

                XElement serverFarmElement = new XElement(XName.Get("ServerFarm", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(serverFarmElement);

                if (parameters.CurrentNumberOfWorkers != null)
                {
                    XElement currentNumberOfWorkersElement = new XElement(XName.Get("CurrentNumberOfWorkers", "http://schemas.microsoft.com/windowsazure"));
                    currentNumberOfWorkersElement.Value = parameters.CurrentNumberOfWorkers.ToString();
                    serverFarmElement.Add(currentNumberOfWorkersElement);
                }

                if (parameters.CurrentWorkerSize != null)
                {
                    XElement currentWorkerSizeElement = new XElement(XName.Get("CurrentWorkerSize", "http://schemas.microsoft.com/windowsazure"));
                    currentWorkerSizeElement.Value = parameters.CurrentWorkerSize.ToString();
                    serverFarmElement.Add(currentWorkerSizeElement);
                }

                XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                nameElement.Value = "DefaultServerFarm";
                serverFarmElement.Add(nameElement);

                XElement numberOfWorkersElement = new XElement(XName.Get("NumberOfWorkers", "http://schemas.microsoft.com/windowsazure"));
                numberOfWorkersElement.Value = parameters.NumberOfWorkers.ToString();
                serverFarmElement.Add(numberOfWorkersElement);

                XElement workerSizeElement = new XElement(XName.Get("WorkerSize", "http://schemas.microsoft.com/windowsazure"));
                workerSizeElement.Value = parameters.WorkerSize.ToString();
                serverFarmElement.Add(workerSizeElement);

                if (parameters.Status != null)
                {
                    XElement statusElement = new XElement(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
                    statusElement.Value = parameters.Status.ToString();
                    serverFarmElement.Add(statusElement);
                }

                requestContent      = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServerFarmCreateResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new ServerFarmCreateResponse();
                    XDocument responseDoc = XDocument.Parse(responseContent);

                    XElement serverFarmElement2 = responseDoc.Element(XName.Get("ServerFarm", "http://schemas.microsoft.com/windowsazure"));
                    if (serverFarmElement2 != null)
                    {
                        XElement currentNumberOfWorkersElement2 = serverFarmElement2.Element(XName.Get("CurrentNumberOfWorkers", "http://schemas.microsoft.com/windowsazure"));
                        if (currentNumberOfWorkersElement2 != null)
                        {
                            int currentNumberOfWorkersInstance = int.Parse(currentNumberOfWorkersElement2.Value, CultureInfo.InvariantCulture);
                            result.CurrentNumberOfWorkers = currentNumberOfWorkersInstance;
                        }

                        XElement currentWorkerSizeElement2 = serverFarmElement2.Element(XName.Get("CurrentWorkerSize", "http://schemas.microsoft.com/windowsazure"));
                        if (currentWorkerSizeElement2 != null)
                        {
                            ServerFarmWorkerSize currentWorkerSizeInstance = (ServerFarmWorkerSize)Enum.Parse(typeof(ServerFarmWorkerSize), currentWorkerSizeElement2.Value, false);
                            result.CurrentWorkerSize = currentWorkerSizeInstance;
                        }

                        XElement nameElement2 = serverFarmElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                        if (nameElement2 != null)
                        {
                            string nameInstance = nameElement2.Value;
                            result.Name = nameInstance;
                        }

                        XElement numberOfWorkersElement2 = serverFarmElement2.Element(XName.Get("NumberOfWorkers", "http://schemas.microsoft.com/windowsazure"));
                        if (numberOfWorkersElement2 != null)
                        {
                            int numberOfWorkersInstance = int.Parse(numberOfWorkersElement2.Value, CultureInfo.InvariantCulture);
                            result.NumberOfWorkers = numberOfWorkersInstance;
                        }

                        XElement workerSizeElement2 = serverFarmElement2.Element(XName.Get("WorkerSize", "http://schemas.microsoft.com/windowsazure"));
                        if (workerSizeElement2 != null)
                        {
                            ServerFarmWorkerSize workerSizeInstance = (ServerFarmWorkerSize)Enum.Parse(typeof(ServerFarmWorkerSize), workerSizeElement2.Value, false);
                            result.WorkerSize = workerSizeInstance;
                        }

                        XElement statusElement2 = serverFarmElement2.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
                        if (statusElement2 != null)
                        {
                            ServerFarmStatus statusInstance = (ServerFarmStatus)Enum.Parse(typeof(ServerFarmStatus), statusElement2.Value, false);
                            result.Status = statusInstance;
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Beispiel #8
0
        private void Game_UpdateFrame(object sender, FrameEventArgs e)
        {
            PreviousMouseState = MouseState;
            PreviousKeyboardState = KeyboardState;

            MouseState = OpenTK.Input.Mouse.GetState();
            KeyboardState = OpenTK.Input.Keyboard.GetState();

            PreviousMousePosition = MousePosition;

            #if GRAPHMAKER
            XDocument doc = new XDocument();
            doc.Add(new XElement("Waypoints"));
            if (MouseState.LeftButton == ButtonState.Pressed && PreviousMouseState.LeftButton == ButtonState.Released) {
            int x = Camera.X + MousePosition.X;
            int y = Camera.Y + MousePosition.Y;

            if (MouseState.LeftButton == ButtonState.Pressed && PreviousMouseState.LeftButton == ButtonState.Released && MousePosition.X > 40) {
               doc.Element("Waypoints").Add(new XElement("Waypoint", new XAttribute("X", x), new XAttribute("Y", y)));
               minID++;
               Minion markerMinion = new Minion(new List<Sprite>() { new Sprite(new List<string>() { "Images/BlueMinion.png" }), new Sprite(new List<string>() { "Images/BlueMinion0.png", "Images/BlueMinion1.png" }) }, minID);
                markerMinion.Pos.X = x;
                markerMinion.Pos.Y = y;
                _player1.AddMinion(markerMinion);
              // doc.Save("TestWaypoint.xml");
            XDocument doc = new XDocument();
            doc.Add(new XElement("Waypoints"));
            if (MouseState.LeftButton == ButtonState.Pressed && PreviousMouseState.LeftButton == ButtonState.Released) {
            }

            if (MouseState.RightButton == ButtonState.Pressed && PreviousMouseState.RightButton == ButtonState.Released && MousePosition.X > 40)
            {
                switch (rightClicks)
                {
                    case 0: clicks[0] = x;
                        clicks[1] = y;
                        break;

                    case 1:
                        clicks[2] = x;
                        clicks[3] = y;
                         minID++;
                         Minion markerMinion = new Minion(new List<Sprite>() { new Sprite(new List<string>() { "Images/square.png" }), new Sprite(new List<string>() { "Images/square.png", "Images/square.png" }) }, minID);
                         WaypointNode waypoint1 = graph.GetClosestWaypoint(clicks[0], clicks[1]);
                         WaypointNode waypoint2 = graph.GetClosestWaypoint(clicks[2], clicks[3]);
                         markerMinion.Pos.X = waypoint1.X + (waypoint2.X - waypoint1.X) / 2;
                         markerMinion.Pos.Y = waypoint1.Y + (waypoint2.Y - waypoint1.Y) / 2;
                _player1.AddMinion(markerMinion);
                graph.ConnectNodes(waypoint1, waypoint2);
                        Console.Write("Added neighbor");
                        break;
                }
                rightClicks++;
                rightClicks = rightClicks % 2;
                graph.WriteGraph("TestWaypointNeighbors.xml");
            }

            _scrollBar.Update(e.Time);
            #else

            _map.Update(e.Time);

            _ui.Update(e.Time);

            #endif
            }

            private void Mouse_Move(object sender, MouseMoveEventArgs e)
            {
            MousePosition = e.Position;
            }
            }
        }
Beispiel #9
0
        public static void CreateXmlFile(Excel.Worksheet worksheet /*CsvReader csv*/, string currDir, XDocument metadataSetStructure)
        {
            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
            string    now = DateTime.Now.ToShortDateString();
            //  XNamespace xhtml = "http://www.w3.org/1999/xhtml";

            XElement ingestion = new XElement("ingestion");

            ingestion.Add(new XAttribute("overwrite", (metadataSetStructure != null).ToString()));
            doc.Add(ingestion);
            XAttribute xmlLang = new XAttribute(XNamespace.Xml + "lang", "en");

            XElement metadataSet;

            string msGuid;

            if (metadataSetStructure == null)
            {
                XElement metadataSets = new XElement("metadata-sets");
                ingestion.Add(metadataSets);

                metadataSet = new XElement("metadata-set");
                metadataSet.Add(new XAttribute("updated", now));
                metadataSet.Add(new XAttribute("created", now));
                metadataSet.Add(new XAttribute("model-type", "Catfish.Core.Models.CFMetadataSet, Catfish.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"));
                metadataSet.Add(new XAttribute("IsRequired", "false"));
                msGuid = Guid.NewGuid().ToString();
                metadataSet.Add(new XAttribute("guid", msGuid));
                metadataSets.Add(metadataSet);

                XElement msName = new XElement("Name");
                metadataSet.Add(msName);

                XElement text = new XElement("text", "StateFundingMetadataSet");
                text.Add(xmlLang);
                msName.Add(text);

                XElement msDescription = new XElement("description");
                metadataSet.Add(msDescription);
                XElement textDesc = new XElement("text", "Metadata set that use by State Funding database");
                textDesc.Add(xmlLang);

                msDescription.Add(textDesc);
                //add metadata fields
                XElement fields = AddMetadataSetFields(doc, xmlLang); //header
                metadataSet.Add(fields);

                XElement entityTypes = AddEntityTypes(msGuid);

                ingestion.Add(entityTypes);
                doc.Save(currDir + "\\SFIngestionFinal2018-MSEntityType.xml");
            }
            else
            {
                metadataSet = metadataSetStructure.Root;
                msGuid      = metadataSet.Attribute("guid").Value;
            }

            XElement aggregations = AddAggregations(msGuid, worksheet, currDir, metadataSet);

            // ingestion.Add(aggregations);

            // doc.Save(currDir + "\\StateFundingIngestion17Jan2018.xml");
        }
Beispiel #10
0
        public static XElement AddAggregations(string msGuid, Excel.Worksheet worksheet /*CsvReader csv*/, string currDir, XElement metadataSet)
        {
            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));

            XElement ingestion = new XElement("ingestion");

            ingestion.Add(new XAttribute("overwrite", "false"));
            doc.Add(ingestion);

            XAttribute xmlLang      = new XAttribute(XNamespace.Xml + "lang", "en");
            XElement   aggregations = new XElement("aggregations");

            int countAggregation = 1;
            int fileCount        = 1;

            Excel.Range range     = worksheet.UsedRange;
            int         rowsCount = range.Rows.Count;

            string inflationField = "amount" + MAX_YEAR + "Inflation";

            for (int i = 2; i <= rowsCount; ++i)
            {
                StateFunding sf = ReadRow(worksheet.get_Range("A" + i, "T" + i));

                try
                {
                    XElement item = new XElement("item");
                    aggregations.Add(item);
                    string now = DateTime.Now.ToShortDateString();
                    item.Add(new XAttribute("created", now));
                    item.Add(new XAttribute("updated", now));
                    item.Add(new XAttribute("model-type", "Catfish.Core.Models.CFItem, Catfish.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"));
                    item.Add(new XAttribute("IsRequired", "false"));
                    item.Add(new XAttribute("guid", Guid.NewGuid().ToString()));
                    item.Add(new XAttribute("entity-type", EntityTypeName));

                    XElement metadata = new XElement("metadata");
                    item.Add(metadata);
                    XElement ms = new XElement(metadataSet);
                    metadata.Add(ms);
                    ms.SetAttributeValue("created", now);
                    ms.SetAttributeValue("updated", now);
                    XElement fields = ms.Element("fields");

                    Action <XElement, string> setValue = (field, value) =>
                    {
                        XElement valueElement = field.Element("value");

                        if (valueElement == null)
                        {
                            valueElement = new XElement("value");
                            field.Add(valueElement);
                        }

                        XElement textValue = valueElement.Element("text");

                        if (textValue == null)
                        {
                            textValue = new XElement("text");
                            valueElement.Add(textValue);

                            textValue.Add(xmlLang);
                        }

                        textValue.Value = value ?? "";
                    };

                    foreach (XElement field in fields.Elements())
                    {
                        field.SetAttributeValue("updated", now);
                        string name = field.Element("name").Element("text").Value;

                        if (name == "jurisdiction")
                        {
                            setValue(field, sf.jurisdiction);
                        }
                        else if (name == "yearFunded")
                        {
                            setValue(field, sf.yearFunded);
                        }
                        else if (name == "recipient")
                        {
                            setValue(field, sf.recipient);
                        }
                        else if (name == "amount")
                        {
                            //TODO: add the inflation amount
                            setValue(field, sf.amount);
                        }
                        else if (name == "ministryAgency")
                        {
                            setValue(field, sf.ministryAgency);
                        }
                        else if (name == "city")
                        {
                            setValue(field, sf.city);
                        }
                        else if (name == "jurisdictionFederal")
                        {
                            setValue(field, sf.jurisdictionFederal);
                        }
                        else if (name == "source")
                        {
                            setValue(field, sf.source);
                        }
                        else if (name == "program")
                        {
                            setValue(field, sf.program);
                        }
                        else if (name == "masterProgram")
                        {
                            setValue(field, sf.masterProgram);
                        }
                        else if (name == "project")
                        {
                            setValue(field, sf.project);
                        }
                        else if (name == "recipientOriginal")
                        {
                            setValue(field, sf.recipientOriginal);
                        }
                        else if (name == "notes")
                        {
                            setValue(field, sf.notes);
                        }
                        else if (name == inflationField)
                        {
                            setValue(field, sf.amountInflation);
                        }
                        else if (name == "movement")
                        {
                            var options = field.Element("options").Elements();

                            foreach (var option in options)
                            {
                                string optionName = option.Element("text").Value;

                                if (optionName == "Aboriginal Peoples")
                                {
                                    option.SetAttributeValue("selected", sf.movementAboriginal == "1");
                                }
                                else if (optionName == "Environment")
                                {
                                    option.SetAttributeValue("selected", sf.movementEnvironment == "1");
                                }
                                else if (optionName == "Human Rights")
                                {
                                    option.SetAttributeValue("selected", sf.movementRights == "1");
                                }
                                else if (optionName == "Women")
                                {
                                    option.SetAttributeValue("selected", sf.movementWomen == "1");
                                }
                                else if (optionName == "Other")
                                {
                                    option.SetAttributeValue("selected", sf.movementOther == "1");
                                }
                                else if (optionName == "Aboriginal Government")
                                {
                                    option.SetAttributeValue("selected", sf.movementABgovt == "1");
                                }
                            }
                        }
                    }

                    XElement access = XElement.Parse(ACCESS);
                    item.Add(access);
                }
                catch (Exception ex)
                {
                    if (sf != null)
                    {
                        Console.WriteLine(string.Format("An error occured while reading enty {0}: {1}", sf.recordNumber, ex.Message));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("An error occured reading line {0} of the excel file:", i, ex.Message));
                    }

                    Console.WriteLine(ex.StackTrace);
                }

                if (countAggregation == TotAggregations) //save the file for every 10k items
                {
                    ingestion.Add(aggregations);
                    doc.Save(currDir + "\\SFundingIngestion-Aggregation-" + fileCount + ".xml");
                    countAggregation = 1;
                    aggregations.RemoveAll();
                    ingestion.RemoveAll();
                    fileCount++;
                }
                else
                {
                    countAggregation++;
                }
            }


            //write the reminding of the file
            ingestion.Add(aggregations);
            doc.Save(currDir + "\\SFundingIngestion-Aggregation-" + fileCount + ".xml");
            //countAggregation = 1;
            // aggregations.RemoveAll();
            // ingestion.RemoveAll();


            return(aggregations);
        }
        public override string WriteXmlRps(NotaServico nota, bool identado, bool showDeclaration)
        {
            string tipoRps;

            switch (nota.IdentificacaoRps.Tipo)
            {
            case TipoRps.RPS:
                tipoRps = "RPS";
                break;

            case TipoRps.NFConjugada:
                tipoRps = "RPS-M";
                break;

            case TipoRps.Cupom:
                tipoRps = "RPS-C";
                break;

            default:
                tipoRps = "";
                break;
            }

            string tipoTributacao;

            switch (nota.TipoTributacao)
            {
            case TipoTributacao.Tributavel:
                tipoTributacao = "T";
                break;

            case TipoTributacao.ForaMun:
                tipoTributacao = "F";
                break;

            case TipoTributacao.Isenta:
                tipoTributacao = "A";
                break;

            case TipoTributacao.ForaMunIsento:
                tipoTributacao = "B";
                break;

            case TipoTributacao.Imune:
                tipoTributacao = "M";
                break;

            case TipoTributacao.ForaMunImune:
                tipoTributacao = "N";
                break;

            case TipoTributacao.Suspensa:
                tipoTributacao = "X";
                break;

            case TipoTributacao.ForaMunSuspensa:
                tipoTributacao = "V";
                break;

            case TipoTributacao.ExpServicos:
                tipoTributacao = "P";
                break;

            default:
                tipoTributacao = "";
                break;
            }

            var situacao = nota.Situacao == SituacaoNFSeRps.Normal ? "N" : "C";

            var issRetido = nota.Servico.Valores.IssRetido == SituacaoTributaria.Retencao ? "true" : "false";

            // RPS
            XNamespace ns = "";

            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));
            var rps    = new XElement(ns + "RPS");

            xmlDoc.Add(rps);

            var hashRps = GetHashRps(nota);

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "Assinatura", 1, 2000, Ocorrencia.Obrigatoria, hashRps));

            var chaveRPS = new XElement("ChaveRPS");

            rps.Add(chaveRPS);
            chaveRPS.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoPrestador", 1, 15, Ocorrencia.Obrigatoria, nota.Prestador.InscricaoMunicipal));
            chaveRPS.AddChild(AdicionarTag(TipoCampo.Int, "", "SerieRPS", 1, 5, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Serie));
            chaveRPS.AddChild(AdicionarTag(TipoCampo.Int, "", "NumeroRPS", 1, 15, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Numero));

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "TipoRPS", 1, 1, Ocorrencia.Obrigatoria, tipoRps));
            rps.AddChild(AdicionarTag(TipoCampo.Dat, "", "DataEmissao", 20, 20, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.DataEmissao));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "StatusRPS", 1, 1, Ocorrencia.Obrigatoria, situacao));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "TributacaoRPS", 1, 1, Ocorrencia.Obrigatoria, tipoTributacao));

            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorServicos", 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorServicos));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorDeducoes", 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorDeducoes));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorPIS", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorPis));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCOFINS", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorCofins));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorINSS", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorInss));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIR", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorIr));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCSLL", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorCsll));

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoServico", 1, 5, Ocorrencia.Obrigatoria, nota.Servico.ItemListaServico));
            rps.AddChild(AdicionarTag(TipoCampo.De4, "", "AliquotaServicos", 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.Aliquota / 100));  // Valor Percentual - Exemplos: 1% => 0.01   /   25,5% => 0.255   /   100% => 1
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "ISSRetido", 1, 4, Ocorrencia.Obrigatoria, issRetido));

            var tomadorCpfCnpj = new XElement("CPFCNPJTomador");

            rps.Add(tomadorCpfCnpj);
            tomadorCpfCnpj.AddChild(AdicionarTagCNPJCPF("", "CPF", "CNPJ", nota.Tomador.CpfCnpj));

            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipalTomador", 1, 8, Ocorrencia.NaoObrigatoria, nota.Tomador.InscricaoMunicipal));
            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoEstadualTomador", 1, 19, Ocorrencia.NaoObrigatoria, nota.Tomador.InscricaoEstadual));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocialTomador", 1, 115, Ocorrencia.NaoObrigatoria, nota.Tomador.RazaoSocial));

            if (!nota.Tomador.Endereco.Logradouro.IsEmpty())
            {
                var endereco = new XElement("EnderecoTomador");
                rps.AddChild(endereco);
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "TipoLogradouro", 1, 3, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.TipoLogradouro));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Logradouro", 1, 125, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Logradouro));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "NumeroEndereco", 1, 10, Ocorrencia.Obrigatoria, nota.Tomador.Endereco.Numero));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "ComplementoEndereco", 1, 10, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Complemento));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Bairro", 1, 60, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Bairro));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "Cidade", 1, 7, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.CodigoMunicipio));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "UF", 2, 2, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Uf));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumberFill, "", "CEP", 8, 8, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Cep));
            }

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "EmailTomador", 1, 75, Ocorrencia.NaoObrigatoria, nota.Tomador.DadosContato.Email));

            if (!nota.Intermediario.CpfCnpj.IsEmpty())
            {
                var intermediarioCpfCnpj = new XElement("CPFCNPJIntermediario");
                rps.Add(intermediarioCpfCnpj);
                intermediarioCpfCnpj.AddChild(AdicionarTagCNPJCPF("", "CPF", "CNPJ", nota.Intermediario.CpfCnpj));

                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "InscricaoMunicipalIntermediario", 1, 8, 0, nota.Intermediario.InscricaoMunicipal));
                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocialIntermediario", 1, 115, 0, nota.Intermediario.RazaoSocial));

                var issRetidoIntermediario = nota.Intermediario.IssRetido == SituacaoTributaria.Retencao ? "true" : "false";
                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "ISSRetidoIntermediario", 1, 4, Ocorrencia.Obrigatoria, issRetidoIntermediario));
                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "EmailIntermediario", 1, 75, Ocorrencia.NaoObrigatoria, nota.Intermediario.EMail));
            }

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "Discriminacao", 1, 2000, Ocorrencia.Obrigatoria, nota.Servico.Discriminacao));

            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCargaTributaria", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorCargaTributaria));
            rps.AddChild(AdicionarTag(TipoCampo.De4, "", "PercentualCargaTributaria", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.AliquotaCargaTributaria / 100));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "FonteCargaTributaria", 1, 10, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.FonteCargaTributaria));

            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoCEI", 1, 12, Ocorrencia.NaoObrigatoria, nota.ConstrucaoCivil.CodigoCEI));
            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "MatriculaObra", 1, 12, Ocorrencia.NaoObrigatoria, nota.ConstrucaoCivil.Matricula));
            //rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "MunicipioPrestacao", 1, 7, Ocorrencia.MaiorQueZero, nota.Servico.CodigoMunicipio));
            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "NumeroEncapsulamento", 1, 7, Ocorrencia.NaoObrigatoria, nota.Material.NumeroEncapsulamento));

            return(xmlDoc.AsString(identado, showDeclaration, Encoding.UTF8));
        }
Beispiel #12
0
        /// <summary>
        /// Write in XML file
        /// </summary>
        /// <param name="path">path</param>
        public void WriteTOXml(string path)
        {
            XDocument xdoc;

            try
            {
                xdoc = XDocument.Load(path);
            }
            catch (FileNotFoundException e)
            {
                xdoc = new XDocument();
                XElement xElement = new XElement("booksandstudents", "");
                xdoc.Add(xElement);
            }

            XElement newbookandstudent = new XElement("bookandstudent");

            //add student element and attributes
            XElement   nameEl    = new XElement("name", Student.Name);
            XElement   addressEl = new XElement("address", Student.Address);
            XElement   faculty   = new XElement("faculty", Student.Faculty);
            XAttribute groupAt   = new XAttribute("group", Student.Group);
            XAttribute courseAt  = new XAttribute("course", Student.Course);

            faculty.Add(groupAt);
            faculty.Add(courseAt);
            //add book element and attributes
            XElement   titleEl   = new XElement("title", Book.Title);
            XElement   authorEl  = new XElement("author", Book.Author);
            XElement   yearEl    = new XElement("year", Book.Year);
            XElement   editionEl = new XElement("edition", Book.Year);
            XAttribute priceAt   = new XAttribute("price", Book.Price);
            XAttribute pagesAt   = new XAttribute("pages", Book.Pages);
            // add data elemebts
            XElement getDAte    = new XElement("getdate", StartRead);
            XElement returnDate = new XElement("returndate", EndRead);

            editionEl.Add(priceAt);
            editionEl.Add(pagesAt);

            ///Add elements in root elements
            newbookandstudent.Add(nameEl);
            newbookandstudent.Add(addressEl);
            newbookandstudent.Add(faculty);
            newbookandstudent.Add(titleEl);
            newbookandstudent.Add(authorEl);
            newbookandstudent.Add(editionEl);
            newbookandstudent.Add(getDAte);
            newbookandstudent.Add(returnDate);

            XElement booksandstudents = xdoc.Element("booksandstudents");

            if (booksandstudents == null)
            {
                booksandstudents = new XElement("booksandstudents");
                xdoc.Add(booksandstudents);
            }

            booksandstudents.Add(newbookandstudent);

            xdoc.Save(path);
        }
Beispiel #13
0
 public void XDocumentToStringThrowsForXDocumentContainingOnlyWhitespaceNodes()
 {
     // XDocument.ToString() throw exception for the XDocument containing whitespace node only
     XDocument d = new XDocument();
     d.Add(" ");
     string s = d.ToString();
 }
        public void Save(string filePath, bool reload = true)
        {
            var  packagesToDeselect = corePackages.Concat(regularPackages).Where(p => p.Path.CleanUpPath() == Path.CleanUpPath()).ToList();
            bool refreshFiles       = false;

            if (packagesToDeselect.Any())
            {
                foreach (var p in packagesToDeselect)
                {
                    if (p.IsCorePackage)
                    {
                        if (GameMain.Config.CurrentCorePackage == p)
                        {
                            refreshFiles = true;
                        }
                        corePackages.RemoveOnMainThread(p);
                    }
                    else
                    {
                        if (GameMain.Config.EnabledRegularPackages.Contains(p))
                        {
                            refreshFiles = true;
                        }
                        regularPackages.RemoveOnMainThread(p);
                    }
                }
                if (IsCorePackage)
                {
                    corePackages.AddOnMainThread(this);
                }
                else
                {
                    regularPackages.AddOnMainThread(this);
                }

                if (refreshFiles)
                {
                    GameMain.Config.DisableContentPackageItems(filesToRemove);
                    GameMain.Config.EnableContentPackageItems(filesToAdd);
                    GameMain.Config.RefreshContentPackageItems(filesToRemove.Concat(filesToAdd).Distinct());
                }
            }
            files.RemoveAll(f => filesToRemove.Contains(f));
            files.AddRange(filesToAdd);
            filesToRemove.Clear(); filesToAdd.Clear();

            XDocument doc = new XDocument();

            doc.Add(new XElement("contentpackage",
                                 new XAttribute("name", Name),
                                 new XAttribute("path", Path.CleanUpPathCrossPlatform(correctFilenameCase: false)),
                                 new XAttribute("corepackage", IsCorePackage)));

            doc.Root.Add(new XAttribute("gameversion", GameVersion.ToString()));

            if (SteamWorkshopId != 0)
            {
                doc.Root.Add(new XAttribute("steamworkshopid", SteamWorkshopId.ToString()));
            }

            if (InstallTime != null)
            {
                doc.Root.Add(new XAttribute("installtime", ToolBox.Epoch.FromDateTime(InstallTime.Value)));
            }

            foreach (ContentFile file in Files)
            {
                doc.Root.Add(new XElement(file.Type.ToString(), new XAttribute("file", file.Path.CleanUpPathCrossPlatform())));
            }

            doc.SaveSafe(filePath);
        }
Beispiel #15
0
        public static void ConvertToXML(string source, string destination)
        {
            var sourcePath      = source;
            var destinationPath = destination;

            if (string.IsNullOrEmpty(destinationPath))
            {
                destinationPath = Path.ChangeExtension(sourcePath, null);
            }

            if (!Path.IsPathRooted(destinationPath))
            {
                destinationPath = Path.Combine(GetExePath(), destinationPath);
            }

            if (!File.Exists(sourcePath))
            {
                return;
            }

            using (var input = File.OpenRead(sourcePath))
            {
                var coal = new CoalescedFileXml();
                coal.Deserialize(input);

                var inputId   = Path.GetFileNameWithoutExtension(sourcePath) ?? "Coalesced";
                var inputName = Path.GetFileName(sourcePath) ?? "Coalesced.bin";

                List <string> OutputFileNames = new List <string>();

                XDocument xDoc;
                XElement  rootElement;

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

                foreach (var file in coal.Files)
                {
                    var fileId = Path.GetFileNameWithoutExtension(file.Name);
                    fileId = ProperNames.FirstOrDefault(s => s.Equals(fileId, StringComparison.InvariantCultureIgnoreCase));

                    var iniPath = $"{destinationPath}/{fileId}.xml";

                    OutputFileNames.Add(Path.GetFileName(iniPath));

                    xDoc = new XDocument();

                    rootElement = new XElement("CoalesceAsset");
                    rootElement.SetAttributeValue("id", fileId);
                    rootElement.SetAttributeValue("name", Path.GetFileName(file.Name));
                    rootElement.SetAttributeValue("source", file.Name);

                    var sectionsElement = new XElement("Sections");

                    foreach (var section in file.Sections)
                    {
                        var sectionElement = new XElement("Section");
                        sectionElement.SetAttributeValue("name", section.Key);

                        //
                        //var classes = Namespace.FromStrings(section.Value.Keys);

                        //

                        foreach (var property in section.Value)
                        {
                            var propertyElement = new XElement("Property");
                            propertyElement.SetAttributeValue("name", property.Key);

                            if (property.Value.Count > 1)
                            {
                                foreach (var value in property.Value)
                                {
                                    var valueElement  = new XElement("Value");
                                    var propertyValue = value.Value;
                                    valueElement.SetAttributeValue("type", value.Type);

                                    if (!string.IsNullOrEmpty(propertyValue))
                                    {
                                        propertyValue = SpecialCharacters.Aggregate(propertyValue, (current, c) => current.Replace(c.Key, c.Value));
                                    }

                                    valueElement.SetValue(propertyValue ?? "null");

                                    propertyElement.Add(valueElement);
                                }
                            }
                            else
                            {
                                switch (property.Value.Count)
                                {
                                case 1:
                                {
                                    propertyElement.SetAttributeValue("type", property.Value[0].Type);
                                    var propertyValue = property.Value[0].Value;

                                    if (!string.IsNullOrEmpty(propertyValue))
                                    {
                                        propertyValue = SpecialCharacters.Aggregate(propertyValue, (current, c) => current.Replace(c.Key, c.Value));
                                    }

                                    propertyElement.SetValue(propertyValue ?? "null");
                                    break;
                                }

                                case 0:
                                {
                                    propertyElement.SetAttributeValue("type", CoalesceProperty.DefaultValueType);
                                    propertyElement.SetValue("");
                                    break;
                                }
                                }
                            }

                            sectionElement.Add(propertyElement);
                        }

                        sectionsElement.Add(sectionElement);
                    }

                    rootElement.Add(sectionsElement);
                    xDoc.Add(rootElement);

                    //
                    using (var writer = new XmlTextWriter(iniPath, Encoding.UTF8))
                    {
                        writer.IndentChar  = '\t';
                        writer.Indentation = 1;
                        writer.Formatting  = Formatting.Indented;

                        xDoc.Save(writer);
                    }

                    //

                    //xDoc.Save(iniPath, SaveOptions.None);
                }

                xDoc = new XDocument();

                rootElement = new XElement("CoalesceFile");
                rootElement.SetAttributeValue("id", inputId);
                rootElement.SetAttributeValue("name", inputName);

                //rootElement.SetAttributeValue("Source", "");

                var assetsElement = new XElement("Assets");

                foreach (var file in OutputFileNames)
                {
                    var assetElement = new XElement("Asset");
                    var path         = $"{file}";
                    assetElement.SetAttributeValue("source", path);

                    assetsElement.Add(assetElement);
                }

                rootElement.Add(assetsElement);
                xDoc.Add(rootElement);

                //
                using (var writer = new XmlTextWriter(Path.Combine(destinationPath, $"{inputId}.xml"), Encoding.UTF8))
                {
                    writer.IndentChar  = '\t';
                    writer.Indentation = 1;
                    writer.Formatting  = Formatting.Indented;

                    xDoc.Save(writer);
                }

                //

                //xDoc.Save(Path.Combine(destinationPath, string.Format("{0}.xml", inputId)), SaveOptions.None);
            }
        }
Beispiel #16
0
 /// <summary>
 /// Runs test for valid cases
 /// </summary>
 /// <param name="nodeType">XElement/XAttribute</param>
 /// <param name="name">name to be tested</param>
 public void RunValidTests(string nodeType, string name)
 {
     XDocument xDocument = new XDocument();
     XElement element = null;
     switch (nodeType)
     {
         case "XElement":
             element = new XElement(name, name);
             xDocument.Add(element);
             IEnumerable<XNode> nodeList = xDocument.Nodes();
             Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
             xDocument.RemoveNodes();
             break;
         case "XAttribute":
             element = new XElement(name, name);
             XAttribute attribute = new XAttribute(name, name);
             element.Add(attribute);
             xDocument.Add(element);
             XAttribute x = element.Attribute(name);
             Assert.Equal(name, x.Name.LocalName);
             xDocument.RemoveNodes();
             break;
         case "XName":
             XName xName = XName.Get(name, name);
             Assert.Equal(name, xName.LocalName);
             Assert.Equal(name, xName.NamespaceName);
             Assert.Equal(name, xName.Namespace.NamespaceName);
             break;
         default:
             break;
     }
 }
Beispiel #17
0
        static void Main(string[] args)
        {
            // ShipTo
            string shipToCompany          = "Marcin Iskra";
            string shipToAttention        = "Marcin Iskra";
            string shipToAddress1         = "Nad Serafą 56A";
            string shipToCountryTerritory = "PL";
            string shipToPostalCode       = "30-864";
            string shipToCity             = "Kraków";
            string shipToPhone            = "603793795";
            string shipToEmail            = "*****@*****.**";

            //AccessPoint
            string pointCompany          = "";
            string pointAddress1         = "";
            string pointCountryTerritory = "";
            string pointPostalCode       = "";
            string pointCity             = "";

            //

            //            XNamespace empNM = "x-schema:OpenShipments.xdr";
            XNamespace empNM = "http://www.ups.com/XMLSchema/CT/WorldShip/ImpExp/ShipmentImport/v1_0_0";

            XDocument xmlFile = new XDocument(
                new XDeclaration("1.0", "WINDOWS-1250", null)
                );

            //, new XElement("OpenShipments")


            XElement openShipments = new XElement(empNM + "OpenShipments");

            xmlFile.Add(openShipments);

            XElement openShipment = new XElement(empNM + "OpenShipment", new XAttribute("ProcessStatus", ""), new XAttribute("ShipmentOption", "EU"));

            openShipments.Add(openShipment);

            XElement shipTo = new XElement(empNM + "ShipTo"
                                           , new XElement(empNM + "CompanyOrName", shipToCompany)
                                           , new XElement(empNM + "Attention", shipToAttention)
                                           , new XElement(empNM + "Address1", shipToAddress1)
                                           , new XElement(empNM + "CountryTerritory", shipToCountryTerritory)
                                           , new XElement(empNM + "PostalCode", shipToPostalCode)
                                           , new XElement(empNM + "City", shipToCity)
                                           , new XElement(empNM + "Phone", shipToPhone)
                                           , new XElement(empNM + "Email", shipToEmail)
                                           );

            openShipment.Add(shipTo);

            XElement accessPoint = new XElement(empNM + "AccessPoint"
                                                , new XElement(empNM + "CompanyOrName", pointCompany)
                                                , new XElement(empNM + "Address1", pointAddress1)
                                                , new XElement(empNM + "CountryTerritory", pointCountryTerritory)
                                                , new XElement(empNM + "PostalCode", pointPostalCode)
                                                , new XElement(empNM + "CityOrTown", pointCity)
                                                );

            openShipment.Add(accessPoint);

            XElement shipmentInformation = new XElement(empNM + "ShipmentInformation"
                                                        , new XElement(empNM + "ShipperNumber", "WW4502")
                                                        );

            openShipment.Add(shipmentInformation);

            XElement qVNOption = new XElement(empNM + "QVNOption");

            shipmentInformation.Add(qVNOption);

            XElement billingOption = new XElement(empNM + "BillingOption");

            shipmentInformation.Add(billingOption);

            XElement holdAtUPSAccessPointOption = new XElement(empNM + "HoldatUPSAccessPointOption");

            shipmentInformation.Add(holdAtUPSAccessPointOption);



            xmlFile.Save("Q:\\text.xml");
        }
Beispiel #18
0
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                foreach (GameScreen screen in tempScreensList)
                {

                    if (screen.IsSerializable)
                    {

                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    screen.Deactivate();
                }

                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
Beispiel #19
0
        public static void SaveXML(string filename, string handlingFile)
        {
            IEnumerable <XElement> handlings = XDocument.Load(handlingFile).Element("CHandlingDataMgr").Element("HandlingData").Elements();

            XDocument doc = new XDocument();

            doc.Add(new XComment(" https://www.gtamodding.com/wiki/Handling.meta "));
            XElement chandlingfields = new XElement("CHandlingData");

            foreach (var item in FieldsNames)
            {
                var      values = handlings.Descendants(item);
                XElement e      = new XElement(item);
                bool     editable;
                dynamic  min = 0, max = 0;

                Type fieldType = GetFieldType(item);
                if (fieldType == typeof(float))
                {
                    editable = true;
                    min      = values.Select(a => float.Parse(a.Attribute("value").Value)).Min();
                    max      = values.Select(a => float.Parse(a.Attribute("value").Value)).Max();
                    e.Add(CreateProperty("Min", min));
                    e.Add(CreateProperty("Max", max));
                }
                else if (fieldType == typeof(int))
                {
                    editable = false;
                    min      = values.Select(a => int.Parse(a.Attribute("value").Value)).Min();
                    max      = values.Select(a => int.Parse(a.Attribute("value").Value)).Max();
                    e.Add(CreateProperty("Min", min));
                    e.Add(CreateProperty("Max", max));
                }
                else if (fieldType == typeof(Vector3))
                {
                    editable = false;
                    var minX = values.Select(a => float.Parse(a.Attribute("x").Value)).Min();
                    var minY = values.Select(a => float.Parse(a.Attribute("y").Value)).Min();
                    var minZ = values.Select(a => float.Parse(a.Attribute("z").Value)).Min();
                    var maxX = values.Select(a => float.Parse(a.Attribute("x").Value)).Max();
                    var maxY = values.Select(a => float.Parse(a.Attribute("y").Value)).Max();
                    var maxZ = values.Select(a => float.Parse(a.Attribute("z").Value)).Max();

                    min = new Vector3(minX, minY, minZ);
                    max = new Vector3(maxX, maxY, maxZ);
                    e.Add(CreateProperty("Min", min));
                    e.Add(CreateProperty("Max", max));
                }
                else
                {
                    editable = false;
                }

                e.Add(new XAttribute("Editable", editable));

                XElement desc = new XElement("Description");
                if (FieldsDescriptions.ContainsKey(item))
                {
                    desc.Value = FieldsDescriptions[item];
                }
                e.Add(desc);

                chandlingfields.Add(e);
            }
            doc.Add(chandlingfields);
            doc.Save(filename);
        }
Beispiel #20
0
        // xml запись сцены в файл
        private void ExportScene_Click(object sender, EventArgs e)
        {
            if (ExportDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    IFormatProvider format = new System.Globalization.CultureInfo("en-us");

                    XDocument document = new XDocument();

                    XElement scene = new XElement("scene");
                    scene.SetAttributeValue("ViewMode", Scene.Mode);

                    var      camera        = Scene.Camera;
                    XElement cameraElement = new XElement("camera");

                    cameraElement.SetElementValue("central-projection", camera.IsCentralProjection);

                    XElement position = new XElement("position");
                    position.SetAttributeValue("x", string.Format(format, "{0:0.00}", camera.Position.X));
                    position.SetAttributeValue("y", string.Format(format, "{0:0.00}", camera.Position.Y));
                    position.SetAttributeValue("z", string.Format(format, "{0:0.00}", camera.Position.Z));
                    cameraElement.Add(position);

                    XElement target = new XElement("target");
                    target.SetAttributeValue("x", string.Format(format, "{0:0.00}", camera.Target.X));
                    target.SetAttributeValue("y", string.Format(format, "{0:0.00}", camera.Target.Y));
                    target.SetAttributeValue("z", string.Format(format, "{0:0.00}", camera.Target.Z));
                    cameraElement.Add(target);

                    XElement clippingplanes = new XElement("clipping-planes");
                    clippingplanes.SetAttributeValue("near", camera.NearClipZ);
                    clippingplanes.SetAttributeValue("far", camera.FarClipZ);
                    cameraElement.Add(clippingplanes);

                    cameraElement.SetElementValue("fov", camera.FOV);

                    scene.Add(cameraElement);

                    var      light        = Scene.Light;
                    XElement lightElement = new XElement("light");

                    XElement lightPosition = new XElement("position");
                    lightPosition.SetAttributeValue("x", string.Format(format, "{0:0.00}", light.X));
                    lightPosition.SetAttributeValue("y", string.Format(format, "{0:0.00}", light.Y));
                    lightPosition.SetAttributeValue("z", string.Format(format, "{0:0.00}", light.Z));
                    lightElement.Add(lightPosition);

                    scene.Add(lightElement);

                    XElement objects = new XElement("objects");
                    foreach (TelescopeObject radio in Scene.Objects)
                    {
                        XElement objectelement;

                        objectelement = new XElement("Telescope");

                        objectelement.SetElementValue("Basis1CylinderRadius", string.Format(format, "{0:0.00}", radio.Basis1CylinderRadius));
                        objectelement.SetElementValue("PrimaryLegsLength", string.Format(format, "{0:0.00}", radio.PrimaryLegsLength));
                        objectelement.SetElementValue("Basis2CylinderRadius", string.Format(format, "{0:0.00}", radio.Basis2CylinderRadius));
                        objectelement.SetElementValue("Basis3CylinderRadius", string.Format(format, "{0:0.00}", radio.Basis3CylinderRadius));
                        objectelement.SetElementValue("LenseRadius", string.Format(format, "{0:0.00}", radio.LenseRadius));
                        objectelement.SetElementValue("SecondaryLegsLength", string.Format(format, "{0:0.00}", radio.SecondaryLegsLength));
                        objectelement.SetElementValue("PrimaryLegsCount", string.Format(format, "{0:0.00}", radio.PrimaryLegsCount));
                        objectelement.SetElementValue("SecondaryLegsCount", string.Format(format, "{0:0.00}", radio.SecondaryLegsCount));
                        objectelement.SetElementValue("HandsCount", radio.HandsCount);
                        objectelement.SetElementValue("HandsRadius", radio.HandsRadius);

                        objectelement.SetAttributeValue("name", radio.ObjectName);

                        XElement objectposition = new XElement("position");
                        objectposition.SetAttributeValue("x", string.Format(format, "{0:0.00}", radio.BasePoint.X));
                        objectposition.SetAttributeValue("y", string.Format(format, "{0:0.00}", radio.BasePoint.Y));
                        objectposition.SetAttributeValue("z", string.Format(format, "{0:0.00}", radio.BasePoint.Z));
                        objectelement.Add(objectposition);

                        XElement objectrotate = new XElement("rotate");
                        objectrotate.SetAttributeValue("x", radio.AngleX);
                        objectrotate.SetAttributeValue("y", radio.AngleY);
                        objectrotate.SetAttributeValue("z", radio.AngleZ);
                        objectelement.Add(objectrotate);

                        XElement objectscale = new XElement("scale");
                        objectscale.SetAttributeValue("x", string.Format(format, "{0:0.00}", radio.ScaleX));
                        objectscale.SetAttributeValue("y", string.Format(format, "{0:0.00}", radio.ScaleY));
                        objectscale.SetAttributeValue("z", string.Format(format, "{0:0.00}", radio.ScaleZ));
                        objectelement.Add(objectscale);

                        objects.Add(objectelement);
                    }
                    scene.Add(objects);

                    document.Add(scene);
                    document.Save(ExportDialog.FileName);
                }
                catch (Exception)
                {
                    MessageBox.Show("Не получается экспортировать сцену!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Сохранить топологию сети с данными.
        /// </summary>
        /// <param name="scheme">Схема.</param>
        /// <param name="pathToSave">Путь к файлу сохранения.</param>
        public static void Save(Dictionary <int, List <Layer> > scheme, out string pathToSave)
        {
            var currentDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;
            var path             = Path.Combine(currentDirectory, SAVE_DIRECTORY);

            var document           = new XDocument();
            var networkBaseElement = new XElement(IOConstants.NETWORK_BASE_ELEMENT_NAME);

            var convolutionLayersAttribute = new XAttribute(IOConstants.TYPE_ATTRIBUTE_NAME,
                                                            IOConstants.CONVOLUTION_LAYER_TYPE);

            var subsamplingLayersAttribute = new XAttribute(IOConstants.TYPE_ATTRIBUTE_NAME,
                                                            IOConstants.SUBSAMPLING_LAYER_TYPE);

            var hiddenLayersAttribute = new XAttribute(IOConstants.TYPE_ATTRIBUTE_NAME,
                                                       IOConstants.HIDDEN_LAYER_TYPE);

            var outputLayersAttribute = new XAttribute(IOConstants.TYPE_ATTRIBUTE_NAME,
                                                       IOConstants.OUTPUT_LAYER_TYPE);

            var dataOfNeuronAttribute = new XAttribute(IOConstants.TYPE_ATTRIBUTE_NAME,
                                                       IOConstants.NEURONS_TYPE);

            var dataOfMapAttribute = new XAttribute(IOConstants.TYPE_ATTRIBUTE_NAME,
                                                    IOConstants.MAP_TYPE);

            foreach (var pair in scheme)
            {
                var layer = pair.Value.First();

                if (layer is InputLayer inputLayer)
                {
                    var map = inputLayer.GetData(Enums.LayerReturnType.Map) as FigureMap;

                    var inputDataSize = new XElement(IOConstants.INPUT_DATA_SIZE_ELEMENT_NAME,
                                                     map.Size);

                    networkBaseElement.Add(inputDataSize);
                }

                if (layer is ConvolutionLayer)
                {
                    var layersElements = new XElement(IOConstants.LAYERS_ELEMENT_NAME);

                    var layerCountAttribute = new XAttribute(IOConstants.COUNT_ATTRIBUTE_NAME,
                                                             pair.Value.Count);

                    layersElements.Add(layerCountAttribute);
                    layersElements.Add(convolutionLayersAttribute);

                    var index = 0;
                    foreach (ConvolutionLayer convolutionLayer in pair.Value)
                    {
                        var convolutionLayerElement = new XElement(IOConstants.CONVOLUTION_LAYER_ELEMENT_NAME);

                        var convolutionLayerNumberAttribute =
                            new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME, index);

                        convolutionLayerElement.Add(convolutionLayerNumberAttribute);

                        var filterMatrixElement = new XElement(IOConstants.FILTER_MATRIX_ELEMENT_NAME);

                        var filterMatrixSizeAttribute =
                            new XAttribute(IOConstants.SIZE_ATTRIBUTE_NAME, convolutionLayer.FilterMatrix.Size);

                        filterMatrixElement.Add(filterMatrixSizeAttribute);

                        foreach (var cell in convolutionLayer.FilterMatrix.Cells)
                        {
                            var cellElement = new XElement(IOConstants.CELL_ELEMENT_NAME, cell.Value);

                            var xAttribute = new XAttribute(IOConstants.X_ATTRIBUTE_NAME, cell.X);
                            var yAttribute = new XAttribute(IOConstants.Y_ATTRIBUTE_NAME, cell.Y);

                            cellElement.Add(xAttribute);
                            cellElement.Add(yAttribute);

                            filterMatrixElement.Add(cellElement);
                        }

                        convolutionLayerElement.Add(filterMatrixElement);
                        layersElements.Add(convolutionLayerElement);

                        ++index;
                    }

                    networkBaseElement.Add(layersElements);
                    continue;
                }

                if (layer is SubsamplingLayer)
                {
                    var layersElements = new XElement(IOConstants.LAYERS_ELEMENT_NAME);

                    var layerCountAttribute = new XAttribute(IOConstants.COUNT_ATTRIBUTE_NAME,
                                                             pair.Value.Count);

                    layersElements.Add(layerCountAttribute);
                    layersElements.Add(subsamplingLayersAttribute);

                    var index = 0;
                    foreach (SubsamplingLayer subsamplingLayer in pair.Value)
                    {
                        var subsamplingLayerElement =
                            new XElement(IOConstants.SUBSAMPLING_LAYER_ELEMENT_NAME);

                        var subsamplingLayerNumberAttribute =
                            new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME, index);

                        subsamplingLayerElement.Add(subsamplingLayerNumberAttribute);

                        var maxPoolingMatrixElement =
                            new XElement(IOConstants.MAX_POOLING_MATRIX_ELEMENT_NAME);

                        var maxPoolingMatrixAttribute =
                            new XAttribute(IOConstants.SIZE_ATTRIBUTE_NAME,
                                           subsamplingLayer.PoolingMatrix.Size);

                        maxPoolingMatrixElement.Add(maxPoolingMatrixAttribute);
                        subsamplingLayerElement.Add(maxPoolingMatrixElement);
                        layersElements.Add(subsamplingLayerElement);

                        ++index;
                    }

                    networkBaseElement.Add(layersElements);
                    continue;
                }

                if (layer is HiddenLayer)
                {
                    var layersElements = new XElement(IOConstants.LAYERS_ELEMENT_NAME);

                    var layerCountAttribute = new XAttribute(IOConstants.COUNT_ATTRIBUTE_NAME,
                                                             pair.Value.Count);

                    layersElements.Add(layerCountAttribute);
                    layersElements.Add(hiddenLayersAttribute);

                    var index = 0;
                    foreach (HiddenLayer hiddenLayer in pair.Value)
                    {
                        var hiddenLayerElement = new XElement(IOConstants.HIDDEN_LAYER_ELEMENT_NAME);

                        var hiddenLayerNumberAttribute = new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME,
                                                                        index);

                        hiddenLayerElement.Add(hiddenLayerNumberAttribute);
                        var neurons = hiddenLayer.GetData(Enums.LayerReturnType.Neurons) as List <NeuronFromMap>;

                        var hiddenLayerNeuronsElement = new XElement(IOConstants.NEURONS_ELEMENT_NAME);

                        var hiddenLayerNeuronsAttribute =
                            new XAttribute(IOConstants.COUNT_ATTRIBUTE_NAME, neurons.Count);

                        hiddenLayerNeuronsElement.Add(hiddenLayerNeuronsAttribute);

                        var neuronIndex = 0;
                        foreach (var neuron in neurons)
                        {
                            var neuronElement = new XElement(IOConstants.NEURON_ELEMENT_NAME);

                            var neuronAttribute = new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME,
                                                                 neuronIndex);

                            neuronElement.Add(neuronAttribute);

                            var weightIndex = 0;
                            foreach (var weight in neuron.Weights)
                            {
                                var weightElement = new XElement(IOConstants.WEIGHT_ELEMENT_NAME, weight);

                                var weighAttribute = new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME,
                                                                    weightIndex);

                                weightElement.Add(weighAttribute);
                                neuronElement.Add(weightElement);

                                ++weightIndex;
                            }

                            hiddenLayerNeuronsElement.Add(neuronElement);
                            ++neuronIndex;
                        }

                        hiddenLayerElement.Add(hiddenLayerNeuronsElement);
                        layersElements.Add(hiddenLayerElement);

                        ++index;
                    }

                    networkBaseElement.Add(layersElements);
                    continue;
                }

                if (layer is OutputLayer outputLayer)
                {
                    var layersElements = new XElement(IOConstants.LAYERS_ELEMENT_NAME);

                    var layerCountAttribute = new XAttribute(IOConstants.COUNT_ATTRIBUTE_NAME,
                                                             pair.Value.Count);

                    layersElements.Add(layerCountAttribute);
                    layersElements.Add(outputLayersAttribute);

                    var outputLayerElement = new XElement(IOConstants.OUTPUT_LAYER_ELEMENT_NAME);

                    var neurons = outputLayer.GetData(Enums.LayerReturnType.Neurons)
                                  as Dictionary <int, Neuron>;

                    var outputLayerNeuronsElement = new XElement(IOConstants.NEURONS_ELEMENT_NAME);

                    var outputLayerNeuronsAttribute = new XAttribute(IOConstants.COUNT_ATTRIBUTE_NAME,
                                                                     neurons.Count);

                    outputLayerNeuronsElement.Add(outputLayerNeuronsAttribute);

                    foreach (var neuron in neurons)
                    {
                        var neuronElement = new XElement(IOConstants.NEURON_ELEMENT_NAME);

                        var neuronAttribute = new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME,
                                                             neuron.Key);

                        neuronElement.Add(neuronAttribute);

                        var weightIndex = 0;
                        foreach (var weight in neuron.Value.Weights)
                        {
                            var weightElement = new XElement(IOConstants.WEIGHT_ELEMENT_NAME, weight);

                            var weighAttribute = new XAttribute(IOConstants.NUMBER_ATTRIBUTE_NAME,
                                                                weightIndex);

                            weightElement.Add(weighAttribute);
                            neuronElement.Add(weightElement);

                            ++weightIndex;
                        }

                        outputLayerNeuronsElement.Add(neuronElement);
                    }

                    outputLayerElement.Add(outputLayerNeuronsElement);
                    layersElements.Add(outputLayerElement);

                    networkBaseElement.Add(layersElements);
                    continue;
                }
            }

            document.Add(networkBaseElement);
            var fullPath = Path.Combine(path, DEFAULT_NAME);

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

            document.Save(fullPath);

            if (File.Exists(fullPath))
            {
                pathToSave = fullPath;
            }
            else
            {
                pathToSave = string.Empty;
                throw new Exception("Файл натроек не был сохранён!");
            }
        }
Beispiel #22
0
        /// <summary>
        /// creates an XML document object from a given KStructure object
        /// </summary>
        ///
        /// <param name="kStructure">KStructure object with a rank order and knowledge structure</param>
        ///
        /// <returns>XmlDocument object</returns>
        public XDocument createXml(KStructure kStructure)
        {
            // [SC] verifying that KStructure object is not null
            if (kStructure == null)
            {
                Log(Severity.Error, "Unable to transform knowledge structure into XML format. kStructure parameter is null. Returning null.");
                return(null);
            }

            // [SC] create xml document object
            XDocument doc = new XDocument();

            // [SC] add xml declaration to the document
            doc.Declaration = new XDeclaration("1.0", "UTF-8", "yes");

            // [SC] add a root element 'TwoA' and declare namespace attributes
            XElement twoAElem = new XElement(XMLFactory.TWOA_ELEM
                                             , new XAttribute(XMLFactory.XMLNS_ATTR, XMLFactory.twoa)
                                             , new XAttribute(XMLFactory.XSD_ATTR, XMLFactory.xsd)
                                             );

            doc.Add(twoAElem);

            // [SC] create a list of categories and a rank order
            if (kStructure.hasRankOrder())
            {
                RankOrder rankOrder = kStructure.rankOrder;
                rankOrder.sortAscending();

                // [SC] add 'TwoA/PCategories' list element
                XElement pcatsElem = new XElement(XMLFactory.PCATS_ELEM);
                twoAElem.Add(pcatsElem);

                // [SC] add 'TwoA/RankOrder' element
                XElement rankOrderElem = new XElement(XMLFactory.RANKORDER_ELEM);
                twoAElem.Add(rankOrderElem);

                // [SC] add 'TwoA/RankOrder/Params' list element
                XElement rankParamsElem = new XElement(XMLFactory.PARAMS_ELEM);
                rankOrderElem.Add(rankParamsElem);

                // [SC] add 'TwoA/RankOrder/Params.Threshold' element
                XElement thresholdElem = new XElement(XMLFactory.THRESHOLD_ELEM);
                rankParamsElem.Add(thresholdElem);
                thresholdElem.SetValue("" + rankOrder.Threshold);

                // [SC] create 'TwoA/RankOrder/Ranks' list element
                XElement ranksElem = new XElement(XMLFactory.RANKS_ELEM);
                rankOrderElem.Add(ranksElem);

                // [SC] iterate through ranks and create correspoinding XML elements
                for (int rankCounter = 0; rankCounter < rankOrder.getRankCount(); rankCounter++)
                {
                    Rank rank = rankOrder.getRankAt(rankCounter);

                    // [SC] add 'TwoA/RankOrder/Ranks/Rank' element
                    XElement rankElem = new XElement(XMLFactory.RANK_ELEM);
                    ranksElem.Add(rankElem);
                    // [SC] add 'TwoA/RankOrder/Ranks/Rank@Index' attribute to the 'Rank' element
                    XAttribute indexAttr = new XAttribute(XMLFactory.INDEX_ATTR, "" + rank.RankIndex);
                    rankElem.Add(indexAttr);

                    // [SC] interate through categories in the rank and create corresponding XML element and reference to it
                    for (int catCounter = 0; catCounter < rank.getCategoryCount(); catCounter++)
                    {
                        PCategory pcat = rank.getCategoryAt(catCounter);

                        // [SC] add 'TwoA/PCategories/PCategory' element with 'xsd:id' attribute
                        XElement pcatElem = new XElement(XMLFactory.PCAT_ELEM);
                        pcatsElem.Add(pcatElem);
                        // [SC] add 'TwoA/PCategories/PCategory@xsd:id' attribute
                        XAttribute idAttr = new XAttribute(XMLFactory.ID_ATTR, "" + pcat.Id);
                        pcatElem.Add(idAttr);
                        // [SC] add 'TwoA/PCategories/PCategory/Rating' element
                        XElement ratingElem = new XElement(XMLFactory.RATING_ELEM);
                        pcatElem.Add(ratingElem);
                        ratingElem.SetValue("" + pcat.Rating);

                        // [SC] add 'TwoA/RankOrder/Ranks/Rank/PCategory' element with 'xsd:idref' attribute
                        XElement pcatRefElem = new XElement(XMLFactory.PCAT_ELEM);
                        rankElem.Add(pcatRefElem);
                        // [SC] add 'TwoA/RankOrder/Ranks/Rank/PCategory@xsd:idref' attribute
                        XAttribute idrefAttr = new XAttribute(XMLFactory.IDREF_ATTR, "" + pcat.Id);
                        pcatRefElem.Add(idrefAttr);
                    }
                }
            }
            else
            {
                Log(Severity.Warning, "Rank order is missing while transforming KStructure object into XML format.");
            }

            // [SC] creates elements for 'KStructure'
            if (kStructure.hasRanks())
            {
                kStructure.sortAscending();

                // [SC] add 'TwoA/KStructure' element
                XElement kStructureElem = new XElement(XMLFactory.KSTRUCTURE_ELEM);
                twoAElem.Add(kStructureElem);

                // [SC] iterate through KSRanks and create corresponding XML elements
                for (int rankCounter = 0; rankCounter < kStructure.getRankCount(); rankCounter++)
                {
                    KSRank rank = kStructure.getRankAt(rankCounter);

                    // [SC] add 'TwoA/KStructure/KSRank' element
                    XElement ksRankElem = new XElement(XMLFactory.KSRANK_ELEM);
                    kStructureElem.Add(ksRankElem);
                    // [SC] add 'TwoA/KStructure/KSRank@Index' attribute
                    XAttribute indexAttr = new XAttribute(XMLFactory.INDEX_ATTR, "" + rank.RankIndex);
                    ksRankElem.Add(indexAttr);


                    // [SC] iterate through states and add corresponding XML elements
                    for (int stateCounter = 0; stateCounter < rank.getStateCount(); stateCounter++)
                    {
                        KState state = rank.getStateAt(stateCounter);

                        // [SC] add 'TwoA/KStructure/KSRank/KState' element with 'xsd:id' attribute
                        XElement stateElem = new XElement(XMLFactory.KSTATE_ELEM);
                        ksRankElem.Add(stateElem);
                        // [SC] add 'TwoA/KStructure/KSRank/KState@xsd:id' attribute
                        XAttribute idAttr = new XAttribute(XMLFactory.ID_ATTR, "" + state.Id);
                        stateElem.Add(idAttr);
                        // [SC] add 'TwoA/KStructure/KSRank/KState@Type' attribute
                        XAttribute typeAttr = new XAttribute(XMLFactory.TYPE_ATTR, "" + state.StateType);
                        stateElem.Add(typeAttr);

                        // [SC] add 'TwoA/KStructure/KSRank/KState/PCategories' list element
                        XElement pcatsElem = new XElement(XMLFactory.PCATS_ELEM);
                        stateElem.Add(pcatsElem);

                        // [SC] iterate through categories in the state
                        for (int catCounter = 0; catCounter < state.getCategoryCount(); catCounter++)
                        {
                            PCategory pcat = state.getCategoryAt(catCounter);

                            // [SC] add 'TwoA/KStructure/KSRank/KState/PCategories/PCategory' element with 'xsd:idref' attribute
                            XElement pcatElem = new XElement(XMLFactory.PCAT_ELEM);
                            pcatsElem.Add(pcatElem);
                            // [SC] add 'TwoA/KStructure/KSRank/KState/PCategories/PCategory@xsd:idref' attribute
                            XAttribute idrefAttr = new XAttribute(XMLFactory.IDREF_ATTR, "" + pcat.Id);
                            pcatElem.Add(idrefAttr);
                        }

                        // [SC] add 'TwoA/KStructure/KSRank/KState/PreviousStates' list element
                        XElement prevStatesElem = new XElement(XMLFactory.PREV_STATES_ELEM);
                        stateElem.Add(prevStatesElem);

                        // [SC] iterate through immediate prerequisite states in the gradient
                        for (int prevStateCounter = 0; prevStateCounter < state.getPrevStateCount(); prevStateCounter++)
                        {
                            KState prevState = state.getPrevStateAt(prevStateCounter);

                            // [SC] add 'TwoA/KStructure/KSRank/KState/PreviousStates/KState' element with 'xsd:idref' attribute
                            XElement prevStateElem = new XElement(XMLFactory.KSTATE_ELEM);
                            prevStatesElem.Add(prevStateElem);
                            // [SC] add 'TwoA/KStructure/KSRank/KState/PreviousStates/KState@xsd:idref' attribute
                            XAttribute idrefAttr = new XAttribute(XMLFactory.IDREF_ATTR, "" + prevState.Id);
                            prevStateElem.Add(idrefAttr);
                        }

                        // [SC] add 'TwoA/KStructure/KSRank/KState/NextStates' list element
                        XElement nextStatesElem = new XElement(XMLFactory.NEXT_STATES_ELEM);
                        stateElem.Add(nextStatesElem);

                        // [SC] iterate through immediate next states in the gradient
                        for (int nextStateCounter = 0; nextStateCounter < state.getNextStateCount(); nextStateCounter++)
                        {
                            KState nextState = state.getNextStateAt(nextStateCounter);

                            // [SC] add 'TwoA/KStructure/KSRank/KState/NextStates/KState' element with 'xsd:idref' attribute
                            XElement nextStateElem = new XElement(XMLFactory.KSTATE_ELEM);
                            nextStatesElem.Add(nextStateElem);
                            // [SC] add 'TwoA/KStructure/KSRank/KState/NextStates/KState@xsd:idref' attribute
                            XAttribute idrefAttr = new XAttribute(XMLFactory.IDREF_ATTR, "" + nextState.Id);
                            nextStateElem.Add(idrefAttr);
                        }
                    }
                }
            }
            else
            {
                Log(Severity.Warning, "Knowledge structure is missing while transforming KStructure object into XML format.");
            }

            return(doc);
        }
Beispiel #23
0
        public async Task Xml_Creat()
        {
            XDocument    xDocument    = new XDocument();//
            XDeclaration xDeclaration = xDocument.Declaration;

            ;
            XElement xElement = new XElement("asix",
                                             new XElement("RecipeParameter",
                                                          new XElement("ID", "0000"),
                                                          new XElement("Name", 123),
                                                          new XElement("CreatTime", DateTime.Now.ToString("D"))
                                                          ),
                                             new XElement("ProcessParameter",
                                                          new XElement("Pressure0", "1.5"),
                                                          new XElement("Pressure1", "1.2"),
                                                          new XElement("Pressure2", "1.3"),
                                                          new XElement("Pressure3", "1.2"),
                                                          new XElement("Pressure4", "1.3"),
                                                          new XElement("Temperature0", "20"),
                                                          new XElement("Temperature1", "45"),
                                                          new XElement("Temperature2", "32"),
                                                          new XElement("Temperature3", "25"),
                                                          new XElement("Temperature4", "13"),
                                                          new XElement("SynchronousDistance0", "1.5"),
                                                          new XElement("SynchronousDistance1", "1.2"),
                                                          new XElement("SynchronousDistance2", "1.3"),
                                                          new XElement("SynchronousDistance3", "1.2"),
                                                          new XElement("SynchronousDistance4", "1.3"),
                                                          new XElement("SynchronousSpeed0", "1.5"),
                                                          new XElement("SynchronousSpeed1", "1.2"),
                                                          new XElement("SynchronousSpeed2", "1.3"),
                                                          new XElement("SynchronousSpeed3", "1.2"),
                                                          new XElement("SynchronousSpeed4", "1.3")

                                                          ),
                                             new XElement("Asix",
                                                          new XElement("ID", "1"),
                                                          new XElement("Name", "1_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "2"),
                                                          new XElement("Name", "2_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "3"),
                                                          new XElement("Name", "3_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "4"),
                                                          new XElement("Name", "4_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "5"),
                                                          new XElement("Name", "5_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "6"),
                                                          new XElement("Name", "6_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "7"),
                                                          new XElement("Name", "7_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "8"),
                                                          new XElement("Name", "8_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "9"),
                                                          new XElement("Name", "9_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "10"),
                                                          new XElement("Name", "10_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "11"),
                                                          new XElement("Name", "11_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "12"),
                                                          new XElement("Name", "12_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "13"),
                                                          new XElement("Name", "13_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "14"),
                                                          new XElement("Name", "14_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "15"),
                                                          new XElement("Name", "15_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000")),
                                             new XElement("Asix",
                                                          new XElement("ID", "16"),
                                                          new XElement("Name", "16_Asix"),
                                                          new XElement("POsition0", "1000"),
                                                          new XElement("Speed0", "1000"),
                                                          new XElement("POsition1", "1000"),
                                                          new XElement("Speed1", "1000"),
                                                          new XElement("POsition2", "1000"),
                                                          new XElement("Speed2", "1000"),
                                                          new XElement("POsition3", "1000"),
                                                          new XElement("Speed3", "1000"),
                                                          new XElement("POsition4", "1000"),
                                                          new XElement("Speed4", "1000"),
                                                          new XElement("POsition5", "1000"),
                                                          new XElement("Speed5", "1000"),
                                                          new XElement("POsition6", "1000"),
                                                          new XElement("Speed6", "1000"),
                                                          new XElement("POsition7", "1000"),
                                                          new XElement("Speed7", "1000"),
                                                          new XElement("POsition8", "1000"),
                                                          new XElement("Speed8", "1000"),
                                                          new XElement("POsition9", "1000"),
                                                          new XElement("Speed9", "1000"))
                                             //new XElement("Asix",//带属性
                                             //           new XElement("ID", "5"),
                                             //            new XElement("Name", "END_Asix"),
                                             //           new XElement("AccDeler", "1000"),
                                             //           new XElement("DecDeler", "1000"),
                                             //           new XElement("POsition0", "100"),
                                             //           new XElement("POsition1", "1000"),
                                             //           new XElement("POsition2", "150"))

                                             );

            xDocument.Add(xElement);

            xmlfilename = "Repice_Xml/" + DateTime.Now.ToString("D") + ".xml";
            if (File.Exists(xmlfilename))
            {
                //System.Windows.MessageBox.Show("该表已经存在"); //  new XElement("POsition2", new XAttribute("AGE", 20)
                await((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("Wow, you typed Return and got", xmlfilename + "已经存在");
            }
            else
            {
                xDocument.Save(xmlfilename);
            }
        }
        public XDocument generateShip(string shipName)
        {
            //shipName = "AEGS_Gladius";
            XDocument xml         = new XDocument();
            string    loadoutName = "Default_Loadout_" + shipName;

            XElement PrefabsLibrary = new XElement("PrefabsLibrary");

            //PrefabsLibrary.Attribute("Name").Value = shipName+"_Ship";
            //PrefabsLibrary.Add(new XAttribute("Name", shipName + "_Ship"));
            PrefabsLibrary.Add(new XAttribute("Name", shipName));

            XElement Prefab   = new XElement("Prefab");
            string   prefabId = genPrefabID();

            //Prefab.Add(new XAttribute("Name", shipName));
            Prefab.Add(new XAttribute("Name", "Ship"));
            Prefab.Add(new XAttribute("Id", prefabId));
            // Prefab.Add(new XAttribute("Library", shipName + "_Ship"));
            Prefab.Add(new XAttribute("Library", shipName));

            XElement Objects = new XElement("Objects");

            ShipImplementation ship    = exporter.GetShipImplementation(shipName);
            Loadout            loadout = exporter.GetLoadout(loadoutName);

            Console.WriteLine(loadout.name);


            XElement Object   = new XElement("Object");
            string   partid   = genID();
            string   layerid  = genID();
            string   parentid = "0";

            parentid = partid;

            Object = addObjects(Object, ship.parts.First(), loadout, parentid, partid, layerid);
            //Object = addPrefabsFromObjectContainers(Object, ship, parentid, layerid);
            Object = addObjectsFromObjectContainers(Object, ship, parentid, layerid);

            if (Object.Attribute("Name") != null)
            {
                Objects.Add(Object);
            }
            //Objects.Add(Object);

            XElement ObjectsNew = new XElement("Objects");

            foreach (XElement obj in Objects.Descendants("Object"))
            {
                XElement ObjectNew = new XElement("Object");
                ObjectNew.Add(new XElement("Properties"));
                foreach (XAttribute atr in obj.Attributes())
                {
                    ObjectNew.Add(atr);
                }
                if (obj.Element("Components") != null)
                {
                    ObjectNew.Add(obj.Element("Components"));
                }

                if (ObjectNew.Attribute("Name") != null)
                {
                    ObjectsNew.Add(ObjectNew);
                }
            }

            Prefab.Add(ObjectsNew);
            PrefabsLibrary.Add(Prefab);
            foreach (XElement pr in prefabs)
            {
                PrefabsLibrary.Add(pr);
            }
            xml.Add(PrefabsLibrary);

            //XDocument xmlpreflib = XDocument.Load(prefablib);
            //XElement preflibel = xmlpreflib.Element("PrefabsLibrary");
            //xml.Add(preflibel);

            return(xml);
        }
Beispiel #25
0
        public void SaveNewPlayerConfig()
        {
            XDocument doc = new XDocument();

            UnsavedSettings = false;

            if (doc.Root == null)
            {
                doc.Add(new XElement("config"));
            }

            doc.Root.Add(
                new XAttribute("language", TextManager.Language),
                new XAttribute("masterserverurl", MasterServerUrl),
                new XAttribute("autocheckupdates", AutoCheckUpdates),
                new XAttribute("musicvolume", musicVolume),
                new XAttribute("soundvolume", soundVolume),
                new XAttribute("verboselogging", VerboseLogging),
                new XAttribute("savedebugconsolelogs", SaveDebugConsoleLogs),
                new XAttribute("enablesplashscreen", EnableSplashScreen),
                new XAttribute("usesteammatchmaking", useSteamMatchmaking),
                new XAttribute("quickstartsub", QuickStartSubmarineName),
                new XAttribute("requiresteamauthentication", requireSteamAuthentication),
                new XAttribute("autoupdateworkshopitems", AutoUpdateWorkshopItems),
                new XAttribute("aimassistamount", aimAssistAmount));

            if (!ShowUserStatisticsPrompt)
            {
                doc.Root.Add(new XAttribute("senduserstatistics", sendUserStatistics));
            }

            XElement gMode = doc.Root.Element("graphicsmode");

            if (gMode == null)
            {
                gMode = new XElement("graphicsmode");
                doc.Root.Add(gMode);
            }

            if (GraphicsWidth == 0 || GraphicsHeight == 0)
            {
                gMode.ReplaceAttributes(new XAttribute("displaymode", windowMode));
            }
            else
            {
                gMode.ReplaceAttributes(
                    new XAttribute("width", GraphicsWidth),
                    new XAttribute("height", GraphicsHeight),
                    new XAttribute("vsync", VSyncEnabled),
                    new XAttribute("displaymode", windowMode));
            }

            XElement audio = doc.Root.Element("audio");

            if (audio == null)
            {
                audio = new XElement("audio");
                doc.Root.Add(audio);
            }
            audio.ReplaceAttributes(
                new XAttribute("musicvolume", musicVolume),
                new XAttribute("soundvolume", soundVolume),
                new XAttribute("voicesetting", VoiceSetting),
                new XAttribute("voicecapturedevice", VoiceCaptureDevice ?? ""),
                new XAttribute("noisegatethreshold", NoiseGateThreshold));

            XElement gSettings = doc.Root.Element("graphicssettings");

            if (gSettings == null)
            {
                gSettings = new XElement("graphicssettings");
                doc.Root.Add(gSettings);
            }

            gSettings.ReplaceAttributes(
                new XAttribute("particlelimit", ParticleLimit),
                new XAttribute("lightmapscale", LightMapScale),
                new XAttribute("specularity", SpecularityEnabled),
                new XAttribute("chromaticaberration", ChromaticAberrationEnabled),
                new XAttribute("losmode", LosMode),
                new XAttribute("hudscale", HUDScale),
                new XAttribute("inventoryscale", InventoryScale));

            foreach (ContentPackage contentPackage in SelectedContentPackages)
            {
                doc.Root.Add(new XElement("contentpackage",
                                          new XAttribute("path", contentPackage.Path)));
            }

            var keyMappingElement = new XElement("keymapping");

            doc.Root.Add(keyMappingElement);
            for (int i = 0; i < keyMapping.Length; i++)
            {
                if (keyMapping[i].MouseButton == null)
                {
                    keyMappingElement.Add(new XAttribute(((InputType)i).ToString(), keyMapping[i].Key));
                }
                else
                {
                    keyMappingElement.Add(new XAttribute(((InputType)i).ToString(), keyMapping[i].MouseButton));
                }
            }

            var gameplay       = new XElement("gameplay");
            var jobPreferences = new XElement("jobpreferences");

            foreach (string jobName in JobPreferences)
            {
                jobPreferences.Add(new XElement("job", new XAttribute("identifier", jobName)));
            }
            gameplay.Add(jobPreferences);
            doc.Root.Add(gameplay);

            var playerElement = new XElement("player",
                                             new XAttribute("name", defaultPlayerName ?? ""),
                                             new XAttribute("headindex", CharacterHeadIndex),
                                             new XAttribute("gender", CharacterGender),
                                             new XAttribute("race", CharacterRace),
                                             new XAttribute("hairindex", CharacterHairIndex),
                                             new XAttribute("beardindex", CharacterBeardIndex),
                                             new XAttribute("moustacheindex", CharacterMoustacheIndex),
                                             new XAttribute("faceattachmentindex", CharacterFaceAttachmentIndex));

            doc.Root.Add(playerElement);

#if CLIENT
            if (Tutorial.Tutorials != null)
            {
                foreach (Tutorial tutorial in Tutorial.Tutorials)
                {
                    if (tutorial.Completed && !CompletedTutorialNames.Contains(tutorial.Name))
                    {
                        CompletedTutorialNames.Add(tutorial.Name);
                    }
                }
            }
#endif
            var tutorialElement = new XElement("tutorials");
            foreach (string tutorialName in CompletedTutorialNames)
            {
                tutorialElement.Add(new XElement("Tutorial", new XAttribute("name", tutorialName)));
            }
            doc.Root.Add(tutorialElement);

            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent              = true,
                OmitXmlDeclaration  = true,
                NewLineOnAttributes = true
            };

            try
            {
                using (var writer = XmlWriter.Create(playerSavePath, settings))
                {
                    doc.WriteTo(writer);
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Saving game settings failed.", e);
                GameAnalyticsManager.AddErrorEventOnce("GameSettings.Save:SaveFailed", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       "Saving game settings failed.\n" + e.Message + "\n" + e.StackTrace);
            }
        }
        protected void SaveToXml(string path)
        {
            XDocument xDoc = new XDocument();

            XElement xRoot = new XElement("ThemeColors");

            // //
            //

            xRoot.Add(new XElement("ListZebraBack1", ListZebraBack1));
            xRoot.Add(new XElement("ListZebraBack2", ListZebraBack2));
            xRoot.Add(new XElement("ListZebraFore", ListZebraFore));

            xRoot.Add(new XElement("TreeDescBack", TreeDescBack));
            xRoot.Add(new XElement("TreeDescFore", TreeDescFore));
            xRoot.Add(new XElement("TreeLeafBack", TreeLeafBack));
            xRoot.Add(new XElement("TreeLeafFore", TreeLeafFore));
            xRoot.Add(new XElement("TreeContainerBack", TreeContainerBack));
            xRoot.Add(new XElement("TreeContainerFore", TreeContainerFore));

            xRoot.Add(new XElement("TextDarkBack", TextDarkBack));
            xRoot.Add(new XElement("TextDarkFore", TextDarkFore));
            xRoot.Add(new XElement("TextLightBack", TextLightBack));
            xRoot.Add(new XElement("TextLightFore", TextLightFore));

            xRoot.Add(new XElement("GalleryItemBack", GalleryItemBack));
            xRoot.Add(new XElement("GalleryItemBorder", GalleryItemBorder));
            xRoot.Add(new XElement("GalleryItemFore", GalleryItemFore));

            xRoot.Add(new XElement("DialogLightBack", DialogLightBack));

            xRoot.Add(new XElement("ToolBarLightBack", ToolBarLightBack));
            xRoot.Add(new XElement("ToolBarLightFore", ToolBarLightFore));

            xRoot.Add(new XElement("AppTitleBack", AppTitleBack));
            xRoot.Add(new XElement("AppTitleFore", AppTitleFore));

            xRoot.Add(new XElement("AppStatusBack", AppStatusBack));
            xRoot.Add(new XElement("AppStatusFore", AppStatusFore));

            xRoot.Add(new XElement("IconBack", IconBack));
            xRoot.Add(new XElement("IconBorder", IconBorder));
            xRoot.Add(new XElement("IconFore", IconFore));

            xRoot.Add(new XElement("ThemeBack", ThemeBack));

            //
            // //
            //

            xDoc.Add(xRoot);

            RscStore store = new RscStore();

            System.IO.Stream strm = store.CreateFile(path);

            xDoc.Save(strm);

            strm.Close();

            //
            // //
        }
Beispiel #27
0
        private void SaveIntervalXML_Click(object sender, RoutedEventArgs e)
        {
            if (intervalControl.Open)
            {
                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.Filter     = "Файл Xml|*.xml";
                sfd.DefaultExt = "xml";

                if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                int      column = 4, row = intervalControl.IntervalGrid.Count();
                double[] lBorder              = intervalControl.IntervalGrid.Select(c => c.leftBorder).ToArray();
                double[] rBorder              = intervalControl.IntervalGrid.Select(c => c.rightBorder).ToArray();
                double[] frequency            = intervalControl.IntervalGrid.Select(c => c.frequency).ToArray();
                double[] accumulatedFrequency = intervalControl.IntervalGrid.Select(c => c.accumulatedFrequency).ToArray();

                XDocument  xdoc      = new XDocument();
                XElement   InputData = new XElement("InputData");
                XAttribute col1      = new XAttribute("LeftBorder", "Левая граница");
                InputData.Add(col1);
                XAttribute col2 = new XAttribute("RightBorder", "Правая граница");
                InputData.Add(col2);
                XAttribute col3 = new XAttribute("Frequency", "Частота");
                InputData.Add(col3);
                XAttribute col4 = new XAttribute("AccumulatedFrequency", "Накопленная частота");
                InputData.Add(col4);

                for (int i = 0; i < row; i++)
                {
                    XElement dataRowElement = new XElement("Row");

                    for (int j = 0; j < column; j++)
                    {
                        string lb = "", rb = "", fre = "", acc = "";
                        lb  = lBorder[i].ToString();
                        rb  = rBorder[i].ToString();
                        fre = frequency[i].ToString();
                        acc = accumulatedFrequency[i].ToString();

                        XElement dataColumnElement1 = new XElement("LeftBorder", lb);
                        XElement dataColumnElement2 = new XElement("RightBorder", rb);
                        XElement dataColumnElement3 = new XElement("Frequency", fre);
                        XElement dataColumnElement4 = new XElement("AccumulatedFrequency", acc);
                        dataRowElement.Add(dataColumnElement1);
                        dataRowElement.Add(dataColumnElement2);
                        dataRowElement.Add(dataColumnElement3);
                    }

                    InputData.Add(dataRowElement);
                }

                XElement analysis = new XElement("DataAnalysis");
                analysis.Add(InputData);
                xdoc.Add(analysis);
                xdoc.Save(sfd.FileName);
            }
            else
            {
                dialogError.IsOpen = true;
            }
        }
        public static XDocument ConvertEntityToXml <T>(T entity) where T : class, new()
        {
            T obj = entity;

            if ((object)obj == null)
            {
                obj = Activator.CreateInstance <T>();
            }
            entity = obj;
            XDocument xdocument = new XDocument();

            xdocument.Add((object)new XElement((XName)"xml"));
            XElement           root            = xdocument.Root;
            Func <string, int> orderByPropName = new Func <string, int>(Enumerable.ToList <string>((IEnumerable <string>) new string[13]
            {
                "ToUserName",
                "FromUserName",
                "CreateTime",
                "MsgType",
                "Content",
                "ArticleCount",
                "Articles",
                "FuncFlag",
                "Title ",
                "Description ",
                "PicUrl",
                "Url",
                "Image"
            }).IndexOf);

            foreach (PropertyInfo propertyInfo in Enumerable.ToList <PropertyInfo>((IEnumerable <PropertyInfo>)Enumerable.OrderBy <PropertyInfo, int>((IEnumerable <PropertyInfo>)entity.GetType().GetProperties(), (Func <PropertyInfo, int>)(p => orderByPropName(p.Name)))))
            {
                string name = propertyInfo.Name;
                if (name == "Articles")
                {
                    XElement xelement = new XElement((XName)"Articles");
                    foreach (Article entity1 in propertyInfo.GetValue((object)entity, (object[])null) as List <Article> )
                    {
                        IEnumerable <XElement> enumerable = EntityHelper.ConvertEntityToXml <Article>(entity1).Root.Elements();
                        xelement.Add((object)new XElement((XName)"item", (object)enumerable));
                    }
                    root.Add((object)xelement);
                }
                else if (name == "Image")
                {
                    XElement xelement = new XElement((XName)"Image");
                    xelement.Add((object)new XElement((XName)"MediaId", (object)new XCData(((Image)propertyInfo.GetValue((object)entity, (object[])null)).MediaId)));
                    root.Add((object)xelement);
                }
                else if (name == "")
                {
                    root.Add((object)new XElement((XName)name, (object)new XCData(propertyInfo.GetValue((object)entity, (object[])null) as string ?? "")));
                }
                else
                {
                    switch (propertyInfo.PropertyType.Name)
                    {
                    case "String":
                        root.Add((object)new XElement((XName)name, (object)new XCData(propertyInfo.GetValue((object)entity, (object[])null) as string ?? "")));
                        break;

                    case "DateTime":
                        root.Add((object)new XElement((XName)name, (object)((DateTime)propertyInfo.GetValue((object)entity, (object[])null)).Ticks));
                        break;

                    case "Boolean":
                        if (name == "FuncFlag")
                        {
                            root.Add((object)new XElement((XName)name, (bool)propertyInfo.GetValue((object)entity, (object[])null) ? (object)"1" : (object)"0"));
                            break;
                        }
                        else
                        {
                            goto default;
                        }

                    case "ResponseMsgType":
                        root.Add((object)new XElement((XName)name, (object)propertyInfo.GetValue((object)entity, (object[])null).ToString().ToLower()));
                        break;

                    case "Article":
                        root.Add((object)new XElement((XName)name, (object)propertyInfo.GetValue((object)entity, (object[])null).ToString().ToLower()));
                        break;

                    default:
                        root.Add((object)new XElement((XName)name, propertyInfo.GetValue((object)entity, (object[])null)));
                        break;
                    }
                }
            }
            return(xdocument);
        }
Beispiel #29
0
        private bool TryResolveReferences(out XDocument resolutionResults, out string errorMessage)
        {
            resolutionResults = new XDocument();
            errorMessage      = string.Empty;

            if (!File.Exists(MsBuildPath))
            {
                errorMessage = string.Format("Unable to locate {0}", MsBuildPath.Red().Bold());
                return(false);
            }

            // Put ReferenceResolver.xml and intermediate result files into a temporary dir
            var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(tempDir);

            try
            {
                _referenceResolverPath = Path.Combine(tempDir, ReferenceResolverFileName);
                var assembly             = typeof(WrapCommand).GetTypeInfo().Assembly;
                var embeddedResourceName = "compiler/resources/" + ReferenceResolverFileName;
                using (var stream = assembly.GetManifestResourceStream(embeddedResourceName))
                {
                    File.WriteAllText(_referenceResolverPath, stream.ReadToEnd());
                }

                resolutionResults.Add(new XElement("root"));
                var projectFiles = new List <string> {
                    CsProjectPath
                };
                var intermediateResultFile = Path.Combine(tempDir, Path.GetRandomFileName());

                for (var i = 0; i != projectFiles.Count; i++)
                {
                    var properties = new[]
                    {
                        string.Format("/p:CustomAfterMicrosoftCommonTargets=\"{0}\"", _referenceResolverPath),
                        string.Format("/p:ResultFilePath=\"{0}\"", intermediateResultFile),
                        string.Format("/p:Configuration={0}", Configuration),
                        "/p:DesignTimeBuild=true",
                        "/p:BuildProjectReferences=false",
                        "/p:_ResolveReferenceDependencies=true" // Dump entire assembly reference closure
                    };

                    var msBuildArgs = string.Format("\"{0}\" /t:ResolveAndDump {1}",
                                                    projectFiles[i], string.Join(" ", properties));

                    Reports.Verbose.WriteLine("Resolving references for {0}", projectFiles[i].Bold());
                    Reports.Verbose.WriteLine();
                    Reports.Verbose.WriteLine("Command:");
                    Reports.Verbose.WriteLine();
                    Reports.Verbose.WriteLine("\"{0}\" {1}", MsBuildPath, msBuildArgs);
                    Reports.Verbose.WriteLine();
                    Reports.Verbose.WriteLine("MSBuild output:");
                    Reports.Verbose.WriteLine();

                    var startInfo = new ProcessStartInfo()
                    {
                        UseShellExecute        = false,
                        FileName               = MsBuildPath,
                        Arguments              = msBuildArgs,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true
                    };

                    var process = Process.Start(startInfo);
                    var stdOut  = process.StandardOutput.ReadToEnd();
                    var stdErr  = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    Reports.Verbose.WriteLine(stdOut);

                    if (process.ExitCode != 0)
                    {
                        errorMessage = string.Format("Failed to resolve references for {0}",
                                                     projectFiles[i].Red().Bold());
                        return(false);
                    }

                    var projectXDoc = XDocument.Parse(File.ReadAllText(intermediateResultFile));

                    foreach (var item in GetItemsByType(projectXDoc.Root, type: "ProjectReference"))
                    {
                        var relativePath = item.Attribute("evaluated").Value;
                        var fullPath     = PathUtility.GetAbsolutePath(projectFiles[i], relativePath);
                        if (!projectFiles.Contains(fullPath))
                        {
                            projectFiles.Add(fullPath);
                        }
                    }

                    resolutionResults.Root.Add(projectXDoc.Root);
                }
            }
            finally
            {
                FileOperationUtils.DeleteFolder(tempDir);
            }

            return(true);
        }
Beispiel #30
0
        /// <summary>
        /// The Create Cloud Service operation creates a Windows Azure cloud
        /// service in a Windows Azure subscription.
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters used to specify how the Create procedure will
        /// function.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationStatusResponse> BeginCreatingAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Description == null)
            {
                throw new ArgumentNullException("parameters.Description");
            }
            if (parameters.GeoRegion == null)
            {
                throw new ArgumentNullException("parameters.GeoRegion");
            }
            if (parameters.Label == null)
            {
                throw new ArgumentNullException("parameters.Label");
            }
            if (parameters.Name == null)
            {
                throw new ArgumentNullException("parameters.Name");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
            }

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + this.Client.Credentials.SubscriptionId.Trim() + "/CloudServices/" + parameters.Name.Trim() + "/";

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2013-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string    requestContent = null;
                XDocument requestDoc     = new XDocument();

                XElement cloudServiceElement = new XElement(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(cloudServiceElement);

                XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                nameElement.Value = parameters.Name;
                cloudServiceElement.Add(nameElement);

                XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
                labelElement.Value = parameters.Label;
                cloudServiceElement.Add(labelElement);

                XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
                descriptionElement.Value = parameters.Description;
                cloudServiceElement.Add(descriptionElement);

                XElement geoRegionElement = new XElement(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure"));
                geoRegionElement.Value = parameters.GeoRegion;
                cloudServiceElement.Add(geoRegionElement);

                requestContent      = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationStatusResponse result = null;
                    result            = new OperationStatusResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Beispiel #31
0
        public static void SalvarXMLMunicipios(string uf, string cidade, int codigomunicipio, string padrao, bool forcaAtualizacao)
        {
            try
            {
                if (uf != null)
                {
                    Municipio mun = null;
                    for (int i = 0; i < Propriedade.Municipios.Count; ++i)
                    {
                        if (Propriedade.Municipios[i].CodigoMunicipio == codigomunicipio)
                        {
                            mun = Propriedade.Municipios[i];
                            break;
                        }
                    }

                    if (padrao == PadroesNFSe.NaoIdentificado.ToString() && mun != null)
                    {
                        Propriedade.Municipios.Remove(mun);
                    }

                    if (padrao != PadroesNFSe.NaoIdentificado.ToString())
                    {
                        if (mun != null)
                        {
                            ///
                            /// é o mesmo padrão definido?
                            /// o parametro "forcaAtualizacao" é "true" somente quando vier da aba "Municipios definidos"
                            /// desde que o datagrid atualiza automaticamente o membro "padrao" da classe "Municipio" quando ele é alterado.
                            if (mun.PadraoStr == padrao && !forcaAtualizacao)
                            {
                                return;
                            }

                            mun.Padrao    = GetPadraoFromString(padrao);
                            mun.PadraoStr = padrao;
                        }
                        else
                        {
                            Propriedade.Municipios.Add(new Municipio(codigomunicipio, uf, cidade.Trim(), GetPadraoFromString(padrao)));
                        }
                    }
                }
                if (System.IO.File.Exists(Propriedade.NomeArqXMLMunicipios))
                {
                    ///
                    /// faz uma copia por segurança
                    if (System.IO.File.Exists(Propriedade.NomeArqXMLMunicipios + ".bck"))
                    {
                        System.IO.File.Delete(Propriedade.NomeArqXMLMunicipios + ".bck");
                    }
                    System.IO.File.Copy(Propriedade.NomeArqXMLMunicipios, Propriedade.NomeArqXMLMunicipios + ".bck");
                }

                /*
                 * <nfes_municipios>
                 *  <Registro ID="4125506" Nome="São José dos Pinais - PR" Padrao="GINFES" />
                 * </nfes_municipios>
                 */

                var      xml       = new XDocument(new XDeclaration("1.0", "utf-8", null));
                XElement elementos = new XElement("nfes_municipios");
                var      r         = (from ss in Propriedade.Municipios orderby ss.Nome select ss);
                foreach (Municipio item in r)//Propriedade.Municipios)
                {
                    elementos.Add(new XElement(NFeStrConstants.Registro,
                                               new XAttribute(TpcnResources.ID.ToString(), item.CodigoMunicipio.ToString()),
                                               new XAttribute(NFeStrConstants.Nome, item.Nome.Trim()),
                                               new XAttribute(NFeStrConstants.Padrao, item.PadraoStr)));
                }
                xml.Add(elementos);
                xml.Save(Propriedade.NomeArqXMLMunicipios);
            }
            catch (Exception ex)
            {
                //recupera a copia feita se houve erro na criacao do XML de municipios
                if (System.IO.File.Exists(Propriedade.NomeArqXMLMunicipios + ".bck"))
                {
                    Functions.Move(Propriedade.NomeArqXMLMunicipios + ".bck", Propriedade.NomeArqXMLMunicipios);
                }
                throw ex;
            }
        }
Beispiel #32
0
        /// <summary> Saves the current world list to worlds.xml. Thread-safe. </summary>
        public static void SaveWorldList()
        {
            const string worldListTempFileName = Paths.WorldListFileName + ".tmp";

            // Save world list
            lock ( SyncRoot ) {
                XDocument doc  = new XDocument();
                XElement  root = new XElement("fCraftWorldList");

                foreach (World world in Worlds)
                {
                    XElement temp = new XElement("World");
                    temp.Add(new XAttribute("name", world.Name));

                    if (world.AccessSecurity.HasRestrictions)
                    {
                        temp.Add(world.AccessSecurity.Serialize(AccessSecurityXmlTagName));
                    }
                    if (world.BuildSecurity.HasRestrictions)
                    {
                        temp.Add(world.BuildSecurity.Serialize(BuildSecurityXmlTagName));
                    }

                    // save backup settings
                    switch (world.BackupEnabledState)
                    {
                    case YesNoAuto.Yes:
                        temp.Add(new XAttribute("backup", world.BackupInterval.ToSecondsString()));
                        break;

                    case YesNoAuto.No:
                        temp.Add(new XAttribute("backup", 0));
                        break;
                    }

                    if (world.Preload)
                    {
                        temp.Add(new XAttribute("noUnload", true));
                    }
                    if (world.IsHidden)
                    {
                        temp.Add(new XAttribute("hidden", true));
                    }
                    temp.Add(world.BlockDB.SaveSettings());

                    World world1 = world; // keeping ReSharper happy
                    foreach (Rank mainedRank in RankManager.Ranks.Where(r => r.MainWorld == world1))
                    {
                        temp.Add(new XElement(RankMainXmlTagName, mainedRank.FullName));
                    }

                    // save loaded/map-changed information
                    if (!String.IsNullOrEmpty(world.LoadedBy))
                    {
                        temp.Add(new XElement("LoadedBy", world.LoadedBy));
                    }
                    if (world.LoadedOn != DateTime.MinValue)
                    {
                        temp.Add(new XElement("LoadedOn", world.LoadedOn.ToUnixTime()));
                    }
                    if (!String.IsNullOrEmpty(world.MapChangedBy))
                    {
                        temp.Add(new XElement("MapChangedBy", world.MapChangedBy));
                    }
                    if (world.MapChangedOn != DateTime.MinValue)
                    {
                        temp.Add(new XElement("MapChangedOn", world.MapChangedOn.ToUnixTime()));
                    }

                    // save environmental settings
                    XElement elEnv = new XElement(EnvironmentXmlTagName);
                    if (world.CloudColor > -1)
                    {
                        elEnv.Add(new XAttribute("cloud", world.CloudColor));
                    }
                    if (world.FogColor > -1)
                    {
                        elEnv.Add(new XAttribute("fog", world.FogColor));
                    }
                    if (world.SkyColor > -1)
                    {
                        elEnv.Add(new XAttribute("sky", world.SkyColor));
                    }
                    if (world.EdgeLevel > -1)
                    {
                        elEnv.Add(new XAttribute("level", world.EdgeLevel));
                    }
                    if (world.EdgeBlock != Block.Water)
                    {
                        elEnv.Add(new XAttribute("edge", world.EdgeBlock));
                    }
                    if (elEnv.HasAttributes)
                    {
                        temp.Add(elEnv);
                    }

                    // save lock information
                    if (world.IsLocked)
                    {
                        temp.Add(new XAttribute("locked", true));
                        if (!String.IsNullOrEmpty(world.LockedBy))
                        {
                            temp.Add(new XElement("LockedBy", world.LockedBy));
                        }
                        if (world.LockedOn != DateTime.MinValue)
                        {
                            temp.Add(new XElement("LockedOn", world.LockedOn.ToUnixTime()));
                        }
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(world.UnlockedBy))
                        {
                            temp.Add(new XElement("UnlockedBy", world.UnlockedBy));
                        }
                        if (world.UnlockedOn != DateTime.MinValue)
                        {
                            temp.Add(new XElement("UnlockedOn", world.UnlockedOn.ToUnixTime()));
                        }
                    }

                    if (!String.IsNullOrEmpty(world.Greeting))
                    {
                        temp.Add(new XElement("Greeting", world.Greeting));
                    }

                    root.Add(temp);
                }
                root.Add(new XAttribute("main", MainWorld.Name));

                doc.Add(root);
                doc.Save(worldListTempFileName);
                Paths.MoveOrReplaceFile(worldListTempFileName, Paths.WorldListFileName);
            }
        }
Beispiel #33
0
        /// <summary>
        /// 将实体转为XML
        /// </summary>
        /// <typeparam name="T">RequestMessage或ResponseMessage</typeparam>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public static XDocument ConvertEntityToXml <T>(this T entity) where T : class, new()
        {
            entity = entity ?? new T();
            var doc = new XDocument();

            doc.Add(new XElement("xml"));
            var root = doc.Root;

            /* 注意!
             * 经过测试,微信对字段排序有严格要求,这里对排序进行强制约束
             */
            var propNameOrder = new List <string>()
            {
                "ToUserName", "FromUserName", "CreateTime", "MsgType"
            };

            //不同返回类型需要对应不同特殊格式的排序
            if (entity is ResponseMessageNews)
            {
                propNameOrder.AddRange(new[] { "ArticleCount", "Articles", "FuncFlag", /*以下是Atricle属性*/ "Title ", "Description ", "PicUrl", "Url" });
            }
            else if (entity is ResponseMessageTransfer_Customer_Service)
            {
                propNameOrder.AddRange(new[] { "TransInfo", "KfAccount", "FuncFlag" });
            }
            else if (entity is ResponseMessageMusic)
            {
                propNameOrder.AddRange(new[] { "Music", "FuncFlag", "ThumbMediaId", /*以下是Music属性*/ "Title ", "Description ", "MusicUrl", "HQMusicUrl" });
            }
            else if (entity is ResponseMessageImage)
            {
                propNameOrder.AddRange(new[] { "Image", /*以下是Image属性*/ "MediaId " });
            }
            else if (entity is ResponseMessageVoice)
            {
                propNameOrder.AddRange(new[] { "Voice", /*以下是Voice属性*/ "MediaId " });
            }
            else if (entity is ResponseMessageVideo)
            {
                propNameOrder.AddRange(new[] { "Video", /*以下是Video属性*/ "MediaId ", "Title", "Description" });
            }
            else
            {
                //如Text类型
                propNameOrder.AddRange(new[] { "Content", "FuncFlag" });
            }

            Func <string, int> orderByPropName = propNameOrder.IndexOf;

            var props = entity.GetType().GetProperties().OrderBy(p => orderByPropName(p.Name)).ToList();

            foreach (var prop in props)
            {
                var propName = prop.Name;
                if (propName == "Articles")
                {
                    //文章列表
                    var atriclesElement = new XElement("Articles");
                    var articales       = prop.GetValue(entity, null) as List <Article>;
                    foreach (var articale in articales)
                    {
                        var subNodes = ConvertEntityToXml(articale).Root.Elements();
                        atriclesElement.Add(new XElement("item", subNodes));
                    }
                    root.Add(atriclesElement);
                }
                else if (propName == "TransInfo")
                {
                    var transInfoElement = new XElement("TransInfo");
                    var transInfo        = prop.GetValue(entity, null) as List <CustomerServiceAccount>;
                    foreach (var account in transInfo)
                    {
                        var trans = ConvertEntityToXml(account).Root.Elements();
                        transInfoElement.Add(trans);
                    }

                    root.Add(transInfoElement);
                }
                else if (propName == "Music" || propName == "Image" || propName == "Video" || propName == "Voice")
                {
                    //音乐、图片、视频、语音格式
                    var musicElement = new XElement(propName);
                    var media        = prop.GetValue(entity, null);// as Music;
                    var subNodes     = ConvertEntityToXml(media).Root.Elements();
                    musicElement.Add(subNodes);
                    root.Add(musicElement);
                }
                else if (propName == "PicList")
                {
                    var picListElement = new XElement("PicList");
                    var picItems       = prop.GetValue(entity, null) as List <PicItem>;
                    foreach (var picItem in picItems)
                    {
                        var item = ConvertEntityToXml(picItem).Root.Elements();
                        picListElement.Add(item);
                    }
                    root.Add(picListElement);
                }
                //else if (propName == "KfAccount")
                //{
                //    //TODO:可以交给string处理
                //    root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower()));
                //}
                else
                {
                    //其他非特殊类型
                    switch (prop.PropertyType.Name)
                    {
                    case "String":
                        root.Add(new XElement(propName,
                                              new XCData(prop.GetValue(entity, null) as string ?? "")));
                        break;

                    case "DateTime":
                        root.Add(new XElement(propName,
                                              DateTimeHelper.GetWeixinDateTime(
                                                  (DateTime)prop.GetValue(entity, null))));
                        break;

                    case "Boolean":
                        if (propName == "FuncFlag")
                        {
                            root.Add(new XElement(propName, (bool)prop.GetValue(entity, null) ? "1" : "0"));
                        }
                        else
                        {
                            goto default;
                        }
                        break;

                    case "ResponseMsgType":
                        root.Add(new XElement(propName, new XCData(prop.GetValue(entity, null).ToString().ToLower())));
                        break;

                    case "Article":
                        root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower()));
                        break;

                    case "TransInfo":
                        root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower()));
                        break;

                    default:
                        if (prop.PropertyType.IsClass && prop.PropertyType.IsPublic)
                        {
                            //自动处理其他实体属性
                            var subEntity = prop.GetValue(entity, null);
                            var subNodes  = ConvertEntityToXml(subEntity).Root.Elements();
                            root.Add(new XElement(propName, subNodes));
                        }
                        else
                        {
                            root.Add(new XElement(propName, prop.GetValue(entity, null)));
                        }
                        break;
                    }
                }
            }
            return(doc);
        }
Beispiel #34
0
        /// <summary>
        /// Runs test for InValid cases
        /// </summary>
        /// <param name="nodeType">XElement/XAttribute</param>
        /// <param name="name">name to be tested</param>
        public void RunInValidTests(string nodeType, string name)
        {
            XDocument xDocument = new XDocument();
            XElement element = null;
            try
            {
                switch (nodeType)
                {
                    case "XElement":
                        element = new XElement(name, name);
                        xDocument.Add(element);
                        IEnumerable<XNode> nodeList = xDocument.Nodes();
                        break;
                    case "XAttribute":
                        element = new XElement(name, name);
                        XAttribute attribute = new XAttribute(name, name);
                        element.Add(attribute);
                        xDocument.Add(element);
                        XAttribute x = element.Attribute(name);
                        break;
                    case "XName":
                        XName xName = XName.Get(name, name);
                        break;
                    default:
                        break;
                }
            }
            catch (XmlException)
            {
                return;
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.True(false, "Expected exception not thrown");
        }
Beispiel #35
0
        static void Main(string[] args)
        {
            Test test1 = new Test("asd", 123);
            Test test2 = new Test("asdz", 12);
            Test test3 = new Test("asdd", 12);
            Test test4 = new Test("asbd", 1233);

            Test[] test = new Test[] { test1, test2, test3, test4 };
            Console.WriteLine("----------------------------------------------------------------");

            BinaryFormatter formatter = new BinaryFormatter();

            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement.dat", FileMode.OpenOrCreate))
            {
                formatter.Serialize(fs, test1);
                Console.WriteLine("Объект сериализован");
            }
            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement.dat", FileMode.OpenOrCreate))
            {
                Test newTest = (Test)formatter.Deserialize(fs);
                Console.WriteLine("Объект десериализован");
                Console.WriteLine($"{newTest.Topic}   {newTest.Numbers}");
            }
            Console.WriteLine("----------------------------------------------------------------");

            SoapFormatter formatter2 = new SoapFormatter();

            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement2.dat", FileMode.OpenOrCreate))
            {
                formatter.Serialize(fs, test2);
                Console.WriteLine("Объект сериализован");
            }

            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement2.dat", FileMode.OpenOrCreate))
            {
                Test newTest2 = (Test)formatter.Deserialize(fs);
                Console.WriteLine("Объект десериализован");
                Console.WriteLine($"{newTest2.Topic}     {newTest2.Numbers}");
            }
            Console.WriteLine("----------------------------------------------------------------");

            DataContractJsonSerializer formatter3 = new DataContractJsonSerializer(typeof(Test));

            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement3.json", FileMode.OpenOrCreate))
            {
                formatter3.WriteObject(fs, test3);
                Console.WriteLine("Объект сериализован");
            }
            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement3.json", FileMode.OpenOrCreate))
            {
                Test newTest3 = (Test)formatter3.ReadObject(fs);
                Console.WriteLine("Объект десериализован");
                Console.WriteLine($"{newTest3.Topic}   {newTest3.Numbers}");
            }
            Console.WriteLine("----------------------------------------------------------------");

            XmlSerializer formatter4 = new XmlSerializer(typeof(Test));

            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement4.xml", FileMode.OpenOrCreate))
            {
                formatter.Serialize(fs, test4);
                Console.WriteLine("Объект сериализован");
            }
            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirement4.xml", FileMode.OpenOrCreate))
            {
                Test newTest4 = (Test)formatter.Deserialize(fs);
                Console.WriteLine("Объект десериализован");
                Console.WriteLine($"{newTest4.Topic}    {newTest4.Numbers}");
            }
            Console.WriteLine("----------------------------------------------------------------");

            BinaryFormatter formatter5 = new BinaryFormatter();

            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirements1.dat", FileMode.OpenOrCreate))
            {
                formatter5.Serialize(fs, test);
                Console.WriteLine("Массив объектов сериализован");
            }
            using (FileStream fs = new FileStream("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\expirements1.dat", FileMode.OpenOrCreate))
            {
                Test[] newTests = (Test[])formatter.Deserialize(fs);
                Console.WriteLine("Массив объектов десериализован");
                foreach (Test item in newTests)
                {
                    Console.WriteLine($"{item.Topic}    {item.Numbers}");
                }
            }
            Console.WriteLine("----------------------------------------------------------------");

            Console.WriteLine("Первый xml запрос (выбор названия):");
            XmlDocument xDoc = new XmlDocument();

            xDoc.Load("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\XMLFile1.xml");
            XmlElement  xRoot       = xDoc.DocumentElement;
            XmlNodeList childnodes1 = xRoot.SelectNodes("test");

            foreach (XmlNode n in childnodes1)
            {
                Console.WriteLine(n.SelectSingleNode("@topic").Value);
            }

            Console.WriteLine("Второй xml запрос (получаем сложность):");
            XmlNodeList childnodes2 = xRoot.SelectNodes("//test/diffuclt");

            foreach (XmlNode n in childnodes2)
            {
                Console.WriteLine(n.InnerText);
            }
            Console.WriteLine("Третий запрос (конкретный возраст):");
            XmlNode childnode3 = xRoot.SelectSingleNode("test[counter='18']");

            if (childnode3 != null)
            {
                Console.WriteLine(childnode3.OuterXml);
            }
            Console.WriteLine("----------------------------------------------------------------");

            XDocument document = new XDocument();
            XElement  root     = new XElement("countries");
            XElement  country1 = new XElement("country");

            root.Add(country1);
            XAttribute number1 = new XAttribute("number", "1");

            country1.Add(number1);
            XElement CounryName1 = new XElement("name", "Belarus");

            country1.Add(CounryName1);
            XElement square1 = new XElement("square", "207 595 км²");

            country1.Add(square1);
            XElement population1 = new XElement("population", "9.508 million");

            country1.Add(population1);

            XElement country2 = new XElement("country");

            root.Add(country2);
            XAttribute number2 = new XAttribute("number", "2");

            country2.Add(number2);
            XElement CounryName2 = new XElement("name", "Russia");

            country2.Add(CounryName2);
            XElement square2 = new XElement("square", "17 100 000 км²");

            country2.Add(square2);
            XElement population2 = new XElement("population", "144,5 million");

            country2.Add(population2);
            document.Add(root);
            document.Save("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\Countries.xml");
            Console.WriteLine("Документ создан при помощи  LINQ to XML");
            Console.WriteLine("----------------------------------------------------------------");

            XmlDocument xdoc = new XmlDocument();

            xdoc.Load("E:\\2 курс\\2_course\\ООП\\Labs_14\\Serializ\\Countries.xml");
            XmlElement Root = xdoc.DocumentElement;

            Console.WriteLine("Первый xml запрос (выбор имён):");
            XmlNodeList childnodes4 = Root.SelectNodes("country");

            foreach (XmlNode n in childnodes4)
            {
                Console.WriteLine(n.SelectSingleNode("name").InnerText);
            }
            Console.WriteLine("Второй xml запрос (получаем площадь):");
            XmlNodeList childnodes5 = Root.SelectNodes("//country/square");

            foreach (XmlNode n in childnodes5)
            {
                Console.WriteLine(n.InnerText);
            }
            Console.WriteLine("Третий запрос (нужное население):");
            XmlNode childnode6 = Root.SelectSingleNode("country[population='144,5 million']");

            if (childnode6 != null)
            {
                Console.WriteLine(childnode6.OuterXml);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Informs the screen manager to serialize its state to disk.
        /// </summary>
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else
            // Open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Create an XML document to hold the list of screen types currently in the stack
                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                // Make a copy of the master screen list, to avoid confusion if
                // the process of deactivating one screen adds or removes others.
                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                // Iterate the screens to store in our XML file and deactivate them
                foreach (GameScreen screen in tempScreensList)
                {
                    // Only add the screen to our XML if it is serializable
                    if (screen.IsSerializable)
                    {
                        // We store the screen's controlling player so we can rehydrate that value
                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    // Deactivate the screen regardless of whether we serialized it
                    screen.Deactivate();
                }

                // Save the document
                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
        /// <summary>
        /// Initializes the xml descriptor for this effect.
        /// </summary>
        private void InitializeXml()
        {
            xml = new XDocument();
            var effect = new XElement("Effect");
            xml.Add(effect);

            var customEffectTypeInfo = customEffectType.GetTypeInfo();

            // Add 
            var customEffectAttribute = Utilities.GetCustomAttribute<CustomEffectAttribute>(customEffectTypeInfo, true);
            effect.Add(CreateXmlProperty("DisplayName", "string", customEffectAttribute != null ? customEffectAttribute.DisplayName : customEffectTypeInfo.Name));
            effect.Add(CreateXmlProperty("Author", "string", customEffectAttribute != null ? customEffectAttribute.Author : string.Empty));
            effect.Add(CreateXmlProperty("Category", "string", customEffectAttribute != null ? customEffectAttribute.Category : string.Empty));
            effect.Add(CreateXmlProperty("Description", "string", customEffectAttribute != null ? customEffectAttribute.Description : string.Empty));

            var inputs = new XElement("Inputs");
            var inputAttributes = Utilities.GetCustomAttributes<CustomEffectInputAttribute>(customEffectTypeInfo, true);
            foreach(var inputAttribute in inputAttributes) {
                var inputXml = new XElement("Input");
                inputXml.SetAttributeValue("name", inputAttribute.Input);
                inputs.Add(inputXml);
            }
            effect.Add(inputs);

            // Add custom properties
            foreach(var binding in Bindings) {
                var property = CreateXmlProperty(binding.PropertyName,  binding.TypeName);

                property.Add(CreateXmlProperty("DisplayName", "string", binding.PropertyName));
                property.Add(CreateXmlProperty("Min", binding.TypeName, binding.Attribute.Min != null ? binding.Attribute.Min.ToString() : string.Empty));
                property.Add(CreateXmlProperty("Max", binding.TypeName, binding.Attribute.Max != null ? binding.Attribute.Max.ToString() : string.Empty));
                property.Add(CreateXmlProperty("Default", binding.TypeName, binding.Attribute.Default != null ? binding.Attribute.Default.ToString() : string.Empty));

                effect.Add(property);
            }
        }