Beispiel #1
0
 public static BasicBlobContainer BlobToBasicBlobContainer(Blob blob)
 {
     var basicBlob = new BasicBlobContainer()
         {
             Name = blob.Name,
             Url = blob.Url,
             Container = blob.Container,
             BlobType = BlobEntryType.Blob
         };
     return basicBlob;
 }
Beispiel #2
0
        public static string ComputeId(Blob blob)
        {
            using (var md = new MessageDigest())
            {
                byte[] data = Encoding.Default.GetBytes(string.Format("blob {0}\0", blob.Size));

                md.Update(data);
                md.Update(blob.Data);

                var digest = md.Digest();

                return Helper.ByteArrayToId(digest);
            }
        }
Beispiel #3
0
        public void WriteBlob()
        {
            using (var repo = GetTrashRepository())
            {
                var blob = Blob.CreateFromFile(repo, "Resources/single_file_commit/i-am-a-file");
                Assert.AreEqual("95ea6a6859af6791464bd8b6de76ad5a6f9fad81", blob.Hash);
                Assert.AreEqual(File.ReadAllText("Resources/single_file_commit/i-am-a-file"), blob.Data);
                var same_blob = new Blob(repo, blob.Hash);
                Assert.AreEqual(File.ReadAllBytes("Resources/single_file_commit/i-am-a-file"), same_blob.RawData);

                blob = Blob.Create(repo, "and this is the data in me\r\n\r\n");
                Assert.AreEqual("95ea6a6859af6791464bd8b6de76ad5a6f9fad81", blob.Hash);

                blob = Blob.Create(repo, Encoding.UTF8.GetBytes("and this is the data in me\r\n\r\n"));
                Assert.AreEqual("95ea6a6859af6791464bd8b6de76ad5a6f9fad81", blob.Hash);
            }
        }
Beispiel #4
0
 public string ReadAsText(Blob blob, string encoding)
 {
     return null;
 }
            public void SetMetadata(string blobName, IDictionary<string, string> metadata, string leaseId)
            {
                Blob existing;
                if (!_items.TryRemove(blobName, out existing))
                {
                    throw new InvalidOperationException();
                }

                if (leaseId == null)
                {
                    existing.ThrowIfLeased();
                }
                else
                {
                    existing.ThrowIfLeaseMismatch(leaseId);
                }

                _items[blobName] = new Blob(existing.BlobType, existing.Contents, metadata, existing.LeaseId,
                    existing.LeaseExpires);
            }
Beispiel #6
0
 public void ReadAsBinaryString(Blob filedata)
 {
 }
Beispiel #7
0
        public void CommitHonorsConfigCommitEncoding()
        {
            string workingDirectory = Path.Combine(trash.FullName, Path.GetRandomFileName());

            // Creating a new repo
            using (var repo = Repository.Init(workingDirectory))
            {
                // Setting the in-memory commitencoding configuration entry
                repo.Config["i18n.commitencoding"] = "ISO-8859-2";

                // Adding a new file to the filesystem
                string filepath = Path.Combine(workingDirectory, "a file.txt");
                File.WriteAllText(filepath, "content");

                // Adding the new file to index
                repo.Index.Add(filepath);

                // Committing
                string message = "Jak se máš?\n\nMám se dobře.";
                Commit c = repo.Commit(message, new Author("nulltoken", "*****@*****.**")); //How are you? I'm fine.

                // Loading the commit
                var commit = new Commit(repo, c.Hash);

                Assert.AreEqual("ISO-8859-2", commit.Encoding.WebName.ToUpperInvariant());

                var blob = new Blob(repo, c.Hash);
                var messageBytes = new byte[message.Length];
                Array.Copy(blob.RawData, 190, messageBytes, 0, message.Length);

                Assert.IsTrue(Encoding.GetEncoding("ISO-8859-2").GetBytes(message).SequenceEqual(messageBytes));
            }
        }
