Exemple #1
0
        /// <summary>
        /// Searches the database for nodes with the given name as used
        /// for mapping new additions.
        /// </summary>
        /// <param name="nodeName">The name of the node to map</param>
        /// <param name="dataType">The data type of the node being searched</param>
        /// <returns>A list of matching records</returns>
        public List <AutocompleteRecord> MappingSearch(string nodeName, NodeContentType dataType)
        {
            List <AutocompleteRecord> records = new List <AutocompleteRecord>();

            // Create a session
            using (ISession session = connection.Connect(autocompleteKeySpace))
            {
                PreparedStatement      statement   = session.Prepare($"SELECT * FROM {autocompleteTable} WHERE prefix = ? AND remaining = ?");
                Tuple <string, string> nameBinding = BindName(nodeName);
                // Run the statement
                RowSet result = session.Execute(statement.Bind(nameBinding.Item1, nameBinding.Item2));
                if (result.Count() > 0)
                {
                    // For each of the rows in the result
                    foreach (Row r in result)
                    {
                        records.Add(new AutocompleteRecord
                        {
                            CommonName  = r.GetValue <string>("commonnme"),
                            MatchedName = r.GetValue <string>("name"),
                            DataType    = (NodeContentType)r.GetValue <int>("datatype"),
                            Id          = r.GetValue <string>("id"),
                        });
                    }
                }
            }

            return(records.Where(x => x.DataType == dataType).ToList());
        }
Exemple #2
0
        public static BasicNodeModel FromINode(INode node)
        {
            BasicNodeModel result = null;

            try
            {
                NodeContentType contentType = (NodeContentType)Enum.Parse(typeof(NodeContentType), node.Labels[0]);
                if (contentType == NodeContentType.Company)
                {
                    result = new CompanyNodeModel
                    {
                        Id          = Guid.Parse(node.Properties["id"].As <string>()),
                        ContentType = contentType,
                        ReleaseDate = node.Properties.ContainsKey("releaseDate") ? DateTime.Parse(node.Properties["releaseDate"].As <string>()) : default(DateTime?),
                        DeathDate   = node.Properties.ContainsKey("deathDate") ? DateTime.Parse(node.Properties["deathDate"].As <string>()) : default(DateTime?),
                        CommonName  = node.Properties.ContainsKey("commonName") ? node.Properties["commonName"].As <string>() : null,
                        OtherNames  = node.Properties.ContainsKey("otherNames") ? node.Properties["otherNames"].As <List <string> >() : new List <string>()
                    };
                }
                else if (contentType == NodeContentType.Media)
                {
                    result = new MediaNodeModel
                    {
                        Id          = Guid.Parse(node.Properties["id"].As <string>()),
                        ContentType = contentType,
                        ReleaseDate = node.Properties.ContainsKey("releaseDate") ? DateTime.Parse(node.Properties["releaseDate"].As <string>()) : default(DateTime?),
                        DeathDate   = node.Properties.ContainsKey("deathDate") ? DateTime.Parse(node.Properties["deathDate"].As <string>()) : default(DateTime?),
                        CommonName  = node.Properties.ContainsKey("commonName") ? node.Properties["commonName"].As <string>() : null,
                        OtherNames  = node.Properties.ContainsKey("otherNames") ? node.Properties["otherNames"].As <List <string> >() : new List <string>(),
                        // Media properties
                        MediaType     = (NodeMediaType)Enum.Parse(typeof(NodeMediaType), node.Labels[1]),
                        FranchiseName = node.Properties.ContainsKey("franchise") ? node.Properties["franchise"].As <string>() : null,
                        Genres        = node.Properties.ContainsKey("genres") ? node.Properties["genres"].As <List <string> >() : new List <string>()
                    };
                }
                else if (contentType == NodeContentType.Person)
                {
                    result = new PersonNodeModel
                    {
                        Id          = Guid.Parse(node.Properties["id"].As <string>()),
                        ContentType = contentType,
                        ReleaseDate = node.Properties.ContainsKey("releaseDate") ? DateTime.Parse(node.Properties["releaseDate"].As <string>()) : default(DateTime?),
                        DeathDate   = node.Properties.ContainsKey("deathDate") ? DateTime.Parse(node.Properties["deathDate"].As <string>()) : default(DateTime?),
                        CommonName  = node.Properties.ContainsKey("commonName") ? node.Properties["commonName"].As <string>() : null,
                        OtherNames  = node.Properties.ContainsKey("otherNames") ? node.Properties["otherNames"].As <List <string> >() : new List <string>(),
                        // Person properties
                        FamilyName = node.Properties.ContainsKey("familyName") ? node.Properties["familyName"].As <string>() : null,
                        GivenName  = node.Properties.ContainsKey("givenName") ? node.Properties["givenName"].As <string>() : null,
                        Status     = node.Properties.ContainsKey("status") ? (PersonStatus)Enum.Parse(typeof(PersonStatus), node.Properties["status"].As <string>()) : 0
                    };
                }
            }
            catch (Exception e)
            {
                throw new ArgumentException("Failed to parse the given node: (Type: " + node.Labels[0] + " Id: " + node.Properties["id"].As <string>(), e);
            }

            return(result);
        }
