示例#1
0
 internal static string ToXml(this object item)
 {
     if (item == null)
         return null;
     try
     {
         using (var stream = new StringWriter())
         {
             var settings = new XmlWriterSettings();
             settings.Indent = false;
             settings.OmitXmlDeclaration = true;
             using (var writer = XmlWriter.Create(stream, settings))
             {
                 var serializer = new XmlSerializer(item.GetType());
                 var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
                 serializer.Serialize(writer, item, emptyNamepsaces);
                 return stream.ToString();
             }
         }
     }
     catch
     {
         throw;
     }
 }
示例#2
0
 public Account()
 {
     _namespaces = new XmlSerializerNamespaces(new[]
     {
         new XmlQualifiedName(string.Empty, "rotmg")
     });
 }
 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);
         }
     }
 }
示例#6
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();
     }
 }
示例#8
0
        public static void WriteAddress()
        {
            Point point = new Point
            {
                BitIndex        = "bitindex",
                DataBit         = "databit",
                Factor          = "factor",
                LocalAddress    = "localaddress",
                ProtocolAddress = "protocoladdress",
                TextContent     = "text"
            };
            Point point2 = new Point
            {
                BitIndex        = "bitindex2",
                DataBit         = "databit2",
                Factor          = "factor2",
                LocalAddress    = "localaddress2",
                ProtocolAddress = "protocoladdress2",
                TextContent     = "text2"
            };
            Point point3 = new Point
            {
                BitIndex        = "bitindex",
                DataBit         = "databit",
                Factor          = "factor",
                LocalAddress    = "localaddress",
                ProtocolAddress = "protocoladdress",
                TextContent     = "text"
            };
            Point point4 = new Point
            {
                BitIndex        = "bitindex2",
                DataBit         = "databit2",
                Factor          = "factor2",
                LocalAddress    = "localaddress2",
                ProtocolAddress = "protocoladdress2",
                TextContent     = "text2"
            };
            PointsConnection points = new PointsConnection
            {
                ID           = "1",
                FunctionCode = "03",
                SlaveId      = "slave",
            };

            points.ID = "11245";
            Point[] pointArr = new Point[] { point, point2 };
            points.PointArray = pointArr;
            PointsConnection points2 = new PointsConnection
            {
                ID           = "12",
                FunctionCode = "032",
                SlaveId      = "slave2",
            };

            Point[] pointArray = new Point[] { point3, point4 };
            points2.PointArray = pointArray;
            PointsTypeConnection pointsType = new PointsTypeConnection();

            PointsConnection[] pointsConnections = new PointsConnection[] { points, points2 };
            pointsType.Add(points); pointsType.Add(points2);
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();

            namespaces.Add("", "");
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(PointsTypeConnection));

            //将对象序列化输出到控制台
            xmlSerializer.Serialize(Console.Out, pointsType, namespaces);

            /*
             * string xml = XmlSerializeUtil.Serializer(typeof(Points), points);
             *
             * byte[] byteToStr = System.Text.Encoding.Default.GetBytes(xml);
             * string str64 = Convert.ToBase64String(byteToStr);
             * Console.WriteLine(Environment.NewLine + str64);
             *
             * byte[] accessory = Convert.FromBase64String(str64);
             * string fromStr = System.Text.Encoding.Default.GetString(accessory);
             * Console.WriteLine("Base64转字符串" + fromStr);
             * FileStream fileStream = File.Create("test2.xml");
             * fileStream.Write(byteToStr, 0, byteToStr.Length);
             * fileStream.Flush();
             * fileStream.Close();
             */
        }
示例#9
0
        public void PostSalesOrderToEDI(EDISalesOrder ediOrder)
        {
            if (!Connector.BSKIdentifier.HasValue)
            {
                Logger.WarnFormat("Connector doesn't have a BSK Identifier");
                return;
            }

            WebOrderRequest request = new WebOrderRequest();

            request.Version        = "1.0";
            request.WebOrderHeader = new WebOrderRequestHeader();
            request.WebOrderHeader.ShipToCustomer = new Concentrator.Web.Objects.EDI.Customer();

            //request.WebOrderHeader.ShipToCustomer.EanIdentifier = webOrderInfo.CustomerID;
            if (ediOrder.IsPickupOrder)
            {
                request.WebOrderHeader.ShipToCustomer.EanIdentifier = "F" + ediOrder.ShopID;
            }
            else
            {
                request.WebOrderHeader.ShipToCustomer.EanIdentifier = ediOrder.CustomerID;
            }

            request.WebOrderHeader.ShipToCustomer.Contact             = new Contact();
            request.WebOrderHeader.ShipToCustomer.Contact.Name        = Configuration.AppSettings.Settings["ContactName"].Value.ToString();
            request.WebOrderHeader.ShipToCustomer.Contact.Email       = Configuration.AppSettings.Settings["ContactEmail"].Value.ToString();
            request.WebOrderHeader.ShipToCustomer.Contact.PhoneNumber = Configuration.AppSettings.Settings["ContactPhoneNumber"].Value.ToString();
            request.WebOrderHeader.ShipToShopID  = ediOrder.CustomerShipping.StoreNumber;
            request.WebOrderHeader.ShipmentCosts = ediOrder.ShippingAmount;
            request.WebOrderHeader.CreationTime  = ediOrder.Created.ToLocalTime();

            if (ediOrder.IsPickupOrder)
            {
                if (!string.IsNullOrEmpty(ediOrder.CustomerShipping.CustomerPO) && ediOrder.CustomerShipping.CustomerPO != null)
                {
                    request.WebOrderHeader.CustomerOrderReference = "Winkel#:" + ediOrder.CustomerShipping.CustomerPO;
                }
                else
                {
                    request.WebOrderHeader.CustomerOrderReference = "Winkel#:" + ediOrder.WebsiteOrderID + "/" + ediOrder.CustomerShipping.MailingName;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(ediOrder.CustomerBilling.CustomerPO) && ediOrder.CustomerBilling.CustomerPO != null)
                {
                    request.WebOrderHeader.CustomerOrderReference = ediOrder.CustomerBilling.CustomerPO;
                }
                else
                {
                    request.WebOrderHeader.CustomerOrderReference = Connector.Name + " - " + ediOrder.CustomerBilling.MailingName;
                }
            }
            request.WebOrderHeader.WebSiteOrderNumber = ediOrder.WebsiteOrderID.ToString();
            request.WebOrderHeader.OrderLanguageCode  = ediOrder.OrderLanguageCode;

            request.WebOrderHeader.RequestedDate = DateTime.Now.AddDays(1);
            request.WebOrderHeader.EdiVersion    = "2.0";
            if (ediOrder.IsPickupOrder)
            {
                request.WebOrderHeader.BSKIdentifier = Connector.ConnectorSettings.GetValueByKey("ShopOrderBSK", Connector.BSKIdentifier.Value);
            }
            else
            {
                request.WebOrderHeader.BSKIdentifier = Connector.BSKIdentifier.Value;
            }


            request.WebOrderHeader.RouteCode = "TRA";

            if (!string.IsNullOrEmpty(ediOrder.CustomerShipping.ServicePointID))
            {
                request.WebOrderHeader.RouteCode = "KIALA";
            }

            if (ediOrder.IsPickupOrder)
            {
                request.WebOrderHeader.PaymentTermsCode  = ediOrder.Payment;
                request.WebOrderHeader.PaymentInstrument = "T";
            }
            else
            {
                #region Determine Payment Codes
                try
                {
                    request.WebOrderHeader.PaymentInstrument = "T";
                    request.WebOrderHeader.PaymentTermsCode  = ediOrder.Payment;
                }
                catch (Exception ex)
                {
                    Dictionary <string, string> error = new Dictionary <string, string>();
                    error.Add("--p", "Fout tijdens het verwerken van de betaling");
                }
                #endregion
            }

            request.WebOrderHeader.CustomerOverride = new CustomerOverride();

            request.WebOrderHeader.CustomerOverride.CustomerContact = new Contact();


            request.WebOrderHeader.CustomerOverride.Dropshipment                     = !ediOrder.IsPickupOrder;
            request.WebOrderHeader.CustomerOverride.CustomerContact.Email            = ediOrder.CustomerShipping.EmailAddress;
            request.WebOrderHeader.CustomerOverride.CustomerContact.ServicePointCode = ediOrder.CustomerShipping.ServicePointCode;
            request.WebOrderHeader.CustomerOverride.CustomerContact.ServicePointID   = ediOrder.CustomerShipping.ServicePointID;
            request.WebOrderHeader.CustomerOverride.CustomerContact.KialaCompanyName = ediOrder.CustomerShipping.KialaCompanyName;


            request.WebOrderHeader.CustomerOverride.OrderAddress = new Address();

            request.WebOrderHeader.CustomerOverride.OrderAddress.AddressLine1   = ediOrder.CustomerShipping.Addressline1;
            request.WebOrderHeader.CustomerOverride.OrderAddress.AddressLine2   = !string.IsNullOrEmpty(ediOrder.CustomerShipping.Addressline2) ? ediOrder.CustomerShipping.Addressline2 : string.Empty;
            request.WebOrderHeader.CustomerOverride.OrderAddress.Name           = ediOrder.CustomerShipping.MailingName;
            request.WebOrderHeader.CustomerOverride.OrderAddress.ZipCode        = ediOrder.CustomerShipping.ZIPcode;
            request.WebOrderHeader.CustomerOverride.OrderAddress.City           = ediOrder.CustomerShipping.City;
            request.WebOrderHeader.CustomerOverride.OrderAddress.Country        = ediOrder.CustomerShipping.Country;
            request.WebOrderHeader.CustomerOverride.OrderAddress.HouseNumber    = ediOrder.CustomerShipping.Number;
            request.WebOrderHeader.CustomerOverride.OrderAddress.HouseNumberExt = ediOrder.CustomerShipping.NumberExtension;
            request.WebOrderHeader.CustomerOverride.OrderAddress.Street         = ediOrder.CustomerShipping.Street;

            request.WebOrderDetails = new WebOrderRequestDetail[ediOrder.OrderLines.Count];

            request.WebCustomer = new CreateCustomer();
            request.WebCustomer.CustomerContact = new WebContact();

            request.WebCustomer.CustomerContact.Email           = ediOrder.CustomerBilling.EmailAddress;
            request.WebCustomer.CustomerAddress                 = new WebAddress();
            request.WebCustomer.CustomerAddress.AddressLine1    = ediOrder.CustomerBilling.Addressline1;
            request.WebCustomer.CustomerAddress.AddressLine2    = ediOrder.CustomerBilling.Addressline2;
            request.WebCustomer.CustomerAddress.Country         = ediOrder.CustomerBilling.Country;
            request.WebCustomer.CustomerAddress.City            = ediOrder.CustomerBilling.City;
            request.WebCustomer.CustomerAddress.Name            = ediOrder.CustomerBilling.MailingName;
            request.WebCustomer.CustomerAddress.ZipCode         = ediOrder.CustomerBilling.ZIPcode;
            request.WebCustomer.CustomerAddress.Number          = ediOrder.CustomerBilling.Number;
            request.WebCustomer.CustomerAddress.NumberExtension = ediOrder.CustomerBilling.NumberExtension;
            request.WebCustomer.CustomerAddress.Street          = ediOrder.CustomerBilling.Street;

            int rowcount = 0;
            Concentrator.Web.ServiceClient.AssortmentService.AssortmentServiceSoapClient soap = new Concentrator.Web.ServiceClient.AssortmentService.AssortmentServiceSoapClient();


            foreach (var salesDetail in ediOrder.OrderLines)
            {
                var    additionalProduct = AdditionalOrderProducts.FirstOrDefault(x => x.ConnectorProductID == salesDetail.ManufacturerID);
                string productID         = string.Empty;

                if (additionalProduct != null)
                {
                    Logger.DebugFormat("Found additional productID for {0}, connectorid {1}", salesDetail.ManufacturerID, Connector.ConnectorID);
                    productID = additionalProduct.VendorProductID;
                }
                else
                {
                    Logger.DebugFormat("Try get productID for {0}, manufactuerID {1}, brand {2} connectorid {3}", salesDetail.ConcentratorProductID, salesDetail.ManufacturerID, salesDetail.BrandName, Connector.ConnectorID);
                    productID = salesDetail.ConcentratorProductID.ToString();//oap.GetVendorItemNumber(salesDetail.ConcentratorProductID, salesDetail.ManufacturerID, salesDetail.BrandName, Connector.ConnectorID);
                    Logger.DebugFormat("Found product {0} for {1}, connector {2}", productID, salesDetail.ConcentratorProductID, Connector.ConnectorID);
                }

                if (string.IsNullOrEmpty(productID))
                {
                    productID = soap.GetVendorItemNumber(0, salesDetail.ManufacturerID, salesDetail.BrandName, Connector.ConnectorID);
                    Logger.DebugFormat("Retry found product {0} for {1}, connector {2}", productID, salesDetail.ConcentratorProductID, Connector.ConnectorID);
                }

                request.WebOrderDetails[rowcount] = new WebOrderRequestDetail();
                request.WebOrderDetails[rowcount].ProductIdentifier = new ProductIdentifier();
                request.WebOrderDetails[rowcount].ProductIdentifier.ProductNumber      = productID;
                request.WebOrderDetails[rowcount].ProductIdentifier.EANIdentifier      = string.Empty;
                request.WebOrderDetails[rowcount].ProductIdentifier.ManufacturerItemID = salesDetail.ManufacturerID;
                request.WebOrderDetails[rowcount].Quantity          = (int)salesDetail.Quantity;
                request.WebOrderDetails[rowcount].VendorItemNumber  = string.Empty;
                request.WebOrderDetails[rowcount].WareHouseCode     = string.Empty;
                request.WebOrderDetails[rowcount].CustomerReference = new CustomerReference();
                request.WebOrderDetails[rowcount].CustomerReference.CustomerOrder = ediOrder.WebsiteOrderID.ToString();
                request.WebOrderDetails[rowcount].UnitPrice    = salesDetail.LinePrice.ToString(new CultureInfo("en-US"));
                request.WebOrderDetails[rowcount].LineDiscount = salesDetail.DiscountAmount.HasValue ? salesDetail.DiscountAmount.Value.ToString(new CultureInfo("en-US")) : null;
                request.WebOrderDetails[rowcount].BasePrice    = salesDetail.BasePrice.ToString(new CultureInfo("en-US"));

                request.WebOrderDetails[rowcount].CustomerReference.CustomerOrderLine = salesDetail.LineNumber.ToString();

                if (salesDetail.DiscountRules != null && salesDetail.DiscountRules.Count > 0)
                {
                    request.WebOrderDetails[rowcount].LineDiscounts = new WebOrderRequestOrderLineDiscount[salesDetail.DiscountRules.Count];
                    for (int i = 0; i < salesDetail.DiscountRules.Count; i++)
                    {
                        request.WebOrderDetails[rowcount].LineDiscounts[i]                = new WebOrderRequestOrderLineDiscount();
                        request.WebOrderDetails[rowcount].LineDiscounts[i].Code           = salesDetail.DiscountRules[i].RuleCode;
                        request.WebOrderDetails[rowcount].LineDiscounts[i].DiscountAmount = salesDetail.DiscountRules[i].DiscountAmount.ToString(new CultureInfo("en-US"));
                        request.WebOrderDetails[rowcount].LineDiscounts[i].IsSet          = salesDetail.DiscountRules[i].IsSetRule;
                        request.WebOrderDetails[rowcount].LineDiscounts[i].Percentage     = salesDetail.DiscountRules[i].Percentage;
                        request.WebOrderDetails[rowcount].LineDiscounts[i].RuleID         = salesDetail.DiscountRules[i].RuleID;
                    }
                }
                rowcount++;
            }

            StringBuilder requestString = new StringBuilder();

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            XmlWriter xw = XmlWriter.Create(requestString, settings);
            xw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");


            Logger.Info(request.WebOrderHeader.ShipmentCosts);
            Logger.Info(request.WebOrderHeader.ShipmentCosts.ToString(new CultureInfo("en-US")));

            XmlSerializer           rxs = new XmlSerializer(typeof(WebOrderRequest));
            XmlSerializerNamespaces ns  = new XmlSerializerNamespaces();
            ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            rxs.Serialize(xw, request, ns);

            //rxs.Serialize(xw, request);
            XmlDocument requestXml = new XmlDocument();
            requestXml.LoadXml(requestString.ToString());


            bool usesShipmentsCosts = Connector.ConnectorSettings.GetValueByKey <bool>("UsesShipmentCosts", false);

            var client = new OrderInbound();
            var res    = client.ImportOrderWithShipmentCosts(requestString.ToString(), Connector.ConnectorID, usesShipmentsCosts);


            Logger.AuditInfo(string.Format("For order : {0}, the status is: {1}, the message is :{2}", ediOrder.WebsiteOrderID, res.StatusCode, res.Message));

            if (res.StatusCode == 200 || res.StatusCode == 400)
            {
                using (var helper = new OrderHelper(Connector.Connection))
                {
                    helper.UpdateOrderStatus(
                        increment_id: ediOrder.WebsiteOrderID.ToString(),
                        state: MagentoOrderState.Processing,
                        status: MagentoOrderStatus.In_Transit
                        );
                }
            }
        }