Beispiel #8
0
 public void ReadAsText(Blob blob, string label)
 {
 }
        private static bool InternalCopyBlob(Blob blobDst, Blob blobSrc)
        {
            blobDst.CloudBlockBlob.StartCopyFromBlob(blobSrc.CloudBlockBlob);

            // requesting operation status
            // todo: measure copy speed, and fetch attributes with less frequency based on avg speed
            while (true)
            {
                blobDst.CloudBlockBlob.FetchAttributes();
                if (blobDst.CloudBlockBlob.CopyState.Status != CopyStatus.Pending)
                    break;

                // sleeping 1 second per remaining 50-megabytes (this is the rate of a commong hard drive)
                var sleep = (blobDst.CloudBlockBlob.CopyState.TotalBytes ?? 0 - blobDst.CloudBlockBlob.CopyState.BytesCopied ?? 0) /
                    (50 * 1024000.0);
                if (sleep > 60)
                    Thread.Sleep(TimeSpan.FromSeconds(60));
                else if (sleep > 0.1)
                    Thread.Sleep(TimeSpan.FromSeconds(sleep));
            }

            var isCopyOk = blobDst.CloudBlockBlob.CopyState.Status == CopyStatus.Success;

            return isCopyOk;
        }
Beispiel #10
0
        private static IEnumerable<Blob> EnumerateFiles(string directory, bool includeDeleted, bool orderByDate, Stream singlePackage)
        {
            if ((directory == null) == (singlePackage == null)) throw new ArgumentException();
            IEnumerable<string> packages;
            if (directory != null)
            {
                directory = Path.GetFullPath(directory);

                packages =
#if NET35
            Directory.GetFiles(
#else
            Directory.EnumerateFiles(
#endif
                directory, "*.shaman-blobs");

                if (orderByDate)
                {
                    packages = packages.Select(x => new { Path = x, Date = File.GetCreationTimeUtc(x) }).OrderBy(x => x.Date).Select(x => x.Path);
                }

            }
            else
            {
                packages = new string[1];
            }
            foreach (var pkg in packages)
            {
                using (var fs = singlePackage ?? File.Open(pkg, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
                {
                    Blob previous = null;
                    var packagePath = pkg;
                    while (true)
                    {
                        var first = fs.ReadByte();
                        if (first == -1) break;
                        var len = 0;
                        len |= first << 0;
                        len |= ReadByteChecked(fs) << 8;
                        len |= ReadByteChecked(fs) << 16;
                        len |= ReadByteChecked(fs) << 24;


                        var nl = 0;
                        nl |= ReadByteChecked(fs) << 0;
                        var d = ReadByteChecked(fs);
                        // var wasNameCorrupted = false;
                        // if (!SupportCorruptedFileNameLengths)
                        {
                            nl |= d << 8;
                        }
                        /* else
                         {
                             if (d != 0)
                             {
                                 wasNameCorrupted = true;
                                 Console.WriteLine("Fixing corrupted entry...");
                                 fs.Seek(-1, SeekOrigin.Current);
                                 fs.WriteByte(0);
                             }
                         }*/

                        var closedCleanly = ReadByteChecked(fs) == 1;
                        var deleted = ReadByteChecked(fs) == 1;
                        var nameBytes = new byte[nl];
                        while (nl != 0)
                        {
                            nl -= fs.Read(nameBytes, nameBytes.Length - nl, nl);
                        }
                        var name = Encoding.UTF8.GetString(nameBytes);
                        var next = fs.Position + len;
                        var blob = new Blob()
                        {
                            PackageFileName = directory != null ? Path.GetFileName(pkg) : null,
                            PackagePath = packagePath,
                            Length = len,
                            Name = name,
                            Path = directory != null ? Path.Combine(directory, name) : null,
                            ClosedCleanly = closedCleanly,
                            DataStartOffset = (int)fs.Position,
                            fileStream = fs,
                            Deleted = deleted,
                        };
                        if (previous != null) previous.fileStream = null;
                        previous = blob;
                        if (!deleted || includeDeleted)
                            yield return blob;
                        fs.Seek(next, SeekOrigin.Begin);
                    }
                    if (previous != null) previous.fileStream = null;
                }
            }
            if (directory != null)
            {
                var additional = new List<Blob>();
                lock (_lock)
                {
                    var dir = GetDirectory(directory);

                    foreach (var file in dir.locationsToAdd)
                    {
                        FileLocation mostRecent;
                        dir.locations.TryGetValue(file.BlobName, out mostRecent);
                        if (mostRecent == file)
                        {
                            additional.Add(new Blob()
                            {
                                DataStartOffset = file.DataStartOffset,
                                PackageFileName = file.PackageFileName,
                                Name = file.BlobName,
                                ClosedCleanly = true,
                                Length = file.Length,
                                Path = Path.Combine(directory, file.BlobName)
                            });
                        }
                    }
                }
                foreach (var item in additional)
                {
                    yield return item;
                }
            }
        }
Beispiel #11
0
 public void ReadAsBinaryString(Blob filedata)
 {
 }
Beispiel #12
0
 public void ReadAsDataURL(Blob blob)
 {
 }
        /// <summary>
        /// Flushes the current block of data.
        /// </summary>
        private void FlushBlock()
        {
            if (_currentEntities.Count == 0) { return; }

            // encode into block.
            var block = new PrimitiveBlock();
            Encoder.Encode(block, _reverseStringTable, _currentEntities);
            _currentEntities.Clear();
            _reverseStringTable.Clear();

            // serialize.
            _buffer.SetLength(0);
            _runtimeTypeModel.Serialize(_buffer, block);
            var blockBytes = _buffer.ToArray();
            _buffer.SetLength(0);

            if (_compress)
            { // compress buffer.
                throw new NotSupportedException();
            }

            // create blob.
            var blob = new Blob();
            blob.raw = blockBytes;
            _runtimeTypeModel.Serialize(_buffer, blob);

            // create blobheader.
            var blobHeader = new BlobHeader();
            blobHeader.datasize = (int)_buffer.Length;
            blobHeader.indexdata = null;
            blobHeader.type = Encoder.OSMData;
            _runtimeTypeModel.SerializeWithLengthPrefix(_stream, blobHeader, _blobHeaderType, ProtoBuf.PrefixStyle.Fixed32BigEndian, 0);

            // serialize to stream.
            _buffer.Seek(0, SeekOrigin.Begin);
            _buffer.CopyTo(_stream);
        }
Beispiel #14
0
 public void ReadAsArrayBuffer(Blob blob)
 {
 }
        /// <summary>
        /// Initializes this target.
        /// </summary>
        public override void Initialize()
        {
            _currentEntities.Clear();

            // write the mandatory header.
            _buffer.Seek(0, SeekOrigin.Begin);

            // create header block.
            var blockHeader = new HeaderBlock();
            blockHeader.required_features.Add("OsmSchema-V0.6");
            blockHeader.required_features.Add("DenseNodes");
            _runtimeTypeModel.Serialize(_buffer, blockHeader);
            var blockHeaderData = _buffer.ToArray();
            _buffer.SetLength(0);

            // create blob.
            var blob = new Blob();
            blob.raw = blockHeaderData;
            _runtimeTypeModel.Serialize(_buffer, blob);

            // create blobheader.
            var blobHeader = new BlobHeader();
            blobHeader.datasize = (int)_buffer.Length;
            blobHeader.indexdata = null;
            blobHeader.type = Encoder.OSMHeader;
            _runtimeTypeModel.SerializeWithLengthPrefix(_stream, blobHeader, _blobHeaderType, ProtoBuf.PrefixStyle.Fixed32BigEndian, 0);

            // flush to stream.
            _buffer.Seek(0, SeekOrigin.Begin);
            _buffer.CopyTo(_stream);
        }
 private void PerformRequest(HttpContext context, Stream output, bool json, string controllerName)
 {
     HttpRequest request = context.Request;
     HttpResponse response = context.Response;
     ControllerConfiguration config = null;
     try
     {
         config = DataControllerBase.CreateConfigurationInstance(GetType(), controllerName);
     }
     catch (Exception )
     {
         response.StatusCode = 404;
         return;
     }
     if (!(AuthorizeRequest(request, config)))
     {
         response.StatusCode = 404;
         return;
     }
     // analyze route segments
     bool isHttpGetMethod = (HttpMethod == "GET");
     string view = null;
     string key = null;
     string fieldName = null;
     string actionGroupId = null;
     string actionId = null;
     string commandName = null;
     AnalyzeRouteValues(request, response, isHttpGetMethod, config, out view, out key, out fieldName, out actionGroupId, out actionId, out commandName);
     if (response.StatusCode == 404)
         return;
     bool keyIsAvailable = !(String.IsNullOrEmpty(key));
     if (String.IsNullOrEmpty(view))
         if (isHttpGetMethod)
             view = Controller.GetSelectView(controllerName);
         else
             if (commandName == "Insert")
                 view = Controller.GetInsertView(controllerName);
             else
                 if (commandName == "Update")
                     view = Controller.GetUpdateView(controllerName);
                 else
                     if (commandName == "Delete")
                         view = Controller.GetDeleteView(controllerName);
     if (SelectView(config, view) == null)
     {
         response.StatusCode = 404;
         return;
     }
     XPathNavigator dataFieldNode = null;
     XPathNavigator fieldNode = null;
     if (!(String.IsNullOrEmpty(fieldName)))
     {
         dataFieldNode = SelectDataField(config, view, fieldName);
         fieldNode = SelectField(config, fieldName);
         if ((dataFieldNode == null) || (fieldNode == null))
         {
             response.StatusCode = 404;
             return;
         }
     }
     // create a filter
     List<string> filter = new List<string>();
     // process key fields
     if (keyIsAvailable)
     {
         string[] values = key.Split(new char[] {
                     ','}, StringSplitOptions.RemoveEmptyEntries);
         XPathNodeIterator keyIterator = config.Select("/c:dataController/c:fields/c:field[@isPrimaryKey=\'true\']");
         int index = 0;
         while (keyIterator.MoveNext())
         {
             filter.Add(String.Format("{0}:={1}", keyIterator.Current.GetAttribute("name", String.Empty), values[index]));
             index++;
         }
     }
     // process quick find
     string quickFind = request.Params["_q"];
     if (!(String.IsNullOrEmpty(quickFind)))
         filter.Add(String.Format("{0}:~{1}", config.SelectSingleNode("/c:dataController/c:views/c:view[@id=\'{0}\']/.//c:dataField[1]/@fieldName", view).Value, quickFind));
     // process filter parameters
     if (!(keyIsAvailable))
         foreach (string filterName in request.Params.Keys)
             if (SelectDataField(config, view, filterName) != null)
                 filter.Add(String.Format("{0}:={1}", filterName, request.Params[filterName]));
             else
             {
                 Match m = BusinessRules.SqlFieldFilterOperationRegex.Match(filterName);
                 string filterFieldName = m.Groups["Name"].Value;
                 if (m.Success && (SelectDataField(config, view, filterFieldName) != null))
                 {
                     string operation = m.Groups["Operation"].Value;
                     RowFilterOperation filterOperation = ((RowFilterOperation)(TypeDescriptor.GetConverter(typeof(RowFilterOperation)).ConvertFromString(operation)));
                     string filterValue = request.Params[filterName];
                     if ((filterOperation == RowFilterOperation.Includes) || (filterOperation == RowFilterOperation.DoesNotInclude))
                         filterValue = Regex.Replace(filterValue, ",", "$or$");
                     else
                         if (filterOperation == RowFilterOperation.Between)
                             filterValue = Regex.Replace(filterValue, ",", "$and$");
                     filter.Add(String.Format("{0}:{1}{2}", filterFieldName, RowFilterAttribute.ComparisonOperations[Convert.ToInt32(filterOperation)], filterValue));
                 }
             }
     // execute request
     if (isHttpGetMethod)
         if (fieldNode != null)
         {
             string style = "o";
             if (request.QueryString["_style"] == "Thumbnail")
                 style = "t";
             string blobPath = String.Format("~/Blob.ashx?{0}={1}|{2}", fieldNode.GetAttribute("onDemandHandler", String.Empty), style, key);
             context.RewritePath(blobPath);
             Blob blobHandler = new Blob();
             ((IHttpHandler)(blobHandler)).ProcessRequest(context);
         }
         else
             ExecuteHttpGetRequest(request, response, output, json, controllerName, view, filter, keyIsAvailable);
     else
         ExecuteActionRequest(request, response, output, json, config, controllerName, view, key, filter, actionGroupId, actionId);
 }
Beispiel #17
0
 public void ReadAsDataURL(Blob blob)
 {
 }
 private static void DeleteBlob(Blob blob, StringBuilder sb, BlobFactory blobFactory)
 {
     // Deleting
     if (blob != null)
     {
         DeleteBlob(blob.ID, sb, blobFactory);
     }
 }
Beispiel #19
0
 public void ReadAsText(Blob blob)
 {
 }
Beispiel #20
0
 public BlobWriter(Blob blob)
     : this(blob.Buffer, blob.Start, blob.Length)
 {
 }
Beispiel #21
0
 public void Send(Blob data)
 {
 }
        /// <summary>
        /// Gets a blob reference to work with.
        /// </summary>
        /// <param name="fileLocation">Location of the blob to get a blob object for.</param>
        /// <param name="fetchAttributes">Whether to fetch blob attributes or not.</param>
        /// <param name="createContainer">Whether to create the container or not.</param>
        /// <returns>Return the blob object for the given file location.</returns>
        private Blob GetCloudBlockBlob(string fileLocation, bool fetchAttributes = false, bool createContainer = false)
        {
            // getting the object representing the blob
            Container container = null;
            Blob blob;

            if (!this.blobsMap.TryGetValue(fileLocation, out blob))
            {
                // Gets the object representing the container.
                var containerName = GetContainerName(fileLocation);

                if (!this.containersMap.TryGetValue(containerName, out container))
                {
                    var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                    var blobClient = storageAccount.CreateCloudBlobClient();
                    var containerRef = blobClient.GetContainerReference(containerName);
                    this.containersMap[containerName]
                        = container
                        = new Container { CloudBlobContainer = containerRef };
                }

                var blobName = GetBlobName(fileLocation);
                var blobRef = container.CloudBlobContainer.GetBlockBlobReference(blobName);
                this.blobsMap[fileLocation]
                    = blob
                    = new Blob { CloudBlockBlob = blobRef, Container = container, };
            }

            if (container == null)
                container = blob.Container;

            // creating container if needed
            if (createContainer && container.Exists != true)
            {
                if (container.CloudBlobContainer.CreateIfNotExists())
                {
                    container.CloudBlobContainer.SetPermissions(
                        new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off });
                    blob.Exists = false;
                }

                container.Exists = true;
            }

            // fetching blob attributes
            if (fetchAttributes && blob.Exists != false && blob.AttributesFetched != true)
            {
                bool ok = false;
                try
                {
                    blob.CloudBlockBlob.FetchAttributes();
                    ok = true;
                }
                catch (StorageClientException e)
                {
                    if (e.ErrorCode != StorageErrorCode.ResourceNotFound)
                        throw;
                }

                blob.Exists = ok;
                blob.AttributesFetched = ok;
            }

            return blob;
        }
Beispiel #23
0
 public static string CreateObjectURL(Blob blob)
 {
     return null;
 }
Beispiel #24
0
        protected virtual string GetBlobImageFile(Blob image)
        {
            var imageStream = image.GetStream();
            var ext = ".bmp";
            switch (image.MimeType)
            {
                case "image/png":
                    ext = ".png";
                    break;
                case "image/bmp":
                    ext = ".bmp";
                    break;
                case "image/jpg":
                    ext = ".jpg";
                    break;
            }

            using (var tmpFile = File.OpenWrite(ReportingHost.TempService.CreateWithExtension(ext)))
            {
                imageStream.WriteAllTo(tmpFile);
                return tmpFile.Name.Replace('\\', '/');
            }
        }
            public CloudBlobStream OpenWriteBlock(string blobName, IDictionary<string, string> metadata)
            {
                if (_items.ContainsKey(blobName))
                {
                    _items[blobName].ThrowIfLeased();
                }

                return new MemoryCloudBlockBlobStream((bytes) => _items[blobName] =
                    new Blob(StorageBlobType.BlockBlob, bytes, metadata, null, null));
            }
Beispiel #26
0
 public void ReadAsText(Blob blob, string label)
 {
 }
Beispiel #27
0
 public void ReadAsText(Blob blob)
 {
 }
Beispiel #28
0
 public ArrayBuffer ReadAsArrayBuffer(Blob blob)
 {
     return default(ArrayBuffer);
 }
Beispiel #29
0
 public string ReadAsBinaryString(Blob blob)
 {
     return null;
 }
Beispiel #30
0
 public static string CreateObjectURL(Blob blob, ObjectUrlOptions options)
 {
     return null;
 }
Beispiel #31
0
 public string ReadAsDataURL(Blob blob)
 {
     return null;
 }
            public CloudBlobStream OpenWritePage(string blobName, long? size, IDictionary<string, string> metadata)
            {
                if (!size.HasValue)
                {
                    throw new NotImplementedException();
                }

                if (size.Value % 512 != 0)
                {
                    throw new InvalidOperationException();
                }

                if (_items.ContainsKey(blobName))
                {
                    _items[blobName].ThrowIfLeased();
                }

                return new MemoryCloudPageBlobStream((bytes) => _items[blobName] =
                    new Blob(StorageBlobType.PageBlob, bytes, metadata, null, null));
            }
Beispiel #33
0
 public string ReadAsText(Blob blob)
 {
     return null;
 }
Beispiel #34
0
        private void DoTest(GenericAsyncClient client, TimeStampAuthorityClient tsaClient)
        {
            //Create common input with info about the requestor, must match SAML
            CommonInputType commonInput = new CommonInputType();
            commonInput.InputReference = "TADM1234567890";
            commonInput.Request = new RequestType();
            commonInput.Request.IsTest = true;
            commonInput.Origin = new OrigineType();
            commonInput.Origin.Package = new PackageType();
            commonInput.Origin.Package.Name = "eH-I Test";
            commonInput.Origin.Package.License = new LicenseType();
            commonInput.Origin.Package.License.Username = "******"; //provide you own license
            commonInput.Origin.Package.License.Password = "******"; //provide your own password
            commonInput.Origin.SiteID = "01"; //CareNet Gateway ID.
            commonInput.Origin.CareProvider = new CareProviderType();
            commonInput.Origin.CareProvider.Nihii = new NihiiType();
            commonInput.Origin.CareProvider.Nihii.Quality = "hospital";
            commonInput.Origin.CareProvider.Nihii.Value = "71022212000";
            commonInput.Origin.CareProvider.Organization = new IdType();
            commonInput.Origin.CareProvider.Organization.Nihii = commonInput.Origin.CareProvider.Nihii;

            //create blob value
            Stream raw = new MemoryStream(Encoding.ASCII.GetBytes(RandomString(1024*1024))); //you might use a file instead
            MemoryStream deflated = new MemoryStream();
            DeflateStream deflater = new DeflateStream(deflated, CompressionMode.Compress, true);
            raw.CopyTo(deflater);
            deflater.Flush();
            deflater.Close();

            //create blob
            Blob blob = new Blob();
            blob.MessageName = "ADM";
            blob.Id = "_" + Guid.NewGuid().ToString();
            blob.ContentType = "text/plain";
            blob.Value = deflated.ToArray();

            //Create Xml with the blob inside it to sign.
            XmlDocument signDoc;
            using(MemoryStream signDocStream = new MemoryStream()) {
                XmlWriter signDocWriter = XmlWriter.Create(signDocStream);
                signDocWriter.WriteStartElement("root");

                XmlSerializer serializer = new XmlSerializer(typeof(Blob), new XmlRootAttribute("Detail"));
                serializer.Serialize(signDocWriter, blob);

                signDocWriter.WriteEndElement();
                signDocWriter.Flush();

                signDocStream.Seek(0, SeekOrigin.Begin);
                signDoc = new XmlDocument();
                signDoc.PreserveWhitespace = true;
                signDoc.Load(signDocStream);
            }

            //create the xades-t
            var xigner = new XadesCreator(sign);
            xigner.TimestampProvider = new EHealthTimestampProvider(tsaClient);
            xigner.DataTransforms.Add(new XmlDsigBase64Transform());
            xigner.DataTransforms.Add(new OptionalDeflateTransform());
            XmlElement xades = xigner.CreateXadesT(signDoc, blob.Id);

            //conver the xades-t to byte array
            MemoryStream xadesSteam = new MemoryStream();
            using (var writer = XmlWriter.Create(xadesSteam))
            {
                xades.WriteTo(writer);
            }

            //Create the Base64 structure
            base64Binary xadesParam = new base64Binary();
            xadesParam.contentType = "text/xml";
            xadesParam.Value = xadesSteam.ToArray();

            //Send the message
            Thread.Sleep(1000); //sleep to let the eID recover :(
            TAck nipAck = client.post(commonInput, blob, xadesParam);

            //check if the messages was correctly send
            Assert.AreEqual("urn:nip:tack:result:major:success", nipAck.ResultMajor);

            //Get any waiting responses
            MsgQuery msgQuery = new MsgQuery();
            msgQuery.Max = 1; //best to specify to avoid quota exceeds or memory issues
            msgQuery.Include = true;
            Query tackQuery = new Query();
            tackQuery.Max = 10; //best to specify, but since they are smaller we can handle more
            tackQuery.Include = true;

            //Get the messages & tACK
            Thread.Sleep(1000); //sleep to let the eID recover :(
            Responses rsp = client.get(commonInput.Origin, msgQuery, tackQuery);

            //Collect the hash values of the messages & the tack
            //Should be a list of bytes arrays, but WCF isn't that smart so you need to do the encoding (base64, sperated by spaces)
            StringBuilder msgHashValues = new StringBuilder();
            if (rsp.MsgResponse != null)
            {
                foreach (MsgResponse msgRsp in rsp.MsgResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(Blob), "urn:be:cin:types:v1");
                        serializer.Serialize(verifyDocWriter, msgRsp.Detail);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(msgRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement prop = (XmlElement) XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    if (msgHashValues.Length != 0) msgHashValues.Append(" ");
                    msgHashValues.Append(Convert.ToBase64String(msgRsp.Detail.HashValue));
                }
            }
            List<String> resend = new List<string>();
            StringBuilder tackContents = new StringBuilder();
            if (rsp.TAckResponse != null)
            {
                foreach (TAckResponse tackRsp in rsp.TAckResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(TAck), "urn:be:cin:nip:async:generic");
                        serializer.Serialize(verifyDocWriter, tackRsp.TAck);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(tackRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement prop = (XmlElement)XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    //send failed, resend later.
                    if ("urn:nip:tack:result:major:success" != tackRsp.TAck.ResultMajor)
                    {
                        resend.Add(tackRsp.TAck.AppliesTo);
                    }

                    if (tackContents.Length != 0) tackContents.Append(" ");
                    tackContents.Append(Convert.ToBase64String(tackRsp.TAck.Value)); //the content of the tAck is already a hash...
                }
            }

            //Confirm the received messages & tack
            Thread.Sleep(1000); //sleep to let the eID recover :(
            client.confirm(commonInput.Origin, msgHashValues.ToString(), tackContents.ToString());

            //We should not have anything to resend
            Assert.AreEqual(0, resend.Count);
        }
Beispiel #35
0
 public void ReadAsArrayBuffer(Blob blob)
 {
 }