Ejemplo n.º 1
0
        public override string GetFormatName(GraphProperty property)
        {
            DisplayFormatAttribute formatAttribute = property.GetAttributes <DisplayFormatAttribute>().FirstOrDefault();

            return(formatAttribute != null && !string.IsNullOrWhiteSpace(formatAttribute.DataFormatString) ?
                   formatAttribute.DataFormatString : null);
        }
Ejemplo n.º 2
0
        public override string GetLabel(GraphProperty property)
        {
            DisplayAttribute displayAttribute = property.GetAttributes <DisplayAttribute>().FirstOrDefault();
            string           defaultLabel     = labelRegex.Replace(property.Name, " $1").Substring(1);

            return(displayAttribute != null?displayAttribute.GetName() : defaultLabel);
        }
Ejemplo n.º 3
0
 static GraphLayoutSchema()
 {
     schema = new GraphSchema("GraphLayoutSchema");
     boundsProperty = schema.Properties.AddNewProperty("Bounds", typeof(System.Windows.Rect));
     labelBoundsProperty = Schema.Properties.AddNewProperty("LabelBounds", typeof(System.Windows.Rect));
     active = Schema.Categories.AddNewCategory("Active");
 }
        /// <summary>
        /// Get the member expression for the given property name.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyInfo">Set to the property info.</param>
        /// <returns>Member expression.</returns>
        public static MemberExpression GetMemberExpression(
            Type entityType, GraphProperty propertyName, out PropertyInfo propertyInfo)
        {
            Utils.ThrowIfNull(entityType, "entityType");

            MemberInfo[] memberInfo = entityType.GetMember(propertyName.ToString());
            if (memberInfo == null || memberInfo.Length != 1)
            {
                throw new ArgumentException("Unable to resolve the property in the specified type.");
            }

            propertyInfo = memberInfo[0] as PropertyInfo;

            // Validate that the JsonProperty attribute can be found on this property
            object[] customAttributes = propertyInfo.GetCustomAttributes(
                typeof(JsonPropertyAttribute), true);

            if (customAttributes == null || customAttributes.Length != 1)
            {
                throw new ArgumentException(
                          "Invalid property used in the filter. JsonProperty attribute was not found.");
            }

            // Create a member expression on a dummy object to create a valid expression.
            // BUGBUG: We shouldn't be creating a dummy instance. We should instead be generating the list from
            // a where clause. Like:
            // var users = FROM graphConnection.Users SELECT users WHERE User.DisplayName == 'blah'
            MemberExpression memberExpression = Expression.MakeMemberAccess(
                Expression.Constant(Activator.CreateInstance(entityType)), memberInfo[0]);

            return(memberExpression);
        }