示例#10
0
 public static void Serialize(T value, XmlWriter stream, XmlSerializerNamespaces ns = null)
 {
     _serializer.Serialize(stream, value, ns);
 }
示例#11
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;
     }
 }
示例#12
0
        public bool SaveAs(string fn, bool writeFreshly = false, PreferredFormat prefFmt = PreferredFormat.None, MemoryStream useMemoryStream = null)
        {
            if (fn.ToLower().EndsWith(".xml"))
            {
                // save only XML
                this.fn = fn;
                try
                {
                    using (var s = new StreamWriter(this.fn))
                    {
                        // TODO: use aasenv serialzers here!
                        var serializer = new XmlSerializer(typeof(AdminShell.AdministrationShellEnv));
                        var nss        = new XmlSerializerNamespaces();
                        nss.Add("xsi", System.Xml.Schema.XmlSchema.InstanceNamespace);
                        nss.Add("aas", "http://www.admin-shell.io/aas/2/0");
                        nss.Add("IEC61360", "http://www.admin-shell.io/IEC61360/2/0");
                        serializer.Serialize(s, this.aasenv, nss);
                    }
                }
                catch (Exception ex)
                {
                    throw (new Exception(string.Format("While writing AAS {0} at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message)));
                }
                return(true);
            }

            if (fn.ToLower().EndsWith(".json"))
            {
                // save only JSON
                // this funcitonality is a initial test
                this.fn = fn;
                try
                {
                    using (var sw = new StreamWriter(fn))
                    {
                        // TODO: use aasenv serialzers here!

                        sw.AutoFlush = true;

                        JsonSerializer serializer = new JsonSerializer()
                        {
                            NullValueHandling     = NullValueHandling.Ignore,
                            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                            Formatting            = Newtonsoft.Json.Formatting.Indented
                        };
                        using (JsonWriter writer = new JsonTextWriter(sw))
                        {
                            serializer.Serialize(writer, this.aasenv);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw (new Exception(string.Format("While writing AAS {0} at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message)));
                }
                return(true);
            }

            if (fn.ToLower().EndsWith(".aasx"))
            {
                // save package AASX
                try
                {
                    // we want existing contents to be preserved, but no possiblity to change file name
                    // therefore: copy file to new name, re-open!
                    // fn could be changed, therefore close "old" package first
                    if (this.openPackage != null)
                    {
                        // ReSharper disable EmptyGeneralCatchClause
                        try
                        {
                            this.openPackage.Close();
                            if (!writeFreshly)
                            {
                                if (this.tempFn != null)
                                {
                                    System.IO.File.Copy(this.tempFn, fn);
                                }
                                else
                                {
                                    System.IO.File.Copy(this.fn, fn);
                                }
                            }
                        }
                        catch { }
                        // ReSharper enable EmptyGeneralCatchClause
                        this.openPackage = null;
                    }

                    // approach is to utilize the existing package, if possible. If not, create from scratch
                    Package package = null;
                    if (useMemoryStream != null)
                    {
                        package = Package.Open(useMemoryStream, (writeFreshly) ? FileMode.Create : FileMode.OpenOrCreate);
                    }
                    else
                    {
                        package = Package.Open((this.tempFn != null) ? this.tempFn : fn, (writeFreshly) ? FileMode.Create : FileMode.OpenOrCreate);
                    }
                    this.fn = fn;

                    // get the origin from the package
                    PackagePart originPart = null;
                    var         xs         = package.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aasx-origin");
                    foreach (var x in xs)
                    {
                        if (x.SourceUri.ToString() == "/")
                        {
                            originPart = package.GetPart(x.TargetUri);
                            break;
                        }
                    }
                    if (originPart == null)
                    {
                        // create, as not existing
                        originPart = package.CreatePart(new Uri("/aasx/aasx-origin", UriKind.RelativeOrAbsolute), System.Net.Mime.MediaTypeNames.Text.Plain, CompressionOption.Maximum);
                        using (var s = originPart.GetStream(FileMode.Create))
                        {
                            var bytes = System.Text.Encoding.ASCII.GetBytes("Intentionally empty.");
                            s.Write(bytes, 0, bytes.Length);
                        }
                        package.CreateRelationship(originPart.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aasx-origin");
                    }

                    // get the specs from the package
                    PackagePart         specPart = null;
                    PackageRelationship specRel  = null;
                    xs = originPart.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aas-spec");
                    foreach (var x in xs)
                    {
                        specRel  = x;
                        specPart = package.GetPart(x.TargetUri);
                        break;
                    }

                    // check, if we have to change the spec part
                    if (specPart != null && specRel != null)
                    {
                        var name = System.IO.Path.GetFileNameWithoutExtension(specPart.Uri.ToString()).ToLower().Trim();
                        var ext  = System.IO.Path.GetExtension(specPart.Uri.ToString()).ToLower().Trim();
                        if ((ext == ".json" && prefFmt == PreferredFormat.Xml) ||
                            (ext == ".xml" && prefFmt == PreferredFormat.Json) ||
                            (name.StartsWith("aasenv-with-no-id")))
                        {
                            // try kill specpart
                            // ReSharper disable EmptyGeneralCatchClause
                            try
                            {
                                originPart.DeleteRelationship(specRel.Id);
                                package.DeletePart(specPart.Uri);
                            }
                            catch { }
                            finally { specPart = null; specRel = null; }
                            // ReSharper enable EmptyGeneralCatchClause
                        }
                    }

                    if (specPart == null)
                    {
                        // create, as not existing
                        var frn = "aasenv-with-no-id";
                        if (this.aasenv.AdministrationShells.Count > 0)
                        {
                            frn = this.aasenv.AdministrationShells[0].GetFriendlyName() ?? frn;
                        }
                        var aas_spec_fn = "/aasx/#/#.aas";
                        if (prefFmt == PreferredFormat.Json)
                        {
                            aas_spec_fn += ".json";
                        }
                        else
                        {
                            aas_spec_fn += ".xml";
                        }
                        aas_spec_fn = aas_spec_fn.Replace("#", "" + frn);
                        specPart    = package.CreatePart(new Uri(aas_spec_fn, UriKind.RelativeOrAbsolute), System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum);
                        originPart.CreateRelationship(specPart.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-spec");
                    }

                    // now, specPart shall be != null!
                    if (specPart.Uri.ToString().ToLower().Trim().EndsWith("json"))
                    {
                        using (var s = specPart.GetStream(FileMode.Create))
                        {
                            JsonSerializer serializer = new JsonSerializer();
                            serializer.NullValueHandling     = NullValueHandling.Ignore;
                            serializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
                            serializer.Formatting            = Newtonsoft.Json.Formatting.Indented;
                            using (var sw = new StreamWriter(s))
                            {
                                using (JsonWriter writer = new JsonTextWriter(sw))
                                {
                                    serializer.Serialize(writer, this.aasenv);
                                }
                            }
                        }
                    }
                    else
                    {
                        using (var s = specPart.GetStream(FileMode.Create))
                        {
                            var serializer = new XmlSerializer(typeof(AdminShell.AdministrationShellEnv));
                            var nss        = new XmlSerializerNamespaces();
                            nss.Add("xsi", System.Xml.Schema.XmlSchema.InstanceNamespace);
                            nss.Add("aas", "http://www.admin-shell.io/aas/2/0");
                            nss.Add("IEC61360", "http://www.admin-shell.io/IEC61360/2/0");
                            serializer.Serialize(s, this.aasenv, nss);
                        }
                    }

                    // there might be pending files to be deleted (first delete, then add, in case of identical files in both categories)
                    foreach (var psfDel in pendingFilesToDelete)
                    {
                        // try find an existing part for that file ..
                        var found = false;

                        // normal files
                        xs = specPart.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aas-suppl");
                        foreach (var x in xs)
                        {
                            if (x.TargetUri == psfDel.uri)
                            {
                                // try to delete
                                specPart.DeleteRelationship(x.Id);
                                package.DeletePart(psfDel.uri);
                                found = true;
                                break;
                            }
                        }

                        // thumbnails
                        xs = package.GetRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail");
                        foreach (var x in xs)
                        {
                            if (x.TargetUri == psfDel.uri)
                            {
                                // try to delete
                                package.DeleteRelationship(x.Id);
                                package.DeletePart(psfDel.uri);
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            throw (new Exception($"Not able to delete pending file {psfDel.uri} in saving package {fn}"));
                        }
                    }

                    // after this, there are no more pending for delete files
                    pendingFilesToDelete.Clear();

                    // write pending supplementary files
                    foreach (var psfAdd in pendingFilesToAdd)
                    {
                        // make sure ..
                        if ((psfAdd.sourceLocalPath == null && psfAdd.sourceGetBytesDel == null) || psfAdd.location != AdminShellPackageSupplementaryFile.LocationType.AddPending)
                        {
                            continue;
                        }

                        // normal file?
                        if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.None ||
                            psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.EmbedAsThumbnail)
                        {
                            // try find an existing part for that file ..
                            PackagePart filePart = null;
                            if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.None)
                            {
                                xs = specPart.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aas-suppl");
                                foreach (var x in xs)
                                {
                                    if (x.TargetUri == psfAdd.uri)
                                    {
                                        filePart = package.GetPart(x.TargetUri);
                                        break;
                                    }
                                }
                            }
                            if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.EmbedAsThumbnail)
                            {
                                xs = package.GetRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail");
                                foreach (var x in xs)
                                {
                                    if (x.SourceUri.ToString() == "/" && x.TargetUri == psfAdd.uri)
                                    {
                                        filePart = package.GetPart(x.TargetUri);
                                        break;
                                    }
                                }
                            }

                            if (filePart == null)
                            {
                                // determine mimeType
                                var mimeType = psfAdd.useMimeType;
                                // reconcile mime
                                if (mimeType == null && psfAdd.sourceLocalPath != null)
                                {
                                    mimeType = AdminShellPackageEnv.GuessMimeType(psfAdd.sourceLocalPath);
                                }
                                // still null?
                                if (mimeType == null)
                                {
                                    // see: https://stackoverflow.com/questions/6783921/which-mime-type-to-use-for-a-binary-file-thats-specific-to-my-program
                                    mimeType = "application/octet-stream";
                                }

                                // create new part and link
                                filePart = package.CreatePart(psfAdd.uri, mimeType, CompressionOption.Maximum);
                                if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.None)
                                {
                                    specPart.CreateRelationship(filePart.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-suppl");
                                }
                                if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.EmbedAsThumbnail)
                                {
                                    package.CreateRelationship(filePart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail");
                                }
                            }

                            // now should be able to write
                            using (var s = filePart.GetStream(FileMode.Create))
                            {
                                if (psfAdd.sourceLocalPath != null)
                                {
                                    var bytes = System.IO.File.ReadAllBytes(psfAdd.sourceLocalPath);
                                    s.Write(bytes, 0, bytes.Length);
                                }

                                if (psfAdd.sourceGetBytesDel != null)
                                {
                                    var bytes = psfAdd.sourceGetBytesDel();
                                    if (bytes != null)
                                    {
                                        s.Write(bytes, 0, bytes.Length);
                                    }
                                }
                            }
                        }
                    }

                    // after this, there are no more pending for add files
                    pendingFilesToAdd.Clear();

                    // flush, but leave open
                    package.Flush();
                    this.openPackage = package;

                    // if in temp fn, close the package, copy to original fn, re-open the package
                    if (this.tempFn != null)
                    {
                        try
                        {
                            package.Close();
                            System.IO.File.Copy(this.tempFn, this.fn, overwrite: true);
                            this.openPackage = Package.Open(this.tempFn, FileMode.OpenOrCreate);
                        }
                        catch (Exception ex)
                        {
                            throw (new Exception(string.Format("While write AASX {0} indirectly at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw (new Exception(string.Format("While write AASX {0} at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message)));
                }
                return(true);
            }

            // Don't know to handle
            throw (new Exception(string.Format($"Not able to handle {fn}.")));
        }
        /// <summary>
        /// Iterate a collection of service descriptions and generate Wsdl's
        /// </summary>
        /// <param name="serviceDescriptions">A ServiceDescriptionCollection containing the colleciton of service descriptions.</param>
        /// <param filename="serviceDescriptions">A string containing the name of th wsdl file. If null the name of the service description is used.</param>
        /// <param name="destinationPath">A string containing the name of a directory where the wsdl file is created.</param>
        public void GenerateWsdls(ServiceDescriptionCollection serviceDescriptions, string filename, string destinationPath)
        {
            // Fix namespaces to Dpws spec
            string dpwsNs   = "http://schemas.xmlsoap.org/ws/2006/02/devprof";
            string policyNs = "http://schemas.xmlsoap.org/ws/2004/09/policy";
            XmlSerializerNamespaces serviceNamespaces = new XmlSerializerNamespaces();

            serviceNamespaces.Add("a", "http://schemas.xmlsoap.org/ws/2004/08/addressing");
            serviceNamespaces.Add("l", "http://schemas.xmlsoap.org/wsdl/");
            serviceNamespaces.Add("p", dpwsNs);
            serviceNamespaces.Add("e", "http://schemas.xmlsoap.org/ws/2004/08/eventing");
            serviceNamespaces.Add("s12", "http://schemas.xmlsoap.org/wsdl/soap12/");
            serviceNamespaces.Add("po", policyNs);
            serviceNamespaces.Add("u", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            // For each service description in the service description collection generate a wsdl
            bool newFile = true;

            foreach (ServiceDescription serviceDesc in serviceDescriptions)
            {
                // Fix the namespaces
                serviceNamespaces.Add("tns", serviceDesc.TargetNamespace);
                serviceDesc.Namespaces = serviceNamespaces;

                XmlSchemaSet schemaSet = new XmlSchemaSet();
                foreach (XmlSchema schema in serviceDesc.Types.Schemas)
                {
                    schemaSet.Add(schema);
                }
                schemaSet.Compile();
                if (filename == null)
                {
                    Logger.WriteLine("Writing Wsdl File: " + destinationPath + serviceDesc.Name + ".wsdl", LogLevel.Normal);

                    // Write the content
                    System.IO.FileStream fileStream = null;
                    fileStream = new System.IO.FileStream(destinationPath + serviceDesc.Name + ".wsdl", System.IO.FileMode.Create);
                    serviceDesc.Write(fileStream);
                    fileStream.Flush();
                    fileStream.Close();
                }
                else
                {
                    System.IO.FileStream fileStream = null;
                    if (serviceDescriptions.Count > 1 && !newFile)
                    {
                        Logger.WriteLine("Appending " + serviceDesc.Name + " Service Description to: " + destinationPath + filename, LogLevel.Normal);
                        fileStream = new System.IO.FileStream(destinationPath + filename, System.IO.FileMode.Append);
                    }
                    else
                    {
                        Logger.WriteLine("Writing " + serviceDesc.Name + " Service Description to: " + destinationPath + filename, LogLevel.Normal);
                        fileStream = new System.IO.FileStream(destinationPath + filename, System.IO.FileMode.Create);
                        newFile    = false;
                    }

                    // Write the content
                    serviceDesc.Write(fileStream);
                    fileStream.Flush();
                    fileStream.Write(new byte[] { 0x0D, 0x0A, 0x0D, 0x0A }, 0, 4);
                    fileStream.Flush();
                    fileStream.Close();
                }
            }
        }
 public void Serialize(System.IO.Stream stream, object o, XmlSerializerNamespaces namespaces)
 {
 }
示例#15
0
        static void Main(string[] args)
        {
            string[] api = File.ReadAllLines(args[0]);

            Dictionary <string, KeyWord> groupedEntries = new Dictionary <string, KeyWord>();

            foreach (string apiEntry in api)
            {
                if (!apiEntry.Contains("("))
                {
                    // Define, ignore until later
                }
                else
                {
                    Regex r = new Regex(@"([^\(]+)\(([^\)]+)\) ([^\(]+)\(([a-zA-Z0-9_-]+)\)");
                    Match m = r.Match(apiEntry);
                    if (m.Success)
                    {
                        // Console.WriteLine("Name: {0}, Params: {1}, Desc: {2}, Ret: {3}", m.Groups[1], m.Groups[2], m.Groups[3], m.Groups[4]);
                        string   name     = m.Groups[1].Value;
                        string[] paramstr = m.Groups[2].Value.Split(',').Select(s => s.Trim()).ToArray();

                        for (int i = 0; i < paramstr.Length; i++)
                        {
                            if (paramstr[i].EndsWith("["))
                            {
                                paramstr[i]     = paramstr[i].Substring(0, paramstr[i].Length - 1).Trim();
                                paramstr[i + 1] = "[" + paramstr[i + 1];
                            }
                        }

                        string desc = m.Groups[3].Value;
                        string ret  = m.Groups[4].Value;

                        if (name.Contains("->"))
                        {
                            // Class method, ignore until later
                        }

                        KeyWord kw = GetEntry(groupedEntries, name);
                        kw.Func = true;
                        kw.Overloads.Add(new Overload
                        {
                            ReturnValue = ret,
                            Params      = paramstr.Select(p => new Param {
                                Name = p
                            }).ToList()
                        });
                    }
                }
            }

            using (var writer = XmlWriter.Create(args[1], new XmlWriterSettings {
                Encoding = Encoding.UTF8, Indent = true
            }))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("AutoComplete");
                XmlSerializer           ser = new XmlSerializer(typeof(KeyWord));
                XmlSerializerNamespaces ns  = new XmlSerializerNamespaces();
                ns.Add("", "");
                foreach (var kw in groupedEntries.Values.OrderBy(k => k.Name))
                {
                    ser.Serialize(writer, kw, ns);
                }
                writer.WriteEndDocument();
            }
        }
 public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces);
 public void Serialize(System.IO.TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
 {
 }
 public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces);
 public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces);
 protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, XmlSerializerNamespaces xmlns);
示例#21
0
        /// <summary>
        /// 对象序列化成 XML 字符串
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="ns">命名空间</param>
        /// <returns></returns>
        public static string SerializeToXml <T>(T obj, XmlSerializerNamespaces ns) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            return(SerializeToXml(serializer, obj, ns));
        }
 public void Serialize(System.Xml.XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
 {
 }
示例#23
0
        public Boolean GenerarXml_Factura(int IdEmpresa, int IdSucursal, int IdBodega, decimal IdCbteVta, string RutaDescarga, ref string msg)
        {
            try
            {
                string sIdCbteFact = "";

                List <vwfa_factura_sri_Info> lista_Factura_sri = new List <vwfa_factura_sri_Info>();
                List <Core.Erp.Info.Facturacion_Grafinpren.fa_factura_graf_Info> Lista_Campos_Adicionales = new List <Core.Erp.Info.Facturacion_Grafinpren.fa_factura_graf_Info>();
                vwfa_factura_sri_Bus Bus_Factura = new vwfa_factura_sri_Bus();

                lista_Factura_sri = Bus_Factura.Get_list_Factura_Sri(IdEmpresa, IdSucursal, IdBodega, IdCbteVta, ref msg);

                if (lista_Factura_sri.Count != 0)
                {
                    //validar objeto
                    if (!Factura.ValidarObjeto_XML_Factura(lista_Factura_sri, ref msg))
                    {
                        return(false);
                    }

                    List <factura> lista = new List <factura>();
                    lista = Factura.Get_List_Xml_Factura(IdEmpresa, IdSucursal, IdBodega, IdCbteVta, ref msg);

                    //campos adicionales
                    Lista_Campos_Adicionales = Factura_Graf.Get_List_factura(IdEmpresa, IdSucursal, IdBodega, IdCbteVta);

                    Info.Facturacion_Grafinpren.fa_factura_graf_Info info = new Info.Facturacion_Grafinpren.fa_factura_graf_Info();
                    info = Lista_Campos_Adicionales.FirstOrDefault();

                    foreach (var item in lista)
                    {
                        if (item.infoAdicional == null)
                        {
                            item.infoAdicional = new List <Info.class_sri.FacturaV2.facturaCampoAdicional>();
                        }
                        if (info.Observacion != null)
                        {
                            facturaCampoAdicional ad = new facturaCampoAdicional();
                            ad.nombre = "Observacion";
                            ad.Value  = info.Observacion;
                            item.infoAdicional.Add(ad);
                        }

                        if (info.pe_direccion != null)
                        {
                            facturaCampoAdicional ad = new facturaCampoAdicional();
                            ad.nombre = "Direccion";
                            ad.Value  = info.pe_direccion;
                            item.infoAdicional.Add(ad);
                        }
                    }

                    if (lista.Count != 0)
                    {
                        foreach (var item in lista)
                        {
                            try
                            {
                                sIdCbteFact = item.infoTributaria.razonSocial.Substring(0, 3) + "-" + Cl_Enumeradores.eTipoCodComprobante.FAC + "-" + item.infoTributaria.estab + "-" + item.infoTributaria.ptoEmi + "-" + item.infoTributaria.secuencial;
                                XmlSerializerNamespaces NamespaceObject = new XmlSerializerNamespaces();
                                NamespaceObject.Add("", "");
                                XmlSerializer mySerializer = new XmlSerializer(typeof(factura));
                                StreamWriter  myWriter     = new StreamWriter(RutaDescarga + sIdCbteFact + ".xml");
                                mySerializer.Serialize(myWriter, item, NamespaceObject);
                                myWriter.Close();
                            }
                            catch (Exception)
                            {
                                msg = "No se generó el XML, posiblemente porque su máquina no tiene acceso a la ruta " + RutaDescarga;
                                return(false);
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                Core.Erp.Info.Log_Exception.LoggingManager.Logger.Log(Core.Erp.Info.Log_Exception.LoggingCategory.Error, ex.Message);
                throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "get_CbteCble_x_Costo_Info", ex.Message), ex)
                      {
                          EntityType = typeof(fa_factura_Bus)
                      };
            }
        }
 public void Serialize(System.Xml.XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
 {
 }
示例#25
0
        /// <summary>
        ///     Serializes the contents of the specified data to the stream using UTF8 encoding.
        /// </summary>
        /// <typeparam name="T">The type of the data.</typeparam>
        /// <param name="data">The data.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="namespaces">The namespaces.</param>
        public static void Serialize <T>(T data, Stream stream, XmlWriterSettings settings, XmlSerializerNamespaces namespaces)
            where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (XmlWriter xw = XmlWriter.Create(stream, settings))
                serializer.Serialize(xw, data, namespaces);
        }
示例#26
0
		public XmlSerializerNamespaces (XmlSerializerNamespaces namespaces)
		{
			throw new NotImplementedException ();
		}
示例#27
0
        public static string ToXml(BFLAN.Header header)
        {
            XmlRoot root = new XmlRoot();

            root.head = new Head();
            root.body = new Body();

            var generator = new Generator();

            root.head.generator = generator;
            generator.name      = "ST";
            generator.version   = "1.0"
            ;
            var create = new Create();

            root.head.create = create;
            create.date      = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss");

            BinaryInfo info = new BinaryInfo();

            info.layout.name     = header.AnimationTag.Name;
            info.version.major   = (byte)header.VersionMajor;
            info.version.minor   = (byte)header.VersionMinor;
            info.version.micro   = (byte)header.VersionMicro;
            info.version.micro2  = (byte)header.VersionMicro2;
            root.head.binaryInfo = info;

            AnimTag  tag      = new AnimTag();
            AnimInfo animInfo = new AnimInfo();

            if (header.AnimationInfo.Loop)
            {
                tag.animLoop = AnimLoopType.Loop;
            }

            tag.descendingBind = header.AnimationTag.ChildBinding;
            tag.name           = header.AnimationTag.Name;
            tag.fileName       = header.AnimationTag.Name;
            tag.startFrame     = header.AnimationTag.StartFrame;
            tag.endFrame       = header.AnimationTag.EndFrame;
            tag.group          = new Group[header.AnimationTag.Groups.Count];
            for (int i = 0; i < header.AnimationTag.Groups.Count; i++)
            {
                tag.group[i]      = new Group();
                tag.group[i].name = header.AnimationTag.Groups[i];
            }

            root.body.animTag[0] = tag;
            root.body.lan[0]     = animInfo;

            var bflanInfo   = header.AnimationInfo;
            var animContent = new AnimContent();

            animInfo.animContent    = new AnimContent[1];
            animInfo.animContent[0] = animContent;
            animInfo.startFrame     = bflanInfo.FrameSize;



            XmlWriterSettings settings = new XmlWriterSettings
            {
                Encoding    = Encoding.UTF8,
                Indent      = true,
                IndentChars = "  ",
            };


            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");

            XmlDocument    doc     = new XmlDocument();
            XmlDeclaration xmldecl = doc.CreateXmlDeclaration("1.0", null, null);

            xmldecl.Encoding   = "UTF-8";
            xmldecl.Standalone = "yes";

            var           stringWriter = new StringWriter();
            XmlSerializer serializer   = new XmlSerializer(typeof(XmlRoot));
            XmlWriter     output       = XmlWriter.Create(stringWriter, settings);

            serializer.Serialize(output, root, ns);
            return(stringWriter.ToString());
        }
 public XmlSerializerNamespaces(XmlSerializerNamespaces namespaces)
 {
 }
示例#29
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);
		}
	}
 protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns);
示例#31
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;
        }
    }
示例#32
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;
    }
        private async Task <ClientResponse> _sendRequestAsync(string url, Request request, string traceNumber = null)
        {
            if (_cache != null && !string.IsNullOrEmpty(traceNumber))
            {
                var previousResponse = _cache.GetValue(traceNumber);
                if (!string.IsNullOrEmpty(previousResponse))
                {
                    return(_contentToClientResponse(previousResponse, traceNumber, true));
                }
            }
            var headers = new Headers(traceNumber, _options.InterfaceVersion, _options.Credentials.MerchantId);

            if (string.IsNullOrEmpty(headers.TraceNumber))
            {
                var newTrace = Guid.NewGuid().GetHashCode();
                if (newTrace < 0)
                {
                    newTrace = newTrace * -1;
                }
                headers.TraceNumber = newTrace.ToString();
            }

            var contentType = headers.ContentType();
            var client      = new HttpClient();

            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("MIME-Version", headers.MIME_Version);
            client.DefaultRequestHeaders.Add("Content-transfer-encoding", headers.ContentTransferEncoding);
            client.DefaultRequestHeaders.Add("Request-number", headers.RequestNumber);
            client.DefaultRequestHeaders.Add("Document-type", headers.DocumentType);
            client.DefaultRequestHeaders.Add("Trace-number", headers.TraceNumber);
            client.DefaultRequestHeaders.Add("Interface-version", headers.InterfaceVersion);
            client.DefaultRequestHeaders.Add("MerchantID", headers.MerchantID);

            string body;
            var    requestSerializer = new XmlSerializer(typeof(Request));

            using (var stream = new MemoryStream())
                using (var writer = new StreamWriter(stream))
                {
                    var ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    requestSerializer.Serialize(writer, request, ns);

                    stream.Position = 0;
                    using (var reader = new StreamReader(stream))
                    {
                        body = reader.ReadToEnd();
                    }
                }

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "");

            httpRequest.Content = new StringContent(body);
            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            var httpResponse = await client.SendAsync(httpRequest);

            var httpResponseContent = await httpResponse.Content.ReadAsStringAsync();

            if (httpResponse.IsSuccessStatusCode)
            {
                var clientResponse = _contentToClientResponse(httpResponseContent, traceNumber);

                var itemType = ResponseTypes.Types[clientResponse.Response.Item.GetType()];

                string procStatus = null;
                switch (itemType)
                {
                case (int)ResponeTypeIds.AccountUpdaterResp:
                    var accountUpdater = (accountUpdaterRespType)clientResponse.Response.Item;
                    procStatus = accountUpdater.ProfileProcStatus;
                    break;

                case (int)ResponeTypeIds.EndOfDayResp:
                    var endOfDay = (endOfDayRespType)clientResponse.Response.Item;
                    procStatus = endOfDay.ProcStatus;
                    break;

                case (int)ResponeTypeIds.FlexCacheResp:
                    var flexCache = (flexCacheRespType)clientResponse.Response.Item;
                    procStatus = flexCache.ProcStatus;
                    break;

                case (int)ResponeTypeIds.InquiryResp:
                    var inquiry = (inquiryRespType)clientResponse.Response.Item;
                    procStatus = inquiry.ProcStatus;
                    break;

                case (int)ResponeTypeIds.MarkForCaptureResp:
                    var markForCapture = (markForCaptureRespType)clientResponse.Response.Item;
                    procStatus = markForCapture.ProcStatus;
                    break;

                case (int)ResponeTypeIds.NewOrderResp:
                    var newOrder = (newOrderRespType)clientResponse.Response.Item;
                    procStatus = newOrder.ProcStatus;
                    break;

                case (int)ResponeTypeIds.ProfileResp:
                    var profile = (profileRespType)clientResponse.Response.Item;
                    procStatus = profile.ProfileProcStatus;
                    break;

                case (int)ResponeTypeIds.QuickResp:
                    var quick = (quickRespType)clientResponse.Response.Item;
                    procStatus = quick.ProcStatus;
                    break;

                case (int)ResponeTypeIds.QuickResponse:
                    var quick_old = (quickRespType_old)clientResponse.Response.Item;
                    procStatus = quick_old.ProcStatus;
                    break;

                case (int)ResponeTypeIds.ReversalResp:
                    var reversal = (reversalRespType)clientResponse.Response.Item;
                    procStatus = reversal.ProcStatus;
                    break;

                case (int)ResponeTypeIds.SafetechFraudAnalysisResp:
                    var safetechFraudAnalysis = (safetechFraudAnalysisRespType)clientResponse.Response.Item;
                    procStatus = safetechFraudAnalysis.ProcStatus;
                    break;

                default:
                    break;
                }

                if (procStatus?.Trim() != "0" && procStatus?.Trim() != "00")
                {
                    throw new Exception($"Request was unsuccesful - response was {httpResponseContent}");
                }
                if (!string.IsNullOrEmpty(traceNumber))
                {
                    _cache.SetValue(traceNumber, httpResponseContent);
                }

                return(clientResponse);
            }
            else
            {
                throw new Exception($"Unsuccesful communication with Chase with response {httpResponseContent}");
            }
        }
示例#34
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;
    }
