Exemplo n.º 1
0
        private static StorageProviderItem CreateStorageProviderItem(StorageProviderItem parent, Metadata item)
        {
            var result = new StorageProviderItem
            {
                Name = item.Name,
                Id = Path.Combine(parent.Id, item.PathLower),
                ParentReferenceId = parent.Id
            };

            if (item.IsFile)
            {
                result.Type = StorageProviderItemType.File;
//                result.Id = item.AsFile.Id; // Path.Combine(parent.Id, item.PathLower)
                result.LastModifiedDateTime = item.AsFile.ServerModified;
            }
            else if (item.IsFolder)
            {
                result.Type = StorageProviderItemType.Folder;
//                result.Id = item.AsFolder.Id; // Path.Combine(parent.Id, item.PathLower);
            }
            else
            {
                result.Type = StorageProviderItemType.Unknown;
            }

            return result;
        }
Exemplo n.º 2
0
 public Asset (string name, string desc, Model[] models, Metadata data, Location location) {
     this.name = name;
     this.desc = desc;
     this.models = models;
     this.data = data;
     this.location = location;
 }
Exemplo n.º 3
0
		public TextExtractionResult Extract(Func<Metadata, InputStream> streamFactory)
		{
			try
			{
				var parser = new AutoDetectParser();
				var metadata = new Metadata();
				var outputWriter = new StringWriter();
				var parseContext = new ParseContext();

                //use the base class type for the key or parts of Tika won't find a usable parser
				parseContext.set(typeof(org.apache.tika.parser.Parser), parser);
				
				using (var inputStream = streamFactory(metadata))
				{
					try
					{
						parser.parse(inputStream, getTransformerHandler(outputWriter), metadata, parseContext);
					}
					finally
					{
						inputStream.close();
					}
				}

				return assembleExtractionResult(outputWriter.ToString(), metadata);
			}
			catch (Exception ex)
			{
				throw new TextExtractionException("Extraction failed.", ex);
			}
		}
Exemplo n.º 4
0
        /// <summary>
        /// The order mapping is a file named order in the same virtual path.
        /// </summary>
        private static Func<string, Metadata> GetMetadataMapping(string virtualPath) {
            var vpp = HostingEnvironment.VirtualPathProvider;
            string metadataFile = VirtualPathUtility.AppendTrailingSlash(virtualPath) + MetadataFile;

            var mapping = new Dictionary<string, Metadata>();
            int index = 0;
            if (vpp.FileExists(metadataFile)) {
                VirtualFile file = vpp.GetFile(metadataFile);
                Stream stream = file.Open();
                using (var reader = new StreamReader(stream)) {
                    string line = null;
                    while ((line = reader.ReadLine()) != null) {
                        mapping[Normalize(line)] = new Metadata {
                            Order = index++
                        };
                    }
                }
            }

            return title => {
                Metadata metadata;
                if (mapping.TryGetValue(title, out metadata)) {
                    return metadata;
                }
                return Metadata.Empty;
            };
        }
Exemplo n.º 5
0
			public Asset (string name, string desc, Model[] models, Metadata data) {
				this.name = name;
				this.desc = desc;
				this.models = models;
				this.data = data;
                location = new Location();
			}
 public void Should_Schedule_Reconnections_In_The_Background()
 {
     var lbp = new RoundRobinPolicy();
     var config = new Configuration(
         new Cassandra.Policies(lbp, new ConstantReconnectionPolicy(1000), FallthroughRetryPolicy.Instance),
         new ProtocolOptions(),
         null,
         new SocketOptions(),
         new ClientOptions(),
         NoneAuthProvider.Instance,
         null,
         new QueryOptions(),
         new DefaultAddressTranslator());
     var testCluster = TestClusterManager.GetNonShareableTestCluster(1, DefaultMaxClusterCreateRetries, true, false);
     var metadata = new Metadata(config);
     metadata.AddHost(new IPEndPoint(IPAddress.Parse(testCluster.InitialContactPoint), ProtocolOptions.DefaultPort));
     var clusterMock = new Mock<ICluster>();
     clusterMock.Setup(c => c.AllHosts()).Returns(() => metadata.Hosts.ToCollection());
     lbp.Initialize(clusterMock.Object);
     using (var cc = NewInstance(testCluster, config, metadata))
     {
         cc.Init();
         var host = metadata.Hosts.First();
         testCluster.Stop(1);
         host.SetDown();
         Thread.Sleep(2000);
         Assert.False(host.IsUp);
         testCluster.Start(1);
         host.BringUpIfDown();
         //Should reconnect using timer
         Thread.Sleep(5000);
         Assert.DoesNotThrow(() => cc.Query("SELECT key FROM system.local", false));
     }
     testCluster.ShutDown();
 }
Exemplo n.º 7
0
        public async Task<Metadata> SaveData(StoreLocation location, Metadata metadata, UpdateAuditInfo audit, Func<IWriteAsyncStream, Task<long?>> savingFunc, CancellationToken token)
        {
            var current = await GetMetadata(location).ConfigureAwait(false);

            var info = current == null ? new AuditInfo() : current.Audit;
            info.UpdatedBy = audit == null ? "0" : audit.UpdatedBy;
            info.UpdatedByName = audit == null ? string.Empty : audit.UpdatedByName;
            info.UpdatedOn = DateTime.UtcNow;

            info.CreatedBy = info.CreatedBy ?? info.UpdatedBy;
            info.CreatedByName = info.CreatedByName ?? info.UpdatedByName;
            info.CreatedOn = info.CreatedOn ?? info.UpdatedOn;

            metadata = metadata ?? new Metadata();
            metadata.Audit = info;

            var key = GetObjectKey(location);
            long? length = null;
            using(var stream = new AmazonMultiUploadStream(_client, _bucket, key, metadata))
            {
                length = await savingFunc(stream).ConfigureAwait(false);
                await stream.Complete(token).ConfigureAwait(false);
                metadata.Snapshot = stream.VersionId;
            }

            if (length.HasValue && (metadata == null || !metadata.ContentLength.HasValue))
            {
                metadata[MetadataConstants.ContentLengthMetadataKey] = length.Value.ToString(CultureInfo.InvariantCulture);

                // Save the length straight away before the snapshot...
                metadata = await SaveMetadata(location, metadata).ConfigureAwait(false);
            }

            return metadata;
        }
