ServiceStack OrmLite CustomSelect not working? - ormlite-servicestack

I'm trying to use the feature documented here :
https://github.com/ServiceStack/ServiceStack.OrmLite#custom-sql-customizations
This is how I'm using it:
var q = Db.From<MemberAccess>().LeftJoin<Member>();
return Db.Select<MemberResponse>(q);
Response object:
public class MemberResponse
{
public Guid Id { get; set; }
public string MemberFirstName { get; set; }
public string MemberLastName { get; set; }
public string MemberEmail { get; set; }
[Default(OrmLiteVariables.SystemUtc)]
public string AccessedOn { get; set; }
[CustomSelect("CONCAT(LEFT(Member.FirstName, 1),LEFT(Member.LastName,1))")]
public string MemberInitial { get; set; }
}
It seems like whatever I put in CustomSelect doesn't get used. Maybe, I'm not using this correctly? Also, the Default attribute doesn't work either.I tried that as it was an example from the doco.
Any idea will be appreciated.
Thanks in advance.

The [CustomSelect] only applies to the source table. Selecting the results in a custom type is used to map the returned resultset on the MemberResponse type, it doesn't have any effect on the query that gets executed.
Likewise with [Default(OrmLiteVariables.SystemUtc)] that's used to define the default value when creating the table which is only used when it creates the Column definition, so it's only useful on the source Table Type.
Both these attributes should only be added on the source MemberAccess to have any effect, which your mapped MemberResponse can access without any attributes, e.g:
public class MemberResponse
{
public Guid Id { get; set; }
public string MemberFirstName { get; set; }
public string MemberLastName { get; set; }
public string MemberEmail { get; set; }
public string AccessedOn { get; set; }
public string MemberInitial { get; set; }
}
Sql.Custom() API
The new Sql.Custom() API added in v4.5.5 that's available on MyGet will let you select a custom SQL Fragment, e.g:
var q = Db.From<MemberAccess>().LeftJoin<Member>()
.Select<MemberAccess,Member>((a,m) => new {
Id = a.Id,
MemberFirstName = m.FirstName,
MemberLastName = m.LastName,
MemberEmail = m.Email,
MemberInitial = Sql.Custom("CONCAT(LEFT(Member.FirstName,1),LEFT(Member.LastName,1))")
});
return Db.Select<MemberResponse>(q);

Related

JsonConvert.DeserializeObject<> is returning null last childtoken of the two childrentokens

I am sending a JObject from the frontend to my API, which is divided into First and Last childtokens, as seen in the picture below:
However, when I am trying to use the following code, the last part of childrendtoken is becoming null
var RVoucher = JsonConvert.DeserializeObject<VMReceive>(request.ToString());
This is what I am having in the debugging mode:
Here, the VMReceive is a viewModel that consists of another viewmodel "VMMonth"and an ado.net generated model class "ReceiveVoucher".
Code of the models are given below:
public class VMReceive
{
public List<VMMonth> Month { get; set; }
public ReceiveVoucher receiveVoucher { get; set; }
}
public class VMMonth
{
public int item_id { get; set; }
public string item_text { get; set; }
}
public partial class ReceiveVoucher
{
public int ReceiveVoucherId { get; set; }
public Nullable<int> MonthId { get; set; }
public string ReceivedBy { get; set; }
public string Remarks { get; set; }
public Nullable<int> ReceivedAmount { get; set; }
}
I have also tried putting [JsonProperty("")] over each property of my "ReceiveVoucher" model class, but got the same 'null' issue.
I am not sure about what I am doing wrong here, your suggestion regarding this will be very helpful.
Your JSON property name doesn't match. Your class uses receiveVoucher whereas the JSON is ReceiveAmount. Also, why are you using JObject in the first place, this should work by just using the class name as the action parameter:
public HttpResponse PostReceive([FromBody] VMReceive RVoucher, int userId)
{
...
}

Best way to parse a Gremlin.Net response?

What is the best way to get POCO's from a Gremlin.Net response?
Right now I manually cast to dictionaries:
var results = await gremlinClient.SubmitAsync<Dictionary<string, object>>("g.V()");
var result = results[0];
var properties = (Dictionary<string, object>)result["properties"];
var value = ((Dictionary<string, object>)properties["myValue"].Single())["value"];
I found that the GremlinClient can only return dynamic objects, if you put anything else as the type, it fails (unless I was just doing something wrong).
What I ended up doing was serialising the dynamic object to JSON and then deserialising it back to the object type I wanted:
var results = await gremlinClient.SubmitAsync<dynamic>("g.V()");
JsonConvert.DeserializeObject<MyResult>(JsonConvert.SerializeObject(results));
The dynamic object is just a Dictionary, but if you serialise it first it has the proper hierarchy of fields/properties which can then be deserialised to what you actually expect.
Seems a bit of a pain to have to do the extra conversion, but only way I got it to work.
You can get your properties by using MyClass similar to
class ProviderProperties {
public object Name { get; set; }
public object contact { get; set; }
public object requesttype { get; set; }
public object address { get; set; }
public object phone { get; set; }
public object description { get; set; }
public object otherState { get; set; }
public object otherCity { get; set; }
public object addressStreet { get; set; }
}
class MyClass {
public string id { get; set; }
public string label { get; set; }
public string type { get; set; }
public ProviderProperties properties { get; set; }
}
and using it in
JsonConvert.DeserializeObject<MyClass>(JsonConvert.SerializeObject(results));
Try this approach
IGremlinClient janusClient = JanusGraphClientBuilder.BuildClientForServer(new GremlinServer("localhost", 8182)).Create();
GraphTraversalSource g = Traversal().WithRemote(new DriverRemoteConnection(janusClient));
IList<Vertex> x = g.V().HasLabel("YourLabel").Has("YourpPopertyName", "some value").ToList();

Post JSON Array in Asp.Net Web API

Hi every one I am new to ASP.Net Web API and I want to Post JSON array data any get there response.
My JSON POST Array format is
{
"User_Id":"admi12n#1234","Key_Code":"3F-47-AB-84-9F-EB-D6-6B-9C-62-CC-85-98-4D-28-6B",
"ProductDetails": [
{"Product_Id":"ELT-7035","Price":"999","Quantity":"5"},
{"Product_Id":"ELT-1254","Price":"1024","Quantity":"3"}
]
}
And I want response as follows
{
"User_Id":"admi12n#1234","Key_Code":"3F-47-AB-84-9F-EB-D6-6B-9C-62-CC-85-98-4D-28-6B",
"OrderID":"Ord-021","Name":"Sabyasachi"
"ProductDetails": [
{"Product_Id":"ELT-7035","Price":"999","Quantity":"5"},
{"Product_Id":"ELT-1254","Price":"1024","Quantity":"3"}
]
}
I generate OrderID as Random and Name from posted User_Id. Here I want to post multiple product in one order.
My Order class is as follows
public class Order
{
[Key]
public long ID { get; set; }
public string Order_Id { get; set; }
public string Product_Id { get; set; }
public long Quantity { get; set; }
public long Amount { get; set; }
public string User_Id { get; set; }
public string Key_Code { get; set; }
public DateTime Order_Date { get; set; }
public DateTime Modified_Date { get; set; }
}
And my Product class as follows
public class Product
{
[Key]
public int Id { get; set; }
public string Product_Code { get; set; }
public string Product_Name { get; set; }
public string Product_Category { get; set; }
public string Product_Description { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public string Image { get; set; }
public DateTime Created_Date { get; set; }
public DateTime Modified_Date { get; set; }
}
I am not able to ind the best way to post the order
public Order Add(Order odrerDetails) //This will not give array of data for products
{
using (var context = new EcommerceDBContext())
{
odrerDetails.Order_Id = Helper.Random(7); //Generate random orderID from my class
odrerDetails.Created_Date = DateTime.Now;
odrerDetails.Modified_Date = DateTime.Now;
//How to Save other details
context.objOrderListing.Add(odrerDetails);
context.SaveChanges();
return odrerDetails;
}
}
In API controllers my code is as follows
public HttpResponseMessage PostOrder([FromBody] Order_Listing orderData)
{
orderData = repository.Add(orderData);
var response = Request.CreateResponse<Order_Listing>(HttpStatusCode.Created, orderData);
string uri = Url.Link("DefaultApi", new { customerID = orderData.ID });
response.Headers.Location = new Uri(uri);
return response;
}
Please help me how to achieve this.
There are several issues with your code:
Your Order and Product classes do not reflect the structure of
your JSON.
The Order class contains product details in a 1:1
relationship. Based on the JSON I assume you want a 1:n relationship.
Properties in your JSON need to have the same name as
in your classes or they won't be mapped.
Change your classes to the following and it should work.
Of course you could also change the property names in your JSON.
If you can't or don't want to change your property names, consider using DTOs
public class Order
{
public string User_Id { get; set; }
public string Key_Code { get; set; }
public string OrderID { get; set; }
public string Name { get; set; }
public List<Product> ProductDetails { get; set; }
// add the rest of your properties
}
public class Product
{
public string Product_Id { get; set; }
public string Price { get; set; }
public string Prd_Qty { get; set; }
// add the rest of your properties
}
Update: added code for Add method and Api method
Your Add method would look like this:
public Order Add(Order orderWithDetails)
{
using (var context = new EcommerceDBContext())
{
orderWithDetails.Order_Id = Helper.Random(7); //Generate random orderID from my class
orderWithDetails.Created_Date = DateTime.Now;
orderWithDetails.Modified_Date = DateTime.Now;
context.objOrderListing.Add(orderWithDetails);
// Save each Product
foreach (var detail in orderWithDetails.ProductDetails)
{
//whatever you need to do in your db-context
context.objOrderDetails.Add(detail); // just an example
}
context.SaveChanges();
return orderWithDetails;
}
}
The signature of your Api method looks wrong. What is Order_Listing? This should be Order, unless it's a DTO, in wich case you need a method to get an Order from Order_Listing.
public HttpResponseMessage PostOrder([FromBody] Order orderData)
{
orderData = repository.Add(orderData);
var response = Request.CreateResponse<Order_Listing>(HttpStatusCode.Created, orderData);
string uri = Url.Link("DefaultApi", new { customerID = orderData.ID });
response.Headers.Location = new Uri(uri);
return response;
}
A few more remarks:
If it is indeed a 1:n relationship, you probably need a property Product.OrderId.
The Order class should not have any reference to Product except for the list.
Quantity and Price should most likely not be String but numerical values, e.g. decimal.
If Order.ID is your primary key, then having Order.Order_ID is really confusing. Consider renaming it to Order.Order_Number.
public class Order
{
public string User_Id { get; set; }
public string Key_Code { get; set; }
public string OrderID { get; set; }
public string Name { get; set; }
public Product[] ProductDetails { get; set; }
}

DocumentDB LAMBDA SqlMethod.Like and .Contains NotImplemented Exception

Im trying to do a simple "LIKE" query using a LAMBDA expression using CreateDocumentQuery; however after trying .Contains and SqlMethod.Like and both times receiving the response NotImplementedException I don't know what to try next!
Update: As of 5/6/15, DocumentDB added a set of String functions including STARTSWITH, ENDSWITH, and CONTAINS. Please note that most of these functions do not run on the index and will force a scan.
LIKE and CONTAINS are not yet supported in DocumentDB.
You'll want to check out the DocumentDB feedback page and vote on features (e.g. LIKE and CONTAINS) to get your voice heard!
Because I only needed to search against a discreet subset of properties of the larger object I implemented a .Contains search function as below. It works as expected though I have no idea regarding performance or scalability.
Domain Models
public interface ITaxonomySearchable
{
string Name { get; set; }
string Description { get; set; }
}
public class TaxonomySearchInfo : ITaxonomySearchable {
[JsonProperty(PropertyName = "id")]
public Guid Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
}
public class TaxonomyContainer : ITaxonomySearchable
{
[JsonProperty(PropertyName = "id")]
public Guid Id { get; set; }
[JsonProperty(PropertyName = "userId")]
public string UserId { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "tags")]
public string[] Tags { get; set; }
[JsonProperty(PropertyName = "taxonomy")]
public Node[] Taxonomy { get; set; }
}
Search method
public async static Task<List<TaxonomySearchInfo>> Search(string searchTerm)
{
var db = GetJsonDocumentDb.GetDb();
using (var client = GetJsonDocumentDb.GetClient())
{
var documentCollection = await GetJsonDocumentDb.GetDocumentCollection(db, client, "TaxonomyContainerCollection");
return client.CreateDocumentQuery<TaxonomySearchInfo>(documentCollection.DocumentsLink)
.AsEnumerable()
.Where(r => r.Name.Contains(searchTerm) || r.Description.Contains(searchTerm))
.ToList();
}
}

Linq Queries and Cannot implicitly convert type error

According to given project id(this id is coming to action as a parameter), I want to find this project and this project's issues and then I want to find some issues which has the "bug" type using linq queries in my MVC asp.net web application. But when I try below code in my action in ProjectController, I take this error: Cannot implicitly convert type 'System.Collection.Generic.List<System.Collections.Generic.List<MVCTest1.Models.Issue>>'to 'System.Collections.Generic.List<MVCTest1.Models.Issue>' and
List<Issue> issueList = (from i in db.Projects where i.projectID == projectId select i.Issues).ToList();
List<Issue> bugList = (from bug in issueList where bug. ) --> I cannot reach properties of bug issue
Here my project Model:
public class Project
{
public int projectID { get; set; }
public string projectName { get; set; }
public string descriptionProject { get; set; }
public Project parentProject { get; set; }
public string identifier { get; set; }
public DateTime date { get; set; }
public List<Project> subProjects { get; set; }
public virtual List<Issue> Issues { get; set; }
}
and my Issue Model:
public class Issue
{
public int issueID { get; set; }
public string description { get; set; }
public string subject { get; set; }
public IssueStatus? status { get; set; }
public Issue parentTask { get; set; }
public DateTime startDate { get; set; }
public DateTime dueDate { get; set; }
public int done { get; set; }
public IssuePriority? priority { get; set; }
public IssueType? type { get; set; }
public virtual List<User> Users { get; set; }
}
finally my enum:
public enum IssueType
{
Bug = 0,
Feature = 1,
Support = 2,
Operation = 3
}
Thanks in advance.
// edit 2
var project = db.Projects.Single(p => p.projectID == projectId);
var issues = project.Issues;
var bugIssues = from bug in issues where bug.type == 0 select bug;
return PartialView(bugIssues);
When I write this I got this error :
The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereListIterator1[MVCTest1.Models.Issue]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[MVCTest1.Models.Issue]'.
The problem is that your Issues property is already a List<Issue>. I suspect you want something like:
// TODO: Fix property naming...
var project = db.Projects.Single(p => p.projectId == projectId);
var issues = project.Issues;
Now issues will be a List<Issue> rather than a List<List<Issue>>.
EDIT: For the next problem, you've got an IEnumerable<Issue> but you're expecting a List<Issue>, so you need to call ToList() at that point. For example:
var project = db.Projects.Single(p => p.projectId == projectId);
return PartialView(project.Issues.Where(b => b.type == 0).ToList());
The problem is in the expected model of the MVC view, it expects a System.Collections.Generic.List<T>, but you gave a System.Linq.Enumerable.
Try do this.
return PartialView(bugIssues.ToList());

Resources