static void Main(string[] args)
 {
     var xmlnamespace = new XmlSerializerNamespaces();
     xmlnamespace.Add("", ""); //used to stop default namespaces from printing
     var writer = XmlWriter.Create("output.xml");
     new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);
 }
    public void AddNote()
    {
        try {

        var mynote=new DeviceNotes();
        mynote.DeviceId = Int32.Parse(TextBox1.Text);

        mynote.TagId=Int32.Parse(TextBox2.Text);
        mynote.Note=TextBox3.Text;

        var request =
        WebRequest.Create(HOST + "/API/v1/mdm/devices/UDID/66A1DD99B2CC191FEAB20DA10A9D747AED988770/addNote") as HttpWebRequest;
        request.Method = "POST";
        InitializeRequest(request);
        request.ContentType= MIME_TYPE;
        var xmlSerializer=new XmlSerializer(typeof(DeviceNotes));

        string inputString;
        using (var writer =new StringWriter()){

        var xmlNamespace = new XmlSerializerNamespaces();

        xmlNamespace.Add(string.Empty, string.Empty);

        xmlSerializer.Serialize(writer, mynote, xmlNamespace);

        inputString = writer.ToString();
        Label2.Text = writer.ToString();
        }

        byte[] requestBytes = Encoding.UTF8.GetBytes (inputString);
        request.ContentLength = inputString.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(requestBytes, 0, requestBytes.Length);
        requestStream.Close();

        var response = (HttpWebResponse)request.GetResponse();
        //Console.WriteLine(new StreamReader (response.GetResponseStream()).ReadToEnd());

        Label1.Text = new StreamReader(response.GetResponseStream()).ReadToEnd().ToString();
        response.Close();
        }
        catch (WebException e) {
        if (e.Response != null) {
        var errorMessageStream = e.Response.GetResponseStream();
        string message = new StreamReader (errorMessageStream).ReadToEnd();
        //Console.WriteLine(message);
        Label1.Text = message.ToString();
        } else {
        //Console.WriteLine(e.Message);
        Label1.Text = e.Message;
        }
        }
        catch (Exception e)
        { //Console.WriteLine(e.Message);
        Label1.Text = e.Message;
        }
    }
 static void Save() {
     using (FileStream stream = new FileStream("Settings.xml", FileMode.Create)) {
         SettingsContainer container = new SettingsContainer();
         XmlWriterSettings writerSettings = new XmlWriterSettings() {
             OmitXmlDeclaration = true,
             Indent = true
         };
         XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
         namespaces.Add("", "");
         using (XmlWriter writer = XmlWriter.Create(stream, writerSettings)) {
             new XmlSerializer(typeof (SettingsContainer)).Serialize(writer, container, namespaces);
         }
     }
 }
Esempio n. 4
0
    public void save(string path)
    {
#if LEVEL_INFO_DEBUG
        Debug.Log("Save level info to " + path);
#endif

        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("","");

        XmlSerializer serializer = new XmlSerializer(typeof(LevelInfo));

        StreamWriter stream = new StreamWriter(path, false, Encoding.UTF8);
        serializer.Serialize(stream, this, ns);
        stream.Close();
    }
 public string GetXMLString()
 {
     XmlWriterSettings settings = new XmlWriterSettings();
     settings.Indent = true;
     settings.IndentChars = ("    ");
     settings.Encoding = new UTF8Encoding(false);
     using (StringWriter str = new StringWriter())
     using (XmlWriter writer = XmlWriter.Create(str, settings))
     {
         XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
         ns.Add(_newsSiteMapPrefix, _imageSiteMapSchema);
         XmlSerializer xser = new XmlSerializer(typeof(GoogleNewsSiteMap));
         xser.Serialize(writer, this, ns);
         return str.ToString();
     }
 }
Esempio n. 6
0
        /// <summary>
        /// Serialize from Configurations to XmlDocument Object
        /// </summary>
        /// <param name="response"></param>
        /// <param name="xmlDoc"></param>
        public void MarshalingToXMLDocument(T xmlObject, out XmlDocument xmlDoc)
        {
            XmlDocument doc = new XmlDocument();
            //XmlSerializer serializer = new XmlSerializer(xmlObject.GetType());
            MemoryStream stream = new System.IO.MemoryStream();

            try
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                xmlSerializer.Serialize(stream, xmlObject, ns);
                stream.Position = 0;
                doc.LoadXml(stream.ToString());
            }
            catch (Exception ex)
            {
                Logger.Instance.GetLogInstance().Error(JsonConvert.SerializeObject(ex));
            }
            finally
            {
                xmlDoc = doc;
                stream.Close();
            }
        }
Esempio n. 7
0
File: StartUp.cs Progetto: Burckz/EF
        public static string GetProductsInRange(ProductShopContext context)
        {
            var products = context.Products
                           .Where(p => p.Price <= 1000 && p.Price >= 500)
                           .OrderBy(p => p.Price)
                           .Select(p => new ProductsInRangeDto {
                name  = p.Name,
                price = p.Price,
                buyer = $"{p.Buyer.FirstName} {p.Buyer.LastName}"
            })
                           .Take(10)
                           .ToList();

            StringBuilder result = new StringBuilder();

            var serializer             = new XmlSerializer(typeof(List <ProductsInRangeDto>), new XmlRootAttribute("Products"));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");

            serializer.Serialize(new StringWriter(result), products, ns);

            return($"{result}");
        }
Esempio n. 8
0
        public static string ToXml <T>(this ICollection <T> data, string rootAttributeName = null)
        {
            XmlSerializer xmls;

            if (rootAttributeName is null)
            {
                xmls = new XmlSerializer(data.GetType());
            }
            else
            {
                xmls = new XmlSerializer(data.GetType(),
                                         new XmlRootAttribute(rootAttributeName));
            }
            using var sw   = new StringWriter();
            using var xmlw = XmlWriter.Create(sw,
                                              new XmlWriterSettings { Indent = true });
            var xmlns = new XmlSerializerNamespaces();

            xmlns.Add("", "");
            xmls.Serialize(xmlw, data, xmlns);
            var xml = sw.ToString();

            return(xml);
        }
Esempio n. 9
0
 public static bool Serialize <T>(T t, out string xml)
 {
     xml = null;
     try
     {
         var ns = new XmlSerializerNamespaces();
         ns.Add("", "");
         var ser = new XmlSerializer(typeof(T));
         using (var ms = new MemoryStream())
         {
             ser.Serialize(ms, t, ns);
             ms.Position = 0;
             var reader = new StreamReader(ms);
             xml = reader.ReadToEnd();
             reader.Close();
         }
         return(true);
     }
     catch (System.Exception ex)
     {
         System.Diagnostics.Trace.Fail(ex.Message, ex.StackTrace);
     }
     return(false);
 }
Esempio n. 10
0
        public void SerializeHyperFindQueryToXml()
        {
            var body = new HyperFindQuery
            {
                HyperFindQueryName = "All Home",
                VisibilityCode     = "Public",
                QueryDateStart     = new DateTime(2017, 2, 11),
                QueryDateEnd       = new DateTime(2017, 2, 12)
            };

            var xmlRequest = new XmlApiRequest <HyperFindQuery>(body, "RunQuery", "user", "passowrd");
            var xs         = new XmlSerializer(typeof(XmlApiRequest <HyperFindQuery>));
            var xmlnsEmpty = new XmlSerializerNamespaces();

            xmlnsEmpty.Add(string.Empty, string.Empty);
            using (var buffer = new MemoryStream())
            {
                xs.Serialize(buffer, xmlRequest, xmlnsEmpty);
                var xml = new XmlDocument();
                xml.LoadXml(Encoding.UTF8.GetString(buffer.ToArray()));
                Assert.NotNull(xml);
                Assert.AreEqual("WFC", xml.DocumentElement.Name);
                Assert.AreEqual("1.0", xml.DocumentElement.Attributes["version"].Value);
                var logon = xml.DocumentElement.SelectNodes("Request")[0];
                Assert.NotNull(logon);
                Assert.AreEqual("Logon", logon.Attributes["Action"].Value);
                var logoff = xml.DocumentElement.SelectNodes("Request")[2];
                Assert.NotNull(logoff);
                Assert.AreEqual("Logoff", logoff.Attributes["Action"].Value);
                var bodyRequest = xml.DocumentElement.SelectNodes("Request")[1].SelectNodes("HyperFindQuery")[0];
                Assert.NotNull(bodyRequest);
                Assert.AreEqual("All Home", bodyRequest.Attributes["HyperFindQueryName"].Value);
                Assert.AreEqual("Public", bodyRequest.Attributes["VisibilityCode"].Value);
                Assert.AreEqual("2/11/2017-2/12/2017", bodyRequest.Attributes["QueryDateSpan"].Value);
            }
        }
Esempio n. 11
0
        public async Task <ICountry> FindCountry(string countryCode)
        {
            this.ValidateInput(new Country {
                CountryCode = countryCode
            });

            var responseStream = await this.client.GetStreamAsync(string.Format("http://api.worldbank.org/v2/country/{0}", countryCode));

            XDocument xDocument = XDocument.Load(responseStream);

            if (!this.ValidateResponse(xDocument))
            {
                return(null);
            }

            XmlSerializer           xmlSerializer           = new XmlSerializer(typeof(WbCountries));
            XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();

            xmlSerializerNamespaces.Add("wb", "http://www.worldbank.org");

            WbCountries wbCountries = xmlSerializer.Deserialize(xDocument.CreateReader()) as WbCountries;

            return(wbCountries.Single().AsCountry());
        }
Esempio n. 12
0
        // Parse xml file using XmlSerializer. The entities for serialization are the same as in
        // Test Management Jira plugin.
        /// <param name="result"> The list of issues for writing </param>
        /// <param name="relativefilePath"> The path to output file </param>
        public static void WriteXml(TestResult result, string relativefilePath)
        {
            string testResultDir = Solution_dir + TargetDir;

            CheckOrCreateDir(testResultDir);

            var                     doc       = new XmlDocument();
            StringWriter            writer    = new StringWriter();
            XmlSerializer           formatter = new XmlSerializer(typeof(TestResult));
            XmlSerializerNamespaces ns        = new XmlSerializerNamespaces();

            ns.Add("", "");

            formatter.Serialize(writer, result, ns);
            doc.Load(new StringReader(writer.ToString()));

            if (doc.FirstChild is XmlDeclaration dec)
            {
                dec.Encoding   = "UTF-8";
                dec.Standalone = "yes";
            }

            doc.Save(Path.Combine(testResultDir, relativefilePath));
        }