Exemplo n.º 8
0
		public void TestConstructFromDictionary1()
		{
			string owner = "Washington State University Libraries";
			string ownerGroup = "Washington State University";
			string[] coOwners = { "CoOwner1", "CoOwner2" };
			long created = DateTime.Now.ToBinary();
			long updated = DateTime.Now.AddDays(1).ToBinary();
			string target = "http://wsulibs.wsu.edu/";
			string status = Metadata.MetadataStatus.Public;

			IDictionary<string, string> map = new Dictionary<string, string>();
			map.Add(Metadata.MetadataKeys.Owner, owner);
			map.Add(Metadata.MetadataKeys.OwnerGroup, ownerGroup);
			map.Add(Metadata.MetadataKeys.CoOwners, string.Join(";", coOwners));
			map.Add(Metadata.MetadataKeys.Created, created.ToString());
			map.Add(Metadata.MetadataKeys.Updated, updated.ToString());
			map.Add(Metadata.MetadataKeys.Target, target);
			map.Add(Metadata.MetadataKeys.Status, status);

			Metadata metadata = new Metadata(map);

			Assert.IsTrue(metadata.Owner == owner);
			Assert.IsTrue(metadata.OwnerGroup == ownerGroup);
			Assert.IsTrue(metadata.CoOwners.Count == coOwners.Length);
			Assert.IsTrue(metadata.CoOwners[0] == coOwners[0]);
			Assert.IsTrue(metadata.CoOwners[1] == coOwners[1]);
			Assert.IsTrue(metadata.Created == created);
			Assert.IsTrue(metadata.Updated == updated);
			Assert.IsTrue(metadata.Target == target);
			Assert.IsTrue(metadata.Status == status);
		}
Exemplo n.º 9
0
 public unsafe PdbInfo(IO.FileStream inputStream, Metadata.Reader reader)
 {
   this.reader = reader;
   this.pdbFunctionMap = PdbFile.LoadFunctionMap(inputStream, out tokenToSourceMapping, out sourceServerData, reader);
   //inputStream.Seek(0L, IO.SeekOrigin.Begin);
   //this.remapTable = PdbFile.LoadRemapTable(inputStream);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UpdateMetadataRequest"/> class
        /// with the given metadata.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="metadata"/> is <c>null</c>.</exception>
        public UpdateMetadataRequest(Metadata metadata)
        {
            if (metadata == null)
                throw new ArgumentNullException("metadata");

            Metadata = metadata;
        }
Exemplo n.º 11
0
        public TextExtractionResult Extract(Func<Metadata, InputStream> streamFactory)
        {
            try
            {
                var parser = new AutoDetectParser();
                var metadata = new Metadata();
                var parseContext = new ParseContext();

                //use the base class type for the key or parts of Tika won't find a usable parser
                parseContext.set(typeof(Parser), parser);

                var content = new System.IO.StringWriter();
                var contentHandlerResult = new TextExtractorContentHandler(content);

                using (var inputStream = streamFactory(metadata))
                {
                    try
                    {
                        parser.parse(inputStream, contentHandlerResult, metadata, parseContext);
                    }
                    finally
                    {
                        inputStream.close();
                    }
                }

                return AssembleExtractionResult(content.ToString(), metadata);
            }
            catch (Exception ex)
            {
                throw new TextExtractionException("Extraction failed.", ex);
            }
        }
Exemplo n.º 12
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            FindViewById<Button> (Resource.Id.NotifyButton).Click += delegate {
                String empty = null;
                try {
                    empty.Contains ("null exception");
                } catch (Exception e) {
                    // You can add extra metadata to the error report to better debug it.
                    // This information will show up in the Bugsnag web app.
                    var md = new Metadata ();
                    md.AddToTab ("Tab1", "key1", "value1");
                    md.AddToTab ("Tab1", "key2", "value2");

                    // Send the error to bugsnag
                    AndroidApp.BugsnagClient.Notify (e, ErrorSeverity.Warning, md);
                }
            };

            FindViewById<Button> (Resource.Id.CrashButton).Click += delegate {
                // When the application crashes, Bugsnag library intercepts the error, writes it to disk and
                // submits it next time the application starts.
                throw new NotSupportedException ("Crash ahoy!");
            };
        }
