I am getting an error on the following code that says:
Here is the code, I need this method to return the Max Value? is it an IEnumerable or an int?
public IEnumerable<int> GraphGetMaxVersion(IEnumerable<Node<VersionNode>> nodeId)
{
IEnumerable<int> nodes = null;
clientConnection = graphOperations.GraphGetConnection();
var query = clientConnection
.Cypher
.Start(new
{
n = nodeId
})
.Return((maxVersion) => new
{
MaxVersion = Return.As<int>("max.Version")
});
nodes = query.Results;
return nodes;
}
Here is the query I would like to perform:
START n=node(2,3,4)
RETURN max(n.property)
You want this:
public int GraphGetMaxVersion(IEnumerable<NodeReference<VersionNode>> nodes)
{
return graphClient.Cypher
.Start(new { n = nodes })
.Return(() => Return.As<int>("max(n.Version)"))
.Results
.Single();
}
I haven't tested that. I just bashed it out here in the textbox, but it should work.
If you don't need to return a complex type, don't. That is, turn Return(() => new { Foo = All.Count() }) into Return(() => All.Count()).
If you don't need to use an identity in your return lambda, don't pass it in. That is, this argument is pointless: Return((somePointlessIdentityHere) => All.Count())
Use either Neo4jClient 1.0.0.570 or above, or change .Start(new { n = nodes }) to .Start(new { n = nodes.ToArray() }).
You should so the following:
// Return Max follwoer node ID:
public float ReturnMaxFollowerID(IGraphClient Client)
{
return Client.Cypher
.Match("(n:User)")
.Return(() => Return.As<float>("max(n.userID)"))
.Results
.Single();
}
No errors are thrown when I made these changes to the method after reading this post.
public int GraphGetMaxVersion(int nodeId)
{
int nodes = 0;
clientConnection = graphOperations.GraphGetConnection();
var query = clientConnection
.Cypher
.Start(new
{
n = nodeId
})
.Return((maxVersion) => new
{
MaxVersion = Return.As<int>("max(n.Version)")
})
.Results
.Single();
nodes = query.MaxVersion;
return nodes;
}
Related
I am working on user roles using Asp.net MVC. I am stuck while working on Admin section. I have mentioned one question above and the second question is similar which is Using the generic type 'System.Collections.Generic.List' requires 1 type arguments
Here is my code.
public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
{
try
{
int intPage = 1;
int intPageSize = 5;
int intTotalPageCount = 0;
if (searchStringUserNameOrEmail != null)
{
intPage = 1;
}
else
{
if (currentFilter != null)
{
searchStringUserNameOrEmail = currentFilter;
intPage = page ?? 1;
}
else
{
searchStringUserNameOrEmail = "";
intPage = page ?? 1;
}
}
ViewBag.CurrentFilter = searchStringUserNameOrEmail;
List col_UserDTO = new List();
int intSkip = (intPage - 1) * intPageSize;
intTotalPageCount = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.Count();
var result = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.OrderBy(x => x.UserName)
.Skip(intSkip)
.Take(intPageSize)
.ToList();
foreach (var item in result)
{
ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
objUserDTO.UserName = item.UserName;
objUserDTO.Email = item.Email;
objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
col_UserDTO.Add(objUserDTO);
}
// Set the number of pages
// Error appears here
var _UserDTOAsIPagedList =
new StaticPagedList
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
return View(_UserDTOAsIPagedList);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
List col_UserDTO = new List(); // Error appears here
return View(col_UserDTO.ToPagedList(1, 25));
}
}
#endregion
`
StaticPagedList is generic. You need to supply the type of collection(for col_UserDTO), in your case List:
var _UserDTOAsIPagedList =
new StaticPagedList<List<ExpandedUserDTO>>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
See http://www.programering.com/a/MTN2gDNwATM.html
You may need to change List col_UserDTO references to List<ExpandedUserDTO> col_UserDTO
Use this instead
var _UserDTOAsIPagedList =
new StaticPagedList<ExpandedUserDTO>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
Using Unit of Work Repository pattern
private UnitOfWork unitOfWork = new UnitOfWork();
private Entities _Entities = new Entities();
var filing_xml = unitOfWork.T_FILING_XMLRepository.Get().Where(a =>
a.filing_id == filingID).FirstOrDefault();
This is taking around 10 seconds to fetch data
var filing_xml = _Entities.T_FILING_XML.Where(a => a.filing_id == filingID).FirstOrDefault();
This is taking around 2 seconds to fetch data
Is there any solution to make the unit of work faster?
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
The unit of work class
public GenericRepository<T_FILING_XML> T_FILING_XMLRepository
{
get
{
if (this.t_filing_xmlRepository == null)
{
this.t_filing_xmlRepository = new GenericRepository<T_FILING_XML>(context);
}
return t_filing_xmlRepository;
}
}
Code #1
private Entities _Entities = new Entities();
var filing_xml = unitOfWork.T_FILING_XMLRepository.Get().Where(a =>
a.filing_id == filingID).FirstOrDefault();
You are fetching all the records from the database then you filter the result in the application to get only one record. Your Get method has a filter parameter, why not using it?
Using the code below, you will only fetch only one record from the database.
var filing_xml = unitOfWork.T_FILING_XMLRepository.Get(a =>
a.filing_id == filingID).FirstOrDefault();
I'm using AsanaNet - which works great, but task assignee is always null, even though the Asana console shows these tasks as having an assignee.
var asana = new Asana("zzzzzzzzzzzzzzzzzzzzzzzzzzzz", AuthenticationType.Basic, errorCallback);
asana.GetWorkspaces(o =>
{
foreach (AsanaWorkspace sp in o)
{
asana.GetUsersInWorkspace(sp, u =>
{
foreach (AsanaUser user in u)
{
//Get a List of WORKSPACES
asana.GetTasksInWorkspace(sp, user, t =>
{
foreach (AsanaTask task in t)
{
asana.GetProjectsOnATask(task, p =>
{
foreach (AsanaProject project in p)
{
bool bSuccess = ProcessTask(task, project);
}
}).Wait();
}
}).Wait();
}
}).Wait();
}
}).Wait();
Hi Im using kendo ui grid in my project.
This is my code to insert records in database.
public static void Insert(StudentViewModel student)
{
student.StudentId = All().OrderByDescending(p => p.StudentId).First().StudentId + 1;
//All().Insert(0, student);
UniRegEntities uniRegEntities = new UniRegEntities();
Student stu =new Student();
stu.FName = student.FirstName;
stu.LName = student.LastName;
stu.Gender = uniRegEntities.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
stu.Id = student.StudentId;
uniRegEntities.Students.Add(stu);
uniRegEntities.SaveChanges();
}
And this is my update statement.
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToUpdate = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
studentToUpdate.FName = student.FirstName;
studentToUpdate.LName = student.LastName;
studentToUpdate.Gender = context.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
context.SaveChanges();
}
Anyone can suggest me the delete method?
You can either get an entity from the DB and then delete it or create one and then delete it.
So:
var e = // Get
ctx.DeleteObject(e);
ctx.SaveChanges();
or
var e = new Foo() { FooId = id };
ctx.Entity.Attach(e);
ctx.DeleteObject(e);
ctx.SaveChanges();
Applied to your situation:
You are getting a record so you want to use DeleteObject()
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToDelete = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
context.Students.DeleteObject(studentToUpdate);
context.SaveChanges();
}
context.Students.Remove(context.students.Single(x=>x.Id==student.Id));
Can you please try with below code snippet?
using (var db= new AppContext(ConnectionStr))
{
try
{
con.Configuration.AutoDetectChangesEnabled = false;
var o = new Student { StudentId = student.StudentId };
db.Students.Attach(o);
db.Students.Remove(o);
db.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message);
}
finally
{
con.Configuration.AutoDetectChangesEnabled = true;
}
}
Trying to look at a relationship in a query like this:
var query = _graph.Cypher.Start(
new
{
me = Node.ByIndexLookup("node_auto_index", "id", p.id)
}).Match("me-[r:FRIENDS_WITH]-friend")
.Where((Person friend) => friend.id == f.id)
.Return<FriendsWith>("r");
Here is the FriendsWith class. I can't add a parameterless constructor for FriendsWith, because the base class (Relationship) doesn't have a parameterless constructor.
public class FriendsWith : Relationship,
IRelationshipAllowingSourceNode<Person>,
IRelationshipAllowingTargetNode<Person>
{
public FriendsWith(NodeReference<Person> targetNode)
: base(targetNode)
{
__created = DateTime.Now.ToString("o");
}
public const string TypeKey = "FRIENDS_WITH";
public string __created { get; set; }
public override string RelationshipTypeKey
{
get { return TypeKey; }
}
}
But I get the error "No parameterless constructor defined for this object." when I try to run it. What is the proper way to return a relationship for a query?
Stack trace
at Neo4jClient.Deserializer.CypherJsonDeserializer1.Deserialize(String content) in c:\TeamCity\buildAgent\work\f1c4cf3efbf1b05e\Neo4jClient\Deserializer\CypherJsonDeserializer.cs:line 53
at Neo4jClient.GraphClient.<>c__DisplayClass1d1.b__1c(Task1 responseTask) in c:\TeamCity\buildAgent\work\f1c4cf3efbf1b05e\Neo4jClient\GraphClient.cs:line 793
at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Just deserialize it into a POCO that represents the data structure:
public class FriendsWith
{
public string __created { get; set; }
}
var query = _graph.Cypher
.Start(new {
me = Node.ByIndexLookup("node_auto_index", "id", p.id)
})
.Match("me-[r:FRIENDS_WITH]-friend")
.Where((Person friend) => friend.id == f.id)
.Return(r => r.As<FriendsWith>())
.Results;
You actually don't need the FriendsWith : Relationship, IRelationshipAllowingSourceNode<Person>, IRelationshipAllowingTargetNode<Person> class at all.
Create relationships using Cypher:
_graph.Cypher
.Start(new {
me = Node.ByIndexLookup("node_auto_index", "id", p.id),
friend = Node.ByIndexLookup("node_auto_index", "id", p.id + 1)
})
.CreateUnique("me-[:FRIENDS_WITH {data}]->friend")
.WithParams(new { data = new FriendsWith { __created = DateTime.Now.ToString("o") } })
.ExecuteWithoutResults();
You'll see more examples on the Neo4jClient wiki. Basically, in this day and age, everything should be Cypher.