Exemplo n.º 1
0
        public byte[] GetFileData(uint index)
        {
            this.lastRequest = DateTime.Now;

            lock (this.objLock)
            {
                if (!this.streamItems.ContainsKey(index))
                {
                    throw new HttpException(404, "HLS file number " + index + " not found");
                }

                StreamItem item = this.streamItems[index];
                if (item.FileData == null)
                {
                    throw new HttpException(404, "No data in HLS file number " + index);
                }

                if (index > KeepUsedFiles)
                {
                    //Vymaze subory starsie ako je aktualny index, ich pocet udava KeepUsedFiles, nezaratava sa aktualny
                    uint[] toRemove = this.streamItems.Keys.Where(a => a < (index - KeepUsedFiles)).ToArray();
                    if (toRemove.Length > 0)
                    {
                        foreach (uint key in toRemove)
                        {
                            this.streamItems.Remove(key);
                        }
                        this.mediaSequence += (uint)toRemove.Length;
                        Monitor.PulseAll(this.objLock);
                    }
                }

                return(item.FileData);
            }
        }
Exemplo n.º 2
0
        private StreamItem[] LoadStreamCollectionItems(SQLiteConnection connection, string streamId)
        {
            List <StreamItem> items = new List <StreamItem>();

            items.Add(new HeaderSpaceStreamItem());

            using (var statement = connection.Prepare(@"SELECT ID, PUBLISHED, TITLE, WEB_URI, CONTENT, UNREAD, NEED_SET_READ_EXPLICITLY, IS_SELECTED, STARRED, SAVED FROM STREAM_ITEM WHERE STREAM_ID = @STREAM_ID;"))
            {
                statement.Bind("@STREAM_ID", streamId);

                while (statement.Step() == SQLiteResult.ROW)
                {
                    var item = new StreamItem
                    {
                        Id                    = (string)statement[0],
                        Published             = DateTimeOffset.Parse((string)statement[1]),
                        Title                 = (string)statement[2],
                        WebUri                = (string)statement[3],
                        Content               = (string)statement[4],
                        Unread                = statement.GetInteger(5) == 1,
                        NeedSetReadExplicitly = statement.GetInteger(6) == 1,
                        IsSelected            = statement.GetInteger(7) == 1,
                        Starred               = statement.GetInteger(8) == 1,
                        Saved                 = statement.GetInteger(9) == 1,
                    };
                    items.Add(item);
                }
            }

            items.Add(new EmptySpaceStreamItem());

            return(items.ToArray());
        }
        public bool AddPhysicianRights(string patientBsn, string physicianIdentification, string signature)
        {
            MultiChain chain    = new MultiChain();
            var        verified = chain.VerifyMessage(new MessageData {
                address = patientBsn, signature = signature, message = physicianIdentification
            }) == "true";

            var        result     = chain.GetStreamItemByKey(patientBsn, authorisation);
            StreamItem streamitem = new StreamItem();

            if (result.streamitems.Any())
            {
                streamitem = result.streamitems.Last();
            }

            var data = streamitem.data.Any() ? this.DeEncryptHexData(streamitem.data) : string.Empty;

            data += this.EncryptHexData((data.Any() ? ";" : string.Empty) + physicianIdentification);

            var transactionkey = this.GetTransactionKey(physicianIdentification);
            var transactionId  = chain.PublishMessage(new PublishMessageData {
                Key = authorisation, HexString = data, StreamName = authorisation
            });

            return(true);

            return(false);
        }
        public bool RemovePhysicianRights(string patientBsn, string physicianIdentification, string physicianToRemove, string signature)
        {
            MultiChain chain    = new MultiChain();
            var        verified = chain.VerifyMessage(new MessageData {
                address = patientBsn, signature = signature, message = physicianIdentification
            }) == "true";

            if (verified)
            {
                var        result     = chain.GetStreamItemByKey(patientBsn, authorisation);
                StreamItem streamitem = new StreamItem();

                if (result.streamitems.Any())
                {
                    streamitem = result.streamitems.Last();
                }

                var data = streamitem.data.Any() ? this.DeEncryptHexData(streamitem.data) : string.Empty;
                var res  = string.Concat(data.Split(';').Where(f => f != physicianToRemove).Select(f => f + ";").ToArray());
                if (res.Any())
                {
                    data = this.EncryptHexData(res);
                }

                var transactionkey = this.GetTransactionKey(physicianIdentification);
                var transactionId  = chain.PublishMessage(new PublishMessageData {
                    Key = transactionkey, HexString = data, StreamName = authorisation
                });
            }

            return(false);
        }
Exemplo n.º 5
0
        public async Task AddAsync(StreamItem item)
        {
            if (_items.Value.Any(t => t.Id == item.Id))
            {
                return;
            }

            var folderName = Guid.NewGuid().ToString("N");

            var parser    = new HtmlParser();
            var plainText = parser.GetPlainText(item.Content, 200);

            var cacheFolder = await _rootCacheFolder.CreateFolderAsync(CacheFolderName, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);

            var folder = await cacheFolder.CreateFolderAsync(folderName).AsTask().ConfigureAwait(false);

            var newHtml = await SaveImagesAsync(folder, item.Content).ConfigureAwait(false);

            var savedItem = new SavedStreamItem
            {
                Id           = item.Id,
                Title        = item.Title,
                Published    = item.Published,
                WebUri       = item.WebUri,
                ShortContent = plainText,
                Content      = newHtml,
                ImageFolder  = folderName
            };

            _items.Value.Add(savedItem);
            _storageManager.Save(savedItem);
        }
Exemplo n.º 6
0
            public new void Add(StreamItem item)
            {
                item.Stream.Position = 0;
                if (_isSingleItem)
                {
                    const string multiStreamNotSupportedErrMessage =
                        "DocumentStreamsBundle initialized with isSingleItem param set to true is for compatibility with old code for signle stream output. Please init the DocumentStreamsBundle without isSingleItem parameter and handle multiple streams result in your code. This error occur usually when Document.SaveAs method was invoked with Stream for result instead with DocumentStreamsBundle.";
                    switch (Count)
                    {
                    case 1:
                        if (_isModified)
                        {
                            throw new InvalidOperationException(multiStreamNotSupportedErrMessage);
                        }
                        base[0].Stream.SetLength(0);
                        item.Stream.CopyTo(base[0].Stream);
                        base[0].FileType = item.FileType;
                        break;

                    case 0:
                        base.Add(item);
                        break;

                    default:
                        throw new InvalidOperationException(multiStreamNotSupportedErrMessage);
                    }
                }
                else
                {
                    base.Add(item);
                }
                _isModified = true;
            }
Exemplo n.º 7
0
        public void CanReturnTheCorrectWebsite()
        {
            const string website       = "website";
            IStreamItem  streamItemSUT = new StreamItem(website, "replacement");

            Assert.AreEqual(website, streamItemSUT.Website);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Load a Cache File from the Disk
        /// </summary>
        /// <param name="flname">the name of the File</param>
        /// <param name="withprogress">true if you want  to set the Progress in the current Wait control</param>
        /// <exception cref="CacheException">Thrown if the File is not readable (ie, wrong Version or Signature)</exception>
        public void Load(string flname, bool withprogress)
        {
            this.filename = flname;
            containers.Clear();

            if (!System.IO.File.Exists(flname))
            {
                return;
            }

            StreamItem si = StreamFactory.UseStream(flname, FileAccess.Read, true);

            try
            {
                BinaryReader reader = new BinaryReader(si.FileStream);

                try
                {
                    ulong sig = reader.ReadUInt64();
                    if (sig != SIGNATURE)
                    {
                        throw new CacheException("Unknown Cache File Signature (" + Helper.HexString(sig) + ")", flname, 0);
                    }

                    version = reader.ReadByte();
                    if (version > VERSION)
                    {
                        throw new CacheException("Unable to read Cache", flname, version);
                    }

                    int count = reader.ReadInt32();
                    if (withprogress)
                    {
                        Wait.MaxProgress = count;
                    }
                    for (int i = 0; i < count; i++)
                    {
                        CacheContainer cc = new CacheContainer(DEFAULT_TYPE);
                        cc.Load(reader);
                        containers.Add(cc);
                        if (withprogress)
                        {
                            Wait.Progress = i;
                        }
                        if (i % 10 == 0)
                        {
                            System.Windows.Forms.Application.DoEvents();
                        }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
            finally
            {
                si.Close();
            }
        }
Exemplo n.º 9
0
        private void AddStreamItem(uint index, double?duration, byte[] fileData)
        {
            //Cislovanie zacina od 1, pre nulty prvok je vyhradeny staticky obraz
            index++;

            lock (this.objLock)
            {
                StreamItem item;
                if (this.streamItems.ContainsKey(index))
                {
                    item = this.streamItems[index];
                    if (duration.HasValue)
                    {
                        item.Duration = duration;
                    }
                    if (fileData != null)
                    {
                        item.FileData = fileData;
                    }
                }
                else
                {
                    item = new StreamItem()
                    {
                        Duration = duration, FileData = fileData
                    };
                    this.streamItems[index] = item;
                }

                if (item.Duration.HasValue && item.FileData != null)
                {
                    Monitor.PulseAll(this.objLock);
                }
            }
        }
Exemplo n.º 10
0
        public void CanReturnTheCorrectWhitespaceReplacement()
        {
            const string replacement = "replacement";

            IStreamItem streamItemSUT = new StreamItem("website", replacement);
            Assert.AreEqual(replacement, streamItemSUT.WhitespaceReplacement);
        }
Exemplo n.º 11
0
        public void CanReturnTheCorrectSelectedItem()
        {
            IStreamItem expectedStreamItem = new StreamItem("a", "b");

            viewModelSUT.SelectedItem = expectedStreamItem;

            Assert.AreEqual(expectedStreamItem, viewModelSUT.SelectedItem);
        }
Exemplo n.º 12
0
        public LoggerViewModel()
        {
            Streams     = new ObservableCollection <StreamItem>();
            LogItems    = new FixedLengthQueue <LogItem>(500);
            LogItemsOld = new FixedLengthQueue <LogItem>(10000);

            _defaultStream = AddStreamItem("Default");
        }
Exemplo n.º 13
0
        public void CanReturnTheCorrectWhitespaceReplacement()
        {
            const string replacement = "replacement";

            IStreamItem streamItemSUT = new StreamItem("website", replacement);

            Assert.AreEqual(replacement, streamItemSUT.WhitespaceReplacement);
        }
Exemplo n.º 14
0
        public void Send(StreamItem item)
        {
            if (item.Secret == ConfigurationManager.AppSettings["TwitterCustomerSecret"])
            {
                var screenname = UsersCollection.PrimaryUser().TwitterScreenName;
                var topTweets  = TwitterModel.Instance.Tweets(screenname).Take(50);
                if (topTweets != null)
                {
                    var tweetsToSend = item.Data.Where(t => t.TweetRank >= topTweets.Min(x => x.TweetRank) && !topTweets.Contains(t)).OrderBy(t => t.CreatedAt);
                    if (tweetsToSend.Count() > 0)
                    {
                        int              index              = tweetsToSend.Count();
                        List <string>    returnValues       = new List <string>();
                        List <string>    returnValuesMobile = new List <string>();
                        ViewEngineResult viewResult         = ViewEngines.Engines.FindPartialView(HomeContext, "_Item");
                        ViewEngineResult viewResultMobile   = ViewEngines.Engines.FindPartialView(MobileContext, "_Item");

                        var tweetCache = TwitterModel.Instance.PrimaryUserTweetCache;
                        if (tweetCache != null)
                        {
                            tweetCache.AddRange(tweetsToSend);
                        }

                        foreach (var tweet in tweetsToSend)
                        {
                            var ViewData = new ViewDataDictionary <ItemData>(new ItemData()
                            {
                                Model       = tweet,
                                index       = index--,
                                isTop10     = false,
                                isTop20     = false,
                                isTop30     = false,
                                randomImage = tweet.Links.Where(l => l.Image != null).OrderBy(x => Guid.NewGuid()).FirstOrDefault(),
                                hasVideo    = tweet.Links.Where(l => l.Video != null).Count() > 0,
                                topN        = ""
                            });
                            using (StringWriter sw = new StringWriter())
                            {
                                ViewContext viewContext = new ViewContext(HomeContext, viewResult.View, ViewData, new TempDataDictionary(), sw);
                                viewResult.View.Render(viewContext, sw);

                                returnValues.Add(sw.GetStringBuilder().ToString());
                            }
                            using (StringWriter sw = new StringWriter())
                            {
                                ViewContext viewContextMobile = new ViewContext(MobileContext, viewResultMobile.View, ViewData, new TempDataDictionary(), sw);
                                viewResultMobile.View.Render(viewContextMobile, sw);

                                returnValuesMobile.Add(sw.GetStringBuilder().ToString());
                            }
                        }
                        Update(returnValues);
                        UpdateMobile(returnValuesMobile);
                    }
                }
            }
        }
Exemplo n.º 15
0
 public MergeService(TwitterRepository twitterRepository, YoutubeRepository youtubeRepository, RssParser rssParser, FacebookRepository facebookRepository, AppSettings appSettings)
 {
     _twitterRepository  = twitterRepository;
     _youtubeRepository  = youtubeRepository;
     _rssParser          = rssParser;
     _facebookRepository = facebookRepository;
     _nagEvery           = appSettings.NagEvery;
     _nag = appSettings.Nag;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Adds a new stream Item to the list.
        /// </summary>
        /// <param name="identifier">The unique string which identifies the stream Item</param>
        /// <param name="item">The stream item which should be added</param>
        internal static async Task <bool> AddStreamItemAsync(string identifier, StreamItem item)
        {
            if (await DeleteStreamItemAsync(identifier))
            {
                Logger.Debug("StreamControl: Identifier {0} is already in list -> deleting old stream item", identifier);
            }

            item.LastActivityTime = DateTime.Now;
            return(STREAM_ITEMS.TryAdd(identifier, item));
        }
Exemplo n.º 17
0
        public static async Task <WebStringResult> ProcessAsync(IOwinContext context, string identifier, string profileName, long startPosition)
        {
            if (identifier == null)
            {
                throw new BadRequestException("InitStream: identifier is null");
            }
            if (profileName == null)
            {
                throw new BadRequestException("InitStream: profileName is null");
            }

            StreamItem streamItem = await StreamControl.GetStreamItemAsync(identifier);

            if (streamItem == null)
            {
                throw new BadRequestException(string.Format("StartStream: Unknown identifier: {0}", identifier));
            }

            // Prefer getting profile by name
            EndPointProfile profile = ProfileManager.Profiles.Values.FirstOrDefault(p => p.Name == profileName);

            // If no ptofile with the specified name, see if there's one with a matching id
            if (profile == null && !ProfileManager.Profiles.TryGetValue(profileName, out profile))
            {
                throw new BadRequestException(string.Format("StartStream: Unknown profile: {0}", profileName));
            }

            streamItem.Profile = profile;
            // Seeking is not supported in live streams
            streamItem.StartPosition = streamItem.RequestedMediaItem is LiveTvMediaItem ? 0 : startPosition;

            Guid?userId = ResourceAccessUtils.GetUser(context);

            streamItem.TranscoderObject = new ProfileMediaItem(identifier, profile, streamItem.IsLive);
            await streamItem.TranscoderObject.Initialize(userId, streamItem.RequestedMediaItem, null);

            if (streamItem.TranscoderObject.TranscodingParameter is VideoTranscoding vt)
            {
                vt.HlsBaseUrl = string.Format("RetrieveStream?identifier={0}&hls=", identifier);
            }

            await StreamControl.StartStreamingAsync(identifier, startPosition);

            string filePostFix = "&file=media.ts";

            if (profile.MediaTranscoding?.VideoTargets?.Any(t => t.Target.VideoContainerType == VideoContainer.Hls) ?? false)
            {
                filePostFix = "&file=manifest.m3u8"; //Must be added for some clients to work (Android mostly)
            }
            string url = GetBaseStreamUrl.GetBaseStreamURL(context) + "/MPExtended/StreamingService/stream/RetrieveStream?identifier=" + identifier + filePostFix;

            return(new WebStringResult {
                Result = url
            });
        }
Exemplo n.º 18
0
        public void CanExecuteMoveUpCmd()
        {
            IStreamItem expectedStreamItem = new StreamItem("c", "d");

            viewModelSUT.Streams.Add(new StreamItem("a", "b"));
            viewModelSUT.Streams.Add(expectedStreamItem);
            viewModelSUT.SelectedItem = viewModelSUT.Streams[1];

            viewModelSUT.MoveUpCmd.Execute(null);

            Assert.AreEqual(expectedStreamItem, viewModelSUT.Streams[0]);
        }
Exemplo n.º 19
0
        public async Task <StreamItem> GetStreamItem()
        {
            var testFilePath = ItemsGenerator.CreateTestFilename();
            await ItemsGenerator.CreateTestFile(testFilePath);

            var fileStream = new FileStream(testFilePath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
            var streamItem = new StreamItem
            {
                Stream = fileStream,
                Id     = ItemsGenerator.TestGuid
            };

            return(streamItem);
        }
Exemplo n.º 20
0
        public static async Task StartAsync()
        {
            // boot...
            var conn = GetConnection();
            await conn.CreateTablesAsync <StreamItem, StoryItem>();

            // do we have any streams?
            var streams = await StreamItem.GetActiveStreamsAsync();

            if (!(streams.Any()))
            {
                await StreamItem.CreateDefaultStreams();
            }
        }
        public bool AddPhysician(string psysicianAddress, string physicianIdentification, string clientBsn, string signature)
        {
            // Create serveral Objects:
            //      Authorisation stream
            //      Items stream

            // autorisatie stream wordt gevuld met de autorisatie van de medicus ten opzichte van andere streams anders dan zijn/haar eigen
            // de streams waarop hij/zij toegang heeft zijn abonnementen
            // de abonnementen kunnen worden ingenomen/ ongedaan gemaakt worden

            MultiChain chain    = new MultiChain();
            var        verified = chain.VerifyMessage(new MessageData {
                address = psysicianAddress, signature = signature, message = physicianIdentification
            }) == "true";
            var itemStreamname          = this.GetChainName(clientBsn, physicianIdentification, items);
            var accessStreamname        = this.GetChainName(clientBsn, physicianIdentification, access);
            var authorisationStreamname = this.GetChainName(clientBsn, physicianIdentification, authorisation);

            chain.CreateNewStream(true, itemStreamname);
            chain.CreateNewStream(true, accessStreamname);
            chain.CreateNewStream(true, authorisationStreamname);

            chain.Subscribe(itemStreamname);
            chain.Subscribe(accessStreamname);
            chain.Subscribe(authorisation);

            // toevoegen authorisatie arts
            var        result     = chain.GetStreamItemByKey(authorisationStreamname, authorisation);
            StreamItem streamitem = new StreamItem {
                data = string.Empty
            };

            if (result != null && result.streamitems.Any())
            {
                streamitem = result.streamitems.Last();
            }

            var data = streamitem.data.Any() ? this.DeEncryptHexData(streamitem.data) : string.Empty;

            data += this.EncryptHexData((data.Any() ? ";" : string.Empty) + physicianIdentification);

            var datalocation = this.CreateFileBackup(data);

            chain.PublishMessage(new PublishMessageData {
                Key = authorisation, HexString = this.EncryptHexData(datalocation + "|" + ("NogGeenKey").Replace("-", string.Empty).Replace(" ", string.Empty)), StreamName = authorisationStreamname
            });

            return(true);
        }
Exemplo n.º 22
0
        private void ExecuteSelectItemCommand(StreamItem item)
        {
            // navigate depending on type
            if (item is NewsItem || (!string.IsNullOrEmpty(item.Type) && item.Type.EndsWith("NewsItem")))
            {
                ShowViewModel <WebViewViewModel>(new { url = item.Url, title = item.Title });
                return;
            }

            if (item is EventItem || (!string.IsNullOrEmpty(item.Type) && item.Type.EndsWith("EventItem")))
            {
                ShowViewModel <EventDetailViewModel>(new { id = item.Id });
                return;
            }
        }
Exemplo n.º 23
0
        public static async Task <WebTranscodingInfo> ProcessAsync(IOwinContext context, string identifier, long?playerPosition)
        {
            if (identifier == null)
            {
                throw new BadRequestException("GetTranscodingInfo: identifier is null");
            }

            StreamItem streamItem = await StreamControl.GetStreamItemAsync(identifier);

            if (streamItem == null)
            {
                throw new BadRequestException(string.Format("GetTranscodingInfo: Unknown identifier: {0}", identifier));
            }

            return(new WebTranscodingInfo(streamItem.StreamContext as TranscodeContext));
        }
Exemplo n.º 24
0
        public bool CrossStreamCommunication(string patientAddress, string address1, string address2, string messageToPost, string signature, string transactionId = null)
        {
            // Als wij van chain naar chain willen communiceren, dan moeten beide of alle partijen, inzage hebben in alle chains
            // Aangezien dit niet wenselijk is, kunnen wij ook de transaction Id's opslaan.
            // Stel voor:
            //              doc A post een vraag -> insert question in stream van doc A
            //              doc B mag niet lezen in stream van doc A
            //              vraag van doc A is gepost in stream van doc A (eigen stream, geen cross stream posts)
            //              doc A -> krijgt transaction Id van vraag -> wordt opgeslagen in streamPatientAddress-crossstreamcomm
            //              doc B krijgt een melding dat er een 'crossstream' communicatie klaar staat
            //              doc B mag vanwege tijdelijke autorisatie op enkel block TxId data lezen in stream van doc A
            //              doc B geeft antwoord in eigen stream (geen cross stream posts)
            //              doc B krijgt TxId terug van de post -> dit TxId wordt gepost in streamPatientAddress-crossstreamcomm onder de TxId van de vraag (Key is zelfde TxId van vraag)
            //              doc A en doc B kunnen historische vraag en antwoord -> van alle posts gekoppeld aan TxId van vraag teruglezen
            //              wanneer doc A verdere vraag uitzet naar doc C wordt ook die gekoppeld onder zelfde TxId -> doc B kan ook resultaat van doc C lezen

            // Address1 = addres from -> posts question
            // Address2 = address to -> receives question
            // patientAddress = adres van patient -> his steams need to be used

            MultiChain chain    = new MultiChain();
            var        verified = chain.VerifyMessage(patientAddress, signature, messageToPost) == "true";

            if (verified)
            {
                if (transactionId != null)
                {
                }
                else
                {
                }

                var        result     = chain.GetStreamItemByKey(patientAddress + "-crossstreamcomm", authorisation);
                StreamItem streamitem = new StreamItem();

                if (result.streamitems.Any())
                {
                    streamitem = result.streamitems.Last();
                }

                var data = streamitem.data.Any() ? this.DeEncryptHexData(streamitem.data) : string.Empty;
                data += this.EncryptHexData((data.Any() ? ";" : string.Empty) + physicianAddress);
                // var transactionId = chain.PublishMessage(authorisation, data);
            }

            return(false);
        }
Exemplo n.º 25
0
        public async Task TestUpdateStreamItem()
        {
            await ItemsGenerator.CreateTestFile(_testFileName);

            using (var fileStream = File.OpenRead(_testFileName))
            {
                var streamItem = new StreamItem
                {
                    Stream = fileStream,
                    Id     = ItemsGenerator.TestGuid
                };

                var fileContent = await _controller.UpdateStreamItem(streamItem);

                Assert.Equal(ItemsGenerator.TestFileContent, fileContent);
            }
        }
Exemplo n.º 26
0
        private void button11_Click(object sender, EventArgs e)
        {
            mystream = chain.GetStreamItem("pinjo", transactionId);

            this.publisher.Text = mystream.publishers.First();
            this.confirmed.Text = mystream.confirmations.ToString();

            this.key.Text       = mystream.key;
            this.txid.Text      = mystream.txid;
            this.blocktime.Text = mystream.blocktime.ToString();
            this.data.Text      = mystream.data;

            var data        = this.chain.HexStringToBytes(mystream.data);
            var data2string = Encoding.Default.GetString(data);

            this.datatrans.Text = data2string;
        }
Exemplo n.º 27
0
        public bool AddPhysician(string patientAddress, string physicianAddress, string signature)
        {
            // Create serveral Objects:
            //      Authorisation stream
            //      Items stream

            // autorisatie stream wordt gevuld met de autorisatie van de medicus ten opzichte van andere streams anders dan zijn/haar eigen
            // de streams waarop hij/zij toegang heeft zijn abonnementen
            // de abonnementen kunnen worden ingenomen/ ongedaan gemaakt worden


            // Create stream client

            MultiChain chain    = new MultiChain();
            var        verified = chain.VerifyMessage(patientAddress, signature, physicianAddress) == "true";

            if (verified)
            {
                var itemStreamname   = this.GetChainName(patientAddress, physicianAddress, "item");
                var accessStreamname = this.GetChainName(patientAddress, physicianAddress, "access");

                chain.CreateNewStream(true, patientAddress);
                chain.CreateNewStream(true, accessStreamname);

                chain.Subscribe(patientAddress);
                chain.Subscribe(accessStreamname);

                // toevoegen authorisatie arts
                var        result     = chain.GetStreamItemByKey(patientAddress, authorisation);
                StreamItem streamitem = new StreamItem();

                if (result.streamitems.Any())
                {
                    streamitem = result.streamitems.Last();
                }

                var data = streamitem.data.Any() ? this.DeEncryptHexData(streamitem.data) : string.Empty;
                data += this.EncryptHexData((data.Any() ? ";" : string.Empty) + physicianAddress);
                var transactionId = chain.PublishMessage(authorisation, data);

                return(true);
            }

            return(false);
        }
Exemplo n.º 28
0
        public async Task <string> UpdateStreamItem(StreamItem streamItem)
        {
            var testFilePath = ItemsGenerator.CreateTestFilename();

            try
            {
                var stream = streamItem.Stream;
                using (var fileStream = File.OpenWrite(testFilePath))
                {
                    await stream.CopyToAsync(fileStream);
                }

                var fileContent = File.ReadAllText(testFilePath);
                return(fileContent);
            }
            finally
            {
                ItemsGenerator.DeleteFile(testFilePath);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Save a Cache File to the Disk
        /// </summary>
        /// <param name="flname">the name of the File</param>
        public void Save(string flname)
        {
            this.filename = flname;
            this.version  = VERSION;

            StreamItem si = StreamFactory.UseStream(flname, FileAccess.Write, true);

            try
            {
                CleanUp();

                si.FileStream.Seek(0, SeekOrigin.Begin);
                si.FileStream.SetLength(0);
                BinaryWriter writer = new BinaryWriter(si.FileStream);

                writer.Write(SIGNATURE);
                writer.Write(version);

                writer.Write((int)containers.Count);
                ArrayList offsets = new ArrayList();
                //prepare the Index
                for (int i = 0; i < containers.Count; i++)
                {
                    offsets.Add(writer.BaseStream.Position);
                    containers[i].Save(writer, -1);
                }

                //write the Data
                for (int i = 0; i < containers.Count; i++)
                {
                    long offset = writer.BaseStream.Position;
                    writer.BaseStream.Seek((long)offsets[i], SeekOrigin.Begin);
                    containers[i].Save(writer, (int)offset);
                }
            }
            finally
            {
                si.Close();
            }
        }
Exemplo n.º 30
0
        public void WritePlaylist(StreamWriter sw)
        {
            this.lastRequest = DateTime.Now;

            sw.WriteLine("#EXTM3U");
            sw.WriteLine("#EXT-X-VERSION:3");
            sw.WriteLine("#EXT-X-ALLOW-CACHE:NO");
            sw.WriteLine("#EXT-X-TARGETDURATION:" + this.segmentTime);
            sw.Flush();

            lock (this.objLock)
            {
                while (this.stopped == false && this.lastPlaylistIdx == this.streamItems.Keys.Max())
                {
                    Monitor.Wait(this.objLock);
                }

                sw.WriteLine("#EXT-X-MEDIA-SEQUENCE:" + this.mediaSequence);

                foreach (uint key in this.streamItems.Keys.OrderBy(a => a))
                {
                    StreamItem item = this.streamItems[key];
                    if (!item.Duration.HasValue || (item.FileData == null && key != 0))
                    {
                        break;
                    }

                    sw.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "#EXTINF:{0:0.000000},", item.Duration));
                    sw.WriteLine(string.Format("{0}_{1}.ts", key, this.sessionId));

                    this.lastPlaylistIdx = Math.Max(this.lastPlaylistIdx, key);
                }

                if (this.stopped)
                {
                    sw.WriteLine("#EXT-X-ENDLIST");
                }
            }
        }
Exemplo n.º 31
0
        StreamItem AddStreamItem(string streamName)
        {
            var stream = new StreamItem()
            {
                Enabled = true,
                Name    = streamName,
                Color   = _colors[(_currentColor++)]
            };

            stream.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == "Enabled")
                {
                    var streamItem = (StreamItem)sender;
                    var e          = new StreamChangedEventArgs(streamItem.Name, streamItem.Enabled);
                    OnStreamChanged(e);
                }
            };

            Streams.Add(stream);

            return(stream);
        }
Exemplo n.º 32
0
        public LoggerManager()
            : base(GearsetSettings.Instance.LoggerConfig)
        {
            // Create the back-end collections
            Streams = new ObservableCollection<StreamItem>();
            LogItems = new FixedLengthQueue<LogItem>(500);
            LogItemsOld = new FixedLengthQueue<LogItem>(10000);
            //LogItems.DequeueTarget = LogItemsOld;
            Streams.Add(_defaultStream = new StreamItem { Name = "Default", Enabled = true, Color = _colors[_currentColor++] });

            // Create the window.
            Window = new LoggerWindow();

            Window.Top = Config.Top;
            Window.Left = Config.Left;
            Window.Width = Config.Width;
            Window.Height = Config.Height;
            Window.IsVisibleChanged += logger_IsVisibleChanged;
            Window.SoloRequested += logger_SoloRequested;

            WindowHelper.EnsureOnScreen(Window);

            if (Config.Visible)
                Window.Show();

            FilteredView = CollectionViewSource.GetDefaultView(LogItems);
            FilteredView.Filter = a => ((LogItem)a).Stream.Enabled;
            FilteredView.GroupDescriptions.Add(new PropertyGroupDescription("UpdateNumber"));
            Window.LogListBox.DataContext = FilteredView;
            Window.StreamListBox.DataContext = Streams;

            Window.LocationChanged += logger_LocationChanged;
            Window.SizeChanged += logger_SizeChanged;

            _scrollViewer = GetDescendantByType(Window.LogListBox, typeof(ScrollViewer)) as ScrollViewer;
        }
Exemplo n.º 33
0
 public SoloRequestedEventArgs(StreamItem item)
 {
     this.StreamItem = item;
 }
Exemplo n.º 34
0
        /// <summary>
        ///     Los a message to the specified stream.
        /// </summary>
        /// <param name="streamName">Name of the Stream to log the message to</param>
        /// <param name="message">Message to log</param>
        public void Log(String streamName, String message)
        {
            var stream = SearchStream(streamName);
            // Is it a new stream?
            if (stream == null) {
                stream = new StreamItem {
                    Enabled = !Config.HiddenStreams.Contains(streamName),
                    Name = streamName,
                    Color = _colors[(_currentColor++)]
                };
                stream.PropertyChanged += stream_PropertyChanged;
                Streams.Add(stream);

                // Repeat the colors.
                if (_currentColor >= _colors.Length)
                    _currentColor = 0;
            }

            // Log even if the stream is disabled.
            var logItem = new LogItem { Stream = stream, Content = message, UpdateNumber = GearsetResources.Console.UpdateCount };
            LogItems.Enqueue(logItem);

            if (stream.Enabled)
                _scrollViewer.ScrollToEnd();
        }
Exemplo n.º 35
0
 public void CanReturnTheCorrectStreamLanguage()
 {
     IStreamItem streamItemSUT = new StreamItem("website", "replacement");
     Assert.AreEqual("English", streamItemSUT.StreamLanguage);
 }
Exemplo n.º 36
0
 public void CanReturnTheCorrectUsedOnTypes()
 {
     IStreamItem streamItemSUT = new StreamItem("website", "replacement");
     Assert.AreEqual("Mixed", streamItemSUT.UsedOnTypes);
 }
Exemplo n.º 37
0
 public void CanReturnTheCorrectWebsite()
 {
     const string website = "website";
     IStreamItem streamItemSUT = new StreamItem(website, "replacement");
     Assert.AreEqual(website, streamItemSUT.Website);
 }
Exemplo n.º 38
0
        public void CanExecuteMoveDownCmd()
        {
            IStreamItem expectedStreamItem = new StreamItem("a", "b");
            viewModelSUT.Streams.Add(expectedStreamItem);
            viewModelSUT.Streams.Add(new StreamItem("c", "d"));
            viewModelSUT.SelectedItem = viewModelSUT.Streams[0];

            viewModelSUT.MoveDownCmd.Execute(null);

            Assert.AreEqual(expectedStreamItem, viewModelSUT.Streams[1]);
        }
Exemplo n.º 39
0
        public void CanReturnTheCorrectSelectedItem()
        {
            IStreamItem expectedStreamItem = new StreamItem("a", "b");
            viewModelSUT.SelectedItem = expectedStreamItem;

            Assert.AreEqual(expectedStreamItem, viewModelSUT.SelectedItem);
        }