Exemple #3
0
        private void BuildRelationshipMergeStatement(StringBuilder builder, IEnumerable <RelationshipModel> relationships,
                                                     NodeContentType targetType, NodeContentType sourceType)
        {
            int    targetIndex = 0;
            string label       = Enum.GetName(typeof(NodeContentType), targetType);

            foreach (RelationshipModel relModel in relationships)
            {
                string identifier = $"target{label}{targetIndex}";
                builder.AppendFormat("MERGE ({0}:{1} ", identifier, label);
                // Start the properties section
                builder.Append('{');
                // Append the properties
                if (relModel.TargetId != null && relModel.TargetId != Guid.Empty)
                {
                    // We have the id
                    builder.AppendFormat("id:'{0}'", relModel.TargetId.ToString());
                }
                else
                {
                    // We do not have the id - create a new node
                    builder.AppendFormat("commonName:'{0}'", relModel.TargetName);
                }
                // End the properties section
                builder.Append("}) ");

                // If we merged based on the name,
                if (relModel.TargetId == null || relModel.TargetId == Guid.Empty)
                {
                    // Append an ON CREATE statement to get the created node an id
                    builder.AppendFormat("ON CREATE SET {0}.id = '{1}' ", identifier, Guid.NewGuid().ToString());
                }
                builder.AppendLine();

                // Append the creation statement for the relationship
                string relProps = "{roles: " + JsonConvert.SerializeObject(relModel.Roles) + "}";
                if (sourceType != targetType)
                {
                    builder.AppendFormat(kCreateRelationshipStatement, identifier, label, relProps, "n");
                }
                else
                {
                    builder.AppendFormat(kCreateRelationshipStatement, "n", label, relProps, identifier);
                }
                builder.AppendLine();

                // Incremenet targetIndex
                targetIndex++;
            }
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("Binding context is null", "bindingContext");
            }
            HttpRequestBase    request = controllerContext.HttpContext.Request;
            BasicNodeViewModel result  = null;

            NodeContentType contentType = (NodeContentType)Enum.Parse(typeof(NodeContentType), request.Form["ContentType"]);
            DateTime?       releaseDate = request.Form["ReleaseDate"] != null?ParseDateTime(request.Form["ReleaseDate"]) : null;

            DateTime?deathDate = contentType == NodeContentType.Media ? null : request.Form["DeathDate"] != null?ParseDateTime(request.Form["DeathDate"]) : null;

            if (contentType == NodeContentType.Company)
            {
                result = new CompanyNodeViewModel();
            }
            else if (contentType == NodeContentType.Media)
            {
                result = new MediaNodeViewModel
                {
                    Genres        = ParseFromJson <IEnumerable <string> >(request.Form["Genres"]),
                    MediaType     = (NodeMediaType)Enum.Parse(typeof(NodeMediaType), request.Form["MediaType"]),
                    FranchiseName = request.Form["FranchiseName"].Trim()
                };
            }
            else if (contentType == NodeContentType.Person)
            {
                result = new PersonNodeViewModel
                {
                    GivenName  = request.Form["GivenName"].Trim(),
                    FamilyName = request.Form["FamilyName"].Trim(),
                    Status     = (PersonStatus)Enum.Parse(typeof(PersonStatus), request.Form["Status"])
                };
            }

            result.Id            = Guid.Parse(request.Form["Id"]);
            result.ContentType   = contentType;
            result.CommonName    = contentType == NodeContentType.Person ? $"{((PersonNodeViewModel)result).GivenName} {((PersonNodeViewModel)result).FamilyName}" : request.Form["CommonName"].Trim();
            result.OtherNames    = ParseFromJson <IEnumerable <string> >(request.Form["OtherNames"]);
            result.ReleaseDate   = releaseDate;
            result.DeathDate     = deathDate;
            result.Relationships = ParseFromJson <IEnumerable <RelationshipViewModel> >(request.Form["Relationships"]);

            // Validate the object
            Validate(result, bindingContext);

            return(result);
        }
Exemple #5
0
        public Dictionary <string, string> SearchForNodes(NodeContentType contentType, string name)
        {
            Dictionary <string, string> results = new Dictionary <string, string>();
            string searchType = Enum.GetName(typeof(NodeContentType), contentType);
            string queryBase  = $"MATCH (n:{searchType}) WHERE n.commonName STARTS WITH $text RETURN n.commonName, n.id";

            using (ISession session = driver.Session())
            {
                session.ReadTransaction(action =>
                {
                    // Run the query
                    IStatementResult statementResult = action.Run(queryBase, new { text = name });
                    // Populate the result
                    foreach (IRecord record in statementResult)
                    {
                        results.Add(record[0].As <string>(), record[1].As <string>());
                    }
                });
            }

            return(results);
        }
Exemple #6
0
        public ActionResult GetInformation(int type)
        {
            NodeContentType contentType = (NodeContentType)type;
            ActionResult    result      = Json(new { msg = $"Invalid type {type}" }, JsonRequestBehavior.AllowGet);

            if (contentType == NodeContentType.Company)
            {
                result = PartialView("_CompanyInformationPartial", new CompanyNodeViewModel());
            }
            else if (contentType == NodeContentType.Media)
            {
                result = PartialView("_MediaInformationPartial", new MediaNodeViewModel());
            }
            else if (contentType == NodeContentType.Person)
            {
                result = PartialView("_PersonInformationPartial", new PersonNodeViewModel());
            }
            else
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }

            return(result);
        }
Exemple #7
0
        private void BuildRelationshipMergeStatement(StringBuilder builder, IEnumerable <RelationshipModel> relationships, NodeContentType sourceType)
        {
            int targetIndex = 0;

            foreach (RelationshipModel relModel in relationships)
            {
                string identifier = $"targetRel{targetIndex}";
                builder.AppendFormat("MERGE ({0}:{1} ", identifier, relModel.GetNodeLabel());

                // Add the properties section - merge by the id of the related node
                builder.Append("{").AppendFormat("id: '{0}'", relModel.TargetId).Append("})").AppendLine();

                // If the related node is a new addition,
                if (relModel.IsNewAddition)
                {
                    // Set the commonName of related node
                    builder.AppendFormat("ON CREATE SET {0}.commonName = '{1}'", identifier, relModel.TargetName).AppendLine();
                }

                // Append the creation statement for the relationship
                string relProps = "{roles: " + JsonConvert.SerializeObject(relModel.Roles) + "}";
                // If this is a media node,
                if (sourceType == NodeContentType.Media)
                {
                    // This relationship goes Target -> Source
                    builder.AppendFormat(kCreateRelationshipStatement, identifier, relModel.GetNodeLabel(), relProps, "n");
                }
                else
                {
                    // This relationship goes Source -> Target
                    builder.AppendFormat(kCreateRelationshipStatement, "n", Enum.GetName(typeof(NodeContentType), sourceType), relProps, identifier);
                }
                builder.AppendLine();
                // Incremenet targetIndex
                targetIndex++;
            }
        }
Exemple #8
0
        private Statement GenerateRelationshipStatement(RelationshipModel relationship, NodeContentType sourceType)
        {
            StringBuilder builder = new StringBuilder();
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            // Create the MATCH statement - all statements will be run separately, so we need to match the node each time
            builder.AppendFormat("MATCH (s:{0} ", sourceType.ToLabelString()).Append("{id: $sId})").AppendLine();
            parameters.Add("sId", relationship.SourceId.ToString());
            // Create the MERGE statement
            builder.AppendFormat("MERGE (t:{0} ", relationship.GetNodeLabel()).Append("{id: $tId})").AppendLine();
            parameters.Add("tId", relationship.TargetId.ToString());
            // If the node is a new addition,
            if (relationship.IsNewAddition)
            {
                // Add the ON CREATE statement
                builder.Append("ON CREATE SET t.commonName = $tName").AppendLine();
                parameters.Add("tName", relationship.TargetName);
            }
            // Append the CREATE statement for the relationship
            builder.AppendFormat("CREATE ({0})-[:Related{1} ", (sourceType == NodeContentType.Media ? "t" : "s"), relationship.GetNodeLabel())
            .Append("{roles: $rRoles}]->").AppendFormat("({0})", sourceType == NodeContentType.Media ? "s" : "t");
            parameters.Add("rRoles", relationship.Roles);

            return(new Statement(builder.ToString(), parameters));
        }
Exemple #9
0
 /// <summary>
 /// Converts the node content type enumeration value into
 /// a string value to be used as the Neo4j query label.
 /// </summary>
 /// <param name="type">The NodeContentType which to convert</param>
 /// <returns>The string representation of the node contentType</returns>
 public static string ToLabelString(this NodeContentType type)
 {
     return(Enum.GetName(typeof(NodeContentType), type));
 }
Exemple #10
0
        /// <summary>
        /// Creates a BasicNodeModel based on the given INode.
        /// </summary>
        /// <exception cref="ArgumentException">If the INode could not be parsed</exception>
        /// <param name="node">The INode from which to create the BasicNodeModel</param>
        /// <returns>The created BasicNodeModel or null if an error occurred</returns>
        public static BasicNodeModel FromINode(INode node)
        {
            BasicNodeModel result = null;

            try
            {
                NodeContentType contentType = (NodeContentType)Enum.Parse(typeof(NodeContentType), node.Labels[0]);
                if (contentType == NodeContentType.Company)
                {
                    result = new CompanyNodeModel();
                }
                else if (contentType == NodeContentType.Media)
                {
                    result = new MediaNodeModel
                    {
                        // Media properties
                        MediaType = node.Labels.Count > 2 ? (NodeMediaType)Enum.Parse(typeof(NodeMediaType), node.Labels[1]) : 0,
                        Franchise = node.Properties.ContainsKey("franchise") ? node.Properties["franchise"].As <string>() : null,
                        Genres    = node.Properties.ContainsKey("genres") ? node.Properties["genres"].As <List <string> >() : new List <string>()
                    };
                }
                else if (contentType == NodeContentType.Person)
                {
                    result = new PersonNodeModel
                    {
                        // Person properties
                        FamilyName = node.Properties.ContainsKey("familyName") ? node.Properties["familyName"].As <string>() : null,
                        GivenName  = node.Properties.ContainsKey("givenName") ? node.Properties["givenName"].As <string>() : null,
                        Status     = node.Properties.ContainsKey("status") ? (PersonStatus)Enum.Parse(typeof(PersonStatus), node.Properties["status"].As <string>()) : 0
                    };

                    // If the family and given name was not populated and there is a common name,
                    if (((PersonNodeModel)result).FamilyName == null && ((PersonNodeModel)result).GivenName == null &&
                        node.Properties.ContainsKey("commonName"))
                    {
                        // Parse the names out of the common name
                        string[] nameParts  = node.Properties["commonName"].As <string>().Split(' ');
                        string   givenName  = "";
                        string   familyName = "";
                        for (int i = 0; i < nameParts.Length; i++)
                        {
                            if (i != nameParts.Length - 1)
                            {
                                givenName += $"{nameParts[i]} ";
                            }
                            else
                            {
                                familyName = nameParts[i];
                            }
                        }

                        ((PersonNodeModel)result).GivenName  = givenName.Trim();
                        ((PersonNodeModel)result).FamilyName = familyName;
                    }
                }
                // Basic properties
                result.Id          = Guid.Parse(node.Properties["id"].As <string>());
                result.ContentType = contentType;
                result.ReleaseDate = node.Properties.ContainsKey("releaseDate") ? node.Properties["releaseDate"].As <long>() : default(long?);
                result.DeathDate   = node.Properties.ContainsKey("deathDate") ? node.Properties["deathDate"].As <long>() : default(long?);
                result.CommonName  = node.Properties.ContainsKey("commonName") ? node.Properties["commonName"].As <string>() : null;
                result.OtherNames  = node.Properties.ContainsKey("otherNames") ? node.Properties["otherNames"].As <List <string> >() : new List <string>();
            }
            catch (Exception e)
            {
                throw new ArgumentException("Failed to parse the given node: (Type: " + node.Labels[0] + " Id: " + node.Properties["id"].As <string>(), e);
            }

            return(result);
        }