Exemplo n.º 13
0
        public void DefaultCtorSplitsAtDashes()
        {
            // Given
            Engine engine = new Engine();
            Metadata metadata = new Metadata(engine);
            Pipeline pipeline = new Pipeline("Pipeline", engine, null);
            IExecutionContext context = new ExecutionContext(engine, pipeline);
            IDocument[] inputs = { new Document(metadata).Clone(@"FM1
            FM2
            ---
            Content1
            Content2") };
            string frontMatterContent = null;
            FrontMatter frontMatter = new FrontMatter(new Execute(x =>
            {
                frontMatterContent = x.Content;
                return new [] {x};
            }));

            // When
            IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context);

            // Then
            Assert.AreEqual(1, documents.Count());
            Assert.AreEqual(@"FM1
            FM2
            ", frontMatterContent);
            Assert.AreEqual(@"Content1
            Content2", documents.First().Content);
        }
Exemplo n.º 14
0
		public MetadataEditorDialog(Metadata originalMetaData)
		{
			_originalMetaData = originalMetaData;
			InitializeComponent();
			_metadataEditorControl.Metadata = _returnMetaData = originalMetaData.DeepCopy();
			ShowCreator = true;
		}
Exemplo n.º 15
0
 public MachineParamsManager(Guid plowmachineId, Metadata.MetadataManager manager)
 {
     _plowMachineId = plowmachineId;
     _manager = manager;
     _connection = DBConnectionProvider.GetConnection();
     _connection.Open();
 }
 public AmazonMultiUploadStream(AmazonS3Client client, string bucket, string key, Metadata metadata)
 {
     _client = client;
     _bucket = bucket;
     _key = key;
     _metadata = metadata;
 }
Exemplo n.º 17
0
            ushort GetStructDef(Type type, Metadata metadata, Metadata[] fields)
            {
                var index = Schema.structs.Count;
                var structDef = new StructDef();
                Schema.structs.Add(structDef);
                structDef.metadata = metadata;

                var baseType = type.GetBaseSchemaType();
                if (baseType != null)
                    structDef.base_def = GetTypeDef(baseType);

                var i = 0;
                foreach (var field in type.GetSchemaFields())
                {
                    var fieldDef = new FieldDef
                    {
                        id = field.Id,
                        metadata = fields[i++],
                        type = GetTypeDef(field.GetSchemaType())
                    };

                    structDef.fields.Add(fieldDef);
                }

                return (ushort) index;
            }
Exemplo n.º 18
0
    /// <summary>
    /// Gets the metadata link tag.
    /// </summary>
    /// <param name="metadata">The metadata.</param>
    /// <param name="metadataListPage">Metadata filtered list page, can be null.</param>
    /// <returns></returns>
    public static string GetMetadataLinkTag(Metadata metadata, Page metadataListPage)
    {
        string tag = string.Empty;

        if (metadata == null)
            return string.Empty;

        if (metadataListPage == null)
        {
            metadataListPage = Litium.Plus.Utilities.PageUtilities.GetFirstPublishedPageTypeInstance("MetadataFilteredList", CurrentState.Current.WebSiteID, Litium.Foundation.GUI.FoundationContext.Current.Token);
        }

        string metadataTranslation = metadata.Translations.GetMetadataTranslation(CurrentState.Current.WebSite.Culture).Translation;

        if (string.IsNullOrEmpty(metadataTranslation))
            return string.Empty;

        if (metadataListPage == null)
        {
            tag = "<span class=\"metadataSpanTag\">" + metadataTranslation + "</span>";
        }
        else
        {
            string linkTag = string.Format("<a href=\"{0}?MetadataID={1}\">{2}</a>", metadataListPage.GetUrlToPage(), metadata.ID, metadata.Translations.GetMetadataTranslation(CurrentState.Current.WebSite.Culture).Translation);
            tag = "<span class=\"metadataSpanTag\">" + linkTag + "</span>";
        }

        return tag;
    }
Exemplo n.º 19
0
 public static void SetMetadata(this NetInfo prefab, Metadata metadata)
 {
     if (metadata.info != prefab)
     {
         throw new Exception("NoPillars: wrong metadata!");
     }
     prefab.m_canCollide = metadata.collide;
     var r2 = prefab.m_netAI as RoadAI;
     if (r2 != null)
     {
         r2.m_enableZoning = metadata.zoning;
     }
     if (Pillars.networkSkinsEnabled)
     {
         return;
     }
     var ta = prefab.m_netAI as TrainTrackBridgeAI;
     if (ta != null)
     {
         ta.m_bridgePillarInfo = metadata.bpi;
         ta.m_middlePillarInfo = metadata.bmi;
     }
     var ra = prefab.m_netAI as RoadBridgeAI;
     if (ra != null)
     {
         ra.m_bridgePillarInfo = metadata.bpi;
         ra.m_middlePillarInfo = metadata.bmi;
     }
     var pa = prefab.m_netAI as PedestrianBridgeAI;
     if (pa != null)
     {
         pa.m_bridgePillarInfo = metadata.bpi;
     }
 }
Exemplo n.º 20
0
 public static Metadata GetMetadata(this NetInfo prefab)
 {
     var mNetAi = prefab.m_netAI;
     var si = new Metadata
     {
         collide = prefab.m_canCollide,
         info = prefab
     };
     var ta = mNetAi as TrainTrackBridgeAI;
     if (ta != null)
     {
         si.bpi = ta.m_bridgePillarInfo;
         si.bmi = ta.m_middlePillarInfo;
     }
     var ra = mNetAi as RoadBridgeAI;
     if (ra != null)
     {
         si.bpi = ra.m_bridgePillarInfo;
         si.bmi = ra.m_middlePillarInfo;
     }
     var pa = mNetAi as PedestrianBridgeAI;
     if (pa != null)
     {
         si.bpi = pa.m_bridgePillarInfo;
     }
     var r2 = mNetAi as RoadAI;
     if (r2 != null)
     {
         si.zoning = r2.m_enableZoning;
     }
     return si;
 }
Exemplo n.º 21
0
        public void DashStringDoesNotSplitAtNonmatchingDashes()
        {
            // Given
            Engine engine = new Engine();
            Metadata metadata = new Metadata(engine);
            Pipeline pipeline = new Pipeline("Pipeline", engine, null);
            IExecutionContext context = new ExecutionContext(engine, pipeline);
            IDocument[] inputs = { new Document(metadata).Clone(@"FM1
            FM2
            ---
            Content1
            Content2") };
            bool executed = false;
            FrontMatter frontMatter = new FrontMatter("-", new Execute(x =>
            {
                executed = true;
                return new[] { x };
            }));

            // When
            IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context);

            // Then
            Assert.AreEqual(1, documents.Count());
            Assert.IsFalse(executed);
            Assert.AreEqual(@"FM1
            FM2
            ---
            Content1
            Content2", documents.First().Content);
        }
        public void Test_AmoebaConverter_Box()
        {
            var key = new Key(HashAlgorithm.Sha256, new byte[32]);
            var metadata = new Metadata(1, key, CompressionAlgorithm.Xz, CryptoAlgorithm.Aes256, new byte[32 + 32]);
            var seed = new Seed(metadata);
            seed.Name = "aaaa.zip";
            seed.Keywords.AddRange(new KeywordCollection
                {
                    "bbbb",
                    "cccc",
                    "dddd",
                });
            seed.CreationTime = DateTime.Now;
            seed.Length = 10000;

            var box = new Box();
            box.Name = "Box";
            box.Seeds.Add(seed);
            box.Boxes.Add(new Box() { Name = "Box" });

            Box box2;

            using (var streamBox = AmoebaConverter.ToBoxStream(box))
            {
                box2 = AmoebaConverter.FromBoxStream(streamBox);
            }

            Assert.AreEqual(box, box2, "AmoebaConverter #3");
        }
Exemplo n.º 23
0
 static void Assign(Metadata to, Metadata from)
 {
     foreach (var kvp in from)
     {
         to.Add(kvp.Key, kvp.Value);
     }
 }
 public void UpdatePeersInfoModifiesPool()
 {
     var metadata = new Metadata(new Configuration());
     var cc = NewInstance(metadata);
     cc.Host = TestHelper.CreateHost("127.0.0.1");
     metadata.AddHost(cc.Host.Address);
     var hostAddress2 = IPAddress.Parse("127.0.0.2");
     var hostAddress3 = IPAddress.Parse("127.0.0.3");
     var rows = TestHelper.CreateRows(new List<Dictionary<string, object>>
     {
         new Dictionary<string, object>{{"rpc_address", hostAddress2}, {"peer", null}, { "data_center", "ut-dc2" }, { "rack", "ut-rack2" }, {"tokens", null}},
         new Dictionary<string, object>{{"rpc_address", IPAddress.Parse("0.0.0.0")}, {"peer", hostAddress3}, { "data_center", "ut-dc3" }, { "rack", "ut-rack3" }, {"tokens", null}}
     });
     cc.UpdatePeersInfo(rows);
     Assert.AreEqual(3, metadata.AllHosts().Count);
     //using rpc_address
     var host2 = metadata.GetHost(new IPEndPoint(hostAddress2, ProtocolOptions.DefaultPort));
     Assert.NotNull(host2);
     Assert.AreEqual("ut-dc2", host2.Datacenter);
     Assert.AreEqual("ut-rack2", host2.Rack);
     //with rpc_address = 0.0.0.0, use peer
     var host3 = metadata.GetHost(new IPEndPoint(hostAddress3, ProtocolOptions.DefaultPort));
     Assert.NotNull(host3);
     Assert.AreEqual("ut-dc3", host3.Datacenter);
     Assert.AreEqual("ut-rack3", host3.Rack);
 }
Exemplo n.º 25
0
        public static List<IWriteFile> ReadHeader(string path)
        {
            List<IWriteFile> subfiles = null;
            using (BinaryReader reader = new BinaryReader(File.OpenRead(path)))
            {
                if (!VerifyHeader(path))
                    throw new InvalidDataException("The supplied file is not a PP archive.");

                byte[] versionHeader = reader.ReadBytes(8);
                int version = BitConverter.ToInt32(DecryptHeaderBytes(reader.ReadBytes(4)), 0);

                DecryptHeaderBytes(reader.ReadBytes(1));  // first byte
                int numFiles = BitConverter.ToInt32(DecryptHeaderBytes(reader.ReadBytes(4)), 0);

                byte[] buf = DecryptHeaderBytes(reader.ReadBytes(numFiles * 288));

                subfiles = new List<IWriteFile>(numFiles);
                for (int i = 0; i < numFiles; i++)
                {
                    int offset = i * 288;
                    ppSubfile subfile = new ppSubfile(path);
                    subfile.Name = Utility.EncodingShiftJIS.GetString(buf, offset, 260).TrimEnd(new char[] { '\0' });
                    subfile.size = BitConverter.ToUInt32(buf, offset + 260);
                    subfile.offset = BitConverter.ToUInt32(buf, offset + 264);

                    Metadata metadata = new Metadata();
                    metadata.LastBytes = new byte[20];
                    System.Array.Copy(buf, offset + 268, metadata.LastBytes, 0, 20);
                    subfile.Metadata = metadata;

                    subfiles.Add(subfile);
                }
            }
            return subfiles;
        }
Exemplo n.º 26
0
 private static string GetDataTypeName(Metadata metadata)
 {
     if (metadata.Hidden.HasValue && metadata.Hidden.Value)
     {
         return "HiddenInput";
     }
     return metadata.DataTypeName;
 }
Exemplo n.º 27
0
 static string GetTemplateHint(Metadata metadata)
 {
     if (metadata.Hidden.HasValue && metadata.Hidden.Value)
     {
         return "HiddenInput";
     }
     return metadata.TemplateHint;
 }
Exemplo n.º 28
0
 private Metadata         metadata;    // the metadata assoc w/ raster
 
 /// <summary>
 /// No arg constructor
 /// </summary>
 /// <remark>
 /// Used before calling Read()
 /// </remark>
 public ImageHeader()
 {
     this.dimensions = new Dimensions(0,0);
     this.bandType = System.TypeCode.Byte;
     this.bandSize = 0;
     this.bandCount = 0;
     this.metadata = new Metadata();
 }
        protected string GetMetadataTranslation(Metadata metadata)
        {
            MetadataTranslation translation = metadata.Translations.GetMetadataTranslation(FoundationContext.Culture);
            string trans = "No translation available for " + FoundationContext.Culture.IetfLanguageTag;
            if (translation != null)
                trans = translation.Translation;

            return trans;
        }
Exemplo n.º 30
0
 protected void WriteData(StoreLocation location, Metadata m, byte[] data)
 {
     var ct = CancellationToken.None;
     _store.SaveData(location, m, null, async (s) =>
     {
         await s.WriteAsync(data, 0, data.Length, ct).ConfigureAwait(false);
         return data.Length;
     }, ct).Wait();
 }
Exemplo n.º 31
0
 public VariableDeclarationsInspector(Metadata metadata) : base(metadata)
 {
 }
Exemplo n.º 32
0
 public ContentSeriesInfo(string name, string link, string img)
 {
     Metadata.Add("name", name);
     Metadata.Add("link", link);
     Metadata.Add("img", img);
 }
Exemplo n.º 33
0
        public IEnumerable <Metadata> Transform(Metadata metadata, TransformOptions opts)
        {
            if (metadata.Vref != null && metadata.Vref.Source == "ksp-avc")
            {
                var json = metadata.Json();

                Log.InfoFormat("Executing internal AVC transformation with {0}", metadata.Kref);
                Log.DebugFormat("Input metadata:{0}{1}", Environment.NewLine, json);

                var noVersion = metadata.Version == null;

                if (noVersion)
                {
                    json["version"] = "0"; // TODO: DBB: Dummy version necessary to the next statement doesn't throw
                }

                var mod = CkanModule.FromJson(json.ToString());

                if (noVersion)
                {
                    json.Remove("version");
                }

                var file = _http.DownloadPackage(metadata.Download, metadata.Identifier, metadata.RemoteTimestamp);
                var avc  = _moduleService.GetInternalAvc(mod, file, metadata.Vref.Id);

                if (avc != null)
                {
                    Log.Info("Found internal AVC version file");

                    var remoteUri = GetRemoteAvcUri(avc);

                    if (remoteUri != null)
                    {
                        try
                        {
                            var remoteJson = _github?.DownloadText(remoteUri)
                                             ?? _http.DownloadText(remoteUri);
                            var remoteAvc = JsonConvert.DeserializeObject <AvcVersion>(remoteJson);

                            if (avc.version.CompareTo(remoteAvc.version) == 0)
                            {
                                // Local AVC and Remote AVC describe the same version, prefer
                                Log.Info("Remote AVC version file describes same version as local AVC version file, using it preferrentially.");
                                avc = remoteAvc;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.InfoFormat("An error occured fetching the remote AVC version file, ignoring: {0}", e.Message);
                            Log.Debug(e);
                        }
                    }

                    ApplyVersions(json, avc);

                    // It's cool if we don't have version info at all, it's optional in the AVC spec.

                    Log.DebugFormat("Transformed metadata:{0}{1}", Environment.NewLine, json);
                }

                yield return(new Metadata(json));
            }
            else
            {
                yield return(metadata);
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Forwards the email to the relay email address.
        /// </summary>
        /// <param name="mimeMessage">The MIME message.</param>
        public void ForwardEmail(MimeMessage mimeMessage)
        {
            Metadata metadata = MetadataFactory.GenerateFrom(mimeMessage);
            // Add tags to the subject
            string      subject    = mimeMessage.Subject;
            IEmailEntry emailEntry = emailEntryCache.Get(toCache.Get(mimeMessage));

            if (!string.IsNullOrEmpty(emailEntry?.Tag))
            {
                metadata.Tag = emailEntry.Tag;
                subject      = $"[{emailEntry.Tag}] {subject}";
            }

            Email email = new Email(
                new System.Net.Mail.MailAddress(_options.GetSender()),
                new System.Net.Mail.MailAddress(_options.RelayEmail))
            {
                Subject = subject,
            };

            foreach (MimeEntity mimeEntity in mimeMessage.BodyParts)
            {
                if (mimeEntity.IsAttachment)
                {
                    if (!(mimeEntity is MimePart mimePart))
                    {
                        continue;
                    }

                    Attachment temporaryAttachment;
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        mimePart.Content.DecodeTo(memoryStream);
                        memoryStream.Seek(0, SeekOrigin.Begin);

                        temporaryAttachment = new TemporaryAttachment(memoryStream)
                        {
                            DisplayFileName = mimePart.FileName,
                            ContentType     = mimePart.ContentType.MimeType,
                            Encoding        = mimePart.ContentTransferEncoding.GetRaw(),
                        };
                    }

                    email.Attachments.Add(temporaryAttachment);
                }
                else if (mimeEntity is TextPart textPart)
                {
                    string text = textPart.Text;
                    if (textPart.ContentType.MimeType == Constants.TextMimeType)
                    {
                        text = MetadataSerializer.SerializeForText(metadata, text);
                    }
                    else if (textPart.ContentType.MimeType == Constants.HtmlMimeType)
                    {
                        text = MetadataSerializer.SerializeForHtml(metadata, text);
                    }

                    email.TextContents.Add(
                        new Text()
                    {
                        RawText  = text,
                        MimeType = textPart.ContentType.MimeType,
                        Charset  = textPart.ContentType.Charset,
                    });
                }
            }

            _sender.SendEmail(email);

            emailEntryCache.Clear();
            toCache.Clear();
        }
Exemplo n.º 35
0
 public Sku()
 {
     this.Attributes = new Metadata();
     this.Metadata   = new Metadata();
 }
Exemplo n.º 36
0
 public UnitButtonInspector(Metadata metadata) : base(metadata)
 {
 }
Exemplo n.º 37
0
 public void RemoveCustom(BEncodedString key)
 {
     Check.Key(key);
     Metadata.Remove(key);
 }
Exemplo n.º 38
0
        private void BUT_samplephoto_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "*.jpg|*.jpg";

            ofd.ShowDialog();

            if (File.Exists(ofd.FileName))
            {
                string fn = ofd.FileName;

                Metadata lcMetadata = null;
                try
                {
                    FileInfo lcImgFile = new FileInfo(fn);
                    // Loading all meta data
                    lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile);
                }
                catch (JpegProcessingException ex)
                {
                    log.InfoFormat(ex.Message);
                    return;
                }

                foreach (AbstractDirectory lcDirectory in lcMetadata)
                {
                    foreach (var tag in lcDirectory)
                    {
                        Console.WriteLine(lcDirectory.GetName() + " - " + tag.GetTagName() + " " + tag.GetTagValue().ToString());
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT))
                    {
                        TXT_imgheight.Text = lcDirectory.GetInt(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_EXIF_IMAGE_WIDTH))
                    {
                        TXT_imgwidth.Text = lcDirectory.GetInt(ExifDirectory.TAG_EXIF_IMAGE_WIDTH).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_PLANE_X_RES))
                    {
                        var unit = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_PLANE_UNIT);

                        // TXT_senswidth.Text = lcDirectory.GetDouble(ExifDirectory.TAG_FOCAL_PLANE_X_RES).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_PLANE_Y_RES))
                    {
                        var unit = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_PLANE_UNIT);

                        // TXT_sensheight.Text = lcDirectory.GetDouble(ExifDirectory.TAG_FOCAL_PLANE_Y_RES).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_LENGTH))
                    {
                        try
                        {
                            var item = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_LENGTH);
                            num_focallength.Value = (decimal)item;
                        }
                        catch { }
                    }


                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_DATETIME_ORIGINAL))
                    {
                    }
                }
            }
        }
