Пример #1
0
        public void LoadLibrary(PortableLibrary portableLibrary, Stream sourceStream, int length)
        {
            var path = GetLibraryPath(portableLibrary);

            using (var fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write))
                sourceStream.CopyToEx(fileStream, length); //explicit really important, else the FW version of CopyTo will be used -> f*****g error in 1.8

            LoadLibrary(path, portableLibrary);
        }
Пример #2
0
        public MainPage()
        {
            InitializeComponent();

            HttpWebRequest.RegisterPrefix("http://", new Handler());
            HttpWebRequest.RegisterPrefix("https://", new Handler());

            PortableLibrary.populateDataAsync(item => this.tree.Items.Add(item));
        }
Пример #3
0
        private static string GetLibraryPath(PortableLibrary library)
        {
            var libraryName = GetFilenameByLibrary(library);

            var libraryDirectory = new DirectoryInfo(Consts.LibrariesDirectory);

            if (!libraryDirectory.Exists)
            {
                libraryDirectory.Create();
                return(Path.Combine(libraryDirectory.FullName, libraryName));
            }

            var libraryNameWithoutExtension = Path.GetFileNameWithoutExtension(libraryName);

            var regex = new Regex("^" + libraryNameWithoutExtension + "(_(?<number>([0-9]{1,2})))?\\.dll");

            var existingLibraries =
                libraryDirectory.GetFiles(libraryNameWithoutExtension + "*.dll", SearchOption.TopDirectoryOnly)
                .Select(x => new PortableLibraryMatch(regex.Match(x.Name), x)).ToList();

            if (existingLibraries.Count > 0)
            {
                //remove unused libraries
                for (int j = existingLibraries.Count - 1; j >= 0; j--)
                {
                    try
                    {
                        existingLibraries[j].FileInfo.Delete();
                        existingLibraries.RemoveAt(j);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }

                var rootFile = new FileInfo(Path.Combine(Consts.LibrariesDirectory, libraryName));
                if (!rootFile.Exists)
                {
                    return(rootFile.FullName);
                }
                else
                {
                    var highestNumber =
                        existingLibraries.Where(x => !string.IsNullOrEmpty(x.Match.Groups["number"].Value))
                        .Select(x => int.Parse(x.Match.Groups["number"].Value))
                        .OrderByDescending(x => x)
                        .First();
                    highestNumber++;
                    return(Path.Combine(Consts.LibrariesDirectory, libraryNameWithoutExtension + "_" + highestNumber + ".dll"));
                }
            }

            return(Path.Combine(Consts.LibrariesDirectory, libraryName));
        }
Пример #4
0
        public SampleDataSource()
        {
            int i = 0;

            PortableLibrary.populateDataAsync(item =>
            {
                var group = new SampleDataGroup(i++.ToString(), item.Title, item.SubTitle, null, item.Description);
                foreach (var subItem in item.SubItems)
                {
                    group.Items.Add(new SampleDataItem(i++.ToString(), subItem.Title, subItem.SubTitle, null, subItem.Description, subItem.Content, group));
                }
                AllGroups.Add(group);
            });
        }
Пример #5
0
        public async Task SendCommand(Command command, byte[] data,
                                      PackageCompression packageCompression = PackageCompression.Auto)
        {
            if (command.Identifier > 1000)
            {
                if (!await PreparePlugin(command.Identifier))
                {
                    return;
                }
            }

            var commandSettings = _commander.GetCommandSettings(command);

            if (commandSettings.Libraries.Count > 0)
            {
                PortableLibrary libraries = commandSettings.Libraries[0];
                for (int i = 1; i < commandSettings.Libraries.Count; i++)
                {
                    libraries |= commandSettings.Libraries[i];
                }

                if (!await LoadLibraries(libraries))
                {
                    return;
                }
            }

            Sender.UnsafeSendCommand(ClientInformation.Id, command.Identifier, new WriterCall(data));

            PackageSent?.Invoke(this, new PackageInformation
            {
                IsReceived  = false,
                Size        = data.Length + 9,
                Timestamp   = DateTime.Now,
                Description = "SendCommand " + Commander.GetCommandDescription(command, data, false)
            });
        }
Пример #6
0
 /// <summary>
 ///     Initialize a new instance of <see cref="ProvideLibraryAttribute" />
 /// </summary>
 /// <param name="library">The library to transmit</param>
 public ProvideLibraryAttribute(PortableLibrary library)
 {
     Library = library;
 }
Пример #7
0
        private async Task <bool> LoadLibraries(PortableLibrary libraries)
        {
            libraries = libraries & ~_loadedLibraries;

            var sendingService = (Sender)Sender;
            var libraryInfos   =
                EnumUtilities.GetUniqueFlags <PortableLibrary>(libraries)
                .Where(x => x != 0)
                .Select(x =>
            {
                var filename = GetFilenameByLibrary(x);
                return(new LocalLibraryInfo(x)
                {
                    Path = File.Exists(filename) ? filename : Path.Combine(LibrariesPath, filename)
                });
            }).ToList();

            if (libraryInfos.Count == 0)
            {
                return(true);
            }

            using (var md5 = new MD5CryptoServiceProvider())
                foreach (var libraryInfo in libraryInfos)
                {
                    using (
                        var fileStream = new FileStream(libraryInfo.Path, FileMode.Open,
                                                        FileAccess.Read)
                        )
                        libraryInfo.Hash = md5.ComputeHash(fileStream);
                }

            using (var autoResetEvent = new AutoResetEvent(false))
            {
                var neededLibraries = PortableLibrary.None;
                EventHandler <LibraryInformationEventArgs> libraryInformationReceiedHandler = (sender, args) =>
                {
                    if (args.ClientId == ClientInformation.Id)
                    {
                        neededLibraries = args.Libraries;
                        autoResetEvent.Set();
                    }
                };

                _connectionManager.LibraryInformationReceived += libraryInformationReceiedHandler;

                sendingService.OpenClientRedirect(ClientInformation.Id, ClientRedirectOptions.IncludeAdministrationId,
                                                  FromAdministrationPackage.RequestLibraryInformation, 4 + 16 * libraryInfos.Count,
                                                  writer =>
                {
                    writer.Write(BitConverter.GetBytes((int)libraries));
                    foreach (var libraryHash in libraryInfos)
                    {
                        writer.Write(libraryHash.Hash);
                    }
                });

                PackageSent?.Invoke(this, new PackageInformation
                {
                    Description = $"ConnectionInfo CheckLibraries ({libraries})",
                    IsReceived  = false,
                    Size        = 4 + 16 * libraryInfos.Count + 14,
                    Timestamp   = DateTime.Now
                });

                try
                {
                    if (!await Task.Run(() => autoResetEvent.WaitOne(20000)))
                    {
                        return(false);
                    }
                }
                finally
                {
                    _connectionManager.LibraryInformationReceived -= libraryInformationReceiedHandler;
                }

                if (neededLibraries == PortableLibrary.None)
                {
                    _loadedLibraries |= neededLibraries;
                    return(true);
                }

                autoResetEvent.Reset();

                var librariesToSend = libraryInfos.Where(x => (neededLibraries & x.Library) == x.Library).ToList();
                await _connectionManager.SendLibraries(librariesToSend, ClientInformation.Id);

                var loadedLibraries = PortableLibrary.None;
                EventHandler <LibraryInformationEventArgs> libraryLoadingResultHandler = (sender, args) =>
                {
                    if (args.ClientId == ClientInformation.Id)
                    {
                        loadedLibraries = args.Libraries;
                        autoResetEvent.Set();
                    }
                };

                _connectionManager.LibraryLoadingResultReceived += libraryLoadingResultHandler;
                try
                {
                    if (!await Task.Run(() => autoResetEvent.WaitOne(20000)))
                    {
                        return(false);
                    }
                }
                finally
                {
                    _connectionManager.LibraryLoadingResultReceived -= libraryLoadingResultHandler;
                }

                _loadedLibraries |= loadedLibraries;
                return(loadedLibraries == neededLibraries);
            }
        }
Пример #8
0
 private static string GetFilenameByLibrary(PortableLibrary library)
 {
     return(library.GetAttributeOfType <PortableLibraryNameAttribute>()?.Name);
 }
Пример #9
0
 public MainPage()
 {
     InitializeComponent();
     PortableLibrary.populateDataAsync(item => this.listBox.Items.Add(item));
 }
Пример #10
0
 public LocalLibraryInfo(PortableLibrary library)
 {
     Library = library;
 }
Пример #11
0
 public LibraryInformationEventArgs(int clientId, PortableLibrary libraries)
 {
     ClientId  = clientId;
     Libraries = libraries;
 }
Пример #12
0
 private void LoadLibrary(string path, PortableLibrary library)
 {
     LoadedLibraries |= library;
     Assembly.LoadFile(path);
 }
Пример #13
0
        public PortableLibrary CheckLibraries(PortableLibrary libraries, List <byte[]> hashes)
        {
            var libraryDirectory = new DirectoryInfo(Consts.LibrariesDirectory);

            if (!libraryDirectory.Exists)
            {
                return(libraries);
            }

            var missingLibraries = PortableLibrary.None;
            var libraryList      = libraries.GetUniqueFlags <PortableLibrary>().Where(x => x != 0).ToList();

            var regex        = new Regex("^(?<name>(.+?))(_(?<number>([0-9]{1,2})))?\\.dll");
            var regexMatches =
                libraryDirectory.GetFiles("*.dll", SearchOption.TopDirectoryOnly)
                .Select(x => new PortableLibraryMatch(regex.Match(x.Name), x)).ToList();

            using (var md5 = new MD5CryptoServiceProvider())
                for (int i = 0; i < libraryList.Count; i++)
                {
                    var library           = libraryList[i];
                    var libraryName       = GetFilenameByLibrary(library);
                    var existingLibraries = regexMatches.Where(x => x.Match.Groups["name"].Value + ".dll" == libraryName).ToList();

                    if (existingLibraries.Count > 0)
                    {
                        string libraryPath;

                        //that might be the root library
                        if (existingLibraries.Count == 1)
                        {
                            libraryPath = existingLibraries[0].FileInfo.FullName;
                        }
                        else
                        {
                            //search in the numbered libraries the latest (= highest number)
                            libraryPath =
                                existingLibraries.Where(x => !string.IsNullOrEmpty(x.Match.Groups["number"].Value))
                                .OrderByDescending(x => int.Parse(x.Match.Groups["number"].Value))
                                .First()
                                .FileInfo.FullName;
                        }

                        using (var fileStream = new FileStream(libraryPath, FileMode.Open, FileAccess.Read))
                        {
                            var hash = md5.ComputeHash(fileStream);
                            if (hash.SequenceEqual(hashes[i]))
                            {
                                try
                                {
                                    LoadLibrary(libraryPath, library);
                                    continue; //exists
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }
                        }
                    }

                    missingLibraries |= libraryList[i];
                }

            return(missingLibraries);
        }