Ejemplo n.º 5
0
 public void AddDeferredPropertySet(GraphNode node, GraphProperty property, object value)
 {
     using (_gate.DisposableWait())
     {
         _deferredPropertySets.Add(Tuple.Create(node, property, value));
     }
 }
        /// <summary>
        /// Lower case the first letter of the graph property name.
        /// </summary>
        /// <param name="graphProperty">Graph property.</param>
        /// <returns>First letter will be lower case.</returns>
        public static string GetPropertyName(GraphProperty graphProperty)
        {
            if (graphProperty == GraphProperty.None || PropertyNameMap.NameMap.Count <= (int)graphProperty)
            {
                throw new ArgumentException("Invalid graph property");
            }

            return(PropertyNameMap.NameMap[(int)graphProperty]);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Validate the architecture
        /// </summary>
        /// <param name="graph">The graph</param>
        public void ValidateArchitecture(Graph graph)
        {
            if (graph == null)
            {
                throw new ArgumentNullException("graph");
            }

            // Uncomment the line below to debug this extension during validation
            // System.Windows.Forms.MessageBox.Show("Attach to GraphCmd.exe with process id " + System.Diagnostics.Process.GetCurrentProcess().Id);

            // Get the graph schema
            GraphSchema schema = graph.DocumentSchema;

            // Get the category for our custom property
            GraphProperty customPropertyCategory = schema.FindProperty(Validator1Property.FullName);

            if (customPropertyCategory == null)
            {
                // The property has not been used in the layer diagram. No need to validate further
                return;
            }

            // Get all layers on the diagram
            foreach (GraphNode layer in graph.Nodes.GetByCategory("Dsl.Layer"))
            {
                // Get the required regex property from the layer node
                string regexPattern = layer[customPropertyCategory] as string;
                if (!string.IsNullOrEmpty(regexPattern))
                {
                    Regex regEx = new Regex(regexPattern);

                    // Get all referenced types in this layer including those from nested layers so each
                    // type is validated against all containing layer constraints.
                    foreach (GraphNode containedType in layer.FindDescendants().Where(node => node.HasCategory("CodeSchema_Type")))
                    {
                        // Check the type name against the required regex
                        CodeGraphNodeIdBuilder builder = new CodeGraphNodeIdBuilder(containedType.Id, graph);
                        string typeName = builder.Type.Name;
                        if (!regEx.IsMatch(typeName))
                        {
                            // Log an error
                            string message = string.Format(CultureInfo.CurrentCulture, Resources.InvalidTypeNameMessage, typeName);
                            this.LogValidationError(graph, typeName + "TypeNameError", message, GraphErrorLevel.Error, layer, new GraphNode[] { containedType });
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Set the deferred stream property.
        /// </summary>
        /// <param name="graphObject">Graph object.</param>
        /// <param name="graphProperty">Property name.</param>
        /// <param name="memoryStream">Memory stream.</param>
        /// <param name="contentType">Content type.</param>
        public virtual void SetStreamProperty(
            GraphObject graphObject, GraphProperty graphProperty, MemoryStream memoryStream, string contentType)
        {
            Utils.ValidateGraphObject(graphObject, "graphObject");
            Utils.ThrowIfNullOrEmpty(memoryStream, "memoryStream");
            Utils.ThrowIfNullOrEmpty(contentType, "contentType");

            Uri requestUri = Utils.GetRequestUri(
                this, graphObject.GetType(), graphObject.ObjectId, Utils.GetPropertyName(graphProperty));

            WebHeaderCollection additionalHeaders = new WebHeaderCollection();

            additionalHeaders[HttpRequestHeader.ContentType] = contentType;

            this.ClientConnection.UploadData(requestUri, HttpVerb.PUT, memoryStream.ToArray(), additionalHeaders);
        }
Ejemplo n.º 9
0
        public GraphNode addNode(String Node, String Type)
        {
            string[] Groups = Node.Split('.');

            GraphNode dbGroup = null;

            if (Groups.Length == 3)
            {
                dbGroup         = graph.Nodes.GetOrCreate(Groups[0].ToUpper());
                dbGroup.Label   = Groups[0];
                dbGroup.IsGroup = true;
            }


            GraphNode schemaGroup = null;

            if (Groups.Length >= 2)
            {
                schemaGroup         = graph.Nodes.GetOrCreate(Groups[0].ToUpper() + "." + Groups[1].ToUpper());
                schemaGroup.Label   = Groups[0] + "." + Groups[1];
                schemaGroup.IsGroup = true;
                if (dbGroup != null)
                {
                    GraphLink gl = graph.Links.GetOrCreate(dbGroup, schemaGroup, "", GraphCommonSchema.Contains);
                }
            }
            GraphPropertyCollection properties = graph.DocumentSchema.Properties;
            GraphProperty           background = properties.AddNewProperty("Background", typeof(Brush));
            GraphProperty           objecttype = properties.AddNewProperty("ObjectType", typeof(String));


            GraphNode nodeSource = graph.Nodes.GetOrCreate(Node.ToUpper());

            nodeSource.Label = Node;

            if (Type != "")
            {
                nodeSource[background] = getBrushForType(Type);
                nodeSource[objecttype] = Type;
            }
            if (schemaGroup != null)
            {
                GraphLink gl2 = graph.Links.GetOrCreate(schemaGroup, nodeSource, "", GraphCommonSchema.Contains);
            }

            return(nodeSource);
        }
Ejemplo n.º 10
0
        public GraphNode addNodeNesting(String Node, String Type)
        {
            string[] Groups = Node.Split('.');

            var newNode = GraphNodeRecurs(null, Groups, 0);

            if (Type != "")
            {
                GraphPropertyCollection properties = graph.DocumentSchema.Properties;
                GraphProperty           background = properties.AddNewProperty("Background", typeof(Brush));
                GraphProperty           objecttype = properties.AddNewProperty("ObjectType", typeof(String));

                newNode[background] = getBrushForType(Type);
                newNode[objecttype] = Type;
            }
            return(newNode);
        }
Ejemplo n.º 11
0
        private string GetStringPropertyForGraphObject(GraphObject graphObject, string graphCommandDefinitionIdentifier, GraphProperty propertyWithoutContainingSymbol, GraphProperty propertyWithContainingSymbol)
        {
            var graphNode = graphObject as GraphNode;

            if (graphNode != null)
            {
                if (graphCommandDefinitionIdentifier != GraphCommandDefinition.Contains.Id)
                {
                    return graphNode.GetValue<string>(propertyWithContainingSymbol);
                }
                else
                {
                    return graphNode.GetValue<string>(propertyWithoutContainingSymbol);
                }
            }

            return null;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sends the asynchronous.
        /// </summary>
        /// <typeparam name="TRequest">The type of the request.</typeparam>
        /// <param name="client">The client.</param>
        /// <param name="request">The request.</param>
        /// <param name="tenant">The tenant.</param>
        /// <param name="scenarioId">The scenario identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The <see cref="IGraphResponse{T}" />.
        /// </returns>
        public static Task <IGraphResponse> SendAsync <TRequest>(
            this IGraphClient client,
            IGraphRequest <TRequest> request,
            string tenant,
            Guid scenarioId,
            CancellationToken cancellationToken = default(CancellationToken))
            where TRequest : class
        {
            if (!string.IsNullOrWhiteSpace(tenant))
            {
                request.Properties.Add(GraphProperty.Property(HttpConstants.HeaderNames.Tenant, tenant));
            }

            request.Properties.Add(GraphProperty.RequestProperty(HttpConstants.HeaderNames.ScenarioId, scenarioId));
            request.Properties.Add(GraphProperty.RequestProperty(HttpConstants.HeaderNames.ClientRequestId, Guid.NewGuid()));

            return(client.SendAsync <TRequest>(request, cancellationToken));
        }
Ejemplo n.º 13
0
        private string GetStringPropertyForGraphObject(
            GraphObject graphObject,
            string graphCommandDefinitionIdentifier,
            GraphProperty propertyWithoutContainingSymbol,
            GraphProperty propertyWithContainingSymbol
            )
        {
            if (graphObject is GraphNode graphNode)
            {
                if (graphCommandDefinitionIdentifier != GraphCommandDefinition.Contains.Id)
                {
                    return(graphNode.GetValue <string>(propertyWithContainingSymbol));
                }
                else
                {
                    return(graphNode.GetValue <string>(propertyWithoutContainingSymbol));
                }
            }

            return(null);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Get the deferred stream property.
        /// </summary>
        /// <param name="graphObject">Graph object.</param>
        /// <param name="graphProperty">Property name.</param>
        /// <returns>Memory stream for the byte buffer.</returns>
        /// <param name="acceptType">Accept type header value.</param>
        public virtual Stream GetStreamProperty(
            GraphObject graphObject, GraphProperty graphProperty, string acceptType)
        {
            Utils.ValidateGraphObject(graphObject, "graphObject");
            Utils.ThrowIfNullOrEmpty(acceptType, "acceptType");

            Uri requestUri = Utils.GetRequestUri(
                this, graphObject.GetType(), graphObject.ObjectId, Utils.GetPropertyName(graphProperty));

            WebHeaderCollection additionalHeaders = new WebHeaderCollection();

            additionalHeaders[HttpRequestHeader.ContentType] = acceptType;
            byte[] buffer = this.ClientConnection.DownloadData(requestUri, additionalHeaders);

            if (buffer != null)
            {
                return(new MemoryStream(buffer));
            }

            return(new MemoryStream());
        }
                /// <summary>
                /// Executed when the set accessor successfully completes. Raises the
                /// <see cref="INotifyPropertyChanged.PropertyChanged"/> event.
                /// </summary>
                /// <param name="eventArgs">Event arguments with information about the
                /// current execution context.</param>
                public override void OnSuccess(MethodExecutionEventArgs eventArgs)
                {
                    // Get the graph instance associated with the current object
                    GraphInstance instance = ((IGraphInstance)eventArgs.Instance).Instance;

                    GraphProperty graphProperty = instance.Type.Properties[property];

                    // Exit immediately if the property is not valid for the current graph type
                    if (graphProperty == null)
                    {
                        return;
                    }

                    object originalValue = eventArgs.MethodExecutionTag;
                    object currentValue  = instance[property];

                    // Raise property change if the current value is different from the original value
                    if ((originalValue == null ^ currentValue == null) || (originalValue != null && !originalValue.Equals(currentValue)))
                    {
                        graphProperty.OnPropertyChanged(instance, originalValue, currentValue);
                    }
                }
Ejemplo n.º 16
0
        internal Assemble(Dictionary <string, string> options, Sources sources)
        {
            this.options = options;
            this.sources = sources;
            this.graph   = new Graph();
            this.nodes   = new Dictionary <Dependency, GraphNode>();

            // set properties
            GraphPropertyCollection properties = this.graph.DocumentSchema.Properties;

            this.size      = properties.AddNewProperty("Size", typeof(string));
            this.group     = properties.AddNewProperty("Group", typeof(string));
            this.reference = properties.AddNewProperty("Reference", typeof(string));
            this.loc       = properties.AddNewProperty("LOC", typeof(int));

            this.sourcePath = options["source"];
            var length = this.sourcePath.Length;

            if (length > 0 && this.sourcePath[length - 1] == System.IO.Path.DirectorySeparatorChar)
            {
                this.sourcePath = this.sourcePath.Substring(0, length - 2);
            }
        }
        /// <summary>
        /// Creates a simple any expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static MethodCallExpression CreateAnyExpression(
            Type entityType, GraphProperty propertyName, object propertyValue)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");

            // TODO: Generate an empty Any() filter when the propertyValue is null.
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            PropertyInfo     propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            Type[] genericArguments = propertyType.GetGenericArguments();

            if (!propertyType.IsGenericType ||
                genericArguments == null ||
                genericArguments.Length != 1 ||
                !propertyType.Name.StartsWith(typeof(ChangeTrackingCollection <>).Name))
            {
                throw new ArgumentException("Any expression is not supported on this type.");
            }

            string expectedPropertyTypeFullName = propertyType.GetGenericArguments()[0].FullName;
            string propertyValueTypeFullName    = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            return(Expression.Call(
                       memberExpression, "Any", new Type[] { }, Expression.Constant(propertyValue)));
        }
        /// <summary>
        /// Creates a simple starts with expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static MethodCallExpression CreateStartsWithExpression(
            Type entityType, GraphProperty propertyName, string propertyValue)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            PropertyInfo     propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            string expectedPropertyTypeFullName = propertyType.FullName;
            string propertyValueTypeFullName    = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            return(Expression.Call(
                       memberExpression, "StartsWith", new Type[] { }, Expression.Constant(propertyValue)));
        }
Ejemplo n.º 19
0
 public void AddDeferredPropertySet(GraphNode node, GraphProperty property, object value)
 {
     using (_gate.DisposableWait())
     {
         _deferredPropertySets.Add(Tuple.Create(node, property, value));
     }
 }
Ejemplo n.º 20
0
 public virtual string GetLabel(GraphProperty property)
 {
     return(null);
 }
Ejemplo n.º 21
0
 set => SetValue(GraphProperty, value);
Ejemplo n.º 22
0
 /// <summary>
 /// Returns the default display format name for the given graph property.
 /// </summary>
 /// <param name="property">The graph property</param>
 /// <returns>The default display format name</returns>
 public virtual string GetFormatName(GraphProperty property)
 {
     return(null);
 }
        /// <summary>
        /// Creates a less than or equals expression, based on the property name and value.
        /// </summary>
        /// <param name="entityTpe">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        /// <remarks>
        /// Conditional expressions supported are Equals, GreaterThanEquals and LessThanEquals
        /// Equals binary expression is supported on all types.
        /// GreaterThanEquals and LessThanEquals are supported in int, long etc.. but not on
        /// strings. To generate these expressions on strings, we need to use the Compare function.
        /// </remarks>
        public static BinaryExpression CreateConditionalExpression(
            Type entityType, GraphProperty propertyName, object propertyValue, ExpressionType expressionType)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            if (expressionType != ExpressionType.Equal &&
                expressionType != ExpressionType.GreaterThanOrEqual &&
                expressionType != ExpressionType.LessThanOrEqual)
            {
                throw new ArgumentException("Unsupported expression type.", "expressionType");
            }

            PropertyInfo propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            string expectedPropertyTypeFullName = propertyType.FullName;

            // Nullable types have to converted before an Expression can be generated.
            bool isConversionRequired = false;
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
            {
                expectedPropertyTypeFullName = propertyType.GetGenericArguments()[0].FullName;
                isConversionRequired = true;
            }

            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            // ge and le are currently supported only on int and strings.
            // TODO: Enable it for DateTime
            if (expressionType == ExpressionType.GreaterThanOrEqual ||
                expressionType == ExpressionType.LessThanOrEqual)
            {
                if (!string.Equals(typeof(string).FullName, expectedPropertyTypeFullName) &&
                    !string.Equals(typeof(int).FullName, expectedPropertyTypeFullName))
                {
                    throw new ArgumentException("Comparison is supported only on string and int values.");
                }
            }

            // Get the method info for Compare and create the expression such that
            // string.compare(propertyName, 'value') <= 0
            Expression methodCallExpression = null;

            if (expectedPropertyTypeFullName.Equals(typeof(string).FullName))
            {
                methodCallExpression = Expression.Call(
                    ExpressionHelper.CompareMethodInfo,
                    memberExpression,
                    Expression.Constant(propertyValue));
            }

            switch (expressionType)
            {
                case ExpressionType.Equal:
                    if (isConversionRequired)
                    {
                        return Expression.Equal(memberExpression, Expression.Constant(propertyValue, propertyType));
                    }

                    return Expression.Equal(memberExpression, Expression.Constant(propertyValue));
                case ExpressionType.LessThanOrEqual:
                    return Expression.LessThanOrEqual(methodCallExpression, Expression.Constant(0));
                case ExpressionType.GreaterThanOrEqual:
                    return Expression.GreaterThanOrEqual(methodCallExpression, Expression.Constant(0));
                default:
                    throw new ArgumentException("Unsupported expression type.");
            }
        }
        /// <summary>
        /// Creates a simple starts with expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static MethodCallExpression CreateStartsWithExpression(
            Type entityType, GraphProperty propertyName, string propertyValue)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            PropertyInfo propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            string expectedPropertyTypeFullName = propertyType.FullName;
            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            return Expression.Call(
                memberExpression, "StartsWith", new Type[]{ } , Expression.Constant(propertyValue));
        }
Ejemplo n.º 25
0
 internal GraphRender(Graph graph)
 {
     _graph           = graph;
     _categories      = graph.DocumentSchema.Categories.ToDictionary(c => c.Id, c => c);
     _projectProperty = _graph.DocumentSchema.FindProperty("Project");
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Bot" /> class.
        /// </summary>
        /// <param name="options">The bot options.</param>
        /// <param name="graphLogger">The graph logger.</param>
        public Bot(BotOptions options, IGraphLogger graphLogger)
        {
            this.botBaseUri = options.BotBaseUrl;
            this.appId      = options.AppId;

            this.GraphLogger = graphLogger;
            var name = this.GetType().Assembly.GetName().Name;

            this.AuthenticationProvider = new AuthenticationProvider(name, options.AppId, options.AppSecret, graphLogger);
            this.Serializer             = new CommsSerializer();

            var authenticationWrapper = new AuthenticationWrapper(this.AuthenticationProvider);

            this.NotificationProcessor = new NotificationProcessor(authenticationWrapper, this.Serializer);
            this.NotificationProcessor.OnNotificationReceived += this.NotificationProcessor_OnNotificationReceived;
            this.RequestBuilder = new GraphServiceClient(options.PlaceCallEndpointUrl.AbsoluteUri, authenticationWrapper);

            // Add the default headers used by the graph client.
            // This will include SdkVersion.
            var defaultProperties = new List <IGraphProperty <IEnumerable <string> > >();

            using (HttpClient tempClient = GraphClientFactory.Create(authenticationWrapper))
            {
                defaultProperties.AddRange(tempClient.DefaultRequestHeaders.Select(header => GraphProperty.RequestProperty(header.Key, header.Value)));
            }

            // graph client
            var productInfo = new ProductInfoHeaderValue(
                typeof(Bot).Assembly.GetName().Name,
                typeof(Bot).Assembly.GetName().Version.ToString());

            this.GraphApiClient = new GraphAuthClient(
                this.GraphLogger,
                this.Serializer.JsonSerializerSettings,
                new HttpClient(),
                this.AuthenticationProvider,
                productInfo,
                defaultProperties);
        }
Ejemplo n.º 27
0
 public override string GetLabel(GraphProperty property)
 {
     DisplayAttribute displayAttribute = property.GetAttributes<DisplayAttribute>().FirstOrDefault();
     string defaultLabel = labelRegex.Replace(property.Name, " $1").Substring(1);
     return displayAttribute != null ? displayAttribute.GetName() : defaultLabel;
 }
Ejemplo n.º 28
0
 public override string GetFormatName(GraphProperty property)
 {
     DisplayFormatAttribute formatAttribute = property.GetAttributes<DisplayFormatAttribute>().FirstOrDefault();
         return formatAttribute != null && !string.IsNullOrWhiteSpace(formatAttribute.DataFormatString) ?
         formatAttribute.DataFormatString : null;
 }
Ejemplo n.º 29
0
 public virtual string GetLabel(GraphProperty property)
 {
     return null;
 }
 static DependenciesGraphSchema()
 {
     IsFrameworkAssemblyFolderProperty = Schema.Properties.AddNewProperty(IsFrameworkAssemblyFolderPropertyId, typeof(bool));
     DependencyProperty = Schema.Properties.AddNewProperty(DependencyPropertyId, typeof(IDependency));
 }
 /// <summary>
 /// Creates a greater than or equals expression, based on the property name and value.
 /// </summary>
 /// <param name="entityType">Entity type.</param>
 /// <param name="propertyName">Property name.</param>
 /// <param name="propertyValue">Property value.</param>
 /// <returns>Equals expression node.</returns>
 public static BinaryExpression CreateGreaterThanEqualsExpression(
     Type entityType, GraphProperty propertyName, object propertyValue)
 {
     return ExpressionHelper.CreateConditionalExpression(
         entityType, propertyName, propertyValue, ExpressionType.GreaterThanOrEqual);
 }
Ejemplo n.º 32
0
        static RoslynGraphProperties()
        {
            Schema = new GraphSchema("Roslyn");

            SymbolKind = Schema.Properties.AddNewProperty(
                id: "SymbolKind",
                dataType: typeof(SymbolKind),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            TypeKind = Schema.Properties.AddNewProperty(
                id: "TypeKind",
                dataType: typeof(TypeKind),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            MethodKind = Schema.Properties.AddNewProperty(
                id: "MethodKind",
                dataType: typeof(MethodKind),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            DeclaredAccessibility = Schema.Properties.AddNewProperty(
                id: "DeclaredAccessibility",
                dataType: typeof(Accessibility),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            SymbolModifiers = Schema.Properties.AddNewProperty(
                id: "SymbolModifiers",
                dataType: typeof(DeclarationModifiers),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            ExplicitInterfaceImplementations = Schema.Properties.AddNewProperty(
                id: "ExplicitInterfaceImplementations",
                dataType: typeof(IList <SymbolKey>),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            SymbolId = Schema.Properties.AddNewProperty(
                id: "SymbolId",
                dataType: typeof(SymbolKey?),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            ContextProjectId = Schema.Properties.AddNewProperty(
                id: "ContextProjectId",
                dataType: typeof(ProjectId),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            ContextDocumentId = Schema.Properties.AddNewProperty(
                id: "ContextDocumentId",
                dataType: typeof(DocumentId),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            Label = Schema.Properties.AddNewProperty(
                id: "Label",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            FormattedLabelWithoutContainingSymbol = Schema.Properties.AddNewProperty(
                id: "FormattedLabelWithoutContainingSymbol",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            FormattedLabelWithContainingSymbol = Schema.Properties.AddNewProperty(
                id: "FormattedLabelWithContainingSymbol",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            Description = Schema.Properties.AddNewProperty(
                id: "Description",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            DescriptionWithContainingSymbol = Schema.Properties.AddNewProperty(
                id: "DescriptionWithContainingSymbol",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));
        }
        /// <summary>
        /// Get the member expression for the given property name.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyInfo">Set to the property info.</param>
        /// <returns>Member expression.</returns>
        public static MemberExpression GetMemberExpression(
            Type entityType, GraphProperty propertyName, out PropertyInfo propertyInfo)
        {
            Utils.ThrowIfNull(entityType, "entityType");

            MemberInfo[] memberInfo = entityType.GetMember(propertyName.ToString());
            if (memberInfo == null || memberInfo.Length != 1)
            {
                throw new ArgumentException("Unable to resolve the property in the specified type.");
            }

            propertyInfo = memberInfo[0] as PropertyInfo;

            // Validate that the JsonProperty attribute can be found on this property
            object[] customAttributes = propertyInfo.GetCustomAttributes(
                typeof(JsonPropertyAttribute), true);

            if (customAttributes == null || customAttributes.Length != 1)
            {
                throw new ArgumentException(
                    "Invalid property used in the filter. JsonProperty attribute was not found.");
            }

            // Create a member expression on a dummy object to create a valid expression.
            // BUGBUG: We shouldn't be creating a dummy instance. We should instead be generating the list from
            // a where clause. Like: 
            // var users = FROM graphConnection.Users SELECT users WHERE User.DisplayName == 'blah'
            MemberExpression memberExpression = Expression.MakeMemberAccess(
                Expression.Constant(Activator.CreateInstance(entityType)), memberInfo[0]);

            return memberExpression;
        }
 static DependenciesGraphSchema()
 {
     ProviderProperty       = Schema.Properties.AddNewProperty(ProviderPropertyId, typeof(IProjectDependenciesSubTreeProvider));
     DependencyNodeProperty = Schema.Properties.AddNewProperty(DependencyPropertyId, typeof(IDependencyNode));
 }
        /// <summary>
        /// Creates a simple any expression, based on the property name and value.
        /// </summary>
        /// <param name="entityType">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        public static MethodCallExpression CreateAnyExpression(
            Type entityType, GraphProperty propertyName, object propertyValue)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");

            // TODO: Generate an empty Any() filter when the propertyValue is null.
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            PropertyInfo propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;
            Type[] genericArguments = propertyType.GetGenericArguments();

            if (!propertyType.IsGenericType ||
                genericArguments == null ||
                genericArguments.Length != 1 ||
                !propertyType.Name.StartsWith(typeof(ChangeTrackingCollection<>).Name))
            {
                throw new ArgumentException("Any expression is not supported on this type.");
            }

            string expectedPropertyTypeFullName = propertyType.GetGenericArguments()[0].FullName;
            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            return Expression.Call(
                memberExpression, "Any", new Type[] { }, Expression.Constant(propertyValue));
        }
Ejemplo n.º 36
0
        public async Task TestSimple()
        {
            Simple.Place cave = new Simple.Place()
            {
                name = "Cave of Hobbit"
            };
            Simple.Place restaurant = new Simple.Place()
            {
                name = "Restaurant Green Dragon"
            };
            Simple.Place europe = new Simple.Place()
            {
                name    = "Europe",
                country = GraphProperty.Create("country", "AT", "MetaTag1", "Austria").AddValue("FI", "MetaTag1", "Finnland")
            };
            Simple.Path hobbitPath = new Simple.Path(cave, restaurant, 2); //TODO: find out why 2.3 has an issue

            await client.CreateGraphDocumentAsync <Simple.Place>(collection, cave);

            await client.CreateGraphDocumentAsync <Simple.Place>(collection, restaurant);

            await client.CreateGraphDocumentAsync <Simple.Place>(collection, europe);

            await client.CreateGraphDocumentAsync <Simple.Path>(collection, hobbitPath);

            MemoryGraph partialGraph = new MemoryGraph();

            string gremlinQueryStatement = "g.V().hasLabel('place')";

            Console.WriteLine($"Executing gremlin query as string: {gremlinQueryStatement}");
            var germlinQuery = client.CreateGremlinQuery <Vertex>(collection, gremlinQueryStatement);

            while (germlinQuery.HasMoreResults)
            {
                // It is not required to pass in a context like partialGraph here. This parameter can be omitted.
                foreach (var result in await germlinQuery.ExecuteNextAsyncAsPOCO <Simple.Place>(partialGraph))
                {
                    Console.WriteLine($"Vertex ==> Label:{result.Label} Name:{result.name}");
                }
            }

            #region EXPERIMENTAL DEMO
            /// =================================================================================================
            /// IMPORTANT: The following code makes use of the internal GraphTraversal class, which should not
            /// be used according to the documentation of Microsofts Graph Library. Use at your own risk.
            /// =================================================================================================
            // Connect with GraphConnection
            object graphConnection = GraphConnectionFactory.Create(client, collection);
            // Drop previous context (optional if the same graph)
            partialGraph.Drop();
            Microsoft.Azure.Graphs.GraphCommand cmd = GraphCommandFactory.Create(graphConnection);

            GraphTraversal placeTrav = cmd.g().V().HasLabel("place");
            GraphTraversal edgeTrav  = cmd.g().E().HasLabel("path");
            {
                Console.WriteLine("Retrieving all places with 'NextAsPOCO'-Extension on GraphTraversal ");
                // Returns a list of all vertices for place
                var places = await placeTrav.NextAsPOCO <Simple.Place>(partialGraph);

                foreach (Simple.Place place in places)
                {
                    Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}");
                }
            }

            // Drop previous context (optional if the same graph)
            partialGraph.Drop();
            IGraphSerializer <Simple.Place> placeGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Simple.Place>(partialGraph);
            foreach (var p in placeTrav)
            {
                IList <Simple.Place> places = placeGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each call
                foreach (Simple.Place place in places)
                {
                    Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}");
                    Console.WriteLine("Serializing to CosmosDB internal represenation: ");
                    string docDBJson = placeGraphSerializer.ConvertToDocDBJObject(place).ToString();
                    Console.WriteLine($"JSON ==> {docDBJson}");
                }
            }

            Console.WriteLine("Iterating over GraphTraversal Paths (Edges) and deserializing GraphSON to custom object ");
            IGraphSerializer <Simple.Path> pathGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Simple.Path>(partialGraph);
            foreach (var p in edgeTrav)
            {
                IList <Simple.Path> paths = pathGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each loop
                foreach (Simple.Path path in paths)
                {
                    Console.WriteLine($"Edge ==> Label:{path.Label} Weight:{path.weight}");
                    Console.WriteLine("Serializing to CosmosDB internal represenation: ");
                    string docDBJson = pathGraphSerializer.ConvertToDocDBJObject(path).ToString();
                    Console.WriteLine($"JSON ==> {docDBJson}");
                }
            }
            #endregion
        }
Ejemplo n.º 37
0
 static DependenciesGraphSchema()
 {
     ResolvedProperty     = Schema.Properties.AddNewProperty(ResolvedPropertyId, typeof(bool));
     DependencyIdProperty = Schema.Properties.AddNewProperty(DependencyIdPropertyId, typeof(string));
     IsFrameworkAssemblyFolderProperty = Schema.Properties.AddNewProperty(IsFrameworkAssemblyFolderPropertyId, typeof(bool));
 }
 /// <summary>
 /// Creates a greater than or equals expression, based on the property name and value.
 /// </summary>
 /// <param name="entityType">Entity type.</param>
 /// <param name="propertyName">Property name.</param>
 /// <param name="propertyValue">Property value.</param>
 /// <returns>Equals expression node.</returns>
 public static BinaryExpression CreateGreaterThanEqualsExpression(
     Type entityType, GraphProperty propertyName, object propertyValue)
 {
     return(ExpressionHelper.CreateConditionalExpression(
                entityType, propertyName, propertyValue, ExpressionType.GreaterThanOrEqual));
 }
Ejemplo n.º 39
0
        static RoslynGraphProperties()
        {
            Schema = new GraphSchema("Roslyn");

            SymbolKind = Schema.Properties.AddNewProperty(
                id: "SymbolKind",
                dataType: typeof(SymbolKind),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            TypeKind = Schema.Properties.AddNewProperty(
                id: "TypeKind",
                dataType: typeof(TypeKind),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            MethodKind = Schema.Properties.AddNewProperty(
                id: "MethodKind",
                dataType: typeof(MethodKind),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            DeclaredAccessibility = Schema.Properties.AddNewProperty(
                id: "DeclaredAccessibility",
                dataType: typeof(Accessibility),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            SymbolModifiers = Schema.Properties.AddNewProperty(
                id: "SymbolModifiers",
                dataType: typeof(DeclarationModifiers),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            ExplicitInterfaceImplementations = Schema.Properties.AddNewProperty(
                id: "ExplicitInterfaceImplementations",
                dataType: typeof(IList<SymbolKey>),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            SymbolId = Schema.Properties.AddNewProperty(
                id: "SymbolId",
                dataType: typeof(SymbolKey?),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            ContextProjectId = Schema.Properties.AddNewProperty(
                id: "ContextProjectId",
                dataType: typeof(ProjectId),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            ContextDocumentId = Schema.Properties.AddNewProperty(
                id: "ContextDocumentId",
                dataType: typeof(DocumentId),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            Label = Schema.Properties.AddNewProperty(
                id: "Label",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            FormattedLabelWithoutContainingSymbol = Schema.Properties.AddNewProperty(
                id: "FormattedLabelWithoutContainingSymbol",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            FormattedLabelWithContainingSymbol = Schema.Properties.AddNewProperty(
                id: "FormattedLabelWithContainingSymbol",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            Description = Schema.Properties.AddNewProperty(
                id: "Description",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));

            DescriptionWithContainingSymbol = Schema.Properties.AddNewProperty(
                id: "DescriptionWithContainingSymbol",
                dataType: typeof(string),
                callback: () => new GraphMetadata(options: GraphMetadataOptions.Sharable | GraphMetadataOptions.Removable));
        }
        /// <summary>
        /// Creates a less than or equals expression, based on the property name and value.
        /// </summary>
        /// <param name="entityTpe">Entity type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="propertyValue">Property value.</param>
        /// <returns>Equals expression node.</returns>
        /// <remarks>
        /// Conditional expressions supported are Equals, GreaterThanEquals and LessThanEquals
        /// Equals binary expression is supported on all types.
        /// GreaterThanEquals and LessThanEquals are supported in int, long etc.. but not on
        /// strings. To generate these expressions on strings, we need to use the Compare function.
        /// </remarks>
        public static BinaryExpression CreateConditionalExpression(
            Type entityType, GraphProperty propertyName, object propertyValue, ExpressionType expressionType)
        {
            Utils.ThrowIfNull(entityType, "entityType");
            Utils.ThrowIfNullOrEmpty(propertyName, "propertyName");
            Utils.ThrowIfNullOrEmpty(propertyValue, "propertyValue");

            if (expressionType != ExpressionType.Equal &&
                expressionType != ExpressionType.GreaterThanOrEqual &&
                expressionType != ExpressionType.LessThanOrEqual)
            {
                throw new ArgumentException("Unsupported expression type.", "expressionType");
            }

            PropertyInfo     propertyInfo;
            MemberExpression memberExpression = ExpressionHelper.GetMemberExpression(
                entityType, propertyName, out propertyInfo);

            Type propertyType = propertyInfo.PropertyType;

            string expectedPropertyTypeFullName = propertyType.FullName;

            // Nullable types have to converted before an Expression can be generated.
            bool isConversionRequired = false;

            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                expectedPropertyTypeFullName = propertyType.GetGenericArguments()[0].FullName;
                isConversionRequired         = true;
            }

            string propertyValueTypeFullName = propertyValue.GetType().FullName;

            if (!String.Equals(expectedPropertyTypeFullName, propertyValueTypeFullName))
            {
                throw new ArgumentException("Property types do not match.");
            }

            // ge and le are currently supported only on int and strings.
            // TODO: Enable it for DateTime
            if (expressionType == ExpressionType.GreaterThanOrEqual ||
                expressionType == ExpressionType.LessThanOrEqual)
            {
                if (!string.Equals(typeof(string).FullName, expectedPropertyTypeFullName) &&
                    !string.Equals(typeof(int).FullName, expectedPropertyTypeFullName))
                {
                    throw new ArgumentException("Comparison is supported only on string and int values.");
                }
            }

            // Get the method info for Compare and create the expression such that
            // string.compare(propertyName, 'value') <= 0
            Expression methodCallExpression = null;

            if (expectedPropertyTypeFullName.Equals(typeof(string).FullName))
            {
                methodCallExpression = Expression.Call(
                    ExpressionHelper.CompareMethodInfo,
                    memberExpression,
                    Expression.Constant(propertyValue));
            }

            switch (expressionType)
            {
            case ExpressionType.Equal:
                if (isConversionRequired)
                {
                    return(Expression.Equal(memberExpression, Expression.Constant(propertyValue, propertyType)));
                }

                return(Expression.Equal(memberExpression, Expression.Constant(propertyValue)));

            case ExpressionType.LessThanOrEqual:
                return(Expression.LessThanOrEqual(methodCallExpression, Expression.Constant(0)));

            case ExpressionType.GreaterThanOrEqual:
                return(Expression.GreaterThanOrEqual(methodCallExpression, Expression.Constant(0)));

            default:
                throw new ArgumentException("Unsupported expression type.");
            }
        }
        static async Task Demo()
        {
            try
            {
                Console.WriteLine("=========================================================");
                Console.WriteLine("Demo for the SpectoLogic.Azure.CosmosDB Extension Library");
                Console.WriteLine("(c) by SpectoLogic e.U. 2017");
                Console.WriteLine("written by Andreas Pollak");
                Console.WriteLine("Licensed under the MIT License");
                Console.WriteLine("=========================================================");

                // Connect with DocumentClient and create necessary Database and Collection
                Console.Write("Creating Collection 'thehobbit'...");
                DocumentClient client = await CosmosDBHelper.ConnectToCosmosDB(Account_DemoBuild_Hobbit, Account_DemoBuild_Hobbit_Key);

                Database db = await CosmosDBHelper.CreateOrGetDatabase(client, "demodb");

                DocumentCollection collection = await CosmosDBHelper.CreateCollection(client, db, "thehobbit", 400, null, null, false);

                Console.WriteLine("Done");

                Console.WriteLine("---------------------------------------------------------");
                Console.WriteLine("DEMO: Delivery Demo ");
                Console.WriteLine("---------------------------------------------------------");

                Delivery.Demo d = new Delivery.Demo();
                await d.Execute(client, collection);

                Console.WriteLine("---------------------------------------------------------");
                Console.WriteLine("DEMO: Create custom objects and populate cosmosdb graph");
                Console.WriteLine("---------------------------------------------------------");

                Place cave = new Place()
                {
                    name = "Cave of Hobbit"
                };
                Place restaurant = new Place()
                {
                    name = "Restaurant Green Dragon"
                };
                Place europe = new Place()
                {
                    name    = "Europe",
                    country = GraphProperty.Create("country", "AT", "MetaTag1", "Austria").AddValue("FI", "MetaTag1", "Finnland")
                };
                Path hobbitPath = new Path(cave, restaurant, 2); //TODO: find out why 2.3 has an issue

                await client.CreateGraphDocumentAsync <Place>(collection, cave);

                await client.CreateGraphDocumentAsync <Place>(collection, restaurant);

                await client.CreateGraphDocumentAsync <Place>(collection, europe);

                await client.CreateGraphDocumentAsync <Path>(collection, hobbitPath);

                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("DEMO: Usage of 'ExecuteNextAsyncAsPOCO<T>'-Extension Method on typed Gremlin Query");
                Console.WriteLine("----------------------------------------------------------------------------------");

                MemoryGraph partialGraph = new MemoryGraph();

                string gremlinQueryStatement = "g.V().hasLabel('place')";
                Console.WriteLine($"Executing gremlin query as string: {gremlinQueryStatement}");
                var germlinQuery = client.CreateGremlinQuery <Vertex>(collection, gremlinQueryStatement);
                while (germlinQuery.HasMoreResults)
                {
                    // It is not required to pass in a context like partialGraph here. This parameter can be omitted.
                    foreach (var result in await germlinQuery.ExecuteNextAsyncAsPOCO <Place>(partialGraph))
                    {
                        Console.WriteLine($"Vertex ==> Label:{result.Label} Name:{result.name}");
                    }
                }

                #region EXPERIMENTAL DEMO
                /// =================================================================================================
                /// IMPORTANT: The following code makes use of the internal GraphTraversal class, which should not
                /// be used according to the documentation of Microsofts Graph Library. Use at your own risk.
                /// =================================================================================================
                Console.WriteLine("--------------------------------------------------------------------");
                Console.WriteLine("DEMO: Usage of 'NextAsPOCO<T>' with GraphCommand and GraphTraversal ");
                Console.WriteLine("--------------------------------------------------------------------");
                Console.Write("Connecting with GraphConnection object...");
                // Connect with GraphConnection
                object graphConnection = GraphConnectionFactory.Create(client, collection);
                Console.WriteLine("Done");

                // Drop previous context (optional if the same graph)
                partialGraph.Drop();

                Microsoft.Azure.Graphs.GraphCommand cmd = GraphCommandFactory.Create(graphConnection);

                GraphTraversal placeTrav = cmd.g().V().HasLabel("place");
                GraphTraversal edgeTrav  = cmd.g().E().HasLabel("path");
                {
                    Console.WriteLine("Retrieving all places with 'NextAsPOCO'-Extension on GraphTraversal ");
                    // Returns a list of all vertices for place
                    var places = await placeTrav.NextAsPOCO <Place>(partialGraph);

                    foreach (Place place in places)
                    {
                        Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}");
                    }
                }

                Console.WriteLine("--------------------------------------------------------------------");
                Console.WriteLine("DEMO: Direct Usage of GraphSerializer<T> with GraphTraversal  ");
                Console.WriteLine("--------------------------------------------------------------------");
                // Drop previous context (optional if the same graph)
                partialGraph.Drop();

                Console.WriteLine("Iterating over GraphTraversal Places (Vertices) and deserializing GraphSON to custom object ");
                IGraphSerializer <Place> placeGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Place>(partialGraph);
                foreach (var p in placeTrav)
                {
                    IList <Place> places = placeGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each call
                    foreach (Place place in places)
                    {
                        Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}");
                        Console.WriteLine("Serializing to CosmosDB internal represenation: ");
                        string docDBJson = placeGraphSerializer.ConvertToDocDBJObject(place).ToString();
                        Console.WriteLine($"JSON ==> {docDBJson}");
                    }
                }

                Console.WriteLine("Iterating over GraphTraversal Paths (Edges) and deserializing GraphSON to custom object ");
                IGraphSerializer <Path> pathGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Path>(partialGraph);
                foreach (var p in edgeTrav)
                {
                    IList <Path> paths = pathGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each loop
                    foreach (Path path in paths)
                    {
                        Console.WriteLine($"Edge ==> Label:{path.Label} Weight:{path.weight}");
                        Console.WriteLine("Serializing to CosmosDB internal represenation: ");
                        string docDBJson = pathGraphSerializer.ConvertToDocDBJObject(path).ToString();
                        Console.WriteLine($"JSON ==> {docDBJson}");
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nError:");
                Console.WriteLine($"Demo failed with {ex.Message}.");
            }
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Returns the default display format name for the given graph property.
 /// </summary>
 /// <param name="property">The graph property</param>
 /// <returns>The default display format name</returns>
 public virtual string GetFormatName(GraphProperty property)
 {
     return null;
 }