Exemplo n.º 39
0
 protected override void ConvertToConfiguration(Metadata data)
 {
 }
Exemplo n.º 40
0
 /// <summary>
 /// Appends OpenTelemetry headers for every outgoing request to Stackdriver Backend.
 /// </summary>
 /// <param name="metadata">The metadata that is sent with every outgoing http request.</param>
 private static void StackdriverCallHeaderAppender(Metadata metadata)
 {
     metadata.Add("AGENT_LABEL_KEY", "g.co/agent");
     metadata.Add("AGENT_LABEL_VALUE_STRING", $"{OpenTelemetryExporterVersion}; stackdriver-exporter {StackdriverExportVersion}");
 }
Exemplo n.º 41
0
        private List <Token> MergeMultipleExtractions(string text, List <ExtractResult> extractionResults)
        {
            var ret      = new List <Token>();
            var metadata = new Metadata
            {
                PossiblyIncludePeriodEnd = true
            };

            if (extractionResults.Count <= 1)
            {
                return(ret);
            }

            var idx = 0;

            while (idx < extractionResults.Count - 1)
            {
                var middleBegin = extractionResults[idx].Start + extractionResults[idx].Length ?? 0;
                var middleEnd   = extractionResults[idx + 1].Start ?? 0;
                if (middleBegin >= middleEnd)
                {
                    idx++;
                    continue;
                }

                var middleStr = text.Substring(middleBegin, middleEnd - middleBegin).Trim().ToLowerInvariant();
                var match     = this.config.TillRegex.Match(middleStr);
                if (match.Success && match.Index == 0 && match.Length == middleStr.Length)
                {
                    var periodBegin = extractionResults[idx].Start ?? 0;
                    var periodEnd   = (extractionResults[idx + 1].Start ?? 0) + (extractionResults[idx + 1].Length ?? 0);

                    // handle "from/between" together with till words (till/until/through...)
                    var beforeStr = text.Substring(0, periodBegin).Trim().ToLowerInvariant();
                    if (this.config.GetFromTokenIndex(beforeStr, out int fromIndex) ||
                        this.config.GetBetweenTokenIndex(beforeStr, out fromIndex))
                    {
                        periodBegin = fromIndex;
                    }

                    ret.Add(new Token(periodBegin, periodEnd, metadata));

                    // merge two tokens here, increase the index by two
                    idx += 2;
                    continue;
                }

                if (this.config.HasConnectorToken(middleStr))
                {
                    var periodBegin = extractionResults[idx].Start ?? 0;
                    var periodEnd   = (extractionResults[idx + 1].Start ?? 0) + (extractionResults[idx + 1].Length ?? 0);

                    // handle "between...and..." case
                    var beforeStr = text.Substring(0, periodBegin).Trim().ToLowerInvariant();
                    if (this.config.GetBetweenTokenIndex(beforeStr, out int beforeIndex))
                    {
                        periodBegin = beforeIndex;
                        ret.Add(new Token(periodBegin, periodEnd, metadata));

                        // merge two tokens here, increase the index by two
                        idx += 2;
                        continue;
                    }
                }
                idx++;
            }

            return(ret);
        }