示例#35
0
        /// <summary>
        /// Main point of application.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        static void Main(string[] args)
        {
            var parameters = CommandLineParser.GetCommandLineArguments(args);

            if (parameters.Count() != 4)
            {
                Console.WriteLine("You should fill in all command line arguments.");
                ShowErrorMessage();
            }

            var parameterKey = (args[0].Trim().StartsWith("--")) ? commandLineParameters : shortCommandLineParameters;

            string fileType = TryGetValue(parameters, parameterKey[0]);
            string filePath = TryGetValue(parameters, parameterKey[1]);

            int recordsAmount = 0;

            if (!Int32.TryParse(TryGetValue(parameters, parameterKey[2]), out recordsAmount))
            {
                Console.WriteLine("Records amount should be integer.");
                ShowErrorMessage();
            }

            int startId = 0;

            if (!Int32.TryParse(TryGetValue(parameters, parameterKey[3]), out startId))
            {
                Console.WriteLine("Start id should be integer.");
                ShowErrorMessage();
            }

            if (!fileType.Equals(CsvString, StringComparison.InvariantCultureIgnoreCase) &&
                !fileType.Equals(XmlString, StringComparison.InvariantCultureIgnoreCase))
            {
                Console.WriteLine("You can only export records into *.csv or *.xml format.");
                return;
            }

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            FileStream stream = default;

            try
            {
                stream = File.Create(filePath);
            }
            catch (UnauthorizedAccessException)
            {
            }

            using var writer = new StreamWriter(stream);
            var records = Generate(startId, recordsAmount);

            if (fileType.Equals(CsvString, StringComparison.CurrentCultureIgnoreCase))
            {
                foreach (var record in records)
                {
                    writer.WriteLine(record.ToString());
                }
            }

            if (fileType.Equals(XmlString, StringComparison.CurrentCultureIgnoreCase))
            {
                var xmlSerializedRecords = new FileCabinetRecordsSerializable(records);

                var xmlSerializer = new XmlSerializerNamespaces();
                xmlSerializer.Add(string.Empty, string.Empty);

                var serializer = new XmlSerializer(typeof(FileCabinetRecordsSerializable));
                serializer.Serialize(writer, xmlSerializedRecords, xmlSerializer);
            }

            Console.WriteLine($"{recordsAmount} records were written to {filePath}");
        }