Esempio n. 13
0
File: StartUp.cs Progetto: Burckz/EF
        public static string GetTotalSalesByCustomer(CarDealerContext context)
        {
            var customers = context.Customers
                            .Where(c => c.Sales.Any())
                            .Select(c => new CustomerDto
            {
                FullName   = c.Name,
                BoughtCars = c.Sales.Count(),
                SpentMoney = c.Sales.Sum(s => s.Car.PartCars.Sum(pc => pc.Part.Price))
            })
                            .OrderByDescending(c => c.SpentMoney)
                            .ToList();

            var serializer = new XmlSerializer(typeof(List <CustomerDto>), new XmlRootAttribute("customers"));
            var ns         = new XmlSerializerNamespaces();

            ns.Add("", "");

            StringBuilder result = new StringBuilder();

            serializer.Serialize(new StringWriter(result), customers, ns);

            return($"{result}");
        }
Esempio n. 14
0
        public static string Serialize <T>(T anything, bool includeDeclaration = false, bool includeNamespaces = false)
        {
            using var writer = new Utf8StringWriter(CultureInfo.InvariantCulture);
            var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = !includeDeclaration,
                Encoding           = Encoding.UTF8
            };
            var names = new XmlSerializerNamespaces();

            names.Add("", "");
            using var xmlWriter = XmlWriter.Create(writer, settings);
            var serializer = GetCachedOrCreate(typeof(T));

            if (includeNamespaces)
            {
                serializer.Serialize(xmlWriter, anything);
            }
            else
            {
                serializer.Serialize(xmlWriter, anything, names);
            }
            return(writer.ToString());
        }
Esempio n. 15
0
        /// <summary>
        /// 将对象转换为其 XML 表示形式。
        /// </summary>
        /// <param name="writer">对象要序列化为的 <see cref="T:System.Xml.XmlWriter"/> 流。</param>
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("FileName", this.FileName);
            writer.WriteElementString("FullName", this.FullName);
            writer.WriteElementString("Name", this.Name);
            writer.WriteElementString("Title", this.Title);
            writer.WriteElementString("Description", this.Description);
            writer.WriteElementString("Version", this.Version == null ? string.Empty : this.Version.ToString());
            writer.WriteElementString("IsExtend", this.IsExtend.ToString().ToLower());
            writer.WriteElementString("DisableStopAndUninstalled", this.DisableStopAndUninstalled.ToString().ToLower());
            writer.WriteElementString("ListOrder", this.ListOrder.ToString());
            writer.WriteElementString("State", this.State.ToString());

            writer.WriteStartElement("Reference");
            if (this.Reference != null)
            {
                this.Reference.ForEach(reference =>
                {
                    writer.WriteElementString("Assembly", reference);
                });
            }
            writer.WriteEndElement();

            writer.WriteStartElement("AbstractModules");
            if (this.AbstractModules != null)
            {
                this.AbstractModules.ForEach(module =>
                {
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add(string.Empty, string.Empty);
                    XmlSerializer xmlSerializer = new XmlSerializer(module.GetType());
                    xmlSerializer.Serialize(writer, module, namespaces);
                });
            }
            writer.WriteEndElement();
        }
Esempio n. 16
0
File: Common.cs Progetto: Gz1d/Gz
        /// <summary>
        /// 序列化成XML文件
        /// </summary>
        /// <param name="entity">要序列化的对象</param>
        /// <param name="path">路径</param>
        public static void SerializeXml(object entity, string path)
        {
            XmlSerializer ser = new XmlSerializer(entity.GetType());

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.OmitXmlDeclaration = false;
            settings.Indent             = true;
            settings.Encoding           = System.Text.Encoding.GetEncoding("gb2312");

            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);


            XmlWriter writer = XmlWriter.Create(path, settings);

            ser.Serialize(writer, entity, namespaces);
            writer.Close();

            //StreamWriter sw = new StreamWriter(path);
            //ser.Serialize(sw, entity);
            //sw.Close();
        }
Esempio n. 17
0
        public static void ExportXml(string xmlFile, MyModelConfiguration configuration)
        {
            XmlSerializer           xmlSerializer = new XmlSerializer(typeof(MyModelConfiguration));
            XmlSerializerNamespaces namespaces    = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (FileStream fileStream = File.Open(xmlFile, FileMode.OpenOrCreate))
                {
                    xmlSerializer.Serialize((Stream)memoryStream, (object)configuration, namespaces);
                    memoryStream.Position = 0L;
                    fileStream.Position   = 0L;
                    if (memoryStream.Length == fileStream.Length && ProgramContext.StreamEquals((Stream)memoryStream, (Stream)fileStream))
                    {
                        return;
                    }
                    fileStream.SetLength(0L);
                    fileStream.Position   = 0L;
                    memoryStream.Position = 0L;
                    memoryStream.WriteTo((Stream)fileStream);
                }
            }
        }
Esempio n. 18
0
        public static string GetCarsFromMakeBmw(CarDealerContext context)
        {
            var cars = context.Cars
                       .Where(x => x.Make.Equals("BMW"))
                       .Select(x => new CarBmwOutputModel
            {
                Id                = x.Id,
                Model             = x.Model,
                TravelledDistance = x.TravelledDistance
            })
                       .OrderBy(x => x.Model)
                       .ThenByDescending(x => x.TravelledDistance)
                       .ToArray();

            var xmlSerializer = new XmlSerializer(typeof(CarBmwOutputModel[]), new XmlRootAttribute("cars"));

            var textWriter = new StringWriter();
            var ns         = new XmlSerializerNamespaces();

            ns.Add("", "");
            xmlSerializer.Serialize(textWriter, cars, ns);

            return(textWriter.ToString());
        }
Esempio n. 19
0
        private static void SaveToDocumentFormat(Object serializableObject, string nameSpace, System.Type[] extraTypes, string path)
        {
            using (TextWriter textWriter = CreateTextWriter(path))
            {
                XmlSerializer xmlSerializer = CreateXmlSerializer(serializableObject, extraTypes);

                //ADDED THIS TO REMOVE DEFAULT NAMESPACE JUNK FROM HEADER

                if (nameSpace != null && nameSpace.Length > 0)
                {
                    //Create our own namespaces for the output
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

                    //Add an empty namespace and empty value
                    ns.Add("", nameSpace);

                    xmlSerializer.Serialize(textWriter, serializableObject, ns);
                }
                else
                {
                    xmlSerializer.Serialize(textWriter, serializableObject);
                }
            }
        }
Esempio n. 20
0
        public static string ObjectToXml(object obj)
        {
            using (StringWriter stringWriter = new StringWriter())
                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
                {
                    try
                    {
                        XmlSerializer serializer = new XmlSerializer(obj.GetType());

                        //Xml limpo. Sem namespace.
                        XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
                        xmlNamespace.Add("", "");

                        serializer.Serialize(xmlTextWriter, obj, xmlNamespace);
                    }

                    catch (Exception ex)
                    {
                        Console.Error.Write($"[XmlParser] - Erro ao serializar o XML.\nException Message: {ex}");
                    }

                    return(RemoveAllNamespaces(stringWriter.ToString()));
                }
        }
Esempio n. 21
0
        //16-Export Local Suppliers
        public static string GetLocalSuppliers(CarDealerContext context)
        {
            var suppliers = context.Suppliers
                            .Where(s => s.IsImporter == false)
                            .Select(s => new ExportLocalSuppliersDto
            {
                Id         = s.Id,
                Name       = s.Name,
                PartsCount = s.Parts.Count()
            })
                            .ToArray();

            var sb = new StringBuilder();

            var namespaces = new XmlSerializerNamespaces();

            namespaces.Add("", "");

            var serializer = new XmlSerializer(typeof(ExportLocalSuppliersDto[]), new XmlRootAttribute("suppliers"));

            serializer.Serialize(new StringWriter(sb), suppliers, namespaces);

            return(sb.ToString().TrimEnd());
        }
        public static string ExportOldestBooks(BookShopContext context, DateTime date)
        {
            /*Export top 10 oldest books that are published before the given date and are of type science.
             * For each book select its name, date (in format "d") and pages.
             * Sort them by pages in descending order and then by date in descending order.
             * NOTE: Before the orders, materialize the query (This is issue by Microsoft in InMemory database library)!!!
             */
            var books = context
                        .Books
                        .Where(b => b.PublishedOn < date && b.Genre == Genre.Science)
                        .ToList()
                        .OrderByDescending(b => b.Pages)
                        .ThenByDescending(b => b.PublishedOn) // again ordering before because of formatting
                        .Select(b => new ExportOldestBooksDto()
            {
                Name  = b.Name,
                Date  = b.PublishedOn.ToString("d", CultureInfo.InvariantCulture),
                Pages = b.Pages
            })
                        .Take(10)
                        .ToList();

            var namespaces = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);

            StringBuilder sb         = new StringBuilder();
            XmlSerializer serializer = new XmlSerializer(typeof(List <ExportOldestBooksDto>), new XmlRootAttribute("Books"));

            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, books, namespaces);
            }

            return(sb.ToString().TrimEnd());
        }
Esempio n. 23
0
        public static string GetSoldProducts(ProductShopContext context)
        {
            StringBuilder sb         = new StringBuilder();
            var           namespaces = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);

            var users = context
                        .Users
                        .Where(x => x.ProductsSold.Count > 0)
                        .Select(x => new ExportUserSoldProducts
            {
                FirstName    = x.FirstName,
                LastName     = x.LastName,
                SoldProducts = x.ProductsSold.Select(y => new ExportProductItemSold
                {
                    Name  = y.Name,
                    Price = y.Price
                }).ToArray()
            })
                        .OrderBy(x => x.LastName)
                        .ThenBy(x => x.FirstName)
                        .Take(5)
                        .ToArray();

            //foreach (var item in users)
            //{
            //    Console.WriteLine(item);
            //}

            XmlSerializer xml = new XmlSerializer(typeof(ExportUserSoldProducts[]), new XmlRootAttribute("Users"));

            xml.Serialize(new StringWriter(sb), users, namespaces);
            return(sb.ToString().TrimEnd());
            //return null;
        }