Exemplo n.º 42
0
 public ContentSeries(string name, SeriesInstallment[] installments)
 {
     Metadata.Add("name", name);
     Installments = installments;
 }
Exemplo n.º 43
0
 public ListAdaptor(Metadata metadata, VariableDeclarationsInspector parentInspector) : base(metadata, parentInspector)
 {
     this.parentInspector = parentInspector;
     alwaysDragAndDrop    = true;
 }
 public virtual bool CanSetRequired(bool isRequired, ConfigurationSource configurationSource)
 => (configurationSource.Overrides(Metadata.GetIsNullableConfigurationSource()) ||
     (Metadata.IsNullable == !isRequired)) &&
 (isRequired ||
  Metadata.ClrType.IsNullableType() ||
  (configurationSource == ConfigurationSource.Explicit));              // let it throw for Explicit
Exemplo n.º 45
0
        public void Write()
        {
            try
            {
                using (Stream objectsMS = GetTempStream())
                {
                    using (Stream metaMS = GetTempStream())
                    {
                        using (AssetsWriter writer = new AssetsWriter(objectsMS))
                        {
                            int ctr = 0;
                            foreach (var obj in Metadata.ObjectInfos)
                            {
                                ctr++;
                                var offset = (int)objectsMS.Position;
                                obj.GetObjectForWrite().Write(writer);
                                writer.Flush();
                                obj.DataOffset = offset;
                                var origSize = obj.DataSize;
                                obj.DataSize = (int)(objectsMS.Position - obj.DataOffset);
                                writer.AlignTo(8);
                            }
                        }
                        using (AssetsWriter writer = new AssetsWriter(metaMS))
                        {
                            Metadata.Write(writer);
                        }

                        Header.FileSize         = Header.HeaderSize + (int)objectsMS.Length + (int)metaMS.Length;
                        Header.ObjectDataOffset = Header.HeaderSize + (int)metaMS.Length;

                        int diff;
                        int alignment = 16; //or 32, I don't know which
                                            //data has to be at least 4096 inward from the start of the file
                        if (Header.ObjectDataOffset < 4096)
                        {
                            diff = 4096 - Header.ObjectDataOffset;
                        }
                        else
                        {
                            diff = alignment - (Header.ObjectDataOffset % alignment);
                            if (diff == alignment)
                            {
                                diff = 0;
                            }
                        }

                        if (diff > 0)
                        {
                            Header.ObjectDataOffset += diff;
                            Header.FileSize         += diff;
                        }

                        Header.MetadataSize = (int)metaMS.Length;
                        objectsMS.Seek(0, SeekOrigin.Begin);
                        metaMS.Seek(0, SeekOrigin.Begin);
                        lock (this)
                        {
                            try
                            {
                                CloseBaseStream();


                                FileProvider.DeleteFiles(AssetsRootPath.CombineFwdSlash(AssetsFilename + ".split*"));

                                using (Stream outputStream = GetTempStream())
                                {
                                    using (AssetsWriter writer = new AssetsWriter(outputStream))
                                    {
                                        Header.Write(writer);
                                    }
                                    metaMS.CopyTo(outputStream);


                                    if (diff > 0)
                                    {
                                        outputStream.Write(new byte[diff], 0, diff);
                                    }

                                    objectsMS.CopyTo(outputStream);

                                    outputStream.Seek(0, SeekOrigin.Begin);
                                    if (FileWasSplit)
                                    {
                                        int    splitCtr = 0;
                                        byte[] buffer   = new byte[1024 * 1024];
                                        do
                                        {
                                            Stream outFile = FileProvider.GetWriteStream($"{AssetsRootPath.CombineFwdSlash(AssetsFilename)}.split{splitCtr}");
                                            var    readLen = (int)(outputStream.Length - outputStream.Position);
                                            if (readLen < buffer.Length)
                                            {
                                                outputStream.Read(buffer, 0, readLen);
                                                outFile.Write(buffer, 0, readLen);
                                                break;
                                            }
                                            outputStream.Read(buffer, 0, buffer.Length);
                                            outFile.Write(buffer, 0, buffer.Length);
                                            splitCtr++;
                                        } while (true);
                                    }
                                    else
                                    {
                                        Stream writeStream = FileProvider.GetWriteStream(AssetsRootPath.CombineFwdSlash(AssetsFilename));
                                        outputStream.CopyTo(writeStream);
                                    }
                                }
                                FileProvider.Save();
                                _hasChanges = false;
                                foreach (var ptr in _knownPointers.Where(x => x.Owner.ObjectInfo.ParentFile == this && x.IsNew))
                                {
                                    ptr.IsNew = false;
                                }
                                OpenBaseStream();
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("CRITICAL: writing and reopening the file failed, the file is possibly destroyed and this object is in an unknown state.", ex);
                            }
                        }
                    }
                }
            }
            finally
            {
                CleanupTempFiles();
            }
        }