示例#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;
    }
示例#37
0
        static T SeriallizeToXml <T>(object o, Encoding encoding = null, bool omitXmlDeclaration = false, string comment = null, bool indent = true)
        {
            if (o == null)
            {
                return(default(T));
            }
            // Create serialization settings.
            encoding = encoding ?? Encoding.UTF8;
            var settings = new XmlWriterSettings();

            settings.OmitXmlDeclaration = omitXmlDeclaration;
            settings.Encoding           = encoding;
            settings.Indent             = indent;
            // Serialize.
            var serializer = GetXmlSerializer(o.GetType());
            // Serialize in memory first, so file will be locked for shorter times.
            var ms = new MemoryStream();
            var xw = XmlWriter.Create(ms, settings);

            try
            {
                lock (serializer)
                {
                    if (!string.IsNullOrEmpty(comment))
                    {
                        xw.WriteStartDocument();
                        xw.WriteComment(comment);
                    }
                    if (omitXmlDeclaration)
                    {
                        //Create our own namespaces for the output
                        var ns = new XmlSerializerNamespaces();
                        //Add an empty namespace and empty value
                        ns.Add("", "");
                        serializer.Serialize(xw, o, ns);
                    }
                    else
                    {
                        serializer.Serialize(xw, o);
                    }
                    if (!string.IsNullOrEmpty(comment))
                    {
                        xw.WriteEndDocument();
                    }
                    // Make sure that all data flushed into memory stream.
                    xw.Flush();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // This will close underlying MemoryStream too.
                xw.Close();
            }
            // ToArray will return all bytes from memory stream despite it being closed.
            // Bytes will start with Byte Order Mark(BOM) and are ready to write into file.
            var xmlBytes = ms.ToArray();

            // If string must be returned then...
            if (typeof(T) == typeof(string))
            {
                // Use StreamReader to remove Byte Order Mark(BOM).
                var ms2       = new MemoryStream(xmlBytes);
                var sr        = new StreamReader(ms2, true);
                var xmlString = sr.ReadToEnd();
                // This will close underlying MemoryStream too.
                sr.Close();
                return((T)(object)xmlString);
            }
            else
            {
                return((T)(object)xmlBytes);
            }
        }
示例#38
0
 public Chars()
 {
     this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
             new XmlQualifiedName(string.Empty, "rotmg")
         });
 }
