How to Cache Sharepoint Managed Client Object Model based objects? - sharepoint

I need to Cache certain objects which are based on SharePoint Managed Client Object Model like ClientContext, GroupCollection, User , List etc. Initially I tried using Appfabric cache but it gives some issues like "cannot be serialized" . Here my question is "Is it possible to serialize SharePoint Managed Client Object Model based Objects?" .
Next I tried with .NET ObjectCache which actually caches the SP's Managed Client Objects but problem over here is I need a distributed / unified caching technique. As per my knowledge we cant make ObjectCache distributed over multiple hosting servers. Can anyone suggest me a solution or show me light to proceed. Thanks in advance.

SharePoint Client Object Model will not support Object Cache w.r.t the Client objects. That is the limitation in Client Object Model.

You cannot serialize the context or the result of a query. Also a ListItem cannot be serialized. Nonetheless: At least when thinking about query-results the most important information you usually want to know is the content of the fields returned.
So, ListItem.FieldValues is a simple Dictionary<string,object> which can be easily serialized.
You could use this Dictionary in combination with the Listitem's ID to create your own caching mechanism.

Related

OWIN with Identity 2 - avoid regularly hitting the database for common objects

I have just taken the plunge and started to learn the OWIN style of authorizing users into MVC applications. One issue I'm having is storing objects since the move away from session objects and into claims.
Traditionally what I would do is authenticate the user, and then store the User object in the session. This is useful when you are regularly using the data from that object all over the application.
Now that I have moved to OWIN with Identity, I instead store the UserId as a claim. I understand that the use of complex objects is best avoided with claims.
So I find that I'm regularly having to hit the database to read User information based on the UserId.
Here is how I am reading the UserId claim:
List<Claim> claims = HttpContext.Current.GetOwinContext().Authentication.User.Claims.ToList();
var ret = claims.FirstOrDefault(x => x.Type == StaffClaims.OrganisationId);
Is there a way that I can avoid taking this ID and reading the corresponding record from the DB each time? I want to achieve something like having the User object stored in memory somewhere.
Alternatively, does Entity Framework 6 allow caching so that I don't hit the database when repeating the same query (unless I know it has changed and should be re-read)?
First, storing the user object in the session is a hugely bad idea. Don't do that ever.
Second, you don't need to store the user id in a claim; you can get it anytime with User.Identity.GetUserId().
Third, Entity Framework does utilize caching, but not in a way I'd consider it as something you could rely on. If you want to cache something, then do it explicitly with System.Runtime.Caching. You can also utilize the OutputCache attribute on actions to cache the rendered view, which has the side effect of not requiring database calls to render it again.
Finally, this is not a big deal in the first place. Just fetch the user when you need it. Before you worry about this one simple query, there's probably 10,000 other areas of your application and could and should be optimized first.

Ensuring query restrictions are honored during SaveChanges - Breeze security

Consider a typical Breeze controller that limits the results of a query to entities that the logged in user has access to. When the browser calls SaveChanges, does Breeze verify on the server that the entities reported as modified are from the original set?
To put it another way, does the EFContextProvider (in the case Entity Framework) keep track of entities that have been handed out, so it can check against malicious data passed to SaveChanges? Or does BeforeSaveEntity need to validate that the user has access to the changed entities?
You must guard against malicious data in your BeforeSaveEntity or BeforeSaveEntities methods.
The idea that the EFContextProvider would keep track of entities that have already been handed out is probably something that we would NOT want to do because
The EFContextProvider would no longer be stateless, which was a design goal to facilitate scaling.
You would still need to guard against malicious data for "Added" entities in the BeforeXXX methods.
It is actually a valid use case for some of our users to "modify" entities without having first queried them.

ServiceStack: Persist custom user object without AuthUser

I'm investigating ServiceStack's Authorization feature and want to use Couchbase as my data store. I understand there isn't an IUserAuthRepository implementation for Couchbase so I'd have to develop my own, which isn't a problem.
The issue I am having is if I store the built-in UserAuth object as-is, CB it uses the Id field as the document identifier. This is a problem because I believe the identifier should be object type specific, otherwise a separate 'bucket' would be required to prevent conflicting id's across different objects. I don't really want to have lots of buckets unless I have to.
My preference would be to have the document id set to the type of the object plus the object specific identifier.
eg Using Id "UserAuth_1234" or using UserName "UserAuth_MikeGoldsmith"
Is my assumption of trying to re-use a bucket for different application objects valid or should I be thinking about a bucket per object-type / namespace?
Any direction would be welcome, both from Couchbase and ServiceStack enthusiasts.
Thanks
Additional Info
Ok, so from John's answer I will assume my additional property for the object type is valid.
I found this post where Mythz suggests the BootStrapApi example extends the AuthUser with custom properties. However, to me it looks like the AuthUser is persisted twice, first as the AuthUser and again as the User object (both times using the OrmLiteAuthRepository). Am I right?
Essentially, I want to utilise the SS auth feature, but control the POCO object that will be saved into Couchbase. Can someone give some direction if this is possible and if so, what I need to implement / hook into?
I tried implementing a Couchbase version of IUserAuthRepository, however it uses the UseAuth concrete type so I can't use my own object.
I also tried hooking into the OnAuthenticated method of AuthUserSession but at this point the UserAuth POCO will have been persisted using the register IUserAuthRepository.
I'm happy to use the CredentialsAuthProvider as I just want username/password authentication. More could be added later.
Thanks again!
Buckets are loosely analogous to databases in the relational world, so generally they shouldn't be mapped to application objects. I'm not familiar with ServiceStack's auth feature, but your suggestion to use meaningful, prefixed keys seems reasonable and is a common approach for providing document taxonomy.
Keep in mind that in Couchbase, there's no field in the document that's considered an "id" or "key" field. The key used to store the document is available in metadata, but is not part of the JSON document itself. So if you're able to take advantage of views, then you could also store a document with a type attribute and then query by some non-id property. In other words, the key in the key value doesn't have to be the way you retrieve the user auth document.
Also, there are developers who use key prefixing as a way to provide document taxonomy for views, so you're key pattern above would work for that too. My preference is a type property, but that's no more valid than your suggestion.
I've come across the ServiceStack UseCase examples, with one that addresses my Custom Authentication issue directy.
I was able to override the TryAuthenticate method and use my own UserRepository that backs onto Couchbase.

Breeze.js - Securing IQueryable calls

I'm rather new at this, but I've come to understand the security risks of using Breeze to expose an IQueryable<>. Would someone please suggest to me some best practices (or merely some recommendations) for securing an IQueryable collection that's exposed in the JavaScript? Thanks.
I would not expose any data via IQueryable that should nto be sent to the client via a random query. So a projection could be exposed or a DTO.
I'm not sure if this answers your question tho ... What "security risks" are you worried about?
I second this question, too. But to add some specifics along the questions that Ward asked:
In securing queryable services, two traditional issues come to mind:
1) Vertical security: Which items is the currently logged in user (based on user identity or roles) NOT allowed to see in the UI. Those need to be removed from the queryable list. IMO, this can be done as part of the queryable ActionFilter magic by chaining some exclude logic on the returned IQueryable.
2) Horizontal security: Some models contain fields that are not appropriate for the logged in user to see (and/or edit). This is more difficult to handle as it's not a matter of just removing instances from the returned IQueryable. The returned class has a different shape and therefore can be handled either by the json formatter omitting the fields based on security (which AFAIK screws up breeze meta data) or you return a DTO in which case since the DTO doesn't exist in the metadata it's not a full life cycle (updatable) class? (I am asking this not stating it)
I would like to see either built-in support or easy to implement recipes for number 2). Perhaps some sample code to amend the client side metadata to make DTOs work perfectly fine comingled with model objects. The newset VS 2012 SPA templates (in the TodoList app) seem to push DTO variants of the model object both on the queryable and insert/update side. This is similar to the traditional MVC modelviews...
Finally - I'd add a request to auto-handling of the overposting security issue for inserts and updates. This is the reciprocal aspect of 2). Some users should not be able to edit certain fields.

CQRS/EventStore - Passing GUIDS to UI?

I am currently using J Oliver's EventStore which as I understand uses Guids for the Stream ID and this is what is used to build my aggregate root.
From a CQRS point of view and a DDD perspective, I should be thinking about the domain and not GUIDs.
So, if I do a GET (Mvc client), am I right to say that my URL should have the identity of my domain object (aggregate root) and from that I get the GUID from the read store which is then used to build my aggregate root from the event store?
Or should I pass the GUID around to my forms and pass them back as hidden form variables? At least this way I know the aggregate root id and do not have to query the read store?
I suppose the first way is the correct way (not using GUIDs in forms) as then all my Gets and POSTS deal with identities of domain objects rather than GUIDSs which the client will not know.
I suppose this also allows me to build as REST based API which focuses on resources and their identities rather than system generated GUIDS. Please correct me if I am wrong
In my opinion you are on the right track here. The ui should rely solely on the read model and not really care about the aggregates. Then when you need to send a command you can use the read model to get the id of the aggregate you are interested in. The read model should be very fast to read from anyway (that's the whole reason behind using different models for reads and writes) and very easy to cache if you need to. This will also give you much nicer urls.

Resources