Exemplo n.º 46
0
 public override string ToString()
 {
     return("BeatInfo{" + "port=" + Port + ", ip='" + Ip + '\'' + ", weight=" + Weight + ", serviceName='" + ServiceName + '\'' + ", cluster='" + Cluster + '\'' + ", metadata=" + Metadata.ToJsonString() + ", scheduled=" + Scheduled + ", period=" + Period + ", stopped=" + Stopped + '}');
 }
Exemplo n.º 47
0
 protected internal Layer(string name, Metadata metadata)
 {
     Name     = name ?? throw new ArgumentNullException(nameof(name));
     Metadata = metadata ?? throw new ArgumentNullException(nameof(metadata));
 }
 public Metadata(string name, Metadata parent)
     : base(name)
 {
     Parent = parent;
 }
Exemplo n.º 49
0
 public void RegisterMetadata(Type type, Metadata metadata)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 50
0
        private List <Token> MergeMultipleExtractions(string text, List <ExtractResult> extractionResults)
        {
            var ret      = new List <Token>();
            var metadata = new Metadata
            {
                PossiblyIncludePeriodEnd = true,
            };

            if (extractionResults.Count <= 1)
            {
                return(ret);
            }

            var idx = 0;

            while (idx < extractionResults.Count - 1)
            {
                var middleBegin = extractionResults[idx].Start + extractionResults[idx].Length ?? 0;
                var middleEnd   = extractionResults[idx + 1].Start ?? 0;
                if (middleBegin >= middleEnd)
                {
                    idx++;
                    continue;
                }

                var middleStr   = text.Substring(middleBegin, middleEnd - middleBegin).Trim();
                var endPointStr = extractionResults[idx + 1].Text;

                if (config.TillRegex.IsExactMatch(middleStr, trim: true) || (string.IsNullOrEmpty(middleStr) &&
                                                                             config.TillRegex.MatchBegin(endPointStr, trim: true).Success))
                {
                    var periodBegin = extractionResults[idx].Start ?? 0;
                    var periodEnd   = (extractionResults[idx + 1].Start ?? 0) + (extractionResults[idx + 1].Length ?? 0);

                    // handle "from/between" together with till words (till/until/through...)
                    var beforeStr = text.Substring(0, periodBegin);

                    var beforeMatch = this.config.RangePrefixRegex.MatchEnd(beforeStr, trim: true);

                    if (beforeMatch.Success)
                    {
                        periodBegin = beforeMatch.Index;
                    }
                    else
                    {
                        var afterStr = text.Substring(periodEnd);

                        var afterMatch = this.config.RangeSuffixRegex.MatchBegin(afterStr, trim: true);

                        if (afterMatch.Success)
                        {
                            periodEnd += afterMatch.Index + afterMatch.Length;
                        }
                    }

                    ret.Add(new Token(periodBegin, periodEnd, metadata));

                    // merge two tokens here, increase the index by two
                    idx += 2;
                    continue;
                }

                idx++;
            }

            return(ret);
        }
Exemplo n.º 51
0
        public IEnumerable <AdamItem> Items(int appId, string contentType, Guid guid, string field, string subfolder, bool usePortalRoot = false)
        {
            var wrapLog = Log.Call <IEnumerable <AdamItem> >("Items",
                                                             $"adam items a:{appId}, i:{guid}, field:{field}, subfold:{subfolder}, useRoot:{usePortalRoot}");
            var state = new AdamSecureState(SxcInstance, appId, contentType, field, guid, usePortalRoot, Log);


            Log.Add("starting permissions checks");
            if (state.UserIsRestricted && !state.FieldPermissionOk(GrantSets.ReadSomething))
            {
                return(wrapLog("user is restricted, and doesn't have permissions on field - return null", null));
            }

            // check that if the user should only see drafts, he doesn't see items of published data
            if (!state.UserIsNotRestrictedOrItemIsDraft(guid, out var _))
            {
                return(wrapLog("user is restricted (no read-published rights) and item is published - return null", null));
            }

            Log.Add("first permission checks passed");


            // get root and at the same time auto-create the core folder in case it's missing (important)
            state.ContainerContext.Folder();

            // try to see if we can get into the subfolder - will throw error if missing
            var currentAdam   = state.ContainerContext.Folder(subfolder, false);
            var folderManager = FolderManager.Instance;
            var currentDnn    = folderManager.GetFolder(currentAdam.Id);

            // ensure that it's super user, or the folder is really part of this item
            if (!state.SuperUserOrAccessingItemFolder(currentDnn.PhysicalPath, out var exp))
            {
                Log.Add("user is not super-user and folder doesn't seem to be an ADAM folder of this item - will throw");
                throw exp;
            }

            var subfolders = folderManager.GetFolders(currentDnn);
            var files      = folderManager.GetFiles(currentDnn);

            var all = new List <AdamItem>();

            // currentFolder is needed to get allowEdit for Adam root folder
            var currentFolder = new AdamItem(currentDnn, usePortalRoot, state)
            {
                Name       = ".",
                MetadataId = Metadata.GetMetadataId(state.AdamAppContext.AppRuntime, currentDnn.FolderID, true)
            };

            all.Insert(0, currentFolder);

            var adamFolders = subfolders.Where(s => s.FolderID != currentDnn.FolderID)
                              .Select(f => new AdamItem(f, usePortalRoot, state)
            {
                MetadataId = Metadata.GetMetadataId(state.AdamAppContext.AppRuntime, f.FolderID, true)
            })
                              .ToList();

            all.AddRange(adamFolders);

            var adamFiles = files
                            .Select(f => new AdamItem(f, usePortalRoot, state)
            {
                MetadataId = Metadata.GetMetadataId(state.AdamAppContext.AppRuntime, f.FileId, false),
                Type       = Classification.TypeName(f.Extension)
            })
                            .ToList();

            all.AddRange(adamFiles);

            Log.Add($"items complete - will return fld⋮{adamFolders.Count}, files⋮{adamFiles.Count} tot⋮{all.Count}");
            return(all);
        }
Exemplo n.º 52
0
 public Token(int s, int e, Metadata metadata = null)
 {
     Start    = s;
     End      = e;
     Metadata = metadata;
 }
Exemplo n.º 53
0
 private static IEnumerable <ModuleMetadata> EnumerateModules(Metadata metadata)
 {
     return((metadata.Kind == MetadataImageKind.Assembly)
       ? ((AssemblyMetadata)metadata).GetModules().AsEnumerable()
       : SpecializedCollections.SingletonEnumerable((ModuleMetadata)metadata));
 }
Exemplo n.º 54
0
        private void FixCollisions(System.Management.Automation.PSCmdlet cmdlet, MappingToolDatabaseDataContext mapDatabaseContext, List <CollisionInfo> collisions)
        {
            List <QueryMapRelationship> relationshipsToReconnect = new List <QueryMapRelationship>();

            foreach (CollisionInfo collision in collisions)
            {
                cmdlet.WriteWarning("Fixing collision.");
                IEnumerable <QueryMapRelationship> relationships = Consumer.GetRelationships(collision.CollisionPoint);

                foreach (QueryMapRelationship relationship in relationships)
                {
                    IEnumerable <QueryMapNode> nodes = Consumer.GetNodes(relationship, collision.CollisionPoint);

                    foreach (QueryMapNode node in nodes)
                    {
                        var rootMapIds = from qNode in mapDatabaseContext.Nodes
                                         where qNode.NodeUid == node.NodeUid
                                         select qNode.RootMapUid;

                        Guid?rootMapId = rootMapIds.FirstOrDefault();

                        if (rootMapId != null && rootMapId == collision.CollidingRootMap.NodeUid)
                        {
                            relationshipsToReconnect.Add(relationship);
                        }
                    }
                }

                DateTime currentTimestamp = DateTime.Now;

                Node copiedNode = new Node();
                copiedNode.NodeUid        = Guid.NewGuid();
                copiedNode.DomainUid      = collision.CollisionPoint.DomainUid;
                copiedNode.RootMapUid     = collision.CollidingRootMap.NodeUid;
                copiedNode.NodeTypeUid    = collision.CollisionPoint.NodeTypeUid;
                copiedNode.NodeOriginalId = collision.CollisionPoint.NodeOriginalId;
                copiedNode.Created        = currentTimestamp;
                copiedNode.Modified       = currentTimestamp;

                mapDatabaseContext.Nodes.InsertOnSubmit(copiedNode);
                mapDatabaseContext.SubmitChanges();

                var originalMetadata = from qMetadata in Consumer.Metadata
                                       where qMetadata.NodeUid == collision.CollisionPoint.NodeUid
                                       select qMetadata;

                foreach (var originalMetadatum in originalMetadata)
                {
                    Metadata copiedMetadata = new Metadata();
                    copiedMetadata.MetadataId        = Guid.NewGuid();
                    copiedMetadata.RootMapUid        = collision.CollidingRootMap.NodeUid;
                    copiedMetadata.DomainUid         = copiedNode.DomainUid;
                    copiedMetadata.MetadataTypeUid   = originalMetadatum.MetadataTypeUid;
                    copiedMetadata.NodeUid           = copiedNode.NodeUid;
                    copiedMetadata.RelationshipUid   = originalMetadatum.RelationshipUid;
                    copiedMetadata.DescriptorTypeUid = originalMetadatum.DescriptorTypeUid;
                    copiedMetadata.MetadataName      = originalMetadatum.MetadataName;
                    copiedMetadata.MetadataValue     = originalMetadatum.MetadataValue;
                    copiedMetadata.Created           = currentTimestamp;
                    copiedMetadata.Modified          = currentTimestamp;

                    mapDatabaseContext.Metadatas.InsertOnSubmit(copiedMetadata);
                }

                mapDatabaseContext.SubmitChanges();

                foreach (QueryMapRelationship relationshipToReconnect in relationshipsToReconnect)
                {
                    var descriptors = from qDescriptor in mapDatabaseContext.Descriptors
                                      where qDescriptor.NodeUid == collision.CollisionPoint.NodeUid && qDescriptor.RelationshipUid == relationshipToReconnect.RelationshipUid
                                      select qDescriptor;

                    if (descriptors != null && descriptors.Count() > 0)
                    {
                        foreach (Descriptor descriptor in descriptors)
                        {
                            descriptor.NodeUid = copiedNode.NodeUid;
                        }
                    }

                    mapDatabaseContext.SubmitChanges();
                }
            }
        }