示例#39
0
        void CreatePeerProjectXml(FictionBook book, ref ISXMLElement pXML)
        {
            PeerProjectBook sbook  = new PeerProjectBook(book);
            Books           sBooks = new Books();

            sBooks.books[0] = sbook;

            MemoryStream ms       = null;
            XmlWriter    writer   = null;
            string       finalXml = String.Empty;

            try {
                XmlSerializer s = new XmlSerializer(typeof(Books));
                s.UnknownNode      += new XmlNodeEventHandler(OnUnknownNode);
                s.UnknownAttribute += new XmlAttributeEventHandler(OnUnknownAttribute);

                ms = new MemoryStream();

                UTF8Encoding utf8 = new UTF8Encoding(false, false);
                writer = new XmlTextWriter(ms, utf8);

                XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                // Don't add any prefixes
                xsn.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                s.Serialize(writer, sBooks, xsn);

                // Start modifying the resulting XML
                XmlDocument doc = new XmlDocument();
                ms.Position = 0;
                doc.Load(ms);
                XmlAttribute schema = doc.CreateAttribute("xsi", "noNamespaceSchemaLocation",
                                                          "http://www.w3.org/2001/XMLSchema-instance");
                schema.Value = Books.URI;
                doc.DocumentElement.SetAttributeNode(schema);
                // Truncate the serialization result and overwrite it with our modified XML
                ms.SetLength(0);
                ms.Position = 0;
                writer      = new XmlTextWriter(ms, utf8);
                doc.Save(writer);

                char[] buffer = Encoding.UTF8.GetChars(ms.ToArray());
                finalXml = new string(buffer);
            } catch (Exception e) {
                Trace.WriteLine(e.Message);
                Exception inner = e.InnerException;
                while (inner != null)
                {
                    Trace.WriteLine(inner.Message);
                    inner = inner.InnerException;
                }
            } finally {
                if (writer != null)
                {
                    writer.Close();
                }
                if (ms != null)
                {
                    ms.Close();
                }
            }
            if (!String.IsNullOrEmpty(finalXml))
            {
                Trace.WriteLine(finalXml);
                ISXMLElement newXML = pXML.FromString(finalXml);
                if (newXML != null)
                {
                    pXML.Elements.Attach(newXML);
                }
            }
        }
示例#40
0
    public static XElement SerializeToXElement <T>(this T obj, XmlSerializer serializer, XmlSerializerNamespaces ns)
    {
        var doc = new XDocument();

        using (var writer = doc.CreateWriter())
            (serializer ?? new XmlSerializer(obj.GetType())).Serialize(writer, obj, ns);
        var element = doc.Root;

        if (element != null)
        {
            element.Remove();
        }
        return(element);
    }
示例#41
0
        public static string ImportPurchases(VaporStoreDbContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var serializer = new XmlSerializer(typeof(List <ImportPurchaseDto>), new XmlRootAttribute("Purchases"));

            var namespaces = new XmlSerializerNamespaces();

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

            var reader = new StringReader(xmlString);

            using (reader)
            {
                var purchaseDtos = (List <ImportPurchaseDto>)serializer.Deserialize(reader);

                var purchasesToAdd = new List <Purchase>();

                foreach (var purchase in purchaseDtos)
                {
                    if (!IsValid(purchase))
                    {
                        sb.AppendLine(ERROR_MESSAGE);

                        continue;
                    }

                    DateTime purchaseDate;

                    var isPurchaseDateValid = DateTime.TryParseExact(purchase.Date, "dd/MM/yyyy HH:mm",
                                                                     CultureInfo.InvariantCulture, DateTimeStyles.None, out purchaseDate);

                    if (!isPurchaseDateValid)
                    {
                        sb.AppendLine(ERROR_MESSAGE);

                        continue;
                    }

                    var game = context.Games.FirstOrDefault(g => g.Name == purchase.GameTitle);

                    if (game == null)
                    {
                        sb.AppendLine(ERROR_MESSAGE);
                    }

                    var card = context.Cards.FirstOrDefault(c => c.Number == purchase.CardNumber);

                    if (card == null)
                    {
                        sb.AppendLine(ERROR_MESSAGE);
                    }

                    var purchaseToAdd = new Purchase()
                    {
                        Game       = game,
                        Type       = purchase.PurchaseType,
                        Date       = purchaseDate,
                        ProductKey = purchase.ProductKey,
                        Card       = card
                    };

                    purchasesToAdd.Add(purchaseToAdd);

                    sb.AppendLine(string.Format(SUCCESSFULLY_ADDED_PURCHASE, game.Name, purchaseToAdd.Card.User.Username));
                }

                context.Purchases.AddRange(purchasesToAdd);

                context.SaveChanges();

                return(sb.ToString());
            }
        }
示例#42
0
 public static string GetXml <T>(this T obj, XmlSerializerNamespaces ns, bool?standalone)
 {
     return(GetXml(obj, null, ns, standalone));
 }
示例#43
0
 /// <summary>
 ///     Serializes the contents of the specified data to the file.
 /// </summary>
 /// <typeparam name="T">The type of data.</typeparam>
 /// <param name="data">The data.</param>
 /// <param name="fileName">Name of the file.</param>
 /// <param name="settings">The settings.</param>
 /// <param name="namespaces">The namespaces.</param>
 public static void Serialize <T>(T data, string fileName, XmlWriterSettings settings, XmlSerializerNamespaces namespaces)
     where T : class
 {
     using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
         Serialize(data, fs, settings, namespaces);
 }
示例#44
0
文件: Class1.cs 项目: Nofuq/Projects
        public static eventsList Events(string tomcat, string login, string password, DateTime from, DateTime to, string[] events)
        {
            string key = "";

            try
            {
                key = Autorize(tomcat, login, password);
                // фильтрация

                eventsRequestData requestData = new eventsRequestData();
                requestData.Items = new object[]
                {
                    new eventsRequestDataEvents()
                    {
                        @event = events.Select(a => new eventsRequestDataEventsEvent()
                        {
                            Value = a
                        }).ToArray()
                    }
                };


                XmlSerializer xmlser = new XmlSerializer(typeof(eventsRequestData));
                var           xns    = new XmlSerializerNamespaces();
                xns.Add(string.Empty, string.Empty);
                StringBuilder sb = new StringBuilder();
                xmlser.Serialize(new StringWriter(sb), requestData, xns);



                var body = sb.ToString().Split('\n').Skip(1).Aggregate((a, b) => a += b + "\n");

                WebClient wc = new WebClient();
                wc.Headers.Add("Content-Type:application/xml");
                wc.Encoding = Encoding.UTF8;
                var url = string.Format("http://{0}/resto/api/events?key={1}&from_time={2}&to_time={3}", tomcat,
                                        key, from.ToString(), to.ToString());
                var result =
                    wc.UploadString(url, "POST", body);
                XmlSerializer xml       = new XmlSerializer(typeof(eventsList));
                var           eventList = (eventsList)xml.Deserialize(new StringReader(result));

                //Еще получаем расшифровку событий


                url = string.Format("http://{0}/resto/api/events/metadata?key={1}", tomcat,
                                    key, from.ToString(), to.ToString());
                result =
                    wc.DownloadString(url);
                xml = new XmlSerializer(typeof(groupsList));
                var groups = (groupsList)xml.Deserialize(new StringReader(result));


                foreach (var ev in eventList.@event)
                {
                    var gr = groups.group.FirstOrDefault(a => a.type?.FirstOrDefault(b => b.id == ev.type) != null);
                    if (gr != null)
                    {
                        ev.GroupName = gr.name;
                        var type = gr.type.FirstOrDefault(b => b.id == ev.type);
                        ev.Name = type.name;
                    }
                }

                return(eventList);
            }
            catch (WebException ex)
            {
                var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                DeAutorize(tomcat, key);
            }
            return(null);
        }
        public async Task <IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken)
        {
            var umbracoNode = new UmbracoNode
            {
                CreateDate     = DateTime.UtcNow,
                Level          = 1,
                NodeObjectType = Const.MemberObjectType,
                NodeUser       = 0,
                ParentId       = -1,
                SortOrder      = 3,
                Text           = user.Email,
                Trashed        = false,
                UniqueId       = Guid.NewGuid(),
                Path           = "-1"
            };

            await umbracoNodeRepository.AddAsync(umbracoNode, cancellationToken);

            await umbracoNodeRepository.SaveChangesAsync(cancellationToken);

            umbracoNode.Path = $"-1,{umbracoNode.Id}";
            umbracoNodeRepository.Update(umbracoNode);

            user.Id = umbracoNode.Id;

            var content = new CmsContent
            {
                ContentType = DefaultMemberContentTypeId,
                NodeId      = umbracoNode.Id
            };

            await contentRepository.AddAsync(content, cancellationToken);

            var xmlWriterSettings = new System.Xml.XmlWriterSettings
            {
                Indent             = false,
                OmitXmlDeclaration = true
            };

            using (var sw = new StringWriter())
                using (var writer = System.Xml.XmlWriter.Create(sw, xmlWriterSettings))
                {
                    var xmlNode = new XmlNode
                    {
                        CreateDate        = umbracoNode.CreateDate,
                        Email             = user.Email,
                        Id                = umbracoNode.Id,
                        LastPasswordReset = DateTime.UtcNow,
                        Level             = umbracoNode.Level,
                        LoginName         = user.Email,
                        NodeName          = umbracoNode.Text,
                        NodeType          = DefaultMemberContentTypeId,
                        NodeTypeAlias     = "Default",
                        ParentId          = umbracoNode.ParentId,
                        Path              = umbracoNode.Path,
                        SortOrder         = umbracoNode.SortOrder,
                        Template          = 0,
                        Version           = umbracoNode.UniqueId,
                        WriterId          = 0,
                        WriterName        = "kkadmin",
                        UrlName           = umbracoNode.Text,
                        UpdateDate        = umbracoNode.CreateDate
                    };

                    var emptyNamespaces       = new XmlSerializerNamespaces(new[] { System.Xml.XmlQualifiedName.Empty });
                    var umbracoNodeSerializer = new XmlSerializer(typeof(XmlNode));
                    umbracoNodeSerializer.Serialize(writer, xmlNode, emptyNamespaces);

                    var contentXml = new CmsContentXml
                    {
                        NodeId = umbracoNode.Id,
                        Xml    = sw.ToString()
                    };

                    await contentXmlRepository.AddAsync(contentXml, cancellationToken);
                }


            var member = new CmsMember
            {
                NodeId    = umbracoNode.Id,
                Email     = user.Email,
                LoginName = user.Alias,
                Password  = user.PasswordHash
            };

            await membersRepository.AddAsync(member, cancellationToken);

            var propertyTypes = propertyTypeRepository
                                .GetAll()
                                .Where(pt => pt.ContentTypeId == DefaultMemberContentTypeId)
                                .ToList();

            var properties = user.GetType().GetProperties(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public)
                             .ToDictionary(pt => pt.Name.ToLower(), pt => pt);


            var cmsContentVersion = new CmsContentVersion
            {
                ContentId   = member.NodeId,
                VersionDate = DateTime.UtcNow,
                VersionId   = Guid.NewGuid()
            };

            await contentVersionRepository.AddAsync(cmsContentVersion, cancellationToken);

            foreach (var pt in propertyTypes)
            {
                var cmsProp = new CmsPropertyData
                {
                    ContentNodeId  = member.NodeId,
                    VersionId      = cmsContentVersion.VersionId,
                    PropertyTypeId = pt.Id
                };

                if (properties.ContainsKey(pt.Alias.ToLower()))
                {
                    var p = properties[pt.Alias.ToLower()];
                    switch (p.PropertyType)
                    {
                    case Type boolType when boolType == typeof(bool):
                        cmsProp.DataInt = (bool)Convert.ChangeType(p.GetValue(user) ?? 0, p.PropertyType) ? 1 : 0;
                        break;

                    case Type dateType when dateType == typeof(DateTime):
                        cmsProp.DataDate = (DateTime?)Convert.ChangeType(p.GetValue(user) ?? 0, p.PropertyType);
                        break;

                    default:
                        cmsProp.DataNvarchar = p.GetValue(user)?.ToString();
                        break;
                    }
                }

                await propertyDataRepository.AddAsync(cmsProp, cancellationToken);
            }

            await propertyTypeRepository.SaveChangesAsync(cancellationToken);

            return(IdentityResult.Success);
        }
示例#46
0
 /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
 {
     Serialize(xmlWriter, o, namespaces, null);
 }
示例#47
0
        public CXml PublishDataBase(string FilePath)
        {
            CXml                    Cxml       = new CXml();
            XmlSerializer           serializer = new XmlSerializer(typeof(CXml));
            XmlSerializerNamespaces ns         = new XmlSerializerNamespaces();

            ElementMap.Values.OrderBy(x => x.File);
            foreach (string key in ElementMap.Keys)
            {
                CElement element = ElementMap[key];
                if (element is CFunction)
                {
                    CFunction function = element as CFunction;
                    //if (function.StorageClass != StorageClass.Static)
                    {
                        Function f = _factory.Fac_GetXmlFunctionType(function);
                        if (function.IsDefinition == false)
                        {
                            IEnumerable <CElement> definition = ElementMap.Values.Where(x => x.ElementID == function.ElementID).ToList();
                            foreach (CElement e in definition)
                            {
                                if (e is CFunction)
                                {
                                    CFunction def = e as CFunction;
                                    if (def.IsDefinition == true)
                                    {
                                        f.Definition = def.ID;
                                    }
                                }
                            }
                        }
                        f.PrototypeID = function.ElementID;
                        f.Component   = _factory.Fac_GetComponentName(function);
                        f.Interface   = _factory.Fac_GetInterfaceName(function);
                        f.CalledFunctions.AddRange(function.Children);
                        Cxml.Functions.Add(f);
                    }
                }
                else if (element is CDataType)
                {
                    Cxml.DataTypes.Add(_factory.Fac_GetXmlDataType(element as CDataType));
                }
                else if (element is CVariable)
                {
                    CVariable cv = element as CVariable;
                    if (cv.VariableType == VariableType.GlobalVariable)
                    {
                        Variable v = _factory.Fac_GetXmlVariableType(element as CVariable);
                        v.Component = _factory.Fac_GetComponentName(element);
                        Cxml.Variables.Add(v);
                    }
                }
            }
            try
            {
                using (var sww = new Utf8StringWriter())
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    settings.NewLineOnAttributes = true;
                    settings.Encoding            = Encoding.ASCII;
                    using (XmlWriter writer = XmlWriter.Create(sww, settings))
                    {
                        serializer.Serialize(writer, Cxml, ns);
                        string       xml = sww.ToString();
                        StreamWriter w   = new StreamWriter(new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite), Encoding.UTF8);
                        w.Write(xml);
                        w.Close();
                    }
                }
            }

            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
            return(Cxml);
        }
示例#48
0
 /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
 public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
 {
     Serialize(xmlWriter, o, namespaces, encodingStyle, null);
 }
示例#49
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);
        }
示例#50
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;
            }
示例#51
0
 public static void WriteSerializedObject(Type type, object serialized, string path, XmlSerializerNamespaces xmlns = null)
 {
     try
     {
         var xs = new XmlSerializer(type);
         using (var fs = new FileStream(path, FileMode.OpenOrCreate))
         {
             StreamWriter myStreamWriter = new StreamWriter(fs);
             if (xmlns != null)
             {
                 xs.Serialize(myStreamWriter, serialized, xmlns);
             }
             else
             {
                 xs.Serialize(myStreamWriter, serialized);
             }
             Console.WriteLine($"File {path} successfully created!");
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"Error: {e.Message}");
     }
 }
示例#52
0
        public GenerateXMLDTO GenerateXML(int id)
        {
            GenerateXMLDTO dto = new GenerateXMLDTO();

            if (!Directory.Exists(Store.C.DELIVERY_PATH))
            {
                throw (new Exception($"Delivery Folder {Store.C.DELIVERY_PATH} Not Exists . ."));
            }

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromMinutes(15)))
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    List <string> IgnorableCVTs = db.CVT.Where(c => c.IsIgnorableInDelivery).Select(c => c.CVTS).ToList();
                    DeliveryBatch deliveryBatch = db.DeliveryBatches.Find(id);
                    var           outXmlPath    = Path.Combine(Store.C.DELIVERY_PATH, deliveryBatch.BatchNumber + ".xml");

                    var tanIds   = deliveryBatch.Tans.Select(t => t.Id).ToList();
                    var tanDatas = db.TanData.Where(td => tanIds.Contains(td.TanId)).ToList();
                    if (!tanDatas.Any())
                    {
                        throw new Exception($"No Curated TANs Found In Delivery Batch {deliveryBatch.BatchNumber}.");
                    }
                    xsd.RXNFILE rxnFile = new xsd.RXNFILE();
                    rxnFile.SOURCE  = "GVKbio";
                    rxnFile.FILENUM = deliveryBatch.BatchNumber;
                    rxnFile.VERSION = 2;
                    var documents = new List <xsd.DOCUMENT>();
                    foreach (var tanData in tanDatas)
                    {
                        XmlUtils.LoadMasterData(tanData);
                        xsd.RXNGRP     rxnGroup = new xsd.RXNGRP();
                        List <xsd.RXN> rxns     = new List <xsd.RXN>();
                        foreach (var reaction in tanData.Tan.Reactions)
                        {
                            #region RXNID
                            var keyProduct = tanData.Tan.Participants.Where(p => p.ReactionId == reaction.Id && p.KeyProduct == true).FirstOrDefault();
                            var rxnId      = new RXNID();
                            rxnId.RXNNUM = keyProduct?.Participant?.NUM.ToString();
                            rxnId.RXNSEQ = keyProduct?.KeyProductSeq.ToString();
                            #endregion

                            #region RXNPROCESS
                            var rxnProcess = new xsd.RXNPROCESS();
                            var xmlStages  = new List <xsd.STAGE>();

                            #region RSNs
                            rxnProcess.RSN = GetRSN(reaction, IgnorableCVTs);
                            #endregion

                            #region Stages
                            foreach (var stage in reaction.Stages)
                            {
                                var xmlStage = new xsd.STAGE();
                                #region Conditions (Sub stages)
                                var subStages = new List <xsd.SUBSTAGE>();
                                foreach (var condition in stage.StageConditions)
                                {
                                    var subStage   = new xsd.SUBSTAGE();
                                    var conditions = new List <xsd.COND>();

                                    if (!String.IsNullOrEmpty(condition.Temperature))
                                    {
                                        conditions.Add(new xsd.COND {
                                            Value = condition.Temperature, TYPE = CondType.TP
                                        });
                                    }
                                    if (!String.IsNullOrEmpty(condition.Pressure))
                                    {
                                        conditions.Add(new xsd.COND {
                                            Value = condition.Pressure, TYPE = CondType.PR
                                        });
                                    }
                                    if (!String.IsNullOrEmpty(condition.Time))
                                    {
                                        conditions.Add(new xsd.COND {
                                            Value = condition.Time, TYPE = CondType.TM
                                        });
                                    }
                                    if (!String.IsNullOrEmpty(condition.PH))
                                    {
                                        conditions.Add(new xsd.COND {
                                            Value = condition.PH, TYPE = CondType.PH
                                        });
                                    }

                                    subStage.COND = conditions.ToArray();
                                    subStages.Add(subStage);
                                }
                                xmlStage.SUBSTAGE = subStages.ToArray();
                                #endregion
                                xmlStages.Add(xmlStage);
                            }
                            rxnProcess.STAGE = xmlStages.ToArray();
                            #endregion
                            #endregion

                            #region XREFGRP
                            var xRefGroup = new xsd.XREFGRP();
                            var nrns      = new List <xsd.NRN>();
                            foreach (var tanParticipant in tanData.Tan.Participants.Where(p => p.Reaction.Id == reaction.Id && p.Participant.ChemicalType != ChemicalType.S8000))
                            {
                                xsd.NRN nrn;
                                if (!nrns.Where(n => n.NRNNUM == tanParticipant.Participant.NUM).Any())
                                {
                                    nrn = new xsd.NRN()
                                    {
                                        NRNNUM = tanParticipant.Participant.NUM,
                                        NRNREG = Int32.Parse(tanParticipant.Participant.RegNumber)
                                    };
                                    nrns.Add(nrn);
                                }
                            }
                            xRefGroup.NRN = nrns.ToArray();
                            #endregion

                            xsd.SUBDESC subDesc           = null;
                            var         s8000Participants = reaction.Tan.Participants.
                                                            Where(rp => rp.ReactionId == reaction.Id && rp.Participant.ChemicalType == ChemicalType.S8000);
                            var subDefinitions = new List <xsd.SUBDEFN>();
                            if (s8000Participants.Any())
                            {
                                foreach (var s8000Particiapnt in s8000Participants)
                                {
                                    var subDefinition = new xsd.SUBDEFN();
                                    if (!subDefinitions.Where(p => p.NRNNUM == s8000Particiapnt.Participant.NUM.ToString()).Any())
                                    {
                                        subDefinition.NRNNUM  = s8000Particiapnt.Participant.NUM.ToString();
                                        subDefinition.SUBNAME = s8000Particiapnt.Participant.Name;
                                        subDefinition.SUBLOC  = String.Join(",", s8000Particiapnt.Participant.MetaData.Select(md => md.PageNo).ToList());
                                        subDefinitions.Add(subDefinition);
                                    }
                                }
                            }
                            subDesc = new xsd.SUBDESC();
                            if (!subDefinitions.Any())
                            {
                                subDefinitions.Add(new SUBDEFN());
                            }
                            subDesc.SUBDEFN = subDefinitions.ToArray();

                            #region RXN
                            var rxn = new xsd.RXN();
                            rxn.NO    = reaction.DisplayOrder;
                            rxn.RXNID = new xsd.RXNID {
                                RXNNUM = reaction.KeyProductNum, RXNSEQ = reaction.KeyProductSequence
                            };
                            rxn.RSD        = reaction.RSD;
                            rxn.XREFGRP    = xRefGroup;
                            rxn.RXNPROCESS = rxnProcess;
                            rxn.SUBDESC    = subDesc;
                            rxns.Add(rxn);
                            #endregion
                        }
                        rxnGroup.RXN = rxns.ToArray();

                        var document = new xsd.DOCUMENT();
                        document.VIEW     = "RXN";
                        document.CAN      = tanData.Tan.CAN;
                        document.TAN      = tanData.Tan.tanNumber;
                        document.ANALYST  = 8005.ToString();
                        document.COMMENTS = tanData.Tan.CommentsForXml;
                        document.RXNGRP   = rxnGroup;
                        documents.Add(document);
                    }
                    rxnFile.DOCUMENT = documents.ToArray();
                    var serializer = new XmlSerializer(typeof(xsd.RXNFILE), String.Empty);
                    var settings   = new XmlWriterSettings
                    {
                        Indent             = false,
                        OmitXmlDeclaration = true
                    };
                    using (var writer = new StreamWriter(outXmlPath))
                        using (var xmlWriter = XmlWriter.Create(writer, settings))
                        {
                            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                            serializer.Serialize(xmlWriter, rxnFile, ns);
                        }

                    return(new GenerateXMLDTO
                    {
                        IsSuccess = true,
                        OutXmlPath = outXmlPath
                    });
                }
        }
示例#53
0
        /// <summary>
        /// 設定保存
        /// </summary>
        /// <param name="iPlayerName"></param>
        /// <returns></returns>
        public bool Save(string iPlayerName)
        {
            //設定の読み込み
            string           xmlFilename = XML_FILENAME_SETTINGS;
            XmlSerializer    serializer;
            SettingsProperty xmlSettings = new SettingsProperty();

            if (File.Exists(xmlFilename))
            {
                FileStream fs = new FileStream(xmlFilename, System.IO.FileMode.Open);
                //シリアライズ
                serializer = new XmlSerializer(typeof(SettingsProperty));
                //読み込み
                xmlSettings = (SettingsProperty)serializer.Deserialize(fs);
                fs.Close();
            }

            //保存データ設定
            bool foundFlg = false;

            foreach (SettingsPlayerProperty v in xmlSettings.Player)
            {
                if (v.Name == iPlayerName)
                {
                    foundFlg             = true;
                    v.FormPosX           = FormPosX;
                    v.FormPosY           = FormPosY;
                    v.TicketUseEach      = TicketUseEach;
                    v.Kamihr3            = Kamihr3;
                    v.LimitTicket        = LimitTicket;
                    v.LimitCp            = LimitCp;
                    v.MenuIndexWorksCall = MenuIndexWorksCall;
                    v.MenuIndexArea      = MenuIndexArea;
                    v.MenuIndexBivouac   = MenuIndexBivouac;
                }
            }
            if (!foundFlg)
            {
                SettingsPlayerProperty player = new SettingsPlayerProperty();
                player.Name               = iPlayerName;
                player.FormPosX           = FormPosX;
                player.FormPosY           = FormPosY;
                player.TicketUseEach      = TicketUseEach;
                player.Kamihr3            = Kamihr3;
                player.LimitTicket        = LimitTicket;
                player.LimitCp            = LimitCp;
                player.MenuIndexWorksCall = MenuIndexWorksCall;
                player.MenuIndexArea      = MenuIndexArea;
                player.MenuIndexBivouac   = MenuIndexBivouac;
                xmlSettings.Player.Add(player);
            }

            //設定の保存
            StreamWriter sw = new StreamWriter(xmlFilename, false, new UTF8Encoding(false));
            //名前空間出力抑制
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add(String.Empty, String.Empty);
            //シリアライズ
            serializer = new XmlSerializer(typeof(SettingsProperty));
            serializer.Serialize(sw, xmlSettings, ns);
            //書き込み
            sw.Flush();
            sw.Close();
            sw = null;
            return(true);
        }
        public static string ObjectToXmlString(Object _object, Type objType)
        {
            string xmlStr = string.Empty;

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = false;
            //settings.OmitXmlDeclaration = true;
            //settings.ConformanceLevel = ConformanceLevel.Document;
            settings.NewLineChars    = string.Empty;
            settings.NewLineHandling = NewLineHandling.None;


            /*
             * // check all these attributes from the folloiwng URL
             * https://csharp.hotexamples.com/examples/System.Xml/XmlWriterSettings/-/php-xmlwritersettings-class-examples.html
             *
             * var settings = new XmlWriterSettings
             * {
             *  Indent = false,
             *  Encoding = new UTF8Encoding(false),
             *  NamespaceHandling = NamespaceHandling.OmitDuplicates,
             *  OmitXmlDeclaration = true,
             *  NewLineOnAttributes = false,
             *  DoNotEscapeUriAttributes = true
             * };
             *
             * var settings = new XmlWriterSettings
             * {
             *   OmitXmlDeclaration = true,
             *   ConformanceLevel = ConformanceLevel.Fragment,
             *   Indent = true,
             *   CloseOutput = false
             * };
             *
             */


            using (StringWriter stringWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
                {
                    /*
                     * XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                     * namespaces.Add(string.Empty, string.Empty);
                     */

                    //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });

                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

                    // this only removes namespace at root level
                    //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    //namespaces.Add(string.Empty, string.Empty);

                    XmlSerializer serializer = new XmlSerializer(objType);
                    serializer.Serialize(xmlWriter, _object, namespaces);

                    xmlStr = stringWriter.ToString();
                    xmlWriter.Close();
                }

                stringWriter.Close();
            }

            return(xmlStr);
        }
示例#55
0
        static void Main(string[] args)
        {
            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
             * <EmployeeId>42</EmployeeId>
             * <FirstName>John</FirstName>
             * <LastName>Doe</LastName>
             * </Employee>
             */
            {
                var employee = new v1.Employee
                {
                    EmployeeId = 42,
                    FirstName  = "John",
                    LastName   = "Doe"
                };

                var path = Path.Combine(Path.GetTempPath(), "employee1.xml");
                Serializer <v1.Employee> .Serialize(employee, path);

                var result = Serializer <v1.Employee> .Deserialize(path);

                Console.WriteLine(File.ReadAllText(path));

                File.Delete(path);
            }

            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="42">
             * <firstName>John</firstName>
             * <lastName>Doe</lastName>
             * </employee>
             */
            {
                var employee = new Employee
                {
                    EmployeeId = 42,
                    FirstName  = "John",
                    LastName   = "Doe"
                };

                var path = Path.Combine(Path.GetTempPath(), "employee1.xml");
                Serializer <Employee> .Serialize(employee, path);

                var result = Serializer <Employee> .Deserialize(path);

                Console.WriteLine(File.ReadAllText(path));

                File.Delete(path);
            }

            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="42">
             * <firstName>John</firstName>
             * <lastName>Doe</lastName>
             * </employee>
             * <?xml version="1.0" encoding="utf-8"?>
             * <Department xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Id="102">
             * <Name>IT</Name>
             * </Department>
             */
            {
                var employee = new Employee
                {
                    EmployeeId = 42,
                    FirstName  = "John",
                    LastName   = "Doe"
                };

                var department = new Department
                {
                    Id   = 102,
                    Name = "IT"
                };

                var path = Path.Combine(Path.GetTempPath(), "employee2.xml");
                using (var wr = File.CreateText(path))
                {
                    Serializer <Employee> .Serialize(employee, wr);

                    wr.WriteLine();
                    Serializer <Department> .Serialize(department, wr);
                }

                Console.WriteLine(File.ReadAllText(path));

                File.Delete(path);
            }

            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1">
             * <Employee id="42">
             *  <firstName>John</firstName>
             *  <lastName>Doe</lastName>
             * </Employee>
             * <Department Id="102">
             *  <Name>IT</Name>
             * </Department>
             * </Data>
             */
            {
                var data = new Data()
                {
                    Version  = 1,
                    Employee = new Employee
                    {
                        EmployeeId = 42,
                        FirstName  = "John",
                        LastName   = "Doe"
                    },
                    Department = new Department
                    {
                        Id   = 102,
                        Name = "IT"
                    }
                };

                var path = Path.Combine(Path.GetTempPath(), "employee3.xml");
                using (var wr = File.CreateText(path))
                {
                    Serializer <Data> .Serialize(data, wr);
                }

                Console.WriteLine(File.ReadAllText(path));

                File.Delete(path);
            }

            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <Data Version="1">
             * <employee id="42">
             *  <firstName>John</firstName>
             *  <lastName>Doe</lastName>
             * </employee>
             * <Department Id="102">
             *  <Name>IT</Name>
             * </Department>
             * </Data>
             */
            {
                var employee = new Employee
                {
                    EmployeeId = 42,
                    FirstName  = "John",
                    LastName   = "Doe"
                };

                var department = new Department
                {
                    Id   = 102,
                    Name = "IT"
                };

                var path = Path.Combine(Path.GetTempPath(), "employee4.xml");

                var settings = new XmlWriterSettings
                {
                    Encoding = Encoding.UTF8,
                    Indent   = true
                };

                var namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);

                using (var wr = XmlWriter.Create(path, settings))
                {
                    wr.WriteStartDocument();
                    wr.WriteStartElement("Data");
                    wr.WriteStartAttribute("Version");
                    wr.WriteValue(1);
                    wr.WriteEndAttribute();

                    var employeeSerializer = new XmlSerializer(typeof(Employee));
                    employeeSerializer.Serialize(wr, employee, namespaces);

                    var depSerializer = new XmlSerializer(typeof(Department));
                    depSerializer.Serialize(wr, department, namespaces);

                    wr.WriteEndElement();
                    wr.WriteEndDocument();
                }

                Console.WriteLine(File.ReadAllText(path));

                var rdsettings = new XmlReaderSettings()
                {
                    IgnoreComments   = true,
                    IgnoreWhitespace = true
                };

                using (var rd = XmlReader.Create(path, rdsettings))
                {
                    string indent = string.Empty;
                    while (rd.Read())
                    {
                        switch (rd.NodeType)
                        {
                        case XmlNodeType.Element:
                            Console.Write($"{indent}{{ {rd.Name} : ");
                            indent = indent + "  ";
                            while (rd.MoveToNextAttribute())
                            {
                                Console.WriteLine();
                                Console.WriteLine($"{indent}{{ {rd.Name} : {rd.Value} }}");
                            }
                            break;

                        case XmlNodeType.Text:
                            Console.Write(rd.Value);
                            break;

                        case XmlNodeType.EndElement:
                            indent = indent.Remove(0, 2);
                            Console.WriteLine($"{indent}}}");
                            break;

                        default:
                            Console.WriteLine($"[{rd.Name} {rd.Value}]");
                            break;
                        }
                    }
                }

                File.Delete(path);
            }
        }
示例#56
0
        public void CompareSerializationFormats()
        {
            var events = new NLogEvents
            {
                BaseTimeUtc = DateTime.UtcNow.Ticks,
                ClientName  = "foo",
                LayoutNames = new StringCollection {
                    "foo", "bar", "baz"
                },
                Strings = new StringCollection {
                    "logger1", "logger2", "logger3"
                },
                Events =
                    new[]
                {
                    new NLogEvent
                    {
                        Id            = 1,
                        LevelOrdinal  = 2,
                        LoggerOrdinal = 0,
                        TimeDelta     = 34,
                        Values        = "1|2|3"
                    },
                    new NLogEvent
                    {
                        Id            = 2,
                        LevelOrdinal  = 3,
                        LoggerOrdinal = 2,
                        TimeDelta     = 345,
                        Values        = "1|2|3",
                    }
                }
            };

            var serializer1 = new XmlSerializer(typeof(NLogEvents));
            var sw1         = new StringWriter();

            using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings {
                Indent = true
            }))
            {
                var namespaces = new XmlSerializerNamespaces();
                namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance");

                serializer1.Serialize(writer1, events, namespaces);
            }

            var serializer2 = new DataContractSerializer(typeof(NLogEvents));
            var sw2         = new StringWriter();

            using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings {
                Indent = true
            }))
            {
                serializer2.WriteObject(writer2, events);
            }

            var xml1 = sw1.ToString();
            var xml2 = sw2.ToString();

            Assert.Equal(xml1, xml2);
        }
示例#57
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
        public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            try
            {
                if (_primitiveType != null)
                {
                    if (encodingStyle != null && encodingStyle.Length > 0)
                    {
                        throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
                    }
                    SerializePrimitive(xmlWriter, o, namespaces);
                }
                else if (ShouldUseReflectionBasedSerialization(_mapping))
                {
                    SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id);
                }
#if !FEATURE_SERIALIZATION_UAPAOT
                else if (_tempAssembly == null || _typedSerializer)
                {
                    // The contion for the block is never true, thus the block is never hit.
                    XmlSerializationWriter writer = CreateWriter();
                    writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
                    try
                    {
                        Serialize(o, writer);
                    }
                    finally
                    {
                        writer.Dispose();
                    }
                }
                else
                {
                    _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                }
#else
                else
                {
                    if (this.innerSerializer != null)
                    {
                        if (!string.IsNullOrEmpty(this.DefaultNamespace))
                        {
                            this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
                        }

                        XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
                        writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        try
                        {
                            this.innerSerializer.Serialize(o, writer);
                        }
                        finally
                        {
                            writer.Dispose();
                        }
                    }
                    else if (ReflectionMethodEnabled)
                    {
                        SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id);
                    }
                    else
                    {
                        throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name));
                    }
                }
#endif
            }
示例#58
0
 public ComponentLink()
 {
     Namespaces = new XmlSerializerNamespaces();
     Namespaces.Add("xlink", "http://www.w3.org/1999/xlink");
 }