Esempio n. 24
0
        public static string GetProductsInRange(ProductShopContext context)
        {
            var products = context.Products
                           .Select(p => new ExportProductsInRangeDTO {
                Price = p.Price, Name = p.Name, Buyer = $"{p.Buyer.FirstName} {p.Buyer.LastName}"
            })
                           .Where(p => p.Price >= 500 && p.Price <= 1000)
                           .OrderBy(p => p.Price)
                           .Take(10)
                           .ToArray();

            using (var writer = new StringWriter())
            {
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                var serializer = new XmlSerializer(typeof(ExportProductsInRangeDTO[]), new XmlRootAttribute("Products"));
                serializer.Serialize(writer, products, ns);

                var productsXml = writer.GetStringBuilder();

                return(productsXml.ToString().TrimEnd());
            }
        }
        /// <summary>
        /// Serializes the dictionary as XML.
        /// </summary>
        /// <param name="writer">An XML writer used for serialization.</param>
        public void WriteXml(XmlWriter writer)
        {
            var keySerializer   = new XmlSerializer(typeof(TKey));
            var valueSerializer = new XmlSerializer(typeof(TValue));
            var xsns            = new XmlSerializerNamespaces();

            xsns.Add(string.Empty, Namespace);

            foreach (var key in this.Keys)
            {
                writer.WriteStartElement("Item", Namespace);

                writer.WriteStartElement("Key");
                keySerializer.Serialize(writer, key, xsns);
                writer.WriteEndElement();

                writer.WriteStartElement("Value");
                var value = this[key];
                valueSerializer.Serialize(writer, value, xsns);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
        }
 private string GetSitemapIndexXMLString()
 {
     using (StringWriter str = new Utf8StringWriter())
         using (XmlWriter writer = XmlWriter.Create(str))
         {
             XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
             ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9");
             XmlSerializer xser = new XmlSerializer(typeof(SiteMapIndexModel));
             var           obj  = new SiteMapIndexModel
             {
                 SiteMapIndexUrls =
                 {
                     new SiteMapIndexNodeModel {
                         Url = "userpages.xml"
                     },
                     new SiteMapIndexNodeModel {
                         Url = "testpage.xml"
                     }
                 }
             };
             xser.Serialize(writer, obj, ns);
             return(str.ToString());
         }
 }
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "text/xml";

            var settings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8
            };

            using (XmlWriter xmlWriter = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))
            {
                if (Namespace == null)
                {
                    new XmlSerializer(typeof(T)).Serialize(xmlWriter, Data);
                }
                else
                {
                    var ns = new XmlSerializerNamespaces();
                    ns.Add("", Namespace);

                    new XmlSerializer(typeof(T), Namespace).Serialize(xmlWriter, Data, ns);
                }
            }
        }
        public override String ToXml(bool includeHeader,
                                     bool includeState,
                                     String name,
                                     String sNameSpace)
        {
            String        s;
            XmlSerializer xmls;

            xmls = new XmlSerializer(this.GetType(), sNameSpace);
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Xml.XmlWriter   xmlw   = System.Xml.XmlWriter.Create(stream, new System.Xml.XmlWriterSettings()
            {
                OmitXmlDeclaration = !includeHeader
            });
            XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();

            xmlns.Add(String.Empty, sNameSpace);
            xmls.Serialize(xmlw, this, xmlns);
            stream.Seek(0L, System.IO.SeekOrigin.Begin);
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            s = sr.ReadToEnd();
            stream.Close();
            return(s);
        }
Esempio n. 29
0
        public static string ObjectToXml(object obj)
        {
            var settings = new XmlWriterSettings
            {
                Indent             = true,
                OmitXmlDeclaration = false,
                Encoding           = Encoding.GetEncoding("UTF-16")
            };

            var namespaces = new XmlSerializerNamespaces();

            namespaces.Add(string.Empty, string.Empty);

            var serializer = new XmlSerializer(obj.GetType());

            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
                {
                    serializer.Serialize(xmlWriter, obj, namespaces);
                }
                return(stringWriter.ToString());
            }
        }
Esempio n. 30
0
        // Problem. 17
        public static string GetCarsWithTheirListOfParts(CarDealerContext context)
        {
            var cars = context.Cars
                       .Select(c => new ExportCarDto
            {
                Make              = c.Make,
                Model             = c.Model,
                TravelledDistance = c.TravelledDistance,
                Parts             = c.PartCars
                                    .Select(p => new ExportCarPartsDto
                {
                    Name  = p.Part.Name,
                    Price = p.Part.Price
                })
                                    .OrderByDescending(p => p.Price)
                                    .ToArray()
            })
                       .OrderByDescending(c => c.TravelledDistance)
                       .ThenBy(c => c.Model)
                       .Take(5)
                       .ToArray();

            var sb = new StringBuilder();

            using var writer = new StringWriter(sb);

            var ns = new XmlSerializerNamespaces();

            ns.Add(string.Empty, string.Empty);

            var serializer = new XmlSerializer(typeof(ExportCarDto[]), new XmlRootAttribute("cars"));

            serializer.Serialize(writer, cars, ns);

            return(sb.ToString().TrimEnd());
        }
Esempio n. 31
0
        public override string Parse(Content text)
        {
            StringWriter  sw = new StringWriter();
            XmlTextWriter tw = null;

            try
            {
                XmlSerializer serializer = new XmlSerializer(text.GetType());
                tw            = new XmlTextWriter(sw);
                tw.Formatting = Formatting.Indented;
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                serializer.Serialize(tw, text, ns);
            }
            catch (Exception ex)
            {
                //Handle Exception Code
            }
            finally
            {
                sw.Close();
                if (tw != null)
                {
                    tw.Close();
                }
            }

            var swSplittedByLine = sw.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var xmlString        = new StringBuilder();

            foreach (var line in swSplittedByLine)
            {
                xmlString.Append($"{line.TrimStart(' ')}{Environment.NewLine}");
            }
            return(xmlString.ToString());
        }
Esempio n. 32
0
        public static void DumpTableScriptMap()
        {
            TableMap tableMap = null;
            string   path     = "Assets/Editor/ResImporter/ImporterData/Table/Table.xml";

            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(TableMap));
                using (FileStream fileStream = new FileStream(path, FileMode.Open))
                {
                    tableMap = (xmlSerializer.Deserialize(fileStream) as TableMap);
                }
                if (tableMap != null)
                {
                    tableMap.tableScriptMap.Clear();
                    foreach (KeyValuePair <string, string> current in XTableAsyncLoader.tableScriptMap)
                    {
                        TableScriptMap tableScriptMap = new TableScriptMap();
                        tableScriptMap.table  = current.Key;
                        tableScriptMap.script = current.Value;
                        tableMap.tableScriptMap.Add(tableScriptMap);
                    }
                    using (FileStream fileStream2 = new FileStream(path, FileMode.Create))
                    {
                        StreamWriter            textWriter = new StreamWriter(fileStream2, Encoding.UTF8);
                        XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
                        xmlSerializerNamespaces.Add(string.Empty, string.Empty);
                        xmlSerializer.Serialize(textWriter, tableMap, xmlSerializerNamespaces);
                    }
                }
            }
            catch (Exception ex)
            {
                XSingleton <XDebug> .singleton.AddWarningLog(ex.Message, null, null, null, null, null);
            }
        }
Esempio n. 33
0
        public static string GetLocalSuppliers(CarDealerContext context)
        {
            var suppliers = context.Suppliers
                            .Where(x => x.IsImporter == false)
                            .Select(x => new SuppliersOutputModel
            {
                Id         = x.Id,
                Name       = x.Name,
                PartsCount = x.Parts.Count()
            })
                            .ToArray();

            var streamWriter = new StringWriter();

            var suppliersSerialized = new XmlSerializer(typeof(SuppliersOutputModel[]), new XmlRootAttribute("suppliers"));

            var ns = new XmlSerializerNamespaces();

            ns.Add("", "");

            suppliersSerialized.Serialize(streamWriter, suppliers, ns);

            return(streamWriter.ToString());
        }
Esempio n. 34
0
        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            UpdateModificationsWithTable();

            try
            {
                StringWriter  sw            = new StringWriter();
                XmlSerializer xmlSerializer = new XmlSerializer(ml.GetType());
                //Remmove namespaces
                System.Xml.Serialization.XmlSerializerNamespaces xs = new XmlSerializerNamespaces();
                xs.Add("", "");
                xmlSerializer.Serialize(sw, ml, xs);

                Properties.Settings.Default.ModificationLib = sw.ToString();
                Properties.Settings.Default.Save();


                MessageBox.Show("Your lib has been updated.");
            }
            catch (Exception e2)
            {
                MessageBox.Show("Error updating: " + e2.Message);
            }
        }
Esempio n. 35
0
    /// <summary>
    /// serializes 'this' instance as XML
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="thisObj"></param>
    /// <param name="xmlRootName"></param>
    /// <returns>returns a string containing the XML representation of the object</returns>
    static public string ToXml <T>(this T thisObj, string xmlRootName = null) where T : class
    {
        if (thisObj == null)
        {
            return(null);
        }

        using (var stream = new StringWriter())
        {
            using (var xw = XmlWriter.Create(stream, new XmlWriterSettings {
                OmitXmlDeclaration = true
            }))
            {
                var ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // tell the serializer we don't want the default xmlns= or xsi= attributes
                new XmlSerializer(thisObj.GetType(), new XmlRootAttribute(xmlRootName ?? thisObj.GetType().GetRootName())
                {
                    Namespace = ""
                }).Serialize(xw, thisObj, ns);
            }
            string xml = stream.ToString();
            return(xml);
        }
    }
Esempio n. 36
0
    //end process asn

    public static bool process_asn_multi_titles_simple_test(int despatchno, string filename)
    {
        bool _result = false;
        //all datetimes in the .xsd schema manually converted to strings otherwise we can't format them as required in ASN specification
        DateTime _now = DateTime.Now;
        //issuedatetime
        string _issue = _now.ToString("yyyy-MM-dd\"T\"HH:mm:sszzz"); //for formatting issue date to 2014-01-30T13:07:45+00:00
        //string _issue = "yyyy-MM-dd\"T\"HH:mm:sszzz"; //for formatting issue date to 2014-01-30T13:07:45+00:00
        int _npallets = 0; //total number of pallets
        int _nlines = 0; //total of line numbers
        int _nunits = 0; //total number of books
        //constants
        const string _carriercode = "Shipper";
        const string _carriernamecode = "PUBLISHIP";
        const decimal _asnversion = 0.9M;
        const string _purpose = "Original";


        //*************************
        //for testing a multi title pallet
        Random _rnd = new Random();
        string[] _titles = { "Cutting Edge: Advanced Teacher's Book: A Practical Approach to Task Based Learning", "Cutting Edge: Upper Intermediate Workbook with Key" }; //{ "New General Maths Jss Sb 1", "New General Maths Jss Sb 2", "New General Maths Ne Ng Ss 3" };
        string[] _impression = { "010", "001" };
        int[] _copies = { 350, 8000 }; //{ 3000 , _rnd.Next(40, 65), _rnd.Next(30, 70)};
        int[] _parcels = { 20, 40 };
        string[] _sscc = { "008957634534534523", "003643244612645260" };
        string[] _isbn = { "9780582469440", "9781447906773" };
        string[] _ponumbers = { "4F00000045336 ", "4F00000045372" };
        string[] _puborder = { "19478484 ", "10033893" };
        //**************************
        //class in xsds folder DAL.Logistics namespace
        //DAL.Logistics.PrintersDespatchAdvice _xml = new DAL.Logistics.PrintersDespatchAdvice  
        PrintersDespatchAdvice _pda = new PrintersDespatchAdvice();

        //header data

        _pda.Header = new PrintersDespatchAdviceHeader();
        _pda.Header.DespatchAdviceNumber = despatchno; //file number? // orderno; //despatch number? 
        _pda.version = _asnversion;
        _pda.Header.IssueDateTime = _issue;
        _pda.Header.PurposeCode = _purpose;
        //reference coded elements
        _pda.Header.ReferenceCoded = new PrintersDespatchAdviceHeaderReferenceCoded();
        _pda.Header.ReferenceCoded.ReferenceNumber = "PDC20033"; ;
        _pda.Header.ReferenceCoded.ReferenceTypeCode = "BuyersReference";
        //datecoded elements
        _pda.Header.DateCoded = new PrintersDespatchAdviceHeaderDateCoded();
        _pda.Header.DateCoded.Date = _now.ToString("yyyyMMdd"); ///format yyyyMMdd 
        _pda.Header.DateCoded.DateQualifierCode = "Not yet shipped";
        //buyer party elements 1-6 address lines  (CUSTOMER? in publiship db)
        _pda.Header.BuyerParty = new PrintersDespatchAdviceHeaderBuyerParty();
        _pda.Header.BuyerParty.PartyName = new PrintersDespatchAdviceHeaderBuyerPartyPartyName();
        _pda.Header.BuyerParty.PartyName.NameLine = "Pearson Education Ltd";
        _pda.Header.BuyerParty.PostalAddress = new PrintersDespatchAdviceHeaderBuyerPartyPostalAddress();
        _pda.Header.BuyerParty.PostalAddress.AddressLine = new string[] { "Halley Court", "Jordan Hill", "Oxford" };
        _pda.Header.BuyerParty.PostalAddress.PostalCode = "OX2 8EJ";
        //seller party elements 1-6 address lines (PRINTER? in publiship db)
        _pda.Header.SellerParty = new PrintersDespatchAdviceHeaderSellerParty();
        _pda.Header.SellerParty.PartyName = new PrintersDespatchAdviceHeaderSellerPartyPartyName();
        _pda.Header.SellerParty.PartyName.NameLine = "Jiwabaru";
        _pda.Header.SellerParty.PostalAddress = new PrintersDespatchAdviceHeaderSellerPartyPostalAddress();
        _pda.Header.SellerParty.PostalAddress.AddressLine = new string[] { "NO: 2, JALAN P/8, KAWASAN MIEL FASA 2", "BANDAR BARU BANGI", "SELANGOR DARUL EHSAN", "43650", "Malaysia" };
        _pda.Header.SellerParty.PostalAddress.PostalCode = "";
        //ship to party party id elements
        _pda.Header.ShipToParty = new PrintersDespatchAdviceHeaderShipToParty();
        //required
        _pda.Header.ShipToParty.PartyID = new PrintersDespatchAdviceHeaderShipToPartyPartyID();
        _pda.Header.ShipToParty.PartyID.PartyIDType = "EAN";
        _pda.Header.ShipToParty.PartyID.Identifier = "PEAR011";
        //
        _pda.Header.ShipToParty.PartyName = new PrintersDespatchAdviceHeaderShipToPartyPartyName();
        _pda.Header.ShipToParty.PartyName.NameLine = "Pearson Distribution Centre";
        _pda.Header.ShipToParty.PostalAddress = new PrintersDespatchAdviceHeaderShipToPartyPostalAddress();
        _pda.Header.ShipToParty.PostalAddress.AddressLine = new string[] { "Unit 1", "Castle Mound Way", "Rugby", "Warwickshire", "UK" };
        _pda.Header.ShipToParty.PostalAddress.PostalCode = "CV23 0WB";
        //delivery elements
        _pda.Header.Delivery = new PrintersDespatchAdviceHeaderDelivery();
        _pda.Header.Delivery.TrailerNumber = "PU1"; //from database
        //delivery carrier
        _pda.Header.Delivery.Carrier = new PrintersDespatchAdviceHeaderDeliveryCarrier();
        //delivery carrier carriername coded
        _pda.Header.Delivery.Carrier.CarrierNameCoded = new PrintersDespatchAdviceHeaderDeliveryCarrierCarrierNameCoded();
        _pda.Header.Delivery.Carrier.CarrierNameCoded.CarrierNameCodeType = _carriercode;
        _pda.Header.Delivery.Carrier.CarrierNameCoded.CarrierNameCode = _carriernamecode;
        //end header        

        //11.11.2014 Pearson aggreed that when we have 4 titles on a delivery we can just give 1 SSCC code per title instead of
        //SSCC codes for every pallet
        //items emuneration
        //we will also build counters for summary data at the same time
        //get total number of books for the ISBN and divide by books per pallet (pack size). the 1st item detail section will contain the
        //carton details that can be delivered in quantities of the pack size. the 2nd item detail section will contain the remainder
        //e.g. no of books = 270, pack size = 40: 1st pallet section number of pallets = 6 x 40, 2nd section = 1 x 30.
        //there should be 2 PrintersDespatchAdviceItemDetail
        PrintersDespatchAdviceItemDetail[] _items = new PrintersDespatchAdviceItemDetail[_titles.Length];
        for (int _ix = 0; _ix < _items.Length; _ix++)
        {
            _nlines += 1;//add to total line count
            _nunits += _copies[_ix];//add to total copies 
            _items[_ix] = new PrintersDespatchAdviceItemDetail();
            _items[_ix].LineNumber = _ix + 1;
            _items[_ix].Impression = _impression[_ix];  //impression number from database
            _items[_ix].Quantity = _copies[_ix];

            //item product id's include isbn and ean13 even if we don't have values for them
            //DateTime? _ets = wwi_func.vdatetime(wwi_func.l.lookup_xml_string("xml\\parameters.xml", "name", "startETS", "value"));
            string[] _ids = { "ISBN", "EAN13" };
            PrintersDespatchAdviceItemDetailProductID[] _productids = new PrintersDespatchAdviceItemDetailProductID[_ids.Length];
            for (int _nx = 0; _nx < _ids.Length; _nx++)
            {
                _productids[_nx] = new PrintersDespatchAdviceItemDetailProductID();
                _productids[_nx].ProductIDType = _ids[_nx];
                //23/03/15 populate ISBN and EAN with ISBN
                _productids[_nx].Identifier = _isbn[_ix]; //_ids[_nx] == "ISBN"? _isbn[_ix]: "";
            }
            _items[_ix].ProductID = _productids;
            //end productids for this item

            //item description
            _items[_ix].ItemDescription = new PrintersDespatchAdviceItemDetailItemDescription();
            _items[_ix].ItemDescription.TitleDetail = _titles[_ix];
            _items[_ix].ItemDescription.BindingDescription = "UNKNOWN";

            //measurements include even if unknown
            string[] _itemx = { "Height", "Width", "Depth", "UnitNetWeight" };
            PrintersDespatchAdviceItemDetailItemDescriptionMeasure[] _measures = new PrintersDespatchAdviceItemDetailItemDescriptionMeasure[_itemx.Length];
            for (int _nx = 0; _nx < _itemx.Length; _nx++)
            {
                _measures[_nx] = new PrintersDespatchAdviceItemDetailItemDescriptionMeasure();
                _measures[_nx].MeasureTypeCode = _itemx[_nx];
                _measures[_nx].MeasurementValue = _nx < 3 ? _rnd.Next(200, 300) : Math.Round(_rnd.NextDouble() * 800, 2);
            }
            _items[_ix].ItemDescription.Measure = _measures;
            //end measurements for item
            //item referencecoded
            string[] _reftypes = { "BuyersOrderNumber", "PrintersJobNumber" };//printers SRR file, publiship order number from database
            PrintersDespatchAdviceItemDetailReferenceCoded[] _refcodes = new PrintersDespatchAdviceItemDetailReferenceCoded[_reftypes.Length];
            for (int _nx = 0; _nx < _reftypes.Length; _nx++)
            {
                _refcodes[_nx] = new PrintersDespatchAdviceItemDetailReferenceCoded();
                _refcodes[_nx].ReferenceTypeCode = _reftypes[_nx];
                _refcodes[_nx].ReferenceNumber = _nx == 0 ? _ponumbers[_nx] : _puborder[_nx];
            }
            _items[_ix].ReferenceCoded = _refcodes;
            //end refcodes
            //there should be no more than 2 pallet detail sections. the 1st one for whole pallets, 2nd for part pallet
            //item pallet detail each pallet will have a pallet identifier SSCC code unless it' a 4 title delivery in which
            //case each pallet with have a single SSCC for the title e.g. if there's 2 pallets they would have the same SSCC
            //for testing generate a random pallet count for the 1st detail section, 2nd detail section should only have the odds
            //
            //testing generate a random number of books per pallet

            double _test = _copies[_ix] / _parcels[_ix];
            double _part = _copies[_ix] % _parcels[_ix]; //get remainder BOOK count to go on part pallets
            double _full = Math.Floor(_test); //get full pallet count
            int _details = _part > 0 ? 2 : 1; //
            PrintersDespatchAdviceItemDetailPalletDetail[] _pallets = new PrintersDespatchAdviceItemDetailPalletDetail[_details];
            for (int _nx = 0; _nx < _pallets.Length; _nx++)
            {
                //do we need to add details for part pallet even if no part pallets exist?
                //if not just move this declaration inside if statement below
                _pallets[_nx] = new PrintersDespatchAdviceItemDetailPalletDetail();

                //if (_nx == 0 && _test > 0 || _nx == 1 && _part > 0)
                //{
                _pallets[_nx].NumberOfPallets = 1; //_nx == 0 ? (int)_full : _part > 0 ? 1: 0;
                _pallets[_nx].BooksPerPallet = _nx == 0 ? (int)_copies[_ix] - (int)_part : (int)_part;
                //add total # of pallets ot pallet count
                _npallets += _pallets[_nx].NumberOfPallets;
                //pallet identifier for each nxpallet, in a 4 title delivery they will all be same for the current title
                //so we only need to put the sscc in ONCE regardless of _nxpallets
                //string[] _id = new string[] { _sscc[_ix] };
                _pallets[_nx].PalletIdentifierList = new string[] { _sscc[_nx] }; //_nx== 0 ? _id : _part > 0 ? _id : new string[] {""};

                //parcel details
                _pallets[_nx].ParcelDetail = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetail();
                _pallets[_nx].ParcelDetail.NumberOfParcels = _nx == 0 ? (int)_full : _part > 0 ? 1 : 0;
                _pallets[_nx].ParcelDetail.BooksPerParcel = _parcels[_ix];//_nx == 0 ? (int)_books : (int)_part;
                _pallets[_nx].ParcelDetail.NumberOfOdds = 0;
                _pallets[_nx].ParcelDetail.ParcelsPerLayer = 10;

                //measurements for parcel
                string[] _parcelx = { "Height", "Width", "Depth", "UnitGrossWeight" };
                PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure[] _parcelmeasures = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure[_parcelx.Length];
                for (int _px = 0; _px < _parcelx.Length; _px++)
                {
                    _parcelmeasures[_px] = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure();
                    _parcelmeasures[_px].MeasureTypeCode = _parcelx[_px];
                    _parcelmeasures[_px].MeasurementValue = _nx < 3 ? _rnd.Next(350, 500) : Math.Round(_rnd.NextDouble() * 500, 2);
                }
                //end parcel measurements
                _pallets[_nx].ParcelDetail.Measure = _parcelmeasures;
                //end parcel
                //}
            }
            _items[_ix].PalletDetail = _pallets;
            //end pallets
        }
        _pda.ItemDetail = _items;
        //end itemdatails

        //footer summary data
        _pda.Summary = new PrintersDespatchAdviceSummary();
        _pda.Summary.NumberOfLines = _nlines;
        _pda.Summary.NumberOfPallets = _npallets;
        _pda.Summary.NumberOfUnits = _nunits;
        //end pda processing

        //serialize to file using sytem.xml.serialization and sytem.io.streamwriter
        //for testing
        //string _path = "c:\\ASNTEST\\" + _filename + ".xml";
        //create a temporary file
        //string _path = "~\\asn\\" + filename + ".xml";
        
        System.Xml.Serialization.XmlSerializer _szr = new System.Xml.Serialization.XmlSerializer((typeof(PrintersDespatchAdvice)));
        //remove namespace references from output
        XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
        _ns.Add("", "");
        XmlWriterSettings _st = new XmlWriterSettings();
        //_st.NewLineOnAttributes = true; //not necessary forcing indent should be enough
        _st.Indent = true;
        _st.OmitXmlDeclaration = true; //remove declaration and create usng WriteRaw and WriteProcessingInstruction below so we can include standalone
        _st.Encoding = Encoding.UTF8;

        //enclose in using to ensure all processes are closed once write is complete
        using (System.Xml.XmlWriter _wrt = System.Xml.XmlWriter.Create(filename, _st))
        {
            //make sure the header lines are on multiple lines
            _wrt.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
            _wrt.WriteRaw(Environment.NewLine);
            _wrt.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"CLDespatchAdvice-BIC.xsl\"");
            _wrt.WriteRaw(Environment.NewLine);
            //make sure standalone=true is included in xml declaration 
            //System.IO.StreamWriter _file = new System.IO.StreamWriter(_path);
            _szr.Serialize(_wrt, _pda, _ns);
        }
        _result = true;
        
        return _result;
    }
Esempio n. 37
0
    //end get file name
    /// <summary>
    /// 
    /// </summary>
    /// <param name="despatchno"></param>
    /// <param name="filename"></param>
    /// <param name="asndata"></param>
    /// <returns></returns>
    public static bool process_asn_titles(int despatchnoteid, string filename)
    {

        bool _result = false;
        //all datetimes in the .xsd schema manually converted to strings otherwise we can't format them as required in ASN specification
        DateTime _now = DateTime.Now;
        //issuedatetime
        string _issue = _now.ToString("yyyy-MM-dd\"T\"HH:mm:sszzz"); //for formatting issue date to 2014-01-30T13:07:45+00:00
        //string _issue = "yyyy-MM-dd\"T\"HH:mm:sszzz"; //for formatting issue date to 2014-01-30T13:07:45+00:00
        int _npallets = 0; //total number of pallets
        int _nlines = 0; //total of line numbers
        int _nunits = 0; //total number of books
        //constants
        const string _carriercode = "Shipper";
        const string _carriernamecode = "PUBLISHIP";
        const decimal _asnversion = 0.9M;
        const string _purpose = "Original";
        const int _perlayer = 10; //parcels per layer default value
        //*************************
        //get datareader for despatch note details and titles

        Query _q = new Query(DAL.Logistics.ViewAsnConsignment.Schema);
        _q.WHERE("despatch_note_id", Comparison.Equals, despatchnoteid);

        DAL.Logistics.ViewAsnConsignmentCollection _v = new ViewAsnConsignmentCollection();
        _v.LoadAndCloseReader(_q.ExecuteReader());
        DataTable _dt = _v.ToDataTable(); 
        //**************************
        
        //should ONLY be 1 printer and buyer, but just in case step though and create a seperate pda for each printer
        //get distinct printers
        string[] _col = { "printer_name", "printer_addr1", "printer_addr2", "printer_addr3", "printer_postcode", 
                          "buyer_name", "buyer_addr1", "buyer_addr2", "buyer_addr3", "buyer_postcode"};
        DataTable _pr = _dt.DefaultView.ToTable(true, _col); 
        
        for (int _pn = 0; _pn < _pr.Rows.Count; _pn++)
        {
            //class in xsds folder DAL.Logistics namespace
            //DAL.Logistics.PrintersDespatchAdvice _xml = new DAL.Logistics.PrintersDespatchAdvice  
            PrintersDespatchAdvice _pda = new PrintersDespatchAdvice();
            
            //header data
            _pda.Header = new PrintersDespatchAdviceHeader();
            _pda.Header.DespatchAdviceNumber = despatchnoteid; //file number? // orderno; //despatch number? 
            _pda.version = _asnversion;
            _pda.Header.IssueDateTime = _issue;
            _pda.Header.PurposeCode = _purpose;
            //reference coded elements
            _pda.Header.ReferenceCoded = new PrintersDespatchAdviceHeaderReferenceCoded();
            _pda.Header.ReferenceCoded.ReferenceNumber = "PDC20033"; ;
            _pda.Header.ReferenceCoded.ReferenceTypeCode = "BuyersReference";
            //datecoded elements
            _pda.Header.DateCoded = new PrintersDespatchAdviceHeaderDateCoded();
            _pda.Header.DateCoded.Date = _now.ToString("yyyyMMdd"); ///format yyyyMMdd 
            _pda.Header.DateCoded.DateQualifierCode = "Not yet shipped";
            //buyer party elements 1-6 address lines  (client? in publiship db)
            _pda.Header.BuyerParty = new PrintersDespatchAdviceHeaderBuyerParty();
            _pda.Header.BuyerParty.PartyName = new PrintersDespatchAdviceHeaderBuyerPartyPartyName();
            _pda.Header.BuyerParty.PartyName.NameLine = _pr.Rows[_pn].IsNull("buyer_name") ? "" : _pr.Rows[_pn]["buyer_name"].ToString(); //"Pearson Education Ltd";
            _pda.Header.BuyerParty.PostalAddress = new PrintersDespatchAdviceHeaderBuyerPartyPostalAddress();
            _pda.Header.BuyerParty.PostalAddress.AddressLine = new string[] { 
                _pr.Rows[_pn].IsNull("buyer_addr1") ? "": _pr.Rows[_pn]["buyer_addr1"].ToString(), 
                _pr.Rows[_pn].IsNull("buyer_addr2") ? "": _pr.Rows[_pn]["buyer_addr2"].ToString(),
                _pr.Rows[_pn].IsNull("buyer_addr3") ? "": _pr.Rows[_pn]["buyer_addr3"].ToString()
            }; //{ "Halley Court", "Jordan Hill", "Oxford" };
            _pda.Header.BuyerParty.PostalAddress.PostalCode = _pr.Rows[_pn].IsNull("buyer_postcode") ? "" : _pr.Rows[_pn]["buyer_postcode"].ToString(); //"OX2 8EJ";
            //seller party elements 1-6 address lines (PRINTER? in publiship db)
            _pda.Header.SellerParty = new PrintersDespatchAdviceHeaderSellerParty();
            _pda.Header.SellerParty.PartyName = new PrintersDespatchAdviceHeaderSellerPartyPartyName();
            _pda.Header.SellerParty.PartyName.NameLine = _pr.Rows[_pn].IsNull("printer_name") ? "" : _pr.Rows[_pn]["printer_name"].ToString(); //"Jiwabaru";
            _pda.Header.SellerParty.PostalAddress = new PrintersDespatchAdviceHeaderSellerPartyPostalAddress();
            _pda.Header.SellerParty.PostalAddress.AddressLine = new string[] { 
                 _pr.Rows[_pn].IsNull("printer_addr1") ? "": _pr.Rows[_pn]["printer_addr1"].ToString(), 
                 _pr.Rows[_pn].IsNull("printer_addr2") ? "": _pr.Rows[_pn]["printer_addr2"].ToString(), 
                 _pr.Rows[_pn].IsNull("printer_addr3") ? "": _pr.Rows[_pn]["printer_addr3"].ToString()
            }; //{ "NO: 2, JALAN P/8, KAWASAN MIEL FASA 2", "BANDAR BARU BANGI", "SELANGOR DARUL EHSAN", "43650", "Malaysia" };
            _pda.Header.SellerParty.PostalAddress.PostalCode = _pr.Rows[_pn].IsNull("printer_postcode") ? "" : _pr.Rows[_pn]["printer_postcode"].ToString(); 
            //ship to party party id elements
            _pda.Header.ShipToParty = new PrintersDespatchAdviceHeaderShipToParty();
            //required
            _pda.Header.ShipToParty.PartyID = new PrintersDespatchAdviceHeaderShipToPartyPartyID();
            _pda.Header.ShipToParty.PartyID.PartyIDType = "EAN";
            _pda.Header.ShipToParty.PartyID.Identifier = "PEAR011";
            //
            _pda.Header.ShipToParty.PartyName = new PrintersDespatchAdviceHeaderShipToPartyPartyName();
            _pda.Header.ShipToParty.PartyName.NameLine = "Pearson Distribution Centre";
            _pda.Header.ShipToParty.PostalAddress = new PrintersDespatchAdviceHeaderShipToPartyPostalAddress();
            _pda.Header.ShipToParty.PostalAddress.AddressLine = new string[] { "Unit 1", "Castle Mound Way", "Rugby", "Warwickshire", "UK" };
            _pda.Header.ShipToParty.PostalAddress.PostalCode = "CV23 0WB";
            //delivery elements
            _pda.Header.Delivery = new PrintersDespatchAdviceHeaderDelivery();
            _pda.Header.Delivery.TrailerNumber = "PU1"; //from database?
            //delivery carrier
            _pda.Header.Delivery.Carrier = new PrintersDespatchAdviceHeaderDeliveryCarrier();
            //delivery carrier carriername coded
            _pda.Header.Delivery.Carrier.CarrierNameCoded = new PrintersDespatchAdviceHeaderDeliveryCarrierCarrierNameCoded();
            _pda.Header.Delivery.Carrier.CarrierNameCoded.CarrierNameCodeType = _carriercode;
            _pda.Header.Delivery.Carrier.CarrierNameCoded.CarrierNameCode = _carriernamecode;
            //end header        

            //11.11.2014 Pearson agreed that when we have 4 titles on a delivery we can just give 1 SSCC code per title instead of
            //SSCC codes for every pallet
            //items emuneration
            //we will also build counters for summary data at the same time
            //get total number of books for the ISBN and divide by books per pallet (pack size). the 1st item detail section will contain the
            //carton details that can be delivered in quantities of the pack size. the 2nd item detail section will contain the remainder
            //e.g. no of books = 270, pack size = 40: 1st pallet section number of pallets = 6 x 40, 2nd section = 1 x 30.
            //there should be 2 PrintersDespatchAdviceItemDetail
            int _itemcount = _dt.Select("printer_name = '" + _pda.Header.SellerParty.PartyName.NameLine.ToString() + "'").Length;
            PrintersDespatchAdviceItemDetail[] _items = new PrintersDespatchAdviceItemDetail[_itemcount];
            for (int _ix = 0; _ix < _items.Length; _ix++)
            {
                string _thisprinter = _dt.Rows[_ix].IsNull("printer_name") ? "" :_dt.Rows[_ix]["printer_name"].ToString();
                int _itemid = _dt.Rows[_ix].IsNull("item_id") ? 0 : wwi_func.vint(_dt.Rows[_ix]["item_id"].ToString());   

                if (_thisprinter == _pda.Header.SellerParty.PartyName.NameLine)
                {
                    //get copies and parcels
                    int _copies = _dt.Rows[_ix].IsNull("total_qty") ? 0 : wwi_func.vint(_dt.Rows[_ix]["total_qty"].ToString());
                    int _parcels = _dt.Rows[_ix].IsNull("parcel_count") ? 0 : wwi_func.vint(_dt.Rows[_ix]["parcel_count"].ToString());
                    //
                    _nlines += 1;//add to total line count
                    _nunits += _copies;//add to total copies 
                    _items[_ix] = new PrintersDespatchAdviceItemDetail();
                    _items[_ix].LineNumber = _ix + 1;
                    _items[_ix].Impression = _dt.Rows[_ix].IsNull("impression") ? "" : _dt.Rows[_ix]["impression"].ToString();  //impression number from database
                    _items[_ix].Quantity = _copies;

                    //item product id's include isbn and ean13 even if we don't have values for them
                    //DateTime? _ets = wwi_func.vdatetime(wwi_func.l.lookup_xml_string("xml\\parameters.xml", "name", "startETS", "value"));
                    string[] _ids = { "ISBN", "EAN13" };
                    PrintersDespatchAdviceItemDetailProductID[] _productids = new PrintersDespatchAdviceItemDetailProductID[_ids.Length];
                    for (int _nx = 0; _nx < _ids.Length; _nx++)
                    {
                        _productids[_nx] = new PrintersDespatchAdviceItemDetailProductID();
                        _productids[_nx].ProductIDType = _ids[_nx];
                        //23/03/15 populate both ISBN and EAN with ISBN 
                        _productids[_nx].Identifier = _dt.Rows[_ix].IsNull("isbn") ? "":  _dt.Rows[_ix]["isbn"].ToString();
                    }
                    _items[_ix].ProductID = _productids;
                    //end productids for this item

                    //item description
                    _items[_ix].ItemDescription = new PrintersDespatchAdviceItemDetailItemDescription();
                    _items[_ix].ItemDescription.TitleDetail = _dt.Rows[_ix]["Title"].ToString();
                    _items[_ix].ItemDescription.BindingDescription = "UNKNOWN";

                    //measurements include even if unknown
                    string[] _itemx = { "Height", "Width", "Depth", "Unit_Net_Weight" };
                    PrintersDespatchAdviceItemDetailItemDescriptionMeasure[] _measures = new PrintersDespatchAdviceItemDetailItemDescriptionMeasure[_itemx.Length];
                    for (int _nx = 0; _nx < _itemx.Length; _nx++)
                    {
                        double _value = _dt.Rows[_ix].IsNull(_itemx[_nx]) ? 0:  wwi_func.vdouble(_dt.Rows[_ix][_itemx[_nx]].ToString());
                        _measures[_nx] = new PrintersDespatchAdviceItemDetailItemDescriptionMeasure();
                        _measures[_nx].MeasureTypeCode = _itemx[_nx].Replace("_", "") ;
                        _measures[_nx].MeasurementValue = _value;
                    }
                    _items[_ix].ItemDescription.Measure = _measures;
                    //end measurements for item
                    //item referencecoded
                    string[] _reftypes = { "Buyers_Order_Number", "Printers_Job_Number" };//printers SRR file, publiship order number from database
                    PrintersDespatchAdviceItemDetailReferenceCoded[] _refcodes = new PrintersDespatchAdviceItemDetailReferenceCoded[_reftypes.Length];
                    for (int _nx = 0; _nx < _reftypes.Length; _nx++)
                    {
                        _refcodes[_nx] = new PrintersDespatchAdviceItemDetailReferenceCoded();
                        _refcodes[_nx].ReferenceTypeCode = _reftypes[_nx].Replace("_", "") ;
                        _refcodes[_nx].ReferenceNumber = _dt.Rows[_ix].IsNull(_reftypes[_nx]) ? "" :  _dt.Rows[_ix][_reftypes[_nx]].ToString();
                    }
                    _items[_ix].ReferenceCoded = _refcodes;
                    //end refcodes
                    //there should be no more than 2 pallet detail sections. the 1st one for whole pallets, 2nd for part pallet
                    //item pallet detail each pallet will have a pallet identifier SSCC code unless it' a 4 title delivery in which
                    //case each pallet with have a single SSCC for the title e.g. if there's 2 pallets they would have the same SSCC
                    //for testing generate a random pallet count for the 1st detail section, 2nd detail section should only have the odds
                    //
                    int _fullpallets = _dt.Rows[_ix].IsNull("full_pallets") ? 0 : wwi_func.vint(_dt.Rows[_ix]["full_pallets"].ToString()); 
                    int _partpallets = _dt.Rows[_ix].IsNull("part_pallets") ? 0: wwi_func.vint( _dt.Rows[_ix]["part_pallets"].ToString());
                    PrintersDespatchAdviceItemDetailPalletDetail[] _pallets = new PrintersDespatchAdviceItemDetailPalletDetail[_partpallets == 0? 1: 2];
                    for (int _nx = 0; _nx < _pallets.Length; _nx++)
                    {
                        //do we need to add details for part pallet even if no part pallets exist?
                        //if not just move this declaration inside if statement below
                        _pallets[_nx] = new PrintersDespatchAdviceItemDetailPalletDetail();

                        //if (_nx == 0 && _test > 0 || _nx == 1 && _part > 0)
                        //{
                        _pallets[_nx].NumberOfPallets = _nx == 0 ? _fullpallets : _partpallets;
                        
                        int _booksperpallet = 0;
                        if(_nx == 0){
                            _booksperpallet = _dt.Rows[_ix].IsNull("units_full") ? 0 : wwi_func.vint(_dt.Rows[_ix]["units_full"].ToString());
                        }
                        else
                        { 
                            _booksperpallet = _dt.Rows[_ix].IsNull("units_part") ? 0: wwi_func.vint(_dt.Rows[_ix]["units_part"].ToString());
                        }

                        _pallets[_nx].BooksPerPallet = _booksperpallet;
                        //add total # of pallets ot pallet count
                        _npallets += _pallets[_nx].NumberOfPallets;
                        //pallet identifier for each nxpallet, in a 4 title delivery they will all be same for the current title
                        //so we only need to put the sscc in ONCE regardless of _nxpallets
                        //string[] _id = new string[] { _sscc[_ix] };
                        string _pallettype = _nx == 0 ? "Full" : "Part";
                        //List<String> _ssccs = new List<String>();
                        DataTable _sscc = DAL.Logistics.DB.Select("SSCC").
                            From(DAL.Logistics.Tables.DespatchNotePalletId).
                            Where(DAL.Logistics.DespatchNotePalletId.DespatchItemIdColumn).IsEqualTo(_itemid).
                            And(DAL.Logistics.DespatchNotePalletId.PalletTypeColumn).IsEqualTo(_pallettype).ExecuteDataSet().Tables[0];
                        string[] _ssccs = wwi_func.datatable_to_array(_sscc, 0); 
                        //split json string and add pallet identifiers for this item
                        _pallets[_nx].PalletIdentifierList = _ssccs;//new string[] { _dt.Rows[_ix].IsNull("SSCC") ? "": _dt.Rows[_ix]["SSCC"].ToString() };
                        //
                        //parcel details
                        _pallets[_nx].ParcelDetail = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetail();
                        _pallets[_nx].ParcelDetail.NumberOfParcels = _dt.Rows[_ix].IsNull("parcel_count") ? 0:  wwi_func.vint(_dt.Rows[_ix]["parcel_count"].ToString()); //_nx == 0 ? (int)_full : _part > 0 ? 1 : 0;
                        _pallets[_nx].ParcelDetail.BooksPerParcel = _dt.Rows[_ix].IsNull("units_per_parcel") ? 0: wwi_func.vint(_dt.Rows[_ix]["units_per_parcel"].ToString()); //_parcels;//_nx == 0 ? (int)_books : (int)_part;
                        _pallets[_nx].ParcelDetail.NumberOfOdds = _dt.Rows[_ix].IsNull("odds_count") ? 0:  wwi_func.vint(_dt.Rows[_ix]["odds_count"].ToString());
                        _pallets[_nx].ParcelDetail.ParcelsPerLayer = _dt.Rows[_ix].IsNull("parcels_per_layer") ? _perlayer : wwi_func.vint(_dt.Rows[_ix]["parcels_per_layer"].ToString()); //default to 10

                        //measurements for parcel
                        string[] _parcelx = { "Parcel_Height", "Parcel_Width", "Parcel_Depth", "Parcel_UnitGrossWeight" };
                        PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure[] _parcelmeasures = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure[_parcelx.Length];
                        for (int _px = 0; _px < _parcelx.Length; _px++)
                        {
                            double _value = _dt.Rows[_ix].IsNull(_itemx[_px]) ? 0: wwi_func.vdouble(_dt.Rows[_ix][_itemx[_px]].ToString());
                            _parcelmeasures[_px] = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure();
                            _parcelmeasures[_px].MeasureTypeCode = _parcelx[_px].Replace("Parcel_", "");
                            _parcelmeasures[_px].MeasurementValue = _value;
                        }
                        //end parcel measurements
                        _pallets[_nx].ParcelDetail.Measure = _parcelmeasures;
                        //end parcel
                        //}
                    }
                    _items[_ix].PalletDetail = _pallets;
                    //end pallets
                }//end if printer namse
            }
            _pda.ItemDetail = _items;
            //end itemdatails

            //footer summary data
            _pda.Summary = new PrintersDespatchAdviceSummary();
            _pda.Summary.NumberOfLines = _nlines;
            _pda.Summary.NumberOfPallets = _npallets;
            _pda.Summary.NumberOfUnits = _nunits;
            //end pda processing

            //serialize to file using sytem.xml.serialization and sytem.io.streamwriter
            //for testing
            //string _path = "c:\\ASNTEST\\" + _filename + ".xml";
            //create a temporary file
            //string _path = "~\\asn\\" + filename + ".xml";

            System.Xml.Serialization.XmlSerializer _szr = new System.Xml.Serialization.XmlSerializer((typeof(PrintersDespatchAdvice)));
            //remove namespace references from output
            XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
            _ns.Add("", "");
            XmlWriterSettings _st = new XmlWriterSettings();
            //_st.NewLineOnAttributes = true; //not necessary forcing indent should be enough
            _st.Indent = true;
            _st.OmitXmlDeclaration = true; //remove declaration and create usng WriteRaw and WriteProcessingInstruction below so we can include standalone
            _st.Encoding = Encoding.UTF8;

            //enclose in using to ensure all processes are closed once write is complete
            using (System.Xml.XmlWriter _wrt = System.Xml.XmlWriter.Create(filename, _st))
            {
                //make sure the header lines are on multiple lines
                _wrt.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
                _wrt.WriteRaw(Environment.NewLine);
                _wrt.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"CLDespatchAdvice-BIC.xsl\"");
                _wrt.WriteRaw(Environment.NewLine);
                //make sure standalone=true is included in xml declaration 
                //System.IO.StreamWriter _file = new System.IO.StreamWriter(_path);
                _szr.Serialize(_wrt, _pda, _ns);
            }
        }//end printers loop

        _result = true;

        return _result;
    }
Esempio n. 38
0
    //end process asn
    
    public static bool process_asn_test_1title(int orderno)
    {
        bool _result = false; //returned value true if processed
        //all datetimes in the .xsd schema manually converted to strings otherwise we can't format them as required in ASN specification
        DateTime _now = DateTime.Now;
        //issuedatetime
        string _issue = _now.ToString("yyyy-MM-dd\"T\"HH:mm:sszzz"); //for formatting issue date to 2014-01-30T13:07:45+00:00
        //string _issue = "yyyy-MM-dd\"T\"HH:mm:sszzz"; //for formatting issue date to 2014-01-30T13:07:45+00:00
        int _npallets = 0; //total number of pallts
        int _nlines = 0; //total of line numbers
        int _nunits = 0; //total number of books
        //constants
        const int _details = 0;
        const string _carriercode = "Shipper";
        const string _carriernamecode = "PUBLISHIP";
        const decimal _asnversion = 0.9M;
        const string _purpose = "Original";

        //*************************
        //for testing a 1 title pallet
        const byte _numpallets = 1;
        string[] _titles = { "8 Hein Maths 4 Number Workbk Pk 8" };
        int[] _copies = { 1200 };
        //full pallets
        string[] _sscc1 = { "000312414124512516", "008956784575745752", "006523877238568293" }; //need an SSCC for each PALLET 
        //odd pallet
        string[] _sscc2 = { "003854336045342954" };
        //**************************
        //class in xsds folder DAL.Logistics namespace
        //DAL.Logistics.PrintersDespatchAdvice _xml = new DAL.Logistics.PrintersDespatchAdvice  
        PrintersDespatchAdvice _pda = new PrintersDespatchAdvice();

        //header data
        _pda.Header = new PrintersDespatchAdviceHeader();
        _pda.version = _asnversion;
        _pda.Header.DespatchAdviceNumber = 1; // orderno; //despatch number? 
        _pda.Header.IssueDateTime = _issue;
        _pda.Header.PurposeCode = _purpose;
        //reference coded elements
        _pda.Header.ReferenceCoded = new PrintersDespatchAdviceHeaderReferenceCoded();
        _pda.Header.ReferenceCoded.ReferenceNumber = "7A00000041172"; ;
        _pda.Header.ReferenceCoded.ReferenceTypeCode = "BuyersReference";
        //datecoded elements
        _pda.Header.DateCoded = new PrintersDespatchAdviceHeaderDateCoded();
        _pda.Header.DateCoded.Date = _now.ToString("yyyyMMdd"); ///format yyyyMMdd 
        _pda.Header.DateCoded.DateQualifierCode = "Not yet shipped";
        //buyer party elements 1-6 address lines  (CUSTOMER? in publiship db)
        _pda.Header.BuyerParty = new PrintersDespatchAdviceHeaderBuyerParty();
        _pda.Header.BuyerParty.PartyName = new PrintersDespatchAdviceHeaderBuyerPartyPartyName();
        _pda.Header.BuyerParty.PartyName.NameLine = "Pearson Education Ltd"; ;
        _pda.Header.BuyerParty.PostalAddress = new PrintersDespatchAdviceHeaderBuyerPartyPostalAddress();
        _pda.Header.BuyerParty.PostalAddress.AddressLine = new string[] { "Halley Court", "Jordan Hill", "Oxford" };
        _pda.Header.BuyerParty.PostalAddress.PostalCode = "OX2 8EJ";
        //seller party elements 1-6 address lines (PRINTER? in publiship db)
        _pda.Header.SellerParty = new PrintersDespatchAdviceHeaderSellerParty();
        _pda.Header.SellerParty.PartyName = new PrintersDespatchAdviceHeaderSellerPartyPartyName();
        _pda.Header.SellerParty.PartyName.NameLine = "CTPS Holdings Inc";
        _pda.Header.SellerParty.PostalAddress = new PrintersDespatchAdviceHeaderSellerPartyPostalAddress();
        _pda.Header.SellerParty.PostalAddress.AddressLine = new string[] { "6/F, Reliance Mfy. Building", "24 Wong Chuk Hang Road", "Hong Kong/China" };
        _pda.Header.SellerParty.PostalAddress.PostalCode = "";
        //ship to party party id elements
        _pda.Header.ShipToParty = new PrintersDespatchAdviceHeaderShipToParty();
        //required
        _pda.Header.ShipToParty.PartyID = new PrintersDespatchAdviceHeaderShipToPartyPartyID();
        _pda.Header.ShipToParty.PartyID.PartyIDType = "EAN";
        _pda.Header.ShipToParty.PartyID.Identifier = "PEAR011";
        //
        _pda.Header.ShipToParty.PartyName = new PrintersDespatchAdviceHeaderShipToPartyPartyName();
        _pda.Header.ShipToParty.PartyName.NameLine = "Pearson Distribution Centre";
        _pda.Header.ShipToParty.PostalAddress = new PrintersDespatchAdviceHeaderShipToPartyPostalAddress();
        _pda.Header.ShipToParty.PostalAddress.AddressLine = new string[] { "Unit 1", "Castle Mound Way", "Rugby", "Warwickshire", "UK" };
        _pda.Header.ShipToParty.PostalAddress.PostalCode = "CV23 0WB";
        //delivery elements
        _pda.Header.Delivery = new PrintersDespatchAdviceHeaderDelivery();
        _pda.Header.Delivery.TrailerNumber = "";
        //delivery carrier
        _pda.Header.Delivery.Carrier = new PrintersDespatchAdviceHeaderDeliveryCarrier();
        //delivery carrier carriername coded
        _pda.Header.Delivery.Carrier.CarrierNameCoded = new PrintersDespatchAdviceHeaderDeliveryCarrierCarrierNameCoded();
        _pda.Header.Delivery.Carrier.CarrierNameCoded.CarrierNameCodeType = _carriercode;
        _pda.Header.Delivery.Carrier.CarrierNameCoded.CarrierNameCode = _carriernamecode;
        //end header        

        //11.11.2014 Pearson aggreeed that when we have 4 titles on a delivery we can just give 1 SSCC code per title instead of
        //SSCC codes for every pallet
        //items emuneration
        //we will also build counters for summary data at the same time
        //get total number of books for the ISBN and divide by books per pallet (pack size). the 1st item detail section will contain the
        //carton details that can be delivered in quantities of the pack size. the 2nd item detail section will contain the remainder
        //e.g. no of books = 270, pack size = 40: 1st pallet section number of pallets = 6 x 40, 2nd section = 1 x 30.
        //there should be 2 PrintersDespatchAdviceItemDetail
        PrintersDespatchAdviceItemDetail[] _items = new PrintersDespatchAdviceItemDetail[_titles.Length];
        for (int _ix = 0; _ix < _items.Length; _ix++)
        {
            _nlines += 1;//add to total line count
            _nunits += _copies[_ix];//add to total copies 
            _items[_ix] = new PrintersDespatchAdviceItemDetail();
            _items[_ix].LineNumber = _ix + 1;
            _items[_ix].Impression = "0";
            _items[_ix].Quantity = _copies[_ix];

            //item product id's
            string[] _ids = { "ISBN" };
            PrintersDespatchAdviceItemDetailProductID[] _productids = new PrintersDespatchAdviceItemDetailProductID[_ids.Length];
            for (int _nx = 0; _nx < _ids.Length; _nx++)
            {
                _productids[_nx] = new PrintersDespatchAdviceItemDetailProductID();
                _productids[_nx].ProductIDType = _ids[_nx];
                _productids[_nx].Identifier = "9781742660301";
            }
            _items[_ix].ProductID = _productids;
            //end produtids for this item


            //item description
            _items[_ix].ItemDescription = new PrintersDespatchAdviceItemDetailItemDescription();
            _items[_ix].ItemDescription.TitleDetail = _titles[_ix];
            _items[_ix].ItemDescription.BindingDescription = "UNKNOWN";

            //measurements include even if unknown
            string[] _itemx = { "Height", "Width", "Depth", "UnitNetWeight" };
            PrintersDespatchAdviceItemDetailItemDescriptionMeasure[] _measures = new PrintersDespatchAdviceItemDetailItemDescriptionMeasure[_itemx.Length];
            for (int _nx = 0; _nx < _itemx.Length; _nx++)
            {
                _measures[_nx] = new PrintersDespatchAdviceItemDetailItemDescriptionMeasure();
                _measures[_nx].MeasureTypeCode = _itemx[_nx];
                _measures[_nx].MeasurementValue = 0;
            }
            _items[_ix].ItemDescription.Measure = _measures;
            //end measurements for item

            //item referencecoded
            string[] _reftypes = { "BuyersOrderNumber", "PrintersJobNumber" };
            PrintersDespatchAdviceItemDetailReferenceCoded[] _refcodes = new PrintersDespatchAdviceItemDetailReferenceCoded[_reftypes.Length];
            for (int _nx = 0; _nx < _reftypes.Length; _nx++)
            {
                _refcodes[_nx] = new PrintersDespatchAdviceItemDetailReferenceCoded();
                _refcodes[_nx].ReferenceTypeCode = _reftypes[_nx];
                _refcodes[_nx].ReferenceNumber = "12345";
            }
            _items[_ix].ReferenceCoded = _refcodes;
            //end refcodes
            //there should be no more than 2 pallet detail sections, 1st for whole pallets, 2nd for part pallet
            //item pallet detail each pallet will have a pallet identifier SSCC code unless it' a 4 title delivery in which
            //case each pallet with have a single SSCC for the title e.g. if there's 2 pallets they would have the same SSCC
            //for testing generate a random pallet count for the 1st detail section, 2nd detail section should only have 1 pallet (the odds)
            PrintersDespatchAdviceItemDetailPalletDetail[] _pallets = new PrintersDespatchAdviceItemDetailPalletDetail[_details];
            for (int _nx = 0; _nx < _pallets.Length; _nx++)
            {
                //add to total pallets
                //enumerate through pallet detail sections add number of pallets in this section, etc
                int _nxpallets = _nx == 0 ? _numpallets : 1; //for testing
                _npallets += _nxpallets;
                _pallets[_nx] = new PrintersDespatchAdviceItemDetailPalletDetail();
                _pallets[_nx].NumberOfPallets = _nxpallets;
                _pallets[_nx].BooksPerPallet = _nx == 0 ? _copies[_ix] / _numpallets : _copies[_ix] % _numpallets;
                //need an SSCC code for EACH pallet
                _pallets[_nx].PalletIdentifierList = _nx == 0 ? _sscc1 : _sscc2;

                //parcel details
                _pallets[_nx].ParcelDetail = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetail();
                _pallets[_nx].ParcelDetail.NumberOfParcels = 1;
                _pallets[_nx].ParcelDetail.NumberOfOdds = 0;
                _pallets[_nx].ParcelDetail.BooksPerParcel = _nx == 0 ? (int)(_copies[_ix] / _nxpallets) : (int)(_copies[_ix] % _numpallets);
                //measurements for parcel
                string[] _parcelx = { "Height", "Width", "Depth", "UnitGrossWeight" };
                PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure[] _parcelmeasures = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure[_parcelx.Length];
                for (int _px = 0; _px < _parcelx.Length; _px++)
                {
                    _parcelmeasures[_px] = new PrintersDespatchAdviceItemDetailPalletDetailParcelDetailMeasure();
                    _parcelmeasures[_px].MeasureTypeCode = _parcelx[_px];
                    _parcelmeasures[_px].MeasurementValue = 0;
                }
                //end parcel measurements
                _pallets[_nx].ParcelDetail.Measure = _parcelmeasures;
                //end parcel
            }
            _items[_ix].PalletDetail = _pallets;
            //end pallets
        }
        _pda.ItemDetail = _items;
        //end itemdatails

        //footer summary data
        _pda.Summary = new PrintersDespatchAdviceSummary();
        _pda.Summary.NumberOfLines = _nlines;
        _pda.Summary.NumberOfPallets = _npallets;
        _pda.Summary.NumberOfUnits = _nunits;
        //end pda processing

        //serialize to file using sytem.xml.serialization and sytem.io.streamwriter
        string _path = "c:\\ASNTEST\\" + orderno.ToString() + "_" + DateTime.Now.Second.ToString() + ".xml";
        System.Xml.Serialization.XmlSerializer _writer = new System.Xml.Serialization.XmlSerializer((typeof(PrintersDespatchAdvice)));
        //remove namespace references from output
        XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
        _ns.Add("", "");
        XmlWriterSettings _st = new XmlWriterSettings();
        //_st.NewLineOnAttributes = true; //not necessary forcing indent should be enough
        _st.Indent = true;
        _st.OmitXmlDeclaration = true; //remove declaration and create usng WriteRaw and WriteProcessingInstruction below so we can include standalone
        _st.Encoding = Encoding.UTF8;

        System.Xml.XmlWriter _file = System.Xml.XmlWriter.Create(_path, _st);
        //make sure the header lines are on multiple lines
        _file.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
        _file.WriteRaw(Environment.NewLine);
        _file.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"CLDespatchAdvice-BIC.xsl\"");
        _file.WriteRaw(Environment.NewLine);
        //make sure standalone=true is included in xml declaration 
        //System.IO.StreamWriter _file = new System.IO.StreamWriter(_path);
        _writer.Serialize(_file, _pda, _ns);
        _result = true;

        return _result;
    }
Esempio n. 39
0
        /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write5"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager) {
            XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema));
            XmlSerializerNamespaces ns;
            
            if (namespaceManager != null) {
                ns = new XmlSerializerNamespaces();
                bool ignoreXS = false;
                if (this.Namespaces != null) { //User may have set both nsManager and Namespaces property on the XmlSchema object
                    ignoreXS = this.Namespaces.Namespaces["xs"] != null || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs);

                }
                if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && 
                    namespaceManager.LookupNamespace("xs") == null ) {
                        ns.Add("xs", XmlReservedNs.NsXs);
                }
                foreach(string prefix in namespaceManager) {
                    if (prefix != "xml" && prefix != "xmlns") {
                        ns.Add(prefix, namespaceManager.LookupNamespace(prefix));
                    }
                }

            } else if (this.Namespaces != null && this.Namespaces.Count > 0) {
                Hashtable serializerNS = this.Namespaces.Namespaces;
                if (serializerNS["xs"] == null && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix
                    serializerNS.Add("xs", XmlReservedNs.NsXs);
                }
                ns = this.Namespaces;
            }
            else {
                ns = new XmlSerializerNamespaces();
                ns.Add("xs", XmlSchema.Namespace);
                if (targetNs != null && targetNs.Length != 0) {
                    ns.Add("tns", targetNs);
                }
            }
            serializer.Serialize(writer, this, ns);
        }
Esempio n. 40
0
    public string Serialize()
    {
        XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.ASCII };

        using (MemoryStream stream = new MemoryStream())
        using (XmlWriter writer = XmlWriter.Create(stream, settings))
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "uuid:24B83862-D136-42F0-A7C8-7A9F785489CF");

            XmlSerializer serializer = new XmlSerializer(typeof(ProductPrice));
            serializer.Serialize(writer, this, ns);

            string xml = Encoding.ASCII.GetString(stream.ToArray());
            return xml;
        }
    }
Esempio n. 41
0
	public void SerializeToPath (string path)
	{	
		using (XmlTextWriter writer = new XmlTextWriter (path, System.Text.Encoding.GetEncoding ("ISO-8859-1"))) {
			XmlSerializerNamespaces ns = new XmlSerializerNamespaces ();
			ns.Add (string.Empty, string.Empty);
			writer.Formatting = Formatting.Indented;
			XmlSerializer serializer = new XmlSerializer (typeof(ILConfig));
			serializer.Serialize (writer, this, ns);
		}
	}
Esempio n. 42
0
            public static string ConvertToXml(object toSerialize, Type objectType)
            {
                // create a string wrtiter to hold the xml string
                // the a xml writer with the proper settings.
                // use that writer to serialize the document.
                // use an  namespace to create a fully qualified odcument.
                StringWriter aWriter = new StringWriter();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                settings.ConformanceLevel = ConformanceLevel.Document; // Fragment fails
                settings.Indent = false;
                settings.Encoding = System.Text.Encoding.UTF8;

                XmlWriter xWriter = XmlWriter.Create(aWriter, settings);

                new XmlSerializerNamespaces();
                XmlSerializerNamespaces myNamespaces = new XmlSerializerNamespaces();
                myNamespaces.Add("wtr", "http://www.cuahsi.org/waterML/1_1/");
                myNamespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");
                myNamespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                myNamespaces.Add("gml", "http://www.opengis.net/gml");
                myNamespaces.Add("xlink", "http://www.w3.org/1999/xlink");
                myNamespaces.Add("xml", "http://www.w3.org/XML/1998/namespace");

                XmlSerializer aSerializer = new XmlSerializer(objectType);
                //aSerialize(xWriter, toSerialize);
                aSerializer.Serialize(xWriter, toSerialize, myNamespaces);
                string xml = aWriter.ToString();
                aWriter.Flush();
                aWriter.Close();
                return xml;
            }
Esempio n. 43
0
 public ComponentLink()
 {
     Namespaces = new XmlSerializerNamespaces();
     Namespaces.Add("xlink", "http://www.w3.org/1999/xlink");
 }
Esempio n. 44
0
 public string ConvertObjectToXml(Object objData)
 {
     try
     {
         var xmlDoc = new XmlDocument(); //Represents an XML document,
         // Initializes a new instance of the XmlDocument class.
         var xmlSerializer = new XmlSerializer(objData.GetType());
         // Create empty namespace
         var namespaces = new XmlSerializerNamespaces();
         namespaces.Add(string.Empty, string.Empty);
         // Creates a stream whose backing store is memory.
         using (var xmlStream = new MemoryStream())
         {
             xmlSerializer.Serialize(xmlStream, objData, namespaces);
             xmlStream.Position = 0;
             //Loads the XML document from the specified string.
             xmlDoc.Load(xmlStream);
             foreach (XmlNode node in xmlDoc)
             {
                 if (node.NodeType == XmlNodeType.XmlDeclaration)
                 {
                     xmlDoc.RemoveChild(node);
                 }
             }
             return xmlDoc.InnerXml;
         }
     }
     catch (Exception ex)
     {
         return ex.Message;
     }
 }