Ejemplo n.º 1
0
        public void Save()
        {
            if (_streams.Count > 0)
            {
                using (var package = System.IO.Packaging.Package.Open(_path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    foreach (var item in _streams)
                    {
                        PackagePart filePart = null;

                        Uri uri = item.Key;

                        if (package.PartExists(uri))
                        {
                            package.DeletePart(uri);
                            package.Flush();
                        }

                        filePart = package.CreatePart(uri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);

                        using (Stream output = filePart?.GetStream(FileMode.Create, FileAccess.Write))
                        {
                            CopyStream(item.Value, output);
                        }
                    }
                }

                _streams.Clear();
            }
        }
Ejemplo n.º 2
0
 public string GetFileHash(PackagePart part)
 {
     using (var inputStream = part.GetStream())
     using (var md5 = new MD5CryptoServiceProvider())
     {
         var hash = md5.ComputeHash(inputStream);
         var sb = new StringBuilder();
         foreach (var b in hash)
         {
             sb.Append(string.Format("{0:X2}", b));
         }
         return sb.ToString();
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Compress multiple files to a byte array.
        /// </summary>
        /// <param name="lstFiles">List of files to compress.</param>
        public static byte[] CompressMutiple(IEnumerable <string> lstFiles)
        {
            MemoryStream objStream  = new MemoryStream();
            Package      objPackage = Package.Open(objStream, FileMode.Create, FileAccess.ReadWrite);

            foreach (string strFile in lstFiles)
            {
                Uri         objUri    = new Uri("/" + (Path.GetFileName(strFile)?.Replace(' ', '_') ?? string.Empty), UriKind.Relative);
                PackagePart objPart   = objPackage.CreatePart(objUri, System.Net.Mime.MediaTypeNames.Application.Zip, CompressionOption.Maximum);
                byte[]      bytBuffer = File.ReadAllBytes(strFile);
                objPart?.GetStream().Write(bytBuffer, 0, bytBuffer.Length);
            }
            objPackage.Close();

            return(objStream.ToArray());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Compress multiple files to a file. This is only used for testing an compressing NPC packs. This is not to be used by end users.
        /// </summary>
        /// <param name="lstFiles">List of files to compress.</param>
        /// <param name="strDestination">File to compress to.</param>
        public static void CompressMutipleToFile(IEnumerable <string> lstFiles, string strDestination)
        {
            Package objPackage = Package.Open(strDestination, FileMode.Create, FileAccess.ReadWrite);

            foreach (string strFile in lstFiles)
            {
                string[] strPath     = Path.GetDirectoryName(strFile)?.Replace(' ', '_').Split(Path.DirectorySeparatorChar) ?? new string[] {};
                string   strPackFile = '/' + strPath[strPath.Length - 2] + '/' + strPath[strPath.Length - 1] + '/' + (Path.GetFileName(strFile)?.Replace(' ', '_') ?? string.Empty);
                strPackFile = strPackFile.TrimStartOnce("/saves");
                Uri         objUri    = new Uri(strPackFile, UriKind.Relative);
                PackagePart objPart   = objPackage.CreatePart(objUri, System.Net.Mime.MediaTypeNames.Application.Zip, CompressionOption.Maximum);
                byte[]      bytBuffer = File.ReadAllBytes(strFile);
                objPart?.GetStream().Write(bytBuffer, 0, bytBuffer.Length);
            }
            objPackage.Close();
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Compress multiple files to a file. This is only used for testing an compressing NPC packs. This is not to be used by end users.
 /// </summary>
 /// <param name="lstFiles">List of files to compress.</param>
 /// <param name="strDestination">File to compress to.</param>
 public static void CompressMutipleToFile(IEnumerable <string> lstFiles, string strDestination)
 {
     if (lstFiles == null)
     {
         throw  new ArgumentNullException(nameof(lstFiles));
     }
     using (Package objPackage = Package.Open(strDestination, FileMode.Create, FileAccess.ReadWrite))
     {
         foreach (string strFile in lstFiles)
         {
             string[] strPath     = Path.GetDirectoryName(strFile)?.Replace(' ', '_').Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries) ?? new string[] { };
             string   strPackFile = ('/' + Path.Combine(strPath[strPath.Length - 2], strPath[strPath.Length - 1], Path.GetFileName(strFile)?.Replace(' ', '_') ?? string.Empty))
                                    .TrimStartOnce("/saves");
             Uri         objUri    = new Uri(strPackFile, UriKind.Relative);
             PackagePart objPart   = objPackage.CreatePart(objUri, System.Net.Mime.MediaTypeNames.Application.Zip, CompressionOption.Maximum);
             byte[]      bytBuffer = File.ReadAllBytes(strFile);
             objPart?.GetStream().Write(bytBuffer, 0, bytBuffer.Length);
         }
     }
 }
Ejemplo n.º 6
0
        public static void FlatToOpc(XDocument doc, string outputPath)
        {
            XNamespace pkg =
                "http://schemas.microsoft.com/office/2006/xmlPackage";
            XNamespace rel =
                "http://schemas.openxmlformats.org/package/2006/relationships";

            using (Package package = Package.Open(outputPath, FileMode.Create))
            {
                // add all parts (but not relationships)
                foreach (XElement xmlPart in doc.Root
                         .Elements()
                         .Where(p =>
                                (string)p.Attribute(pkg + "contentType") !=
                                "application/vnd.openxmlformats-package.relationships+xml"))
                {
                    var name        = (string)xmlPart.Attribute(pkg + "name");
                    var contentType = (string)xmlPart.Attribute(pkg + "contentType");
                    if (contentType.EndsWith("xml"))
                    {
                        var         u    = new Uri(name, UriKind.Relative);
                        PackagePart part = package.CreatePart(u, contentType,
                                                              CompressionOption.SuperFast);
                        using (Stream str = part.GetStream(FileMode.Create))
                            using (XmlWriter xmlWriter = XmlWriter.Create(str))
                                xmlPart.Element(pkg + "xmlData")
                                .Elements()
                                .First()
                                .WriteTo(xmlWriter);
                    }
                    else
                    {
                        var         u    = new Uri(name, UriKind.Relative);
                        PackagePart part = package.CreatePart(u, contentType,
                                                              CompressionOption.SuperFast);
                        using (Stream str = part.GetStream(FileMode.Create))
                            using (var binaryWriter = new BinaryWriter(str))
                            {
                                var base64StringInChunks =
                                    (string)xmlPart.Element(pkg + "binaryData");
                                char[] base64CharArray = base64StringInChunks
                                                         .Where(c => c != '\r' && c != '\n').ToArray();
                                byte[] byteArray =
                                    Convert.FromBase64CharArray(base64CharArray,
                                                                0, base64CharArray.Length);
                                binaryWriter.Write(byteArray);
                            }
                    }
                }

                foreach (XElement xmlPart in doc.Root.Elements())
                {
                    var name        = (string)xmlPart.Attribute(pkg + "name");
                    var contentType = (string)xmlPart.Attribute(pkg + "contentType");
                    if (contentType ==
                        "application/vnd.openxmlformats-package.relationships+xml")
                    {
                        // add the package level relationships
                        if (name == "/_rels/.rels")
                        {
                            foreach (XElement xmlRel in
                                     xmlPart.Descendants(rel + "Relationship"))
                            {
                                var id         = (string)xmlRel.Attribute("Id");
                                var type       = (string)xmlRel.Attribute("Type");
                                var target     = (string)xmlRel.Attribute("Target");
                                var targetMode =
                                    (string)xmlRel.Attribute("TargetMode");
                                if (targetMode == "External")
                                {
                                    package.CreateRelationship(
                                        new Uri(target, UriKind.Absolute),
                                        TargetMode.External, type, id);
                                }
                                else
                                {
                                    package.CreateRelationship(
                                        new Uri(target, UriKind.Relative),
                                        TargetMode.Internal, type, id);
                                }
                            }
                        }
                        else

                        // add part level relationships
                        {
                            string directory    = name.Substring(0, name.IndexOf("/_rels"));
                            string relsFilename = name.Substring(name.LastIndexOf('/'));
                            string filename     =
                                relsFilename.Substring(0, relsFilename.IndexOf(".rels"));
                            PackagePart fromPart = package.GetPart(
                                new Uri(directory + filename, UriKind.Relative));
                            foreach (XElement xmlRel in
                                     xmlPart.Descendants(rel + "Relationship"))
                            {
                                var id         = (string)xmlRel.Attribute("Id");
                                var type       = (string)xmlRel.Attribute("Type");
                                var target     = (string)xmlRel.Attribute("Target");
                                var targetMode =
                                    (string)xmlRel.Attribute("TargetMode");
                                if (targetMode == "External")
                                {
                                    fromPart.CreateRelationship(
                                        new Uri(target, UriKind.Absolute),
                                        TargetMode.External, type, id);
                                }
                                else
                                {
                                    fromPart.CreateRelationship(
                                        new Uri(target, UriKind.Relative),
                                        TargetMode.Internal, type, id);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// This holds the logic for unpacking the deck from the .deck package and saving it locally
        /// </summary>
        /// <param name="zipFilename">.deck file path</param>
        /// <param name="newDeckGUID">New deck foldername</param>
        public static string ExtractFromZip(string zipFilename)
        {
            try
            {
                string deckGuid  = string.Empty;
                string deckTitle = string.Empty;
                string outputPath;
                using (Package unZip = System.IO.Packaging.Package.Open(zipFilename, FileMode.Open, FileAccess.Read))
                {
                    Uri         uri       = new Uri("/deck.xml", UriKind.RelativeOrAbsolute);
                    PackagePart xmlPart   = unZip.GetPart(uri);
                    Stream      xmlStream = xmlPart.GetStream(FileMode.Open, FileAccess.Read);

                    XmlSerializer SerializerObj = new XmlSerializer(typeof(CardDeck));
                    CardDeck      cDeck         = (CardDeck)SerializerObj.Deserialize(xmlStream);

                    xmlStream.Close();


                    Uri uriFilesXml = new Uri("/files.xml", UriKind.RelativeOrAbsolute);
                    xmlPart   = unZip.GetPart(uriFilesXml);
                    xmlStream = xmlPart.GetStream(FileMode.Open, FileAccess.Read);

                    SerializerObj = new XmlSerializer(typeof(string[]));
                    string[] fileNames = (string[])SerializerObj.Deserialize(xmlStream);


                    xmlStream.Close();

                    // prepare dictionary
                    Dictionary <string, string> dic = new Dictionary <string, string>();
                    for (int i = 0; i < fileNames.Length; i += 2)
                    {
                        dic[fileNames[i]] = fileNames[i + 1];
                    }



                    deckGuid   = cDeck.DeckGUID;
                    deckTitle  = cDeck.Title;
                    outputPath = Path.Combine(DeckFileHelper.ApplicationTempPath, deckGuid);

                    if (!Directory.Exists(outputPath))
                    {
                        Directory.CreateDirectory(outputPath);
                    }
                    foreach (PackagePart part in unZip.GetParts())
                    {
                        string destFilename = Path.Combine(outputPath, Path.GetFileName(part.Uri.OriginalString));
                        if (dic.ContainsKey(Path.GetFileName(part.Uri.OriginalString)))
                        {
                            destFilename = Path.Combine(outputPath, dic[Path.GetFileName(part.Uri.OriginalString)]);
                        }
                        using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
                        {
                            using (Stream dest = File.OpenWrite(destFilename))
                            {
                                Utils.CopyStream(source, dest);
                            }
                        }
                    }
                }

                return(outputPath);
            }
            catch (Exception e)
            {
                Utils.LogException(MethodBase.GetCurrentMethod(), e);
                return(string.Empty);
            }
        }
Ejemplo n.º 8
0
    void ProcessPart(string packagePath, PackagePart part)
    {
        var originalString = part.Uri.OriginalString;
        if (originalString.StartsWith("/_rels") || originalString.StartsWith("/package"))
        {
            return;
        }
        var fullPath = Path.GetFullPath(Path.Combine(packagePath, "." + originalString));
        Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

        if (Directory.Exists(fullPath))
        {
            return;
        }
        using (var stream = part.GetStream())
        using (var output = File.OpenWrite(fullPath))
        {
            stream.CopyTo(output);
        }
    }
Ejemplo n.º 9
0
        /// <param name="dir"></param>
        /// <param name="dout"></param>
        /// <param name="debug"></param>
        public void packing(string dir, string dout, bool debug)
        {
            const string EXT_NUSPEC       = ".nuspec";
            const string EXT_NUPKG        = ".nupkg";
            const string TAG_META         = "metadata";
            const string DEF_CONTENT_TYPE = "application/octet";   //System.Net.Mime.MediaTypeNames.Application.Octet
            const string MANIFEST_URL     = "http://schemas.microsoft.com/packaging/2010/07/manifest";

            // Tags
            const string ID  = "id";
            const string VER = "version";

            Action <string, object> dbg = delegate(string s, object p) {
                if (debug)
                {
                    Log.Debug(s, p);
                }
            };

            // Get metadata

            var nuspec = Directory.GetFiles(dir, "*" + EXT_NUSPEC, SearchOption.TopDirectoryOnly).FirstOrDefault();

            if (nuspec == null)
            {
                throw new FileNotFoundException(String.Format("The {0} file is not found in `{1}`", EXT_NUSPEC, dir));
            }
            Log.Debug("Found {0}: `{1}`", EXT_NUSPEC, nuspec);

            var root = XDocument.Load(nuspec).Root.Elements().FirstOrDefault(x => x.Name.LocalName == TAG_META);

            if (root == null)
            {
                throw new FileNotFoundException(String.Format("The `{0}` not contains {1}.", nuspec, TAG_META));
            }

            var metadata = new Dictionary <string, string>();

            foreach (var tag in root.Elements())
            {
                metadata[tag.Name.LocalName.ToLower()] = tag.Value;
            }

            // Validate data - rules of nuget core

            if (metadata[ID].Length > 100 || !Regex.IsMatch(metadata[ID],
                                                            @"^\w+([_.-]\w+)*$",
                                                            RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
            {
                throw new FormatException(String.Format("The data format of `{0}` is not correct.", ID));
            }
            new System.Version(metadata[VER]); // check with System.Version

            // Format package

            var ignore = new string[] { // to ignore from package
                Path.Combine(dir, "_rels"),
                Path.Combine(dir, "package"),
                Path.Combine(dir, "[Content_Types].xml")
            };

            string pout = String.Format("{0}.{1}{2}", metadata[ID], metadata[VER], EXT_NUPKG);

            if (!String.IsNullOrWhiteSpace(dout))
            {
                if (!Directory.Exists(dout))
                {
                    Directory.CreateDirectory(dout);
                }
                pout = Path.Combine(dout, pout);
            }

            Log.Debug("Started packing `{0}` ...", pout);
            using (Package package = Package.Open(pout, FileMode.Create))
            {
                // manifest relationship

                Uri manifestUri = new Uri(String.Format("/{0}{1}", metadata[ID], EXT_NUSPEC), UriKind.Relative);
                package.CreateRelationship(manifestUri, TargetMode.Internal, MANIFEST_URL);

                // content

                foreach (var file in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
                {
                    if (ignore.Any(x => file.StartsWith(x, StringComparison.Ordinal)))
                    {
                        continue;
                    }

                    string pUri;
                    if (file.StartsWith(dir, StringComparison.OrdinalIgnoreCase))
                    {
                        pUri = file.Substring(dir.Length).TrimStart(Path.DirectorySeparatorChar);
                    }
                    else
                    {
                        pUri = file;
                    }
                    dbg("-> `{0}`", pUri);

                    // to protect path without separators
                    var escaped = String.Join("/", pUri.Split('\\', '/').Select(p => Uri.EscapeDataString(p)));
                    Uri uri     = PackUriHelper.CreatePartUri(new Uri(escaped, UriKind.Relative));

                    PackagePart part = package.CreatePart(uri, DEF_CONTENT_TYPE, CompressionOption.Maximum);

                    using (Stream tstream = part.GetStream())
                        using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) {
                            fileStream.CopyTo(tstream);
                        }
                }

                // metadata for package

                Func <string, string> getmeta = delegate(string key) {
                    return((metadata.ContainsKey(key))? metadata[key] : "");
                };

                package.PackageProperties.Creator        = getmeta("authors");
                package.PackageProperties.Description    = getmeta("description");
                package.PackageProperties.Identifier     = metadata[ID];
                package.PackageProperties.Version        = metadata[VER];
                package.PackageProperties.Keywords       = getmeta("tags");
                package.PackageProperties.Title          = getmeta("title");
                package.PackageProperties.LastModifiedBy = String.Format("{0} v{1} - GetNuTool Core", Settings.APP_NAME, Version.numberWithRevString);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns a System.IO.Packaging.Package stream for the given range.
        /// </summary>
        /// <param name="range">Range in word document</param>
        /// <returns></returns>
        public static Stream GetPackageStreamFromRange(this Range range)
        {
            XDocument  doc = XDocument.Parse(range.WordOpenXML);
            XNamespace pkg =
                "http://schemas.microsoft.com/office/2006/xmlPackage";
            XNamespace rel =
                "http://schemas.openxmlformats.org/package/2006/relationships";
            Package      InmemoryPackage = null;
            MemoryStream memStream       = new MemoryStream();

            using (InmemoryPackage = Package.Open(memStream, FileMode.Create))
            {
                // add all parts (but not relationships)
                foreach (var xmlPart in doc.Root
                         .Elements()
                         .Where(p =>
                                (string)p.Attribute(pkg + "contentType") !=
                                "application/vnd.openxmlformats-package.relationships+xml"))
                {
                    string name        = (string)xmlPart.Attribute(pkg + "name");
                    string contentType = (string)xmlPart.Attribute(pkg + "contentType");
                    if (contentType.EndsWith("xml"))
                    {
                        Uri         u    = new Uri(name, UriKind.Relative);
                        PackagePart part = InmemoryPackage.CreatePart(u, contentType,
                                                                      CompressionOption.SuperFast);
                        using (Stream str = part.GetStream(FileMode.Create))
                            using (XmlWriter xmlWriter = XmlWriter.Create(str))
                                xmlPart.Element(pkg + "xmlData")
                                .Elements()
                                .First()
                                .WriteTo(xmlWriter);
                    }
                    else
                    {
                        Uri         u    = new Uri(name, UriKind.Relative);
                        PackagePart part = InmemoryPackage.CreatePart(u, contentType,
                                                                      CompressionOption.SuperFast);
                        using (Stream str = part.GetStream(FileMode.Create))
                            using (BinaryWriter binaryWriter = new BinaryWriter(str))
                            {
                                string base64StringInChunks =
                                    (string)xmlPart.Element(pkg + "binaryData");
                                char[] base64CharArray = base64StringInChunks
                                                         .Where(c => c != '\r' && c != '\n').ToArray();
                                byte[] byteArray =
                                    System.Convert.FromBase64CharArray(base64CharArray,
                                                                       0, base64CharArray.Length);
                                binaryWriter.Write(byteArray);
                            }
                    }
                }
                foreach (var xmlPart in doc.Root.Elements())
                {
                    string name        = (string)xmlPart.Attribute(pkg + "name");
                    string contentType = (string)xmlPart.Attribute(pkg + "contentType");
                    if (contentType ==
                        "application/vnd.openxmlformats-package.relationships+xml")
                    {
                        // add the package level relationships
                        if (name == "/_rels/.rels")
                        {
                            foreach (XElement xmlRel in
                                     xmlPart.Descendants(rel + "Relationship"))
                            {
                                string id         = (string)xmlRel.Attribute("Id");
                                string type       = (string)xmlRel.Attribute("Type");
                                string target     = (string)xmlRel.Attribute("Target");
                                string targetMode =
                                    (string)xmlRel.Attribute("TargetMode");
                                if (targetMode == "External")
                                {
                                    InmemoryPackage.CreateRelationship(
                                        new Uri(target, UriKind.Absolute),
                                        TargetMode.External, type, id);
                                }
                                else
                                {
                                    InmemoryPackage.CreateRelationship(
                                        new Uri(target, UriKind.Relative),
                                        TargetMode.Internal, type, id);
                                }
                            }
                        }
                        else
                        // add part level relationships
                        {
                            string directory    = name.Substring(0, name.IndexOf("/_rels"));
                            string relsFilename = name.Substring(name.LastIndexOf('/'));
                            string filename     =
                                relsFilename.Substring(0, relsFilename.IndexOf(".rels"));
                            PackagePart fromPart = InmemoryPackage.GetPart(
                                new Uri(directory + filename, UriKind.Relative));
                            foreach (XElement xmlRel in
                                     xmlPart.Descendants(rel + "Relationship"))
                            {
                                string id         = (string)xmlRel.Attribute("Id");
                                string type       = (string)xmlRel.Attribute("Type");
                                string target     = (string)xmlRel.Attribute("Target");
                                string targetMode =
                                    (string)xmlRel.Attribute("TargetMode");
                                if (targetMode == "External")
                                {
                                    fromPart.CreateRelationship(
                                        new Uri(target, UriKind.Absolute),
                                        TargetMode.External, type, id);
                                }
                                else
                                {
                                    fromPart.CreateRelationship(
                                        new Uri(target, UriKind.Relative),
                                        TargetMode.Internal, type, id);
                                }
                            }
                        }
                    }
                }
                InmemoryPackage.Flush();
            }
            return(memStream);
        }
Ejemplo n.º 11
0
        private void Apply(Package package, string localFilename, bool installed)
        {
            using (Package setPkg = Package.Open(localFilename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            {
                // Extract information about the target set
                PackageRelationship defRelationship =
                    setPkg.GetRelationshipsByType("http://schemas.octgn.org/set/definition").First();
                PackagePart definition = setPkg.GetPart(defRelationship.TargetUri);
                Set         set;
                using (XmlReader reader = XmlReader.Create(definition.GetStream(), XmlSettings))
                {
                    reader.ReadToFollowing("set"); // <?xml ... ?>
                    set = new Set(localFilename, reader, _game.Repository);
                    // Check if the set game matches the patch
                    if (set.Game != _game)
                    {
                        return;
                    }
                }

                // Check if there is a patch for this set
                string relationId = "S" + set.Id.ToString("N");
                if (!package.RelationshipExists(relationId))
                {
                    return;
                }

                PackagePart patchPart = package.GetPart(package.GetRelationship(relationId).TargetUri);
                XDocument   patchDoc;
                using (Stream stream = patchPart.GetStream())
                    patchDoc = XDocument.Load(stream);

                // Check if the set is at least the required version for patching
                if (set.Version < patchDoc.Root.Attr <Version>("minVersion"))
                {
                    return;
                }
                if (set.Version > patchDoc.Root.Attr <Version>("maxVersion"))
                {
                    return;
                }

                if (installed)
                {
                    _game.DeleteSet(_game.Sets.FirstOrDefault(s => s.PackageName == localFilename));
                }

                // Process the set
                if (patchDoc.Root != null)
                {
                    foreach (XElement action in patchDoc.Root.Elements())
                    {
                        switch (action.Name.LocalName)
                        {
                        case "new":
                        {
                            var         targetUri      = new Uri(action.Attr <string>("targetUri"), UriKind.Relative);
                            var         relationshipId = action.Attr <string>("relationshipId");
                            var         contentType    = action.Attr <string>("contentType");
                            PackagePart part           = setPkg.PartExists(targetUri)
                                                           ? setPkg.GetPart(targetUri)
                                                           : setPkg.CreatePart(targetUri, contentType,
                                                                               CompressionOption.Normal);
                            if (part != null)
                            {
                                using (Stream targetStream = part.GetStream(FileMode.Create, FileAccess.Write))
                                    using (
                                        Stream srcStream =
                                            package.GetPart(patchPart.GetRelationship(relationshipId).TargetUri).
                                            GetStream())
                                        srcStream.CopyTo(targetStream);
                            }
                            break;
                        }

                        case "newrel":
                        {
                            var partUri          = new Uri(action.Attr <string>("partUri"), UriKind.Relative);
                            var relationshipId   = action.Attr <string>("relationshipId");
                            var targetUri        = new Uri(action.Attr <string>("targetUri"), UriKind.Relative);
                            var relationshipType = action.Attr <string>("relationshipType");

                            PackagePart part = setPkg.GetPart(partUri);
                            if (part.RelationshipExists(relationshipId))
                            {
                                part.DeleteRelationship(relationshipId);
                            }
                            part.CreateRelationship(targetUri, TargetMode.Internal, relationshipType,
                                                    relationshipId);
                            break;
                        }

                        default:
                            throw new InvalidFileFormatException("Unknown patch action: " + action.Name);
                        }
                    }
                }
            }

            OnProgress(string.Format("{0} patched.", Path.GetFileName(localFilename)));

            if (installed)
            {
                try
                {
                    _game.InstallSet(localFilename);
                }
                catch (Exception ex)
                {
                    OnProgress(string.Format("{0} can't be re-installed.\nDetails: {1}", localFilename, ex.Message),
                               true);
                }
            }
        }
Ejemplo n.º 12
0
        public override FileMetadata AnalyzeFile()
        {
            try
            {
                this.foundMetadata = new FileMetadata();
                using (Package pZip = Package.Open(this.fileStream))
                {
                    if (pZip.PackageProperties != null)
                    {
                        this.foundMetadata.Add(new User(pZip.PackageProperties.Creator, false));
                        this.foundMetadata.Add(new User(pZip.PackageProperties.LastModifiedBy, false));
                        if (pZip.PackageProperties.Created.HasValue)
                        {
                            this.foundMetadata.Dates.CreationDate = pZip.PackageProperties.Created.Value;
                        }
                        if (pZip.PackageProperties.Modified.HasValue)
                        {
                            this.foundMetadata.Dates.ModificationDate = pZip.PackageProperties.Modified.Value;
                        }
                        if (pZip.PackageProperties.LastPrinted.HasValue)
                        {
                            this.foundMetadata.Dates.PrintingDate = pZip.PackageProperties.LastPrinted.Value;
                        }
                        if (!String.IsNullOrWhiteSpace(pZip.PackageProperties.Title))
                        {
                            this.foundMetadata.Title = pZip.PackageProperties.Title;
                        }
                        if (!String.IsNullOrWhiteSpace(pZip.PackageProperties.Keywords))
                        {
                            this.foundMetadata.Keywords = pZip.PackageProperties.Keywords;
                        }
                    }

                    Uri uriFile = new Uri("/docProps/core.xml", UriKind.Relative);
                    if (pZip.PartExists(uriFile))
                    {
                        PackagePart pDocument = pZip.GetPart(uriFile);
                        using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                        {
                            AnalizeFileCore(stmDoc);
                        }
                    }
                    uriFile = new Uri("/docProps/app.xml", UriKind.Relative);
                    if (pZip.PartExists(uriFile))
                    {
                        PackagePart pDocument = pZip.GetPart(uriFile);
                        using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                        {
                            AnalizeFileApp(stmDoc);
                        }
                    }

                    //Control de versiones
                    if (strExtlo == ".docx")
                    {
                        uriFile = new Uri("/word/document.xml", UriKind.Relative);
                        if (pZip.PartExists(uriFile))
                        {
                            PackagePart pDocument = pZip.GetPart(uriFile);
                            using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                            {
                                AnalizeFileDocument(stmDoc);
                            }
                        }
                        //Consulta el fichero settings para recuperar el idioma del documento
                        if (foundMetadata.Language == string.Empty)
                        {
                            uriFile = new Uri("/word/settings.xml", UriKind.Relative);
                            if (pZip.PartExists(uriFile))
                            {
                                PackagePart pDocument = pZip.GetPart(uriFile);
                                using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                                {
                                    AnalizeFileSettings(stmDoc);
                                }
                            }
                        }
                        //Consulta el fichero document.xml.rels para obtener los links del documento
                        uriFile = new Uri("/word/_rels/document.xml.rels", UriKind.Relative);
                        if (pZip.PartExists(uriFile))
                        {
                            PackagePart pDocument = pZip.GetPart(uriFile);
                            using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                            {
                                AnalizeLinks(stmDoc);
                            }
                        }
                    }
                    //Obtiene el nombre de las impresoras y los links de los documentos xlsx
                    else if (strExtlo == ".xlsx")
                    {
                        foreach (PackagePart pp in pZip.GetParts())
                        {
                            if (pp.Uri.ToString().StartsWith("/xl/printerSettings/printerSettings"))
                            {
                                PackagePart pDocument = pZip.GetPart(pp.Uri);
                                if (pDocument != null)
                                {
                                    char[] name = new char[32];
                                    using (StreamReader sr = new StreamReader(pDocument.GetStream(FileMode.Open, FileAccess.Read), Encoding.Unicode))
                                    {
                                        sr.Read(name, 0, 32);
                                    }
                                    this.foundMetadata.Add(new Printer(Functions.FilterPrinter((new string(name).Replace("\0", "")))));
                                }
                            }
                            if (pp.Uri.ToString().StartsWith("/xl/worksheets/_rels/"))
                            {
                                PackagePart pDocument = pZip.GetPart(pp.Uri);
                                using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                                {
                                    AnalizeLinks(stmDoc);
                                }
                            }
                        }
                    }
                    else if (strExtlo == ".pptx")
                    {
                        foreach (PackagePart pp in pZip.GetParts())
                        {
                            if (pp.Uri.ToString().StartsWith("/ppt/slides/_rels/"))
                            {
                                PackagePart pDocument = pZip.GetPart(pp.Uri);
                                using (Stream stmDoc = pDocument.GetStream(FileMode.Open, FileAccess.Read))
                                {
                                    AnalizeLinks(stmDoc);
                                }
                            }
                        }
                    }
                    //Extraer información EXIF de cada imagen
                    foreach (PackagePart pp in pZip.GetParts())
                    {
                        string strFileName   = pp.Uri.ToString();
                        string strFileNameLo = strFileName.ToLower();
                        //Filtro que se queda con todas las imagenes *.jpg y *.jpeg de las 3 posibles carpetas
                        if ((strFileNameLo.StartsWith("/word/media/") ||
                             strFileNameLo.StartsWith("/ppt/media/") ||
                             strFileNameLo.StartsWith("/xl/media/")) &&
                            (strFileNameLo.EndsWith(".jpg") ||
                             strFileNameLo.EndsWith(".jpeg") ||
                             strFileNameLo.EndsWith(".png")))
                        {
                            using (EXIFDocument eDoc = new EXIFDocument(pp.GetStream(FileMode.Open, FileAccess.Read)))
                            {
                                FileMetadata exifMetadata = eDoc.AnalyzeFile();
                                foundMetadata.EmbeddedImages.Add(System.IO.Path.GetFileName(strFileName), exifMetadata);
                                //Copiamos los metadatos sobre usuarios y Applications de la imagen al documento
                                this.foundMetadata.AddRange(exifMetadata.Users.ToArray());
                                this.foundMetadata.AddRange(exifMetadata.Applications.ToArray());
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }

            return(this.foundMetadata);
        }
Ejemplo n.º 13
0
 public ZipPackageFile(PackagePart part)
     : base(UriUtility.GetPath(part.Uri))
 {
     Debug.Assert(part != null, "part should not be null");
     _streamFactory = () => part.GetStream();
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
        /// stored in a <see cref="Package"/>.
        /// </summary>
        /// <param name="document">The document in Flat OPC format.</param>
        /// <param name="package">The <see cref="Package"/> in which to store the OpenXml package.</param>
        /// <returns>The <see cref="Package"/> containing the OpenXml package.</returns>
        protected static Package FromFlatOpcDocumentCore(XDocument document, Package package)
        {
            // Add all parts (but not relationships).
            foreach (var xmlPart in document.Root
                     .Elements()
                     .Where(p =>
                            (string)p.Attribute(pkg + "contentType") !=
                            "application/vnd.openxmlformats-package.relationships+xml"))
            {
                string name        = (string)xmlPart.Attribute(pkg + "name");
                string contentType = (string)xmlPart.Attribute(pkg + "contentType");
                if (contentType.EndsWith("xml"))
                {
                    Uri         uri  = new Uri(name, UriKind.Relative);
                    PackagePart part = package.CreatePart(uri, contentType, CompressionOption.SuperFast);
                    using (Stream stream = part.GetStream(FileMode.Create))
                        using (XmlWriter xmlWriter = XmlWriter.Create(stream))
                            xmlPart.Element(pkg + "xmlData")
                            .Elements()
                            .First()
                            .WriteTo(xmlWriter);
                }
                else
                {
                    Uri         uri  = new Uri(name, UriKind.Relative);
                    PackagePart part = package.CreatePart(uri, contentType, CompressionOption.SuperFast);
                    using (Stream stream = part.GetStream(FileMode.Create))
                        using (BinaryWriter binaryWriter = new BinaryWriter(stream))
                        {
                            string base64StringInChunks = (string)xmlPart.Element(pkg + "binaryData");
                            char[] base64CharArray      = base64StringInChunks
                                                          .Where(c => c != '\r' && c != '\n').ToArray();
                            byte[] byteArray =
                                System.Convert.FromBase64CharArray(
                                    base64CharArray, 0, base64CharArray.Length);
                            binaryWriter.Write(byteArray);
                        }
                }
            }

            foreach (var xmlPart in document.Root.Elements())
            {
                string name        = (string)xmlPart.Attribute(pkg + "name");
                string contentType = (string)xmlPart.Attribute(pkg + "contentType");
                if (contentType == "application/vnd.openxmlformats-package.relationships+xml")
                {
                    if (name == "/_rels/.rels")
                    {
                        // Add the package level relationships.
                        foreach (XElement xmlRel in xmlPart.Descendants(rel + "Relationship"))
                        {
                            string id         = (string)xmlRel.Attribute("Id");
                            string type       = (string)xmlRel.Attribute("Type");
                            string target     = (string)xmlRel.Attribute("Target");
                            string targetMode = (string)xmlRel.Attribute("TargetMode");
                            if (targetMode == "External")
                            {
                                package.CreateRelationship(
                                    new Uri(target, UriKind.Absolute),
                                    TargetMode.External, type, id);
                            }
                            else
                            {
                                package.CreateRelationship(
                                    new Uri(target, UriKind.Relative),
                                    TargetMode.Internal, type, id);
                            }
                        }
                    }
                    else
                    {
                        // Add part level relationships.
                        string      directory    = name.Substring(0, name.IndexOf("/_rels"));
                        string      relsFilename = name.Substring(name.LastIndexOf('/'));
                        string      filename     = relsFilename.Substring(0, relsFilename.IndexOf(".rels"));
                        PackagePart fromPart     = package.GetPart(new Uri(directory + filename, UriKind.Relative));
                        foreach (XElement xmlRel in xmlPart.Descendants(rel + "Relationship"))
                        {
                            string id         = (string)xmlRel.Attribute("Id");
                            string type       = (string)xmlRel.Attribute("Type");
                            string target     = (string)xmlRel.Attribute("Target");
                            string targetMode = (string)xmlRel.Attribute("TargetMode");
                            if (targetMode == "External")
                            {
                                fromPart.CreateRelationship(
                                    new Uri(target, UriKind.Absolute),
                                    TargetMode.External, type, id);
                            }
                            else
                            {
                                fromPart.CreateRelationship(
                                    new Uri(target, UriKind.Relative),
                                    TargetMode.Internal, type, id);
                            }
                        }
                    }
                }
            }

            // Save contents of all parts and relationships contained in package.
            package.Flush();
            return(package);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Returns the part content stream that was opened using a specified FileMode and FileAccess.
        /// </summary>
        /// <param name="mode">The I/O mode to be used to open the content stream.</param>
        /// <param name="access">The access permissions to be used to open the content stream.</param>
        /// <returns>The content stream of the part. </returns>
        public Stream GetStream(FileMode mode, FileAccess access)
        {
            ThrowIfObjectDisposed();

            return(PackagePart.GetStream(mode, access));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Returns the content stream that was opened using a specified I/O FileMode.
        /// </summary>
        /// <param name="mode">The I/O mode to be used to open the content stream.</param>
        /// <returns>The content stream of the part. </returns>
        public Stream GetStream(FileMode mode)
        {
            ThrowIfObjectDisposed();

            return(PackagePart.GetStream(mode));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Returns the part content data stream.
        /// </summary>
        /// <returns>The content data stream for the part. </returns>
        public Stream GetStream()
        {
            ThrowIfObjectDisposed();

            return(PackagePart.GetStream());
        }
Ejemplo n.º 18
0
        public void Save()
        {
            // build map of enumerations
            Dictionary <string, DocPropertyEnumeration> mapPropEnum = new Dictionary <string, DocPropertyEnumeration>();

            foreach (DocSection docSection in this.m_project.Sections)
            {
                foreach (DocSchema docSchema in docSection.Schemas)
                {
                    foreach (DocPropertyEnumeration docEnum in docSchema.PropertyEnums)
                    {
                        mapPropEnum.Add(docEnum.Name, docEnum);
                    }
                }
            }

            using (Package zip = ZipPackage.Open(this.m_stream, FileMode.Create))
            {
                foreach (DocSection docSection in this.m_project.Sections)
                {
                    foreach (DocSchema docSchema in docSection.Schemas)
                    {
                        if (this.m_type == null || this.m_type == typeof(DocPropertySet))
                        {
                            foreach (DocPropertySet docPset in docSchema.PropertySets)
                            {
                                if (m_included == null || this.m_included.ContainsKey(docPset))
                                {
                                    if (docPset.IsVisible())
                                    {
                                        Uri         uri  = PackUriHelper.CreatePartUri(new Uri(docPset.Name + ".xml", UriKind.Relative));
                                        PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
                                        using (Stream refstream = part.GetStream())
                                        {
                                            refstream.SetLength(0);
                                            PropertySetDef psd = Program.ExportPsd(docPset, mapPropEnum, this.m_project);
                                            using (FormatXML format = new FormatXML(refstream, typeof(PropertySetDef), PropertySetDef.DefaultNamespace, null))
                                            {
                                                format.Instance = psd;
                                                format.Save();
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (this.m_type == null || this.m_type == typeof(DocQuantitySet))
                        {
                            foreach (DocQuantitySet docQset in docSchema.QuantitySets)
                            {
                                if (m_included == null || this.m_included.ContainsKey(docQset))
                                {
                                    Uri         uri  = PackUriHelper.CreatePartUri(new Uri(docQset.Name + ".xml", UriKind.Relative));
                                    PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
                                    using (Stream refstream = part.GetStream())
                                    {
                                        refstream.SetLength(0);
                                        QtoSetDef psd = Program.ExportQto(docQset, this.m_project);
                                        using (FormatXML format = new FormatXML(refstream, typeof(QtoSetDef), PropertySetDef.DefaultNamespace, null))
                                        {
                                            format.Instance = psd;
                                            format.Save();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Create the AMLX File with the correct AML File and optional pictures
        /// </summary>
        /// <param name="device">The device which will be created</param>
        /// <param name="isEdit">true if an amlx file get update, false if a new file will be created</param>
        /// <returns></returns>
        public string CreateDevice(MWDevice device, bool isEdit)
        {
            CAEXDocument          document = null;
            AutomationMLContainer amlx     = null;

            // Init final .amlx Filepath
            //first of all create a folder on "Vendor Name"
            string vendorCompanyName = device.vendorName;

            string amlFilePath;

            string fileName = device.fileName;

            if (fileName.Contains(".amlx"))
            {
                amlFilePath = System.IO.Path.Combine(device.filepath, fileName);
            }
            else
            {
                amlFilePath = System.IO.Path.Combine(device.filepath, fileName + ".amlx");
            }



            FileInfo file = new FileInfo(amlFilePath);



            // Create directory if it's not existing
            file.Directory.Create();


            // Init CAEX Document
            if (isEdit)
            {
                // Load the amlx file
                amlx = new AutomationMLContainer(amlFilePath, FileMode.Open);

                IEnumerable <PackagePart> rootParts = amlx.GetPartsByRelationShipType(AutomationMLContainer.RelationshipType.Root);

                // We expect the aml to only have one root part
                if (rootParts.First() != null)
                {
                    PackagePart part = rootParts.First();

                    // load the aml file as an CAEX document
                    document = CAEXDocument.LoadFromStream(part.GetStream());
                }
                else
                {
                    // the amlx contains no aml file
                    document = CAEXDocument.New_CAEXDocument();
                }
            }
            else
            {
                // create a new CAEX document
                document = CAEXDocument.New_CAEXDocument();
                try
                {
                    amlx = new AutomationMLContainer(amlFilePath, FileMode.Create);
                }
                catch (Exception)
                {
                }
            }



            // Init the default Libs
            AutomationMLBaseRoleClassLibType.RoleClassLib(document);
            AutomationMLInterfaceClassLibType.InterfaceClassLib(document);

            var structureRoleFamilyType = AutomationMLBaseRoleClassLibType.RoleClassLib(document).Structure;


            SystemUnitFamilyType systemUnitClass = null;

            // Create the SystemUnitClass for our device
            if (!isEdit)
            {
                systemUnitClass = document.CAEXFile.SystemUnitClassLib.Append("ComponentSystemUnitClassLib").SystemUnitClass.Append(device.deviceName);


                device.listWithURIConvertedToString = new List <AttachablesDataGridViewParameters>();
                foreach (AttachablesDataGridViewParameters eachparameter in device.dataGridAttachablesParametrsList)
                {
                    if (eachparameter.FilePath.Contains("https://") || eachparameter.FilePath.Contains("http://") || eachparameter.FilePath.Contains("www") || eachparameter.FilePath.Contains("WWW"))
                    {
                        interneturl(eachparameter.FilePath, eachparameter.ElementName.ToString(), "ExternalDataConnector", systemUnitClass);
                    }
                    else
                    {
                        Boolean myBool;
                        Boolean.TryParse(eachparameter.AddToFile, out myBool);

                        if (myBool == true)
                        {
                        }

                        Uri eachUri = null;
                        AttachablesDataGridViewParameters par = new AttachablesDataGridViewParameters();
                        eachUri         = createPictureRef(eachparameter.FilePath, eachparameter.ElementName.ToString(), "ExternalDataConnector", systemUnitClass);
                        par.ElementName = eachUri.ToString();
                        par.FilePath    = eachparameter.FilePath;

                        device.listWithURIConvertedToString.Add(par);
                    }
                }

                foreach (var pair in device.DictionaryForRoleClassofComponent)
                {
                    Match  numberfromElectricalConnectorType = Regex.Match(pair.Key.ToString(), @"\((\d+)\)");
                    string initialnumberbetweenparanthesisofElectricalConnectorType =
                        numberfromElectricalConnectorType.Groups[1].Value;
                    // string stringinparanthesis = Regex.Match(pair.Key.ToString(), @"\{(\d+)\}").Groups[1].Value;

                    string supportedRoleClassFromDictionary = Regex.Replace(pair.Key.ToString(), @"\(.+?\)", "");
                    supportedRoleClassFromDictionary = Regex.Replace(supportedRoleClassFromDictionary, @"\{.+?\}", "");



                    var SRC = systemUnitClass.SupportedRoleClass.Append();



                    var attributesOfSystemUnitClass = systemUnitClass.Attribute;

                    foreach (var valueList in pair.Value)
                    {
                        foreach (var item in valueList)
                        {
                            if (item.AttributePath.Contains("/") || item.AttributePath.Contains("."))
                            {
                                int          count               = 2;
                                int          counter             = 0;
                                Stack <char> stack               = new Stack <char>();
                                string       searchAttributeName =
                                    item.AttributePath.Substring(0, item.AttributePath.Length - item.Name.Length);

                                foreach (var character in searchAttributeName.Reverse())
                                {
                                    if (!char.IsLetterOrDigit(character))
                                    {
                                        counter++;
                                        if (counter == count)
                                        {
                                            break;
                                        }
                                    }

                                    if (char.IsLetterOrDigit(character))
                                    {
                                        stack.Push(character);
                                    }
                                }

                                string finalAttributeName = new string(stack.ToArray());

                                foreach (var attribute in systemUnitClass.Attribute)
                                {
                                    if (attribute.Name == finalAttributeName)
                                    {
                                        var eachattribute = attribute.Attribute.Append(item.Name.ToString());
                                        eachattribute.Value             = item.Value;
                                        eachattribute.DefaultValue      = item.Default;
                                        eachattribute.Unit              = item.Unit;
                                        eachattribute.AttributeDataType = item.DataType;
                                        eachattribute.Description       = item.Description;
                                        eachattribute.Copyright         = item.CopyRight;

                                        eachattribute.ID = item.ID;

                                        foreach (var val in item.RefSemanticList.Elements)
                                        {
                                            var refsem = eachattribute.RefSemantic.Append();
                                            refsem.CorrespondingAttributePath = val.FirstAttribute.Value;
                                        }



                                        SRC.RefRoleClassPath = item.SupportesRoleClassType;
                                    }

                                    if (attribute.Attribute.Exists)
                                    {
                                        SearchForAttributesInsideAttributesofAutomationComponent(finalAttributeName,
                                                                                                 attribute, item, SRC);
                                    }
                                }
                            }
                            else
                            {
                                var eachattribute = attributesOfSystemUnitClass.Append(item.Name.ToString());
                                eachattribute.Value             = item.Value;
                                eachattribute.DefaultValue      = item.Default;
                                eachattribute.Unit              = item.Unit;
                                eachattribute.AttributeDataType = item.DataType;
                                eachattribute.Description       = item.Description;
                                eachattribute.Copyright         = item.CopyRight;

                                eachattribute.ID = item.ID;


                                foreach (var val in item.RefSemanticList.Elements)
                                {
                                    var refsem = eachattribute.RefSemantic.Append();
                                    refsem.CorrespondingAttributePath = val.FirstAttribute.Value;
                                }


                                SRC.RefRoleClassPath = item.SupportesRoleClassType;
                            }
                        }
                    }


                    foreach (var pairofList in device.DictionaryForExternalInterfacesUnderRoleClassofComponent)
                    {
                        Match  numberfromElectricalConnectorPins = Regex.Match(pairofList.Key.ToString(), @"\((\d+)\)");
                        string initialnumberbetweenparanthesisElectricalConnectorPins =
                            numberfromElectricalConnectorPins.Groups[1].Value;

                        string electricalConnectorPinName = Regex.Replace(pairofList.Key.ToString(), @"\(.*?\)", "");
                        electricalConnectorPinName = Regex.Replace(electricalConnectorPinName, @"\{.*?\}", "");
                        electricalConnectorPinName =
                            electricalConnectorPinName.Replace(supportedRoleClassFromDictionary, "");
                    }
                }
            }
            else
            {
                // check if our format is given in the amlx file if not: create it
                bool foundSysClassLib = false;
                foreach (var sysclasslib in document.CAEXFile.SystemUnitClassLib)
                {
                    if (sysclasslib.Name.Equals("ComponentSystemUnitClassLib"))
                    {
                        bool foundSysClass = false;
                        foreach (var sysclass in sysclasslib.SystemUnitClass)
                        {
                            if (sysclass.Name.Equals(device.deviceName))
                            {
                                foundSysClass   = true;
                                systemUnitClass = sysclass;
                                break;
                            }
                        }
                        if (!foundSysClass)
                        {
                            systemUnitClass = sysclasslib.SystemUnitClass.Append(device.deviceName);
                        }
                        foundSysClassLib = true;
                    }
                }
                if (!foundSysClassLib)
                {
                    systemUnitClass = document.CAEXFile.SystemUnitClassLib.Append("ComponentSystemUnitClassLib").SystemUnitClass.Append(device.deviceName);
                }
            }

            // Create the internalElement Interfaces
            if (device.vendorName != null)
            {
                InternalElementType  electricalInterface = null;
                RoleRequirementsType roleRequirements    = null;
                foreach (var internalElement in systemUnitClass.InternalElement)
                {
                    if (internalElement.Name.Equals("Interfaces"))
                    {
                        electricalInterface = internalElement;
                        roleRequirements    = electricalInterface.RoleRequirements.Append();
                        roleRequirements.RefBaseRoleClassPath = structureRoleFamilyType.CAEXPath();
                        break;
                    }
                }
                if (electricalInterface == null)
                {
                    electricalInterface = systemUnitClass.InternalElement.Append("Interfaces");
                }
                roleRequirements = electricalInterface.RoleRequirements.Append();

                roleRequirements.RefBaseRoleClassPath = structureRoleFamilyType.CAEXPath();

                foreach (var pair in device.DictionaryForInterfaceClassesInElectricalInterfaces)
                {
                    InternalElementType   internalElementofElectricalConnectorType = null;
                    ExternalInterfaceType electricalConnectorType = null;

                    ExternalInterfaceType electricalConnectorPins = null;

                    Match  numberfromElectricalConnectorType = Regex.Match(pair.Key.ToString(), @"\((\d+)\)");
                    string initialnumberbetweenparanthesisofElectricalConnectorType = numberfromElectricalConnectorType.Groups[1].Value;


                    string electricalConnectorTypeName = Regex.Replace(pair.Key.ToString(), @"\(.+?\)", "");
                    electricalConnectorTypeName = Regex.Replace(electricalConnectorTypeName, @"\{.+?\}", "");

                    internalElementofElectricalConnectorType = electricalInterface.InternalElement.Append(electricalConnectorTypeName);

                    electricalConnectorType = internalElementofElectricalConnectorType.ExternalInterface.Append(electricalConnectorTypeName);

                    var attributesOfConnectorType = electricalConnectorType.Attribute;

                    foreach (var valueList in pair.Value)
                    {
                        foreach (var item in valueList)
                        {
                            if (item.AttributePath.Contains("/") || item.AttributePath.Contains("."))
                            {
                                int          count               = 2;
                                int          counter             = 0;
                                Stack <char> stack               = new Stack <char>();
                                string       searchAttributeName = item.AttributePath.Substring(0, item.AttributePath.Length - item.Name.Length);

                                foreach (var character in searchAttributeName.Reverse())
                                {
                                    if (!char.IsLetterOrDigit(character))
                                    {
                                        counter++;
                                        if (counter == count)
                                        {
                                            break;
                                        }
                                    }
                                    if (char.IsLetterOrDigit(character))
                                    {
                                        stack.Push(character);
                                    }
                                }

                                string finalAttributeName = new string(stack.ToArray());

                                foreach (var attribute in electricalConnectorType.Attribute)
                                {
                                    if (attribute.Name == finalAttributeName)
                                    {
                                        var eachattribute = attribute.Attribute.Append(item.Name.ToString());
                                        eachattribute.Value             = item.Value;
                                        eachattribute.DefaultValue      = item.Default;
                                        eachattribute.Unit              = item.Unit;
                                        eachattribute.AttributeDataType = item.DataType;
                                        eachattribute.Description       = item.Description;
                                        eachattribute.Copyright         = item.CopyRight;

                                        eachattribute.ID = item.ID;

                                        foreach (var val in item.RefSemanticList.Elements)
                                        {
                                            var refsem = eachattribute.RefSemantic.Append();
                                            refsem.CorrespondingAttributePath = val.FirstAttribute.Value;
                                        }

                                        electricalConnectorType.RefBaseClassPath = item.RefBaseClassPath;
                                    }
                                    if (attribute.Attribute.Exists)
                                    {
                                        SearchAttributesInsideAttributesOFElectricConnectorType(finalAttributeName, attribute, item, electricalConnectorType);
                                    }
                                }
                            }
                            else
                            {
                                var eachattribute = attributesOfConnectorType.Append(item.Name.ToString());
                                eachattribute.Value             = item.Value;
                                eachattribute.DefaultValue      = item.Default;
                                eachattribute.Unit              = item.Unit;
                                eachattribute.AttributeDataType = item.DataType;
                                eachattribute.Description       = item.Description;
                                eachattribute.Copyright         = item.CopyRight;

                                eachattribute.ID = item.ID;

                                foreach (var val in item.RefSemanticList.Elements)
                                {
                                    var refsem = eachattribute.RefSemantic.Append();
                                    refsem.CorrespondingAttributePath = val.FirstAttribute.Value;
                                }

                                electricalConnectorType.RefBaseClassPath = item.RefBaseClassPath;
                            }
                        }
                    }


                    foreach (var pairofList in device.DictionaryForExternalInterfacesUnderInterfaceClassInElectricalInterfaces)
                    {
                        Match  numberfromElectricalConnectorPins = Regex.Match(pairofList.Key.ToString(), @"\((\d+)\)");
                        string initialnumberbetweenparanthesisElectricalConnectorPins = numberfromElectricalConnectorPins.Groups[1].Value;

                        string electricalConnectorPinName = Regex.Replace(pairofList.Key.ToString(), @"\(.*?\)", "");
                        electricalConnectorPinName = Regex.Replace(electricalConnectorPinName, @"\{.*?\}", "");
                        electricalConnectorPinName = electricalConnectorPinName.Replace(electricalConnectorTypeName, "");



                        if (initialnumberbetweenparanthesisofElectricalConnectorType == initialnumberbetweenparanthesisElectricalConnectorPins)
                        {
                            electricalConnectorPins = electricalConnectorType.ExternalInterface.Append(electricalConnectorPinName);

                            var attributesOfConnectorPins = electricalConnectorPins.Attribute;

                            foreach (var valueList in pairofList.Value)
                            {
                                foreach (var item in valueList)
                                {
                                    if (item.AttributePath.Contains("/") || item.AttributePath.Contains("."))
                                    {
                                        int          count               = 2;
                                        int          counter             = 0;
                                        Stack <char> stack               = new Stack <char>();
                                        string       searchAttributeName = item.AttributePath.Substring(0, item.AttributePath.Length - item.Name.Length);

                                        foreach (var character in searchAttributeName.Reverse())
                                        {
                                            if (!char.IsLetterOrDigit(character))
                                            {
                                                counter++;
                                                if (counter == count)
                                                {
                                                    break;
                                                }
                                            }
                                            if (char.IsLetterOrDigit(character))
                                            {
                                                stack.Push(character);
                                            }
                                        }

                                        string finalAttributeName = new string(stack.ToArray());

                                        foreach (var attribute in electricalConnectorPins.Attribute)
                                        {
                                            if (attribute.Name == finalAttributeName)
                                            {
                                                var eachattribute = attribute.Attribute.Append(item.Name.ToString());
                                                eachattribute.Value             = item.Value;
                                                eachattribute.DefaultValue      = item.Default;
                                                eachattribute.Unit              = item.Unit;
                                                eachattribute.AttributeDataType = item.DataType;
                                                eachattribute.Description       = item.Description;
                                                eachattribute.Copyright         = item.CopyRight;

                                                eachattribute.ID = item.ID;

                                                foreach (var val in item.RefSemanticList.Elements)
                                                {
                                                    var refsem = eachattribute.RefSemantic.Append();
                                                    refsem.CorrespondingAttributePath = val.FirstAttribute.Value;
                                                }

                                                electricalConnectorPins.RefBaseClassPath = item.RefBaseClassPath;
                                            }
                                            if (attribute.Attribute.Exists)
                                            {
                                                SearchAttributesInsideAttributesOFElectricConnectorType(finalAttributeName, attribute, item, electricalConnectorPins);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var eachattribute = attributesOfConnectorPins.Append(item.Name.ToString());
                                        eachattribute.Value             = item.Value;
                                        eachattribute.DefaultValue      = item.Default;
                                        eachattribute.Unit              = item.Unit;
                                        eachattribute.AttributeDataType = item.DataType;
                                        eachattribute.Description       = item.Description;
                                        eachattribute.Copyright         = item.CopyRight;

                                        eachattribute.ID = item.ID;

                                        foreach (var val in item.RefSemanticList.Elements)
                                        {
                                            var refsem = eachattribute.RefSemantic.Append();
                                            refsem.CorrespondingAttributePath = val.FirstAttribute.Value;
                                        }

                                        electricalConnectorPins.RefBaseClassPath = item.RefBaseClassPath;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            string[] splitName   = fileName.Split('\\');
            string   newFileName = splitName[splitName.Length - 1];

            // create the PackageUri for the root aml file
            Uri partUri = PackUriHelper.CreatePartUri(new Uri("/" + newFileName + "-root.aml", UriKind.Relative));

            // create the aml file as a temporary file
            string path = Path.GetTempFileName();

            document.SaveToFile(path, true);

            if (isEdit)
            {
                // delete the old aml file
                amlx.Package.DeletePart(partUri);

                // delete all files in the amlx package.
                // Directory.Delete(Path.GetFullPath(amlx.ContainerFilename), true);
            }

            // write the new aml file into the package
            PackagePart root = amlx.AddRoot(path, partUri);


            if (!isEdit)
            {
                foreach (AttachablesDataGridViewParameters listWithUri in device.listWithURIConvertedToString)
                {
                    if (listWithUri.ElementName != null)
                    {
                        Uri newuri = null;
                        newuri = new Uri(listWithUri.ElementName, UriKind.Relative);
                        amlx.AddAnyContent(root, listWithUri.FilePath.ToString(), newuri);
                    }
                }
            }
            DirectoryInfo directory = new DirectoryInfo(Path.GetDirectoryName(amlFilePath));

            foreach (FileInfo fileInfos in directory.GetFiles())
            {
                if (fileInfos.Extension != ".amlx")
                {
                    fileInfos.Delete();
                }
            }


            amlx.Save();
            amlx.Close();

            if (isEdit)
            {
                return("Sucessfully updated device!\nFilepath " + amlFilePath);
            }
            else
            {
                return("Device description file created!\nFilepath " + amlFilePath);
            }
        }
        /// <summary>
        /// Reading file raw data from file byte data.
        /// </summary>
        /// <param name="data">File resources as byte arrays.</param>
        /// <returns>An array of objects containing raw data.</returns>
        public TempData[] ReadFileRawDataFromByteArray(byte[] data)
        {
            try
            {
                using (WordprocessingDocument wordprocessingDocument =
                           WordprocessingDocument.Open(new MemoryStream(data), false))
                {
                    List <TempData>     result                 = new List <TempData>();
                    XDocument           xDoc                   = null;
                    var                 wordPackage            = wordprocessingDocument.Package;
                    PackageRelationship docPackageRelationship =
                        wordPackage
                        .GetRelationshipsByType(DocumentRelationshipType)
                        .FirstOrDefault();
                    if (docPackageRelationship != null)
                    {
                        Uri documentUri =
                            PackUriHelper
                            .ResolvePartUri(
                                new Uri("/", UriKind.Relative),
                                docPackageRelationship.TargetUri);
                        PackagePart documentPart = wordPackage.GetPart(documentUri);

                        //  Load the document XML in the part into an XDocument instance.
                        xDoc = XDocument.Load(XmlReader.Create(documentPart.GetStream()));
                    }

                    // Find all paragraphs in the document.
                    var paragraphs =
                        from para in xDoc
                        .Root
                        .Element(wordNamespace + "body")
                        .Descendants(wordNamespace + "p")
                        where !para.Parent.Name.LocalName.Equals("tc")
                        select new
                    {
                        ParagraphNode = para
                    };

                    // Retrieve the text of each paragraph.
                    var paraWithText =
                        from para in paragraphs
                        select ParagraphText(para.ParagraphNode);

                    result.AddRange(TempData.GetTempDataIEnumerable(StorageType.TextType, paraWithText));

                    // Find all tables in the document.
                    var tables =
                        wordprocessingDocument.MainDocumentPart.Document.Body.Elements <Table>();

                    // Retrieve the text of each table.
                    var tablesText = tables.Select(table =>
                    {
                        var rows     = table.Elements <TableRow>();
                        var rowsText = rows.Select(row =>
                        {
                            var cells     = row.Elements <TableCell>();
                            var cellsText = cells.Select(cell =>
                            {
                                // Find the first paragraph in the table cell.
                                Paragraph p = cell.Elements <Paragraph>().FirstOrDefault();

                                if (p == null)
                                {
                                    return("<td></td>");
                                }
                                // Find the first run in the paragraph.
                                Run r = p.Elements <Run>().FirstOrDefault();
                                if (r == null)
                                {
                                    return("<td></td>");
                                }

                                // Set the text for the run.
                                Text t   = r.Elements <Text>().FirstOrDefault();
                                var text = t == null ? string.Empty : t.Text;

                                // For the brower can display xml snippet normally.
                                text = text.Replace("<", @"&lt;");
                                return("<td>" + text + "</td>");
                            });
                            return("<tr>" + string.Join(string.Empty, cellsText) + "</tr>");
                        });
                        if (rowsText != null && rowsText.Count() > 0)
                        {
                            return(string.Join(string.Empty, rowsText));
                        }

                        return(string.Empty);
                    });

                    result.AddRange(TempData.GetTempDataIEnumerable(StorageType.TableType, tablesText));

                    // Find image and add to the result.
                    var    imageParts      = wordprocessingDocument.MainDocumentPart.ImageParts;
                    byte[] streamByteArray = null;
                    Stream stream          = null;
                    foreach (ImagePart item in imageParts)
                    {
                        stream          = item.GetStream();
                        streamByteArray = new byte[stream.Length];
                        stream.Read(streamByteArray, 0, (int)stream.Length);
                        result.Add(new TempData {
                            StorageType = StorageType.ImageType, Data = Convert.ToBase64String(streamByteArray)
                        });
                    }

                    return(result.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 21
0
        // Token: 0x06003F2B RID: 16171 RVA: 0x00120E30 File Offset: 0x0011F030
        internal Stream CreateXamlStream()
        {
            PackagePart packagePart = this.CreateWpfEntryPart();

            return(packagePart.GetStream());
        }
Ejemplo n.º 22
0
        public String DocPropTitle(String docFile)
        {
            int     titleFlag = 0;
            String  styleVal  = "";
            string  temp      = "";
            Package pack;

            pack = Package.Open(docFile, FileMode.Open, FileAccess.ReadWrite);
            String title = pack.PackageProperties.Title;

            pack.Close();
            if (title != "")
            {
                return(title);
            }
            else
            {
                pack = Package.Open(docFile, FileMode.Open, FileAccess.ReadWrite);
                foreach (PackageRelationship searchRelation in pack.GetRelationshipsByType(wordRelationshipType))
                {
                    packRelationship = searchRelation;
                    break;
                }
                Uri         partUri     = PackUriHelper.ResolvePartUri(packRelationship.SourceUri, packRelationship.TargetUri);
                PackagePart mainPartxml = pack.GetPart(partUri);
                XmlDocument doc         = new XmlDocument();
                doc.Load(mainPartxml.GetStream());
                NameTable nt = new NameTable();
                pack.Close();
                XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
                nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
                XmlNodeList getParagraph = doc.SelectNodes("//w:body/w:p/w:pPr/w:pStyle", nsManager);
                for (int j = 0; j < getParagraph.Count; j++)
                {
                    XmlAttributeCollection paraGraphAttribute = getParagraph[j].Attributes;
                    for (int i = 0; i < paraGraphAttribute.Count; i++)
                    {
                        if (paraGraphAttribute[i].Name == "w:val")
                        {
                            styleVal = paraGraphAttribute[i].Value;
                        }
                        if (styleVal != "" && styleVal == "Title")
                        {
                            XmlNodeList getStyle = getParagraph[j].ParentNode.ParentNode.SelectNodes("w:r", nsManager);
                            if (getStyle != null)
                            {
                                for (int k = 0; k < getStyle.Count; k++)
                                {
                                    XmlNode getText = getStyle[k].SelectSingleNode("w:t", nsManager);
                                    temp = temp + " " + getText.InnerText;
                                }
                            }
                            titleFlag = 1;
                            break;
                        }
                        if (titleFlag == 1)
                        {
                            break;
                        }
                    }
                    if (titleFlag == 1)
                    {
                        break;
                    }
                }

                title = temp;
            }
            return(title);
        }
Ejemplo n.º 23
0
        public bool OpenEncryptedDocument(string xpsFile)
        {
            // Check to see if the document is encrypted.
            // If not encrypted, use OpenDocument().
            if (!EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile))
            {
                return(OpenDocument(xpsFile));
            }

            ShowStatus("Opening encrypted '" + Filename(xpsFile) + "'");

            // Get the ID of the current user log-in.
            string currentUserId;

            try
            { currentUserId = GetDefaultWindowsUserName(); }
            catch
            { currentUserId = null; }
            if (currentUserId == null)
            {
                MessageBox.Show("No valid user ID available", "Invalid User ID",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   No valid user ID available.");
                return(false);
            }

            ShowStatus("   Current user ID:  '" + currentUserId + "'");
            ShowStatus("   Using " + _authentication + " authentication.");
            ShowStatus("   Checking rights list for user:\n       " +
                       currentUserId);
            ShowStatus("   Initializing the environment.");

            try
            {
                string applicationManifest = "<manifest></manifest>";
                if (File.Exists("rvc.xml"))
                {
                    ShowStatus("   Reading manifest 'rvc.xml'.");
                    StreamReader manifestReader = File.OpenText("rvc.xml");
                    applicationManifest = manifestReader.ReadToEnd();
                }

                //<SnippetRmPkgViewSecEnv>
                ShowStatus("   Initiating SecureEnvironment as user: \n       " +
                           currentUserId + " [" + _authentication + "]");
                if (SecureEnvironment.IsUserActivated(
                        new ContentUser(currentUserId, _authentication)))
                {
                    ShowStatus("   User is already activated.");
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                                          new ContentUser(currentUserId, _authentication));
                }
                else // if user is not yet activated.
                {
                    ShowStatus("   User is NOT activated,\n       activating now....");
                    // If using the current Windows user, no credentials are
                    // required and we can use UserActivationMode.Permanent.
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                                          _authentication, UserActivationMode.Permanent);

                    // If not using the current Windows user, use
                    // UserActivationMode.Temporary to display the Windows
                    // credentials pop-up window.
                    ///_secureEnv = SecureEnvironment.Create(applicationManifest,
                    ///     a_authentication, UserActivationMode.Temporary);
                }
                ShowStatus("   Created SecureEnvironment for user:\n       " +
                           _secureEnv.User.Name +
                           " [" + _secureEnv.User.AuthenticationType + "]");
                //</SnippetRmPkgViewSecEnv>

                //<SnippetRmPkgViewOpenPkg>
                ShowStatus("   Opening the encrypted Package.");
                EncryptedPackageEnvelope ePackage =
                    EncryptedPackageEnvelope.Open(xpsFile, FileAccess.ReadWrite);
                RightsManagementInformation rmi =
                    ePackage.RightsManagementInformation;

                ShowStatus("   Looking for an embedded UseLicense for user:\n       " +
                           currentUserId + " [" + _authentication + "]");
                UseLicense useLicense =
                    rmi.LoadUseLicense(
                        new ContentUser(currentUserId, _authentication));

                ReadOnlyCollection <ContentGrant> grants;
                if (useLicense == null)
                {
                    ShowStatus("   No Embedded UseLicense found.\n       " +
                               "Attempting to acqure UseLicnese\n       " +
                               "from the PublishLicense.");
                    PublishLicense pubLicense = rmi.LoadPublishLicense();

                    ShowStatus("   Referral information:");

                    if (pubLicense.ReferralInfoName == null)
                    {
                        ShowStatus("       Name: (null)");
                    }
                    else
                    {
                        ShowStatus("       Name: " + pubLicense.ReferralInfoName);
                    }

                    if (pubLicense.ReferralInfoUri == null)
                    {
                        ShowStatus("    Uri: (null)");
                    }
                    else
                    {
                        ShowStatus("    Uri: " +
                                   pubLicense.ReferralInfoUri.ToString());
                    }

                    useLicense = pubLicense.AcquireUseLicense(_secureEnv);
                    if (useLicense == null)
                    {
                        ShowStatus("   User DOES NOT HAVE RIGHTS\n       " +
                                   "to access this document!");
                        return(false);
                    }
                }// end:if (useLicense == null)
                ShowStatus("   UseLicense acquired.");
                //</SnippetRmPkgViewOpenPkg>

                //<SnippetRmPkgViewBind>
                ShowStatus("   Binding UseLicense with the SecureEnvironment" +
                           "\n       to obtain the CryptoProvider.");
                rmi.CryptoProvider = useLicense.Bind(_secureEnv);

                ShowStatus("   Obtaining BoundGrants.");
                grants = rmi.CryptoProvider.BoundGrants;

                // You can access the Package via GetPackage() at this point.

                rightsBlock.Text = "GRANTS LIST\n-----------\n";
                foreach (ContentGrant grant in grants)
                {
                    rightsBlock.Text += "USER  :"******" [" +
                                        grant.User.AuthenticationType + "]\n";
                    rightsBlock.Text += "RIGHT :" + grant.Right.ToString() + "\n";
                    rightsBlock.Text += "    From:  " + grant.ValidFrom + "\n";
                    rightsBlock.Text += "    Until: " + grant.ValidUntil + "\n";
                }
                //</SnippetRmPkgViewBind>

                //<SnippetRmPkgViewDecrypt>
                if (rmi.CryptoProvider.CanDecrypt == true)
                {
                    ShowStatus("   Decryption granted.");
                }
                else
                {
                    ShowStatus("   CANNOT DECRYPT!");
                }

                ShowStatus("   Getting the Package from\n" +
                           "      the EncryptedPackage.");
                _xpsPackage = ePackage.GetPackage();
                if (_xpsPackage == null)
                {
                    MessageBox.Show("Unable to get Package.");
                    return(false);
                }

                // Set a PackageStore Uri reference for the encrypted stream.
                // ("sdk://packLocation" is a pseudo URI used by
                //  PackUriHelper.Create to define the parserContext.BaseURI
                //  that XamlReader uses to access the encrypted data stream.)
                Uri packageUri = new Uri(@"sdk://packLocation", UriKind.Absolute);
                // Add the URI package
                PackageStore.AddPackage(packageUri, _xpsPackage);
                // Determine the starting part for the package.
                PackagePart startingPart = GetPackageStartingPart(_xpsPackage);

                // Set the DocViewer.Document property.
                ShowStatus("   Opening in DocumentViewer.");
                ParserContext parserContext = new ParserContext();
                parserContext.BaseUri = PackUriHelper.Create(
                    packageUri, startingPart.Uri);
                parserContext.XamlTypeMapper = XamlTypeMapper.DefaultMapper;
                DocViewer.Document           = XamlReader.Load(
                    startingPart.GetStream(), parserContext)
                                               as IDocumentPaginatorSource;

                // Enable document menu controls.
                menuFileClose.IsEnabled        = true;
                menuFilePrint.IsEnabled        = true;
                menuViewIncreaseZoom.IsEnabled = true;
                menuViewDecreaseZoom.IsEnabled = true;

                // Give the DocumentViewer focus.
                DocViewer.Focus();
                //</SnippetRmPkgViewDecrypt>
            }// end:try
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                                ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                                "Exception",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            this.Title = "RightsManagedPackageViewer SDK Sample - " +
                         Filename(xpsFile) + " (encrypted)";
            return(true);
        }// end:OpenEncryptedDocument()
Ejemplo n.º 24
0
        private void EnsurePackageFiles()
        {
            if ((this._files == null) || ((this._expandedFolderPath == null) || !this._expandedFileSystem.DirectoryExists(this._expandedFolderPath)))
            {
                this._files = new Dictionary <string, PhysicalPackageFile>();
                this._supportedFrameworks = null;
                PackageName key = new PackageName(base.Id, base.Version);
                if (!ReferenceEquals(this._expandedFileSystem, _tempFileSystem) && !this._forceUseCache)
                {
                    this._expandedFolderPath = this.GetExpandedFolderPath();
                }
                else
                {
                    Tuple <string, DateTimeOffset> tuple;
                    DateTimeOffset lastModified = this._fileSystem.GetLastModified(this._packagePath);
                    if (!_cachedExpandedFolder.TryGetValue(key, out tuple) || (tuple.Item2 < lastModified))
                    {
                        tuple = Tuple.Create <string, DateTimeOffset>(this.GetExpandedFolderPath(), lastModified);
                        _cachedExpandedFolder[key] = tuple;
                    }
                    this._expandedFolderPath = tuple.Item1;
                }
                using (Stream stream = this.GetStream())
                {
                    using (IEnumerator <PackagePart> enumerator = (from part in Package.Open(stream).GetParts()
                                                                   where ZipPackage.IsPackageFile(part)
                                                                   select part).GetEnumerator())
                    {
                        string path;
                        string str2;
                        goto TR_0023;
TR_000E:
                        PhysicalPackageFile file1 = new PhysicalPackageFile();
                        file1.SourcePath          = this._expandedFileSystem.GetFullPath(str2);
                        file1.TargetPath          = path;
                        this._files[path]         = file1;
TR_0023:
                        while (true)
                        {
                            if (enumerator.MoveNext())
                            {
                                PackagePart current = enumerator.Current;
                                path = UriUtility.GetPath(current.Uri);
                                str2 = Path.Combine(this._expandedFolderPath, path);
                                bool flag = true;
                                if (this._expandedFileSystem.FileExists(str2))
                                {
                                    using (Stream stream2 = current.GetStream())
                                    {
                                        using (Stream stream3 = this._expandedFileSystem.OpenFile(str2))
                                        {
                                            flag = stream2.Length != stream3.Length;
                                        }
                                    }
                                }
                                if (flag)
                                {
                                    Stream stream4 = current.GetStream();
                                    try
                                    {
                                        using (Stream stream5 = this._expandedFileSystem.CreateFile(str2))
                                        {
                                            stream4.CopyTo(stream5);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                    finally
                                    {
                                        if (stream4 != null)
                                        {
                                            stream4.Dispose();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                return;
                            }
                            break;
                        }
                        goto TR_000E;
                    }
                }
            }
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            try
            {
                if (dumpArgs)
                {
                    write("args.Length = " + args.Length);

                    for (int i = 0; args != null && i < args.Length; ++i)
                    {
                        write("args[" + i + "] = " + args[i]);
                    }
                }

                bool buildRelease = String.Compare(args[0], "Release", true) == 0;

                string   @base = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
                string[] uri   = null;

                if (buildRelease)
                {
                    uri = new string[] {
                        "/epsg", "text/plain", @"..\3rd Party\epsg\epsg.txt",
                        "/Proj.4-Core.x86.dll", "application/octet-stream", @"..\Core-x86\Release\Proj.4-Core.x86.dll",
                        "/Proj.4-Core.x64.dll", "application/octet-stream", @"..\Core-x64\Release\Proj.4-Core.x64.dll"
                    }
                }
                ;
                else
                {
                    uri = new string[] {
                        "/epsg", "text/plain", @"..\3rd Party\epsg\epsg.txt",
                        "/Proj.4-Core.x86.dll", "application/octet-stream", @"..\Core-x86\Debug\Proj.4-Core.x86d.dll",
                        "/Proj.4-Core.x64.dll", "application/octet-stream", @"..\Core-x64\Debug\Proj.4-Core.x64d.dll"
                    }
                };

                if (!buildRelease)
                {
                    write("creating DEBUG resource package");
                }
                else
                {
                    write("creating RELEASE resource package");
                }

                using (Package p = ZipPackage.Open(@base + @"resources.zip", FileMode.Create))
                {
                    for (int i = 0; i < uri.Length; i += 3)
                    {
                        PackagePart pp = p.CreatePart(new Uri(uri[i], UriKind.Relative), uri[i + 1], CompressionOption.Maximum);

                        byte[] raw = (i == 0 ? readAndReformatEPSGDatabase(@base + uri[i + 2]) :
                                      File.ReadAllBytes(@base + uri[i + 2]));

                        write("+ " + uri[i + 2] + " (" + raw.Length / 1024 + "kB)");

                        using (Stream stm = pp.GetStream())
                            stm.Write(raw, 0, raw.Length);
                    }
                }

                write("size of resulting package: " +
                      (new FileInfo(@base + @"resources.zip").Length / 1024) + "kB");

                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    write("failed with " + ex.GetType().FullName + ": " + ex.Message);
                    write(ex.StackTrace.ToString());

                    ex = ex.InnerException;
                }

                Environment.Exit(-1);
            }
        }
Ejemplo n.º 26
0
        public void SaveTestorData(TestorData testorData, TestConfig config)
        {
            testorData.AcceptChanges();
            Dictionary <string, string> testKeys    = new Dictionary <string, string>();
            Dictionary <string, string> questCounts = new Dictionary <string, string>();

            foreach (TestorData.CoreTestsRow test in testorData.CoreTests)
            {
                testKeys.Add(test.TestKey.ToString(), test.TestName);
                questCounts.Add(test.TestKey.ToString(),
                                testorData.CoreQuestions.Where(c => c.TestId == test.TestId).Count().ToString());
            }
            PackagePart dataPart;
            PackagePart configPart;
            bool        createNew = true;
            Guid        fname     = Guid.NewGuid();
            Uri         partUri   = new Uri(
                String.Format("/tests/{0}.bin", fname.ToString()), UriKind.Relative);
            Uri configUri = new Uri(
                String.Format("/tests/{0}.conf", fname.ToString()), UriKind.Relative);
            List <Uri> parts = new List <Uri>();

            foreach (var rel in _manager.CurrentPackage.GetRelationships())
            {
                if (testKeys.Keys.Contains(rel.RelationshipType) &&
                    !parts.Contains(rel.TargetUri))
                {
                    parts.Add(rel.TargetUri);
                }
            }
            if (parts.Count == 1)
            {
                createNew = false;
                configUri = _manager.GetConfigUri(parts[0]);
                partUri   = parts[0];
            }
            else if (parts.Count > 1)
            {
                throw new Exception("Невозможно сохранить тесты в разных parts.");
            }
            if (createNew)
            {
                dataPart = _manager.CurrentPackage.CreatePart(partUri,
                                                              _manager.CnitType + ContentType.Test.ToString(), _testCompression);
                configPart = _manager.CurrentPackage.CreatePart(configUri,
                                                                _manager.CnitType + ContentType.TestConfig.ToString(), _testCompression);
                foreach (var id in testKeys)
                {
                    config.Uri           = partUri;
                    config.TestName      = id.Value;
                    config.QuestionCount = int.Parse(questCounts[id.Key]);
                    _manager.CurrentPackage.CreateRelationship(partUri, TargetMode.Internal, id.Key);
                }
            }
            else
            {
                dataPart   = _manager.CurrentPackage.GetPart(partUri);
                configPart = _manager.CurrentPackage.GetPart(configUri);
                Dictionary <string, TestConfig> testObjects = GetTestObjects(partUri);
                foreach (var key in testKeys)
                {
                    if (!testObjects.ContainsKey(key.Key))
                    {
                        _manager.CurrentPackage.CreateRelationship(partUri, TargetMode.Internal, key.Key);
                    }
                    config.Uri           = partUri;
                    config.TestName      = key.Value;
                    config.QuestionCount = int.Parse(questCounts[key.Key]);
                }
            }
            Uri versionUri = new Uri("/version.dat", UriKind.Relative);

            if (!_manager.CurrentPackage.PartExists(versionUri))
            {
                _manager.CurrentPackage.CreatePart(versionUri, _manager.CnitType + ContentType.VersionData.ToString());
                PackagePart versionPart = _manager.CurrentPackage.GetPart(versionUri);
                using (Stream versionStream = versionPart.GetStream())
                {
                    StreamWriter sw = new StreamWriter(versionStream);
                    sw.WriteLine("FileFormatVersion:{0}", _fileFormatVersion);
                    sw.Close();
                    versionStream.Close();
                }
            }
            BinaryFormatter bin = new BinaryFormatter();

            using (Stream stream = dataPart.GetStream())
            {
                bin.Serialize(stream, testorData);
                stream.Close();
            }
            using (Stream stream = configPart.GetStream())
            {
                bin.Serialize(stream, config);
                stream.Close();
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Saves the XmlDocument into the package at the specified Uri.
        /// </summary>
        /// <param name="uri">The Uri of the component</param>
        /// <param name="xmlDoc">The XmlDocument to save</param>
        internal void SavePart(Uri uri, XmlDocument xmlDoc)
        {
            PackagePart part = _package.GetPart(uri);

            xmlDoc.Save(part.GetStream(FileMode.Create, FileAccess.Write));
        }
Ejemplo n.º 28
0
        public static List <DocxParagraph> GetDocxParagraphs(String filePath)
        {
            const string documentRelationshipType =
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
            const string stylesRelationshipType =
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
            const string wordmlNamespace =
                "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            XNamespace w = wordmlNamespace;

            XDocument xDoc     = null;
            XDocument styleDoc = null;

            using (Package wdPackage = Package.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                PackageRelationship docPackageRelationship =
                    wdPackage.GetRelationshipsByType(documentRelationshipType).FirstOrDefault();

                if (docPackageRelationship != null)
                {
                    // Resolve the Relationship Target Uri
                    // so the Document Part can be retrieved (expected /word/document.xml)
                    Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
                                                                   docPackageRelationship.TargetUri);
                    PackagePart documentPart = wdPackage.GetPart(documentUri);

                    // Load the style XML to the part into an XDocument instance.
                    xDoc = XDocument.Load(XmlReader.Create(documentPart.GetStream()));

                    // Find the style part.
                    PackageRelationship styleRelation =
                        documentPart.GetRelationshipsByType(stylesRelationshipType)
                        .FirstOrDefault();
                    if (null != styleRelation)
                    {
                        Uri         styleUri  = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
                        PackagePart stylePart = wdPackage.GetPart(styleUri);

                        // load the style XML in the part into an XDocument instance.
                        styleDoc = XDocument.Load(XmlReader.Create(stylePart.GetStream()));
                    }
                }
            }

            // <w:style w:type="paragraph" w:default="1" w:styleId="a">
            //  <w:name w:val="Normal" />
            //  <w:qFormat />
            // </w:style>
            // Get styleId, we can get "a" from the below sample xml
            string defaultStyle =
                (string)(from style in styleDoc.Root.Elements(w + "style")
                         where (string)style.Attribute(w + "type") == "paragraph" &&
                         (string)style.Attribute(w + "default") == "1"
                         select style)
                .First().Attribute(w + "styleId");


            // Find all paragraphs in the document.
            var paragraphs =
                from para in xDoc
                .Root
                .Element(w + "body")
                .Descendants(w + "p")
                let styleNode = para
                                .Elements(w + "pPr")
                                .Elements(w + "pStyle")
                                .FirstOrDefault()
                                select new
            {
                ParagraphNode = para,
                StyleName     = styleNode != null ? (string)styleNode.Attribute(w + "val") : defaultStyle
            };

            // Retrieve the text of each paragraph
            var paraWithText =
                from para in paragraphs
                select new
            {
                StyleName = para.StyleName,
                Text      = ParagraphText(para.ParagraphNode)
            };

            return(paraWithText.Select(para => new DocxParagraph()
            {
                StyleName = para.StyleName,
                Text = para.Text
            }).ToList());
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Adds a copy of a worksheet
        /// </summary>
        /// <param name="Name">The name of the workbook</param>
        /// <param name="Copy">The worksheet to be copied</param>
        public ExcelWorksheet Add(string Name, ExcelWorksheet Copy)
        {
            int sheetID;
            Uri uriWorksheet;

            if (GetByName(Name) != null)
            {
                throw (new InvalidOperationException(ERR_DUP_WORKSHEET));
            }

            GetSheetURI(ref Name, out sheetID, out uriWorksheet);

            //Create a copy of the worksheet XML
            PackagePart  worksheetPart   = _pck.Package.CreatePart(uriWorksheet, WORKSHEET_CONTENTTYPE, _pck.Compression);
            StreamWriter streamWorksheet = new StreamWriter(worksheetPart.GetStream(FileMode.Create, FileAccess.Write));
            XmlDocument  worksheetXml    = new XmlDocument();

            worksheetXml.LoadXml(Copy.WorksheetXml.OuterXml);
            worksheetXml.Save(streamWorksheet);
            streamWorksheet.Close();
            _pck.Package.Flush();


            //Create a relation to the workbook
            string         relID = CreateWorkbookRel(Name, sheetID, uriWorksheet);
            ExcelWorksheet added = new ExcelWorksheet(_namespaceManager, _pck, relID, uriWorksheet, Name, sheetID, _worksheets.Count + 1, eWorkSheetHidden.Visible);

            //Copy comments
            if (Copy.Comments.Count > 0)
            {
                CopyComment(Copy, added);
            }
            else if (Copy.VmlDrawingsComments.Count > 0)    //Vml drawings are copied as part of the comments.
            {
                CopyVmlDrawing(Copy, added);
            }

            //Copy HeaderFooter
            CopyHeaderFooterPictures(Copy, added);

            //Copy all relationships
            //CopyRelationShips(Copy, added);
            if (Copy.Drawings.Count > 0)
            {
                CopyDrawing(Copy, added);
            }
            if (Copy.Tables.Count > 0)
            {
                CopyTable(Copy, added);
            }
            if (Copy.PivotTables.Count > 0)
            {
                CopyPivotTable(Copy, added);
            }
            if (Copy.Names.Count > 0)
            {
                CopySheetNames(Copy, added);
            }

            //Copy all cells
            CloneCells(Copy, added);

            _worksheets.Add(_worksheets.Count + 1, added);

            //Remove any relation to printersettings.
            XmlNode pageSetup = added.WorksheetXml.SelectSingleNode("//d:pageSetup", _namespaceManager);

            if (pageSetup != null)
            {
                XmlAttribute attr = (XmlAttribute)pageSetup.Attributes.GetNamedItem("id", ExcelPackage.schemaRelationships);
                if (attr != null)
                {
                    relID = attr.Value;
                    // first delete the attribute from the XML
                    pageSetup.Attributes.Remove(attr);
                }
            }

            return(added);
        }
Ejemplo n.º 30
0
        public void AddTableEntries <T>(List <T> list, string searchAttribute, string targetXPath)
        {
            if (list.Count < 2)//bail-out if we dont have to add rows
            {
                return;
            }

            PackagePart documentPart = null;

            // Given a file name, retrieve the "start" part--the document part.
            const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";

            //  Get the main document part (workbook.xml, document.xml, presentation.xml).
            foreach (System.IO.Packaging.PackageRelationship relationship in pckg.GetRelationshipsByType(documentRelationshipType))
            {
                documentPart = pckg.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri));
                break; //There should only be one document part in the package.
            }

            //load the doc to a dom object (XmlDocument)
            XmlDocument doc = new XmlDocument();

            doc.Load(documentPart.GetStream());

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("ds", "http://schemas.openxmlformats.org/officeDocument/2006/customXml");
            nsmgr.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            nsmgr.AddNamespace(String.Empty, String.Empty);

            XmlNodeList tableNodeList = doc.SelectNodes("//w:tbl", nsmgr);

            foreach (XmlNode tableNode in tableNodeList)//iterate through all the tables of the doc
            {
                XmlNode tableCellProcSdtPropNode = tableNode.SelectSingleNode(@"./w:tr[2]/w:tc[1]//w:sdt/w:sdtPr/w:tag", nsmgr);
                if (tableCellProcSdtPropNode != null)
                {
                    foreach (XmlAttribute attrNode in tableCellProcSdtPropNode.Attributes)//iterate through the content control's attributes to locate the "tag"
                    {
                        if ((attrNode.Name == "w:val") && (attrNode.Value == searchAttribute))
                        {
                            for (int i = 0; i < list.Count - 1; i++)
                            {
                                XmlNode newRowNode = tableNode.AppendChild(tableNode.SelectSingleNode(@"./w:tr[2]", nsmgr).CloneNode(true));
                                foreach (XmlNode cellNode in newRowNode.SelectNodes(@"./w:tc", nsmgr))//take up all the cells of the newly added row in order to fix their attributes
                                {
                                    foreach (XmlAttribute attr in cellNode.SelectSingleNode(@".//w:sdt/w:sdtPr/w:dataBinding", nsmgr).Attributes)
                                    {
                                        if (attr.Name == "w:xpath")
                                        {
                                            attr.Value = string.Format(targetXPath, i + 2) + attr.Value.Substring(attr.Value.LastIndexOf('/'));
                                        }
                                    }
                                    cellNode.SelectSingleNode(@".//w:sdt/w:sdtPr", nsmgr).RemoveChild(cellNode.SelectSingleNode(@".//w:sdt/w:sdtPr/w:id", nsmgr));
                                }
                            }
                        }
                    }
                }
            }

            documentPart.GetStream().Seek(0, SeekOrigin.Begin);//reset the stream-pointer
            documentPart.GetStream().SetLength(0);
            doc.Save(documentPart.GetStream());
        }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("specify one directory to update");
            }
            if (!Directory.Exists(args[0]))
            {
                Console.WriteLine("directory does not exist");
            }
            IEnumerable <FileInfo> files = Directory.GetFiles(args[0]).Where(x => Path.GetExtension(x) == ".xlsx").Select(x => new FileInfo(x));

            foreach (FileInfo file in files)
            {
                using (FileStream fileStream = File.Open(file.FullName, FileMode.OpenOrCreate)) {
                    using (ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Update)) {
                        ZipArchiveEntry    entry = archive.GetEntry("customXml/item1.xml");
                        IEnumerable <byte> bytes;
                        using (Stream entryStream = entry.Open()) {
                            XDocument doc                      = XDocument.Load(entryStream);
                            byte[]    dataMashup               = Convert.FromBase64String(doc.Root.Value);
                            int       version                  = BitConverter.ToUInt16(dataMashup.Take(FIELDS_LENGTH).ToArray(), 0);
                            int       packagePartsLength       = BitConverter.ToUInt16(dataMashup.Skip(FIELDS_LENGTH).Take(FIELDS_LENGTH).ToArray(), 0);
                            byte[]    packageParts             = dataMashup.Skip(FIELDS_LENGTH * 2).Take(packagePartsLength).ToArray();
                            int       permissionsLength        = BitConverter.ToUInt16(dataMashup.Skip(FIELDS_LENGTH * 2 + packagePartsLength).Take(FIELDS_LENGTH).ToArray(), 0);
                            byte[]    permissions              = dataMashup.Skip(FIELDS_LENGTH * 3).Take(permissionsLength).ToArray();
                            int       metadataLength           = BitConverter.ToUInt16(dataMashup.Skip(FIELDS_LENGTH * 3 + packagePartsLength + permissionsLength).Take(FIELDS_LENGTH).ToArray(), 0);
                            byte[]    metadata                 = dataMashup.Skip(FIELDS_LENGTH * 4 + packagePartsLength + permissionsLength).Take(metadataLength).ToArray();
                            int       permissionsBindingLength = BitConverter.ToUInt16(dataMashup.Skip(FIELDS_LENGTH * 4 + packagePartsLength + permissionsLength + metadataLength).Take(FIELDS_LENGTH).ToArray(), 0);
                            byte[]    permissionsBinding       = dataMashup.Skip(FIELDS_LENGTH * 5 + packagePartsLength + permissionsLength + metadataLength).Take(permissionsBindingLength).ToArray();
                            // use double memory stream to solve issue as memory stream will change
                            // size when re-saving the data mashup object
                            using (MemoryStream packagePartsStream = new MemoryStream(packageParts)) {
                                using (MemoryStream ms = new MemoryStream()) {
                                    packagePartsStream.CopyTo(ms);
                                    using (Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite)) {
                                        PackagePart section = package.GetParts().Where(x => x.Uri.OriginalString == "/Formulas/Section1.m").FirstOrDefault();
                                        string      query;
                                        using (StreamReader reader = new StreamReader(section.GetStream())) {
                                            query = reader.ReadToEnd();
                                            // do other replacing, removing of query here
                                            query = query.Replace("old-server", "new-server");
                                        }
                                        using (BinaryWriter writer = new BinaryWriter(section.GetStream())) {
                                            writer.Write(Encoding.ASCII.GetBytes(query));
                                        }
                                    }
                                    packageParts = ms.ToArray();
                                }
                                bytes = BitConverter.GetBytes(version)
                                        .Concat(BitConverter.GetBytes(packageParts.Length))
                                        .Concat(packageParts)
                                        .Concat(BitConverter.GetBytes(permissionsLength))
                                        .Concat(permissions)
                                        .Concat(BitConverter.GetBytes(metadataLength))
                                        .Concat(metadata)
                                        .Concat(BitConverter.GetBytes(permissionsBindingLength))
                                        .Concat(permissionsBinding);
                                doc.Root.Value = Convert.ToBase64String(bytes.ToArray());
                                entryStream.SetLength(0);
                                doc.Save(entryStream);
                            }
                        }
                    }
                }
            }
        }
        public ActionResult GenerateAAS()
        {
            try
            {
                string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "UANodeSet.aasx");
                using (Package package = Package.Open(packagePath, FileMode.Create))
                {
                    // add package origin part
                    PackagePart origin = package.CreatePart(new Uri("/aasx/aasx-origin", UriKind.Relative), MediaTypeNames.Text.Plain, CompressionOption.Maximum);
                    using (Stream fileStream = origin.GetStream(FileMode.Create))
                    {
                        var bytes = Encoding.ASCII.GetBytes("Intentionally empty.");
                        fileStream.Write(bytes, 0, bytes.Length);
                    }
                    package.CreateRelationship(origin.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aasx-origin");

                    // create package spec part
                    string packageSpecPath = Path.Combine(Directory.GetCurrentDirectory(), "aasenv-with-no-id.aas.xml");
                    using (StringReader reader = new StringReader(System.IO.File.ReadAllText(packageSpecPath)))
                    {
                        XmlSerializer aasSerializer = new XmlSerializer(typeof(AasEnv));
                        AasEnv        aasEnv        = (AasEnv)aasSerializer.Deserialize(reader);

                        aasEnv.AssetAdministrationShells.AssetAdministrationShell.SubmodelRefs.Clear();
                        aasEnv.Submodels.Clear();

                        foreach (string filename in _nodeSetFilenames)
                        {
                            string submodelPath = Path.Combine(Directory.GetCurrentDirectory(), "submodel.aas.xml");
                            using (StringReader reader2 = new StringReader(System.IO.File.ReadAllText(submodelPath)))
                            {
                                XmlSerializer aasSubModelSerializer = new XmlSerializer(typeof(AASSubModel));
                                AASSubModel   aasSubModel           = (AASSubModel)aasSubModelSerializer.Deserialize(reader2);

                                SubmodelRef nodesetReference = new SubmodelRef();
                                nodesetReference.Keys     = new Keys();
                                nodesetReference.Keys.Key = new Key
                                {
                                    IdType = "URI",
                                    Local  = true,
                                    Type   = "Submodel",
                                    Text   = "http://www.opcfoundation.org/type/opcua/" + Path.GetFileName(filename).Replace(".", "").ToLower()
                                };

                                aasEnv.AssetAdministrationShells.AssetAdministrationShell.SubmodelRefs.Add(nodesetReference);

                                aasSubModel.Identification.Text += Path.GetFileName(filename).Replace(".", "").ToLower();
                                aasSubModel.SubmodelElements.SubmodelElement.SubmodelElementCollection.Value.SubmodelElement.File.Value =
                                    aasSubModel.SubmodelElements.SubmodelElement.SubmodelElementCollection.Value.SubmodelElement.File.Value.Replace("TOBEREPLACED", Path.GetFileName(filename));
                                aasEnv.Submodels.Add(aasSubModel);
                            }
                        }

                        XmlTextWriter aasWriter = new XmlTextWriter(packageSpecPath, Encoding.UTF8);
                        aasSerializer.Serialize(aasWriter, aasEnv);
                        aasWriter.Close();
                    }

                    // add package spec part
                    PackagePart spec = package.CreatePart(new Uri("/aasx/aasenv-with-no-id/aasenv-with-no-id.aas.xml", UriKind.Relative), MediaTypeNames.Text.Xml);
                    using (FileStream fileStream = new FileStream(packageSpecPath, FileMode.Open, FileAccess.Read))
                    {
                        CopyStream(fileStream, spec.GetStream());
                    }
                    origin.CreateRelationship(spec.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-spec");

                    // add nodeset files
                    for (int i = 0; i < _nodeSetFilenames.Count; i++)
                    {
                        PackagePart supplementalDoc = package.CreatePart(new Uri("/aasx/" + Path.GetFileName(_nodeSetFilenames[i]), UriKind.Relative), MediaTypeNames.Text.Xml);
                        string      documentPath    = Path.Combine(Directory.GetCurrentDirectory(), _nodeSetFilenames[i]);
                        using (FileStream fileStream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
                        {
                            CopyStream(fileStream, supplementalDoc.GetStream());
                        }
                        package.CreateRelationship(supplementalDoc.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-suppl");
                    }
                }

                return(File(new FileStream(Path.Combine(Directory.GetCurrentDirectory(), "UANodeSet.aasx"), FileMode.Open, FileAccess.Read), "APPLICATION/octet-stream", "UANodeSet.aasx"));
            }
            catch (Exception ex)
            {
                OpcSessionModel sessionModel = new OpcSessionModel
                {
                    ErrorMessage = HttpUtility.HtmlDecode(ex.Message)
                };

                return(View("Error", sessionModel));
            }
        }