Exemplo n.º 55
0
 /// <summary>
 /// Extract tiff information (used by raw files)
 /// </summary>
 /// <param name="aMetadata">where to extract information</param>
 /// <returns>the information extracted</returns>
 public Metadata ExtractTiff(Metadata aMetadata)
 {
     return(this.ExtractIFD(aMetadata, 0));
 }
Exemplo n.º 56
0
 public ContentResource(MediaType resourceType, string link)
 {
     Metadata.Set("type", resourceType.ToString());
     Metadata.Set("link", link);
 }
Exemplo n.º 57
0
        /// <summary>
        /// Performs the Exif data extraction, adding found values to the specified instance of Metadata.
        /// </summary>
        /// <param name="aMetadata">where to add meta data</param>
        /// <returns>the aMetadata</returns>
        public override Metadata Extract(Metadata metadata)
        {
            this.metadata = metadata;
            if (base.data == null)
            {
                return(this.metadata);
            }

            // once we know there'str some data, create the directory and start working on it
            AbstractDirectory directory = this.metadata.GetDirectory("com.drew.metadata.exif.ExifDirectory");

            if (base.data.Length <= 14)
            {
                directory.HasError = true;
                Trace.TraceError("Exif data segment must contain at least 14 bytes");
                return(this.metadata);
            }
            if (!"Exif\0\0".Equals(Utils.Decode(base.data, 0, 6, false)))
            {
                directory.HasError = true;
                Trace.TraceError("Exif data segment doesn't begin with 'Exif'");
                return(this.metadata);
            }

            // this should be either "MM" or "II"
            string byteOrderIdentifier = Utils.Decode(base.data, 6, 2, false);

            if (!SetByteOrder(byteOrderIdentifier))
            {
                directory.HasError = true;
                Trace.TraceError("Unclear distinction between Motorola/Intel byte ordering");
                return(this.metadata);
            }

            // Check the next two values for correctness.
            if (Get16Bits(8) != 0x2a)
            {
                directory.HasError = true;
                Trace.TraceError("Invalid Exif start - should have 0x2A at offSet 8 in Exif header");
                return(this.metadata);
            }

            int firstDirectoryOffSet = Get32Bits(10) + TIFF_HEADER_START_OFFSET;

            // David Ekholm sent an digital camera image that has this problem
            if (firstDirectoryOffSet >= base.data.Length - 1)
            {
                directory.HasError = true;
                Trace.TraceError("First exif directory offSet is beyond end of Exif data segment");
                // First directory normally starts 14 bytes in -- try it here and catch another error in the worst case
                firstDirectoryOffSet = 14;
            }

            // 0th IFD (we merge with Exif IFD)
            //ProcessDirectory(directory, firstDirectoryOffSet);
            // after the extraction process, if we have the correct tags, we may be able to extract thumbnail information
            //ExtractThumbnail(directory);

            Dictionary <int, string> processedDirectoryOffsets = new Dictionary <int, string>();

            // 0th IFD (we merge with Exif IFD)
            ProcessDirectory(directory, processedDirectoryOffsets, firstDirectoryOffSet, TIFF_HEADER_START_OFFSET);

            // after the extraction process, if we have the correct tags, we may be able to store thumbnail information
            StoreThumbnailBytes(directory, TIFF_HEADER_START_OFFSET);


            return(this.metadata);
        }
Exemplo n.º 58
0
 public override void SetMetadata(Metadata data)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 59
0
 public SeriesInstallment(string name, string link)
     : base()
 {
     Metadata.Add("name", name);
     Metadata.Add("link", link);
 }
Exemplo n.º 60
0
        public Metadata GetMetadata(HttpRequestMessage request)
        {
            var host                  = request.RequestUri.Scheme + "://" + request.RequestUri.Authority + request.GetRequestContext().VirtualPathRoot;
            var descriptions          = config.Services.GetApiExplorer().ApiDescriptions;
            var documentationProvider = config.Services.GetDocumentationProvider();

            ILookup <HttpControllerDescriptor, ApiDescription> apiGroups = descriptions
                                                                           .Where(a => !a.ActionDescriptor.ControllerDescriptor.ControllerType.IsAbstract &&
                                                                                  !a.RelativePath.Contains("Swagger") &&
                                                                                  !a.RelativePath.Contains("docs"))
                                                                           .ToLookup(a => a.ActionDescriptor.ControllerDescriptor);

            var metadata = new Metadata
            {
                Definitions = from d in apiGroups
                              where !d.Key.ControllerType.IsExcluded()
                              select new ControllerDefinition
                {
                    Name          = d.Key.ControllerName,
                    Description   = documentationProvider == null ? "" : documentationProvider.GetDocumentation(d.Key) ?? "",
                    ActionMethods = from a in descriptions
                                    where !a.ActionDescriptor.ControllerDescriptor.ControllerType.IsExcluded() &&
                                    !a.ActionDescriptor.IsExcluded() &&
                                    !a.RelativePath.Contains("Swagger") &&
                                    !a.RelativePath.Contains("docs") &&
                                    a.ActionDescriptor.ControllerDescriptor.ControllerName == d.Key.ControllerName
                                    select new ActionMethodDefinition
                    {
                        Name          = a.ActionDescriptor.ActionName,
                        BodyParameter = (from b in a.ParameterDescriptions
                                         where b.Source == ApiParameterSource.FromBody
                                         select new ParameterDefinition
                        {
                            Name = b.ParameterDescriptor.ParameterName,
                            Type = ParseType(b.ParameterDescriptor.ParameterType),
                            Description = b.Documentation ?? ""
                        }).FirstOrDefault(),
                        UrlParameters = from b in a.ParameterDescriptions.Where(p => p.ParameterDescriptor != null)
                                        where b.Source == ApiParameterSource.FromUri
                                        select new ParameterDefinition
                        {
                            Name         = b.ParameterDescriptor.ParameterName,
                            Type         = ParseType(b.ParameterDescriptor.ParameterType),
                            Description  = b.Documentation ?? "",
                            IsOptional   = b.ParameterDescriptor.IsOptional,
                            DefaultValue = b.ParameterDescriptor.DefaultValue
                        },
                        Url = a.RelativePath,

                        Description = a.Documentation ?? "",
                        ReturnType  = ParseType(a.ResponseDescription.ResponseType ?? a.ResponseDescription.DeclaredType),
                        Type        = a.HttpMethod.Method
                    }
                },
                Models = models,
                Host   = (null != host && host.Length > 0 && host[host.Length - 1] != '/') ? string.Concat(host, "/") : host
            };

            metadata.Definitions = metadata.Definitions.Distinct().OrderBy(d => d.Name);
            metadata.Models      = metadata.Models.Distinct(new ModelDefinitionEqualityComparer()).OrderBy(d => d.Name);
            return(metadata);
        }