Beispiel #1
0
        public ValueTask <SerializableClassifiedSpans> GetClassificationsAsync(
            PinnedSolutionInfo solutionInfo,
            DocumentId documentId,
            TextSpan span,
            ClassificationType type,
            ClassificationOptions options,
            StorageDatabase database,
            bool isFullyLoaded,
            CancellationToken cancellationToken)
        {
            return(RunServiceAsync(async cancellationToken =>
            {
                var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
                var document = solution.GetDocument(documentId) ?? await solution.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
                Contract.ThrowIfNull(document);

                using var _ = ArrayBuilder <ClassifiedSpan> .GetInstance(out var temp);
                await AbstractClassificationService.AddClassificationsInCurrentProcessAsync(
                    document, span, type, options, temp, cancellationToken).ConfigureAwait(false);

                if (isFullyLoaded)
                {
                    // Once fully loaded, there's no need for us to keep around any of the data we cached in-memory
                    // during the time the solution was loading.
                    lock (_cachedData)
                        _cachedData.Clear();

                    // Enqueue this document into our work queue to fully classify and cache.
                    _workQueue.AddWork((document, type, options, database));
                }

                return SerializableClassifiedSpans.Dehydrate(temp.ToImmutable());
            }, cancellationToken));
        }
Beispiel #2
0
        public static IMetric[] ParseMetrics(
            Dataset dataset,
            Array <string> metricsNames,
            ClassificationType classificationType
            )
        {
            if (metricsNames.IsEmpty)
            {
                throw new ArgumentException(nameof(metricsNames) + " can't be empty.");
            }

            var metrics = new IMetric[metricsNames.Length];

            for (int i = 0; i < metricsNames.Length; i++)
            {
                var currentMetricName = metricsNames[i];
                metrics[i] = (metricsNames[i], classificationType) switch
                {
                    ("fscore", ClassificationType.SingleLabel) => new SingleLabelFScore(dataset),
                    ("fscore", ClassificationType.MultiLabel) => new MultiLabelFScore(dataset),
                    ("average-rule-volume", _) => new AverageRuleVolume(dataset),
                    ("rule-count", _) => new RuleCount(),
                    ("model-size", _) => new ModelSize(),

                    _ => throw new ArgumentException($"Unsupported (Metric, ClassificationType): ({currentMetricName}, {classificationType})."),
                };
            }
Beispiel #3
0
        public override bool Execute(CommandActivity commandActivity)
        {
            try
            {
                var hostObject = (Incoming)commandActivity.WorkItem;

                if (hostObject.BaseFile != null)
                {
                    return(true);
                }

                //Get tartet file
                var echDocument = hostObject.FileContentHierarchyFlat.OfType <Document>()
                                  .First(d => d.Type == ClassificationType.GetObject(Rubicon.Gever.Bund.EGovInterface.Domain
                                                                                     .WellKnownObjects.DocumentClassification.EchImport.GetObjectID()));

                var targetFile = ImportHelper.TenantKnowsObject(echDocument);

                if (targetFile == null)
                {
                    throw new ActivityCommandException("").WithUserMessage(LocalizedUserMessages.FileNotImported
                                                                           .ToLocalizedName()
                                                                           .FormatWith(commandActivity));
                }

                hostObject.Insert(targetFile);
            }
            catch (Exception ex)
            {
                s_logger.Error(ex.Message, ex);
                throw;
            }

            return(true);
        }
        /// <summary>
        /// Creates a ClassificationType.
        /// </summary>
        /// <param name="classificationScheme">The classification scheme.</param>
        /// <param name="classifiedObject">The classified object UUID.</param>
        /// <param name="nodeRepresentation">The node representation.</param>
        /// <param name="slots">The SlotType1 entries in the classification.</param>
        /// <param name="name">The name of the classiciation.</param>
        /// <returns>ClassificationType.</returns>
        internal ClassificationType CreateClassificationType(
            string id,
            string classificationScheme,
            string classifiedObject,
            string nodeRepresentation,
            List <SlotType1> slots,
            InternationalStringType name)
        {
            var classification = new ClassificationType();

            classification.classificationScheme = classificationScheme;
            classification.classifiedObject     = classifiedObject;
            classification.nodeRepresentation   = nodeRepresentation;
            classification.objectType           = XDS_CLASSIFICATION;
            classification.id = id;

            if (slots != null && slots.Count > 0)
            {
                classification.Slot = slots.ToArray();
            }

            if (name != null)
            {
                classification.Name = name;
            }

            return(classification);
        }
Beispiel #5
0
 public VCard ExportVCard(ClassificationType classificationType)
 {
     return(new VCard
     {
         Version = VCardVersion.V4,
         FirstName = FirstName,
         LastName = LastName,
         FormattedName = FullName,
         Organization = OrganisationName,
         Classification = classificationType,
         Note = Notes,
         Url = new Uri(WebsiteUrl),
         Kind = Kind.Individual,
         Categories = Categories.ToDtos().ToArray(),
         CustomExtensions = CustomFields?
                            .Select(x => new CustomExtension
         {
             Key = x.Key,
             Value = x.Value
         }
                                    ).ToArray(),
         Telephones = Phones?
                      .Select(x => new Telephone
         {
             Number = x.PhoneNo,
             Type = x.Type switch
             {
                 PhoneType.Home => TelephoneType.Home,
                 PhoneType.Mobile => TelephoneType.Cell,
                 PhoneType.Work => TelephoneType.Work,
                 _ => throw new InvalidDataException($"Invalid Phone Type")
             }
         }).ToArray(),
        private Dto.Xsd.IncomeClassificationType MapIncomeClassificationType(ClassificationType classificationType)
        {
            switch (classificationType)
            {
            case ClassificationType.RetailSalesOfGoodsAndServicesPrivateClientele:
                return(Dto.Xsd.IncomeClassificationType.RetailSalesOfGoodsAndServicesPrivateClientele);

            case ClassificationType.OtherSalesOfGoodsAndServices:
                return(Dto.Xsd.IncomeClassificationType.OtherSalesOfGoodsAndServices);

            case ClassificationType.OtherOrdinaryIncome:
                return(Dto.Xsd.IncomeClassificationType.OtherOrdinaryIncome);

            case ClassificationType.CreditExchangeDifferences:
                return(Dto.Xsd.IncomeClassificationType.CreditExchangeDifferences);

            case ClassificationType.IntraCommunityForeignSalesOfGoodsAndServices:
                return(Dto.Xsd.IncomeClassificationType.IntraCommunityForeignSalesOfGoodsAndServices);

            case ClassificationType.ThirdCountryForeignSalesOfGoodsAndServices:
                return(Dto.Xsd.IncomeClassificationType.ThirdCountryForeignSalesOfGoodsAndServices);

            default:
                throw new ArgumentException($"Cannot map ClassificationType {classificationType} to {nameof(Dto.Xsd.IncomeClassificationType)}.");
            }
        }
Beispiel #7
0
        private static async Task <bool> TryGetCachedClassificationsAsync(
            Document document,
            TextSpan textSpan,
            ClassificationType type,
            RemoteHostClient client,
            bool isFullyLoaded,
            ArrayBuilder <ClassifiedSpan> result,
            CancellationToken cancellationToken)
        {
            // Only try to get cached classifications if we're not fully loaded yet.
            if (isFullyLoaded)
            {
                return(false);
            }

            var(documentKey, checksum) = await SemanticClassificationCacheUtilities.GetDocumentKeyAndChecksumAsync(
                document, cancellationToken).ConfigureAwait(false);

            var cachedSpans = await client.TryInvokeAsync <IRemoteSemanticClassificationService, SerializableClassifiedSpans?>(
                document.Project,
                (service, solutionInfo, cancellationToken) => service.GetCachedClassificationsAsync(
                    documentKey, textSpan, type, checksum, cancellationToken),
                cancellationToken).ConfigureAwait(false);

            // if the remote call fails do nothing (error has already been reported)
            if (!cachedSpans.HasValue || cachedSpans.Value == null)
            {
                return(false);
            }

            cachedSpans.Value.Rehydrate(result);
            return(true);
        }
        public RootNodeType MapFrom(ClassificationType classificationType)
        {
            switch (classificationType)
            {
            case ClassificationType.ObservedData:
                return(RootNodeTypes.ObservedDataFolder);

            case ClassificationType.Simulation:
                return(RootNodeTypes.SimulationFolder);

            case ClassificationType.Comparison:
                return(RootNodeTypes.ComparisonFolder);

            case ClassificationType.ParameterIdentification:
                return(RootNodeTypes.ParameterIdentificationFolder);

            case ClassificationType.SensitiviyAnalysis:
                return(RootNodeTypes.SensitivityAnalysisFolder);

            case ClassificationType.QualificationPlan:
                return(RootNodeTypes.QualificationPlanFolder);

            default:
                throw new ArgumentOutOfRangeException(nameof(classificationType));
            }
        }
Beispiel #9
0
        /// <summary>
        /// Creates an classification type.
        /// </summary>
        /// <param name="classificationScheme">The classification scheme.</param>
        /// <param name="nodeRepresentation">The node representation.</param>
        /// <param name="name">The name.</param>
        /// <param name="slots">The slots.</param>
        /// <returns>Returns the created classification type.</returns>
        public static ClassificationType CreateClassification(XdsGuidType classificationScheme, string nodeRepresentation, string name, params SlotType1[] slots)
        {
            var retVal = new ClassificationType()
            {
                id = $"urn:uuid:{Guid.NewGuid().ToString()}",
                classificationScheme = classificationScheme.ToString(),
                nodeRepresentation   = nodeRepresentation
            };

            if (name != null)
            {
                retVal.Name = new InternationalStringType()
                {
                    LocalizedString = new LocalizedStringType[] {
                        new LocalizedStringType()
                        {
                            value = name
                        }
                    }
                };
            }

            // Slots
            retVal.Slot = slots;

            return(retVal);
        }
                public static void SendPacket(byte[] msgBytes, out ClassificationType classificationType,
                                              out ushort TCPNumber, out ushort originator, out byte TTL, /*out ushort pathLength,*/ out ushort payloadLength)
                {
                    var idx = 1; // Start at 1 since we've already checked the message ID

                    classificationType = (ClassificationType)msgBytes[idx];
                    idx += 1;

                    TCPNumber = BitConverter.ToUInt16(msgBytes, idx);
                    idx      += sizeof(ushort);

                    originator = BitConverter.ToUInt16(msgBytes, idx);
                    idx       += sizeof(ushort);

                    TTL  = msgBytes[idx];
                    idx += 1;

                    /*
                     * pathLength = BitConverter.ToUInt16(msgBytes, idx);
                     * idx += sizeof(ushort);
                     *
                     * ushort[] path = new ushort[pathLength];
                     * int i;
                     * for(i = 0; i < pathLength; i = i + 1){
                     *  path[i] = BitConverter.ToUInt16(msgBytes, idx);
                     *  idx += sizeof(ushort);
                     * }
                     */
                    payloadLength = BitConverter.ToUInt16(msgBytes, idx);
                    idx          += sizeof(ushort);
                    //return path;
                }
        private void DrawSourceLines()
        {
            lineWidth = Math.Ceiling(canvas.RenderSize.Height / RowCount);
            if (lineWidth < 1)
            {
                lineWidth = 1;
            }
            if (LeftSourceCode == null && RightSourceCode == null)
            {
                return;
            }
            for (int i = 0; i < RowCount; i++)
            {
                ClassificationType lineType = GetLineDiffClassificationType(i);
                if (lineType == ClassificationType.NotModifiedLine || lineType == ClassificationType.ImaginaryLine)
                {
                    // There is no difference in this line or the line is imaginary, so nothing needs to be drawn.
                    continue;
                }

                var    myLine           = new Line();
                double lineYCoordinates = GetLineHorisontalCoordinates(i);
                myLine.Stroke            = new SolidColorBrush(DiffBackgroundRenderer.GetColorFromClassificationType(lineType));
                myLine.X1                = 0;
                myLine.X2                = canvas.RenderSize.Width;
                myLine.Y1                = lineYCoordinates;
                myLine.Y2                = lineYCoordinates;
                myLine.UseLayoutRounding = true;

                myLine.StrokeThickness = lineWidth;
                canvas.Children.Add(myLine);
            }
        }
                /// <summary>
                /// Compose a detection message
                /// </summary>
                /// <param name="msgBytes"></param>
                /// <param name="originator"></param>
                /// <param name="classificatonType"></param>
                /// <param name="detectionNum"></param>
                /// <returns></returns>
                public static int Detection(byte[] msgBytes, ushort originator, ClassificationType classificatonType,
                                            int detectionNum, byte TTL)
                {
                    var idx = 0;

                    // Detection message type
                    msgBytes[idx] = (byte)MessageIds.Detect;
                    idx++;

                    // Classification
                    msgBytes[idx] = (byte)classificatonType;
                    idx++;

                    // Detection message number
                    var detectNum = (ushort)Math.Min(detectionNum, ushort.MaxValue);

                    BitConverter.InsertValueIntoArray(msgBytes, idx, detectNum);
                    idx += sizeof(ushort);

                    // Message originator
                    BitConverter.InsertValueIntoArray(msgBytes, idx, originator);
                    idx += sizeof(ushort);

                    // TTL
                    msgBytes[idx] = (byte)TTL;
                    idx++;

                    // Check if message is the right size
                    if (idx != DetectionMessageSize)
                    {
                        throw new Exception("Compose Detection: message composed is " + idx + " bytes; should be " + DetectionMessageSize);
                    }

                    return(idx);
                }
Beispiel #13
0
 public void SetClassification(int cellX, int cellY, ClassificationType type)
 {
     if (this._classification != null)
     {
         _classification[cellX, cellY] = (int)type;
     }
 }
Beispiel #14
0
        /// <summary>
        /// Creates an classification type.
        /// </summary>
        /// <param name="classifiedObject">The classified object.</param>
        /// <param name="scheme">The scheme.</param>
        /// <param name="nodeRepresentation">The node representation.</param>
        /// <param name="name">The name.</param>
        /// <param name="slots">The slots.</param>
        /// <returns>Returns the created classification type.</returns>
        public static ClassificationType CreateClassification(RegistryObjectType classifiedObject, XdsGuidType scheme, string nodeRepresentation, string name, params SlotType1[] slots)
        {
            var retClass = new ClassificationType
            {
                id = $"urn:uuid:{Guid.NewGuid().ToString()}",
                classificationScheme = scheme.ToString(),
                classifiedObject     = classifiedObject.id,
                nodeRepresentation   = nodeRepresentation,
                Slot = slots
            };

            if (name != null)
            {
                retClass.Name = new InternationalStringType()
                {
                    LocalizedString = new LocalizedStringType[] {
                        new LocalizedStringType()
                        {
                            value = name
                        }
                    }
                };
            }

            return(retClass);
        }
Beispiel #15
0
 private static ILabel[] ReadLabelFile(string filename, ClassificationType classificationType)
 {
     return(classificationType switch
     {
         ClassificationType.SingleLabel => throw new NotImplementedException(),
         ClassificationType.MultiLabel => ReadMultiLabelFile(filename),
         _ => throw CommonExceptions.UnknownClassificationType,
     });
Beispiel #16
0
        private static ClassificationType CreateClassificationType()
        {
            ClassificationType c = new ClassificationType();

            c.Description = "Omschrijving";
            c.Id          = CreateEntityIdType();
            return(c);
        }
Beispiel #17
0
 public LasPoint2Long(byte bitsField, ClassificationType classification, ushort intensity, ushort pointSourceId,
                      sbyte scanAngleRank, byte userData, int x, int y, int z, ushort red, ushort green, ushort blue)
     : base(bitsField, classification, intensity, pointSourceId, scanAngleRank, userData, x, y, z)
 {
     _red   = red;
     _green = green;
     _blue  = blue;
 }
Beispiel #18
0
 static ILabel ComputeDefaultLabel(Array <ILabel> labels, ClassificationType classificationType)
 {
     return(classificationType switch
     {
         ClassificationType.SingleLabel => ComputeMajorityClass(labels),
         ClassificationType.MultiLabel => ComputeAverageLabels(labels),
         _ => throw CommonExceptions.UnknownClassificationType,
     });
 public LasPoint2Short(ClassificationType classification, ushort intensity, ushort pointSourceId, int x,
     int y, int z, ushort red, ushort green, ushort blue)
     : base(classification, intensity, pointSourceId, x, y, z)
 {
     _red = red;
     _green = green;
     _blue = blue;
 }
        private RootNode createRootNode(RootNodeType rootNodeType, ClassificationType classificationType)
        {
            var node = new RootNode(rootNodeType);

            A.CallTo(() => _rootNodeTypeMapper.MapFrom(classificationType)).Returns(rootNodeType);
            A.CallTo(() => _explorerPresenter.NodeByType(rootNodeType)).Returns(node);
            return(node);
        }
Beispiel #21
0
 protected LasPointLong(byte bitsField, ClassificationType classification, ushort intensity,
                        ushort pointSourceId,
                        sbyte scanAngleRank, byte userData, int x, int y, int z)
     : base(classification, intensity, pointSourceId, x, y, z)
 {
     _bitsField     = new BitsField(bitsField);
     _scanAngleRank = scanAngleRank;
     _userData      = userData;
 }
Beispiel #22
0
 public RootNodeType(string name, ApplicationIcon icon, ClassificationType classificationType = ClassificationType.Unknown)
 {
     Id              = ShortGuid.NewGuid().ToString();
     Name            = name;
     Icon            = icon;
     _classification = new Classification {
         ClassificationType = classificationType
     };
 }
        private static string getValueFromName(ClassificationType ct)
        {
            string rv = "";

            if (ct.Name != null && ct.Name.LocalizedString.Length > 0)
            {
                rv = ct.Name.LocalizedString[0].value;
            }
            return(rv);
        }
Beispiel #24
0
 public LasPoint(ClassificationType classification, ushort intensity, ushort pointSourceId,
                 int x, int y, int z)
 {
     _classification = (byte)classification;
     _intensity      = intensity;
     _pointSourceId  = pointSourceId;
     _x = x;
     _y = y;
     _z = z;
 }
        public static string ContinuousToClassifiedMRR(string strInFilePath, string strOutFilePath)
        {
            const ClassificationType outClassType = ClassificationType.Classified;

            UndefinedClassInfo undefinedClassInfo = new UndefinedClassInfo();

            undefinedClassInfo.SetNullForUndefinedRange = false;
            undefinedClassInfo.UndefinedClassColor      = Color.FromArgb(0, 128, 64, 0);
            undefinedClassInfo.UndefinedClassLabel      = "Undefined";
            undefinedClassInfo.UndefinedValue           = -9999;

            ClassInfo[] newClassInfo = new ClassInfo[5];
            //Initalize class items
            for (int i = 0; i < newClassInfo.Length; i++)
            {
                newClassInfo[i] = new ClassInfo();
            }

            //Set classify ranges
            newClassInfo[0].LowerBound = 0.0f;
            newClassInfo[0].UpperBound = 4.0f;
            newClassInfo[1].LowerBound = 4.0f;
            newClassInfo[1].UpperBound = 8.0f;
            newClassInfo[2].LowerBound = 8.0f;
            newClassInfo[2].UpperBound = 12.0f;
            newClassInfo[3].LowerBound = 12.0f;
            newClassInfo[3].UpperBound = 16.0f;
            newClassInfo[4].LowerBound = 16.0f;
            newClassInfo[4].UpperBound = 20.0f;

            //Set new class values
            newClassInfo[0].NewValue = 4.0f;
            newClassInfo[1].NewValue = 8.0f;
            newClassInfo[2].NewValue = 12.0f;
            newClassInfo[3].NewValue = 16.0f;
            newClassInfo[4].NewValue = 20.0f;

            //Set new class names
            newClassInfo[0].NewLabel = "0 - 4";
            newClassInfo[1].NewLabel = "4 - 8";
            newClassInfo[2].NewLabel = "8 - 12";
            newClassInfo[3].NewLabel = "12 -16";
            newClassInfo[4].NewLabel = "16 - 20";

            //Set new class color
            newClassInfo[0].NewColor = Color.FromArgb(0, 0, 255, 255);   //cyan
            newClassInfo[1].NewColor = Color.FromArgb(0, 255, 128, 192); //Pink Color
            newClassInfo[2].NewColor = Color.FromArgb(0, 255, 128, 64);  //Orange
            newClassInfo[3].NewColor = Color.FromArgb(0, 128, 0, 255);
            newClassInfo[4].NewColor = Color.FromArgb(0, 255, 0, 0);

            RasterAnalysis.ClassifyRaster(strInFilePath, strOutFilePath, "MI_MRR", outClassType, newClassInfo, undefinedClassInfo);

            return(strOutFilePath);
        }
Beispiel #26
0
 public ItemEntry(String name, String type, ClassificationType classification, UInt16 width, UInt16 height, Boolean stackable, Boolean usable, Boolean throwable)
 {
     Name           = name;
     Type           = type;
     Classification = classification;
     Width          = width;
     Height         = height;
     Stackable      = stackable;
     Usable         = usable;
     Throwable      = throwable;
 }
Beispiel #27
0
 public ItemEntry(ItemName name, string type, ClassificationType classification, ushort width, ushort height, bool stackable, bool usable, bool throwable)
 {
     Name           = name;
     Type           = type;
     Classification = classification;
     Width          = width;
     Height         = height;
     Stackable      = stackable;
     Usable         = usable;
     Throwable      = throwable;
 }
Beispiel #28
0
        /// <summary>
        /// Creates an node classification type.
        /// </summary>
        /// <param name="registryObject">The registry object.</param>
        /// <param name="classificationNode">The classification node.</param>
        /// <returns>Returns the created node classification type.</returns>
        public static ClassificationType CreateNodeClassification(RegistryObjectType registryObject, XdsGuidType classificationNode)
        {
            var retClass = new ClassificationType
            {
                id = $"urn:uuid:{Guid.NewGuid()}",
                classificationNode = classificationNode.ToString(),
                classifiedObject   = registryObject.id
            };

            return(retClass);
        }
 protected AbstractSemanticOrEmbeddedClassificationViewTaggerProvider(
     IThreadingContext threadingContext,
     ClassificationTypeMap typeMap,
     IGlobalOptionService globalOptions,
     IAsynchronousOperationListenerProvider listenerProvider,
     ClassificationType type)
     : base(threadingContext, globalOptions, listenerProvider.GetListener(FeatureAttribute.Classification))
 {
     _typeMap       = typeMap;
     _globalOptions = globalOptions;
     _type          = type;
 }
Beispiel #30
0
 public Matrix(string imagePath, int cols, int rows, Dictionary <string, Dictionary <string, double> > gridData)
 {
     this.GridData  = gridData;
     this.ImagePath = imagePath;
     this.Cols      = cols;
     this.Rows      = rows;
     this.Type      = ClassificationType.SELF;
     InitializeComponent();
     PostInit();
     Classify();
     BuildGrid();
     BuildTree();
 }
        static XamlSyntaxHighlightingHelper()
        {
            XamlAttribute = new ClassificationType("xamlAttribute");
            XamlElement = new ClassificationType("xamlElement");
            XamlComment = new ClassificationType("xamlComment");
            XamlTag = new ClassificationType("xamlTag");
            XamlString = new ClassificationType("xamlString");
            XamlContent = new ClassificationType("xamlContent");

            XamlAttributeFormatDefinition = new TextFormatDefinition(new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x00, 0x4E)));
            XamlElementFormatDefinition = new TextFormatDefinition(new SolidColorBrush(Color.FromArgb(0xFF, 0xA3, 0x15, 0x15)));
            XamlCommentFormatDefinition = new TextFormatDefinition(new SolidColorBrush(Color.FromArgb(0xFF, 0x53, 0x7D, 0x01)));
            XamlContentFormatDefinition = new TextFormatDefinition(new SolidColorBrush(Color.FromArgb(0xFF, 0x01, 0x60, 0xE5)));
            XamlStringFormatDefinition = new TextFormatDefinition(new SolidColorBrush(Color.FromArgb(0xFF, 0x01, 0x60, 0xE5)));
            XamlTagFormatDefinition = new TextFormatDefinition(new SolidColorBrush(Color.FromArgb(0xFF, 0x01, 0x60, 0xE5)));
        }
Beispiel #32
0
 public Cluster(IndivData p, ClassificationType t)
 {
     switch (t)
     {
         case ClassificationType.Hierar:
             AddHierar(p);
             break;
         case ClassificationType.KMeans:
             AddKMeans(p);
             break;
         case ClassificationType.Utility:
             AddUtility(p);
             break;
         default:
             break;
     }
 }
        /// <summary>
        /// Do the classification for a <paramref name="fileToClassify"/>.
        /// </summary>
        /// <returns>Task that represents the classification process.</returns>
		/// <param name="targetDirectory">The directory where files will be classified.</param>
		/// <param name="fileToClassify">The file to classify.</param>
        /// <param name="actionType">Specify action to classify media files.</param> 
		/// <param name="hierarchy">Hierarchy of classification.</param>
		public async Task ClassifiyFileAsync(string targetDirectory, string fileToClassify, ActionType actionType, ClassificationType[] hierarchy)
        {
			ClassifiableFile classifiable = await GetClassifiableFromFileAsync(fileToClassify, hierarchy);
			string classificationDirectory = GetClassificationDirectory(targetDirectory, classifiable, hierarchy);
			_directory.CreateDirectory(classificationDirectory);
			string targetFile = _path.Combine(classificationDirectory, _path.GetFileName(fileToClassify));
            switch(actionType)
            {
                case ActionType.Copy:
                    _file.Copy(fileToClassify, targetFile, true);
                    break;
                case ActionType.Move:
                    if (_file.Exists(targetFile))
                    {
                        if (_fileSystemHelper.IsSymbolicLink(targetFile))
                        {
                            _file.Delete(targetFile);
							_file.Move(fileToClassify, targetFile);
                        }
                        else
                        {
							_file.Delete(fileToClassify);
                        }
                    }
                    else
                    {
						_file.Move(fileToClassify, targetFile);
                    }
                    break;
                case ActionType.Link:
					_fileSystemHelper.CreateSymbolicLink(fileToClassify, _path.Combine(classificationDirectory, _path.GetFileName(fileToClassify)));
                    break;
            }
        }
        /// <summary>
        /// Gets the classification directory.
        /// </summary>
        /// <returns>The classification directory.</returns>
        /// <param name="classifiable">Classifiable.</param>
		/// <param name="hierarchy">Hierarchy of classification.</param>
		private string GetClassificationDirectory(string targetDirectory, ClassifiableFile classifiable, ClassificationType[] hierarchy)
		{
            string directory = targetDirectory;
            foreach (var currentOrder in hierarchy)
            {
                switch (currentOrder)
                {
                    case ClassificationType.Year:
                        directory = _path.Combine(directory, classifiable.DateTaken.Year.ToString());
                        break;
					case ClassificationType.Month:
						directory = _path.Combine(directory, classifiable.DateTaken.Month.ToString());
						break;
					case ClassificationType.Day:
						directory = _path.Combine(directory, classifiable.DateTaken.Day.ToString());
						break;
					case ClassificationType.Hour:
						directory = _path.Combine(directory, classifiable.DateTaken.Hour.ToString());
						break;
					case ClassificationType.Minute:
						directory = _path.Combine(directory, classifiable.DateTaken.Minute.ToString());
						break;
					case ClassificationType.Second:
						directory = _path.Combine(directory, classifiable.DateTaken.Second.ToString());
						break;
					case ClassificationType.Country:
						directory = _path.Combine(directory, 
							(classifiable.Location != null && !string.IsNullOrWhiteSpace(classifiable.Location.Country)) ? classifiable.Location.Country : "Unknown country".T());
						break;
					case ClassificationType.State:
						directory = _path.Combine(directory, 
							(classifiable.Location != null && !string.IsNullOrWhiteSpace(classifiable.Location.State)) ? classifiable.Location.State : "Unknown state".T());
						break;
					case ClassificationType.AdministrativeArea:
						directory = _path.Combine(directory, 
							(classifiable.Location != null && !string.IsNullOrWhiteSpace(classifiable.Location.AdministrativeArea)) ? classifiable.Location.AdministrativeArea : "Unknown administrative area".T());
						break;
					case ClassificationType.Locality:
						directory = _path.Combine(directory, 
							(classifiable.Location != null && !string.IsNullOrWhiteSpace(classifiable.Location.Locality)) ? classifiable.Location.Locality : "Unknown locality".T());
						break;
					case ClassificationType.Route:
						directory = _path.Combine(directory, 
							(classifiable.Location != null && !string.IsNullOrWhiteSpace(classifiable.Location.Route)) ? classifiable.Location.Route : "Unknown route".T());
						break;
					case ClassificationType.MediaType:
						directory = _path.Combine(directory, classifiable.MediaType.ToString());
						break;
                }
            }

            return directory;
        }
Beispiel #35
0
 /// <summary>
 /// Creates a new XDS.b Classification object
 /// </summary>
 /// <param name="cScheme">Classification Scheme</param>
 /// <param name="cObject">Classification Object</param>
 /// <param name="cNode">Classification Node</param>
 /// <param name="nRepr">Classification Representation</param>
 /// <param name="name">Classification Name</param>
 /// <param name="slots">Classification Slots</param>
 /// <returns>The new XDS Classification object.</returns>
 public static ClassificationType CreateClassification(string cScheme, string cObject, string cNode, string nRepr, string id, string name, SlotType[] slots)
 {
     ClassificationType c = new ClassificationType(cScheme, cObject, cNode, nRepr, id, name, slots);
     return c;
 }
        protected override void OnTokenKindChanged()
        {
            switch (this.Kind)
            {
                case TokenKind.WhiteSpace:
                    ClassificationType = ClassificationTypes.WhiteSpace;
                    break;

                case TokenKind.KeyWord:
                    ClassificationType = ClassificationTypes.Keyword;
                    break;

                case TokenKind.Literal:
                    ClassificationType = ClassificationTypes.Literal;
                    break;

                case TokenKind.Reference:
                    ClassificationType = ClassificationTypes.Identifier;
                    break;

                case TokenKind.Error:
                    ClassificationType = ClassificationTypes.Literal;
                    break;

                case TokenKind.MailSenderLink:
                    ClassificationType = JDClassificationTypes.MailLink;
                    break;

                case TokenKind.JDUpdateLinkButton:
                    ClassificationType = JDClassificationTypes.UpdateJdLink;
                    break;

                case TokenKind.JDUpdateText:
                    ClassificationType = JDClassificationTypes.UpdateJdText;
                    break;

                case TokenKind.Text:
                    ClassificationType = JDClassificationTypes.Text;
                    break;

                case TokenKind.NotResolvedReference:
                    ClassificationType = JDClassificationTypes.NotResolvedReference;
                    break;

                case TokenKind.DocumentationTag:
                    ClassificationType = JDClassificationTypes.DocumentationTag;
                    break;

                case TokenKind.Comment:
                    ClassificationType = ClassificationTypes.Comment;
                    break;

                case TokenKind.XmlAttribute:
                    ClassificationType = JDClassificationTypes.XmlAttribute;
                    break;

                case TokenKind.FakeReference:
                    ClassificationType = JDClassificationTypes.FakeIdentifier;
                    break;

                case TokenKind.NewLine:
                    ClassificationType = JDClassificationTypes.Text;
                    break;

                default:
                    ClassificationType = ClassificationTypes.StringLiteral;
                    break;
            }
        }