Save a Image using ContentService in Umbraco - umbraco

I want to add a image using contentservice in umbraco , can it bo done simply using setValue method, what do I need to pass to the setValue Method?

You should use the MediaService instead of the contentservice.
// check ApplicationContext.Current != null
var ms = ApplicationContext.Current.Services.MediaService;
var newMediaItem = ms.CreateMedia(file.FileName, <parentId>, Constants.Conventions.MediaTypes.Image);
newMediaItem.SetValue(Constants.Conventions.Media.File, file);
ms.Save(newMediaItem);

Related

How to get multiple RecordSets from StoredProcedure with NReco.Data in Asp.NetCore

I use NReco.Data in my Asp.NetCore Application to make db-calls, because I don't want to use EF and DataTable isn't supported yet.
Now I need to call a StoredProcedure and get Multiple RecordSets (or Dictionarylists).
At the moment I called this:
dbAdapter.Select($"STOREDNAME #{nameof(SQLPARAMETER)}", SQLPARAMETER).ToRecordSet()
But the stored gives me more than 1 recordset, can anyone help me to get the others?
Currently NReco.Data.DbDataAdapter has no API for processing multiple result sets returned by single IDbCommand.
You can compose IDbCommand by yourself, execute data reader and read multiple result sets in the following way:
IDbCommand spCmd; // lets assume that this is DB command for 'STOREDNAME'
RecordSet rs1 = null;
RecordSet rs2 = null;
spCmd.Connection.Open();
try {
using (var rdr = spCmd.ExecuteReader()) {
rs1 = RecordSet.FromReader(rdr);
if (rdr.NextResult())
rs2 = RecordSet.FromReader(rdr);
}
} finally {
spCmd.Connection.Close();
}
As NReco.Data author I think that support for multiple result sets may be easily added to DbDataAdapter API (I've just created an issue for that on github).
-- UPDATE --
Starting from NReco.Data v.1.0.2 it is possible to handle multiple result sets in the following way:
(var companies, var contacts) = DbAdapter.Select("exec STOREDNAME").ExecuteReader(
(rdr) => {
var companiesRes = new DataReaderResult(rdr).ToList<CompanyModel>();
rdr.NextResult();
var contactsRes = new DataReaderResult(rdr).ToList<ContactModel>();
return (companiesRes, contactsRes);
});
In the same manner DataReaderResult can map results to dictionaries or RecordSet if needed.

Breeze - How to Load Navigation property from cache

I am getting a single entity by using a method fetchEntityByKey, after that I am loading navigation property for the entity by entityAspect.loadNavigationProperty. But loadNavigationProperty always make a call to the server, what I am wondering if I can first check it from cache, if it is exist then get it from there otherwise go the server. How is it possible? Here is my current code
return datacontext.getProjectById(projectId)
.then(function (data) {
vm.project = data;
vm.project.entityAspect.loadNavigationProperty('messages');
});
Here is a function that I encapsulated inside datacontext service.
function getProjectById(projectId) {
return manager.fetchEntityByKey('Project', projectId)
.then(querySucceeded, _queryFailed);
function querySucceeded(data) {
return data.entity;
}
}
Also, how is it possible to load navigation property with some limit. I don't want to have all records for navigation property at once for performance reason.
You can use the EntityQuery.fromEntityNavigation method to construct a query based on an entity and a navigationProperty . From there you can execute the resulting query locally, via the EntityManager.executeQueryLocally method. So in your example once you have a 'project' entity you can do the following.
var messagesNavProp = project.entityType.getProperty("messages");
var query = EntityQuery.fromEntityNavigation(project, messagesNavProp);
var messages = myEntityManager.executeQueryLocally(query);
You can also make use of the the EntityQuery.using method to toggle a query between remote and local execution, like this:
query = query.using(FetchStrategy.FromLocalCache);
vs
query = query.using(FetchStrategy.FromServer);
please take a look here: http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html
as you can see fetchEntityByKey ( typeName keyValues checkLocalCacheFirst ) also have a third optional param that you can use to tell breeze to first check the manager cache for that entity
hope this helps

How do I set a property on a breeze entity client-side?

I've tried drilling down into the object and looking at the docs but haven't found anything. I've created an entity and I need to assign some properties manually. I see _backingStore and entityAspect on the object... and I know the property names but don't know how to set them via the breeze entity.
In case it matters, I'm creating a new object and then copying properties over from another object to facilitate cloning.
function createDocument() {
var manager = datacontext.manager;
var ds = datacontext.serviceName;
if (!manager.metadataStore.hasMetadataFor(ds)) {
manager.fetchMetadata(ds).then(function () {
return manager.createEntity("Document");
})
}
else {
return manager.createEntity("Document");
}
}
function cloneDocument(doc) {
var clonedDocument = createDocument();
// Copy Properties Here - how?
saveChanges()
.fail(cloneFailed)
.fin(cloneSucceeded);
}
Not knowing what your properties might be, here are two scenarios -
function cloneDocument(doc) {
var clonedDocument = createDocument();
clonedDocument.docId(doc.docId());
clonedDocument.description(doc.description());
saveChanges()
.fail(cloneFailed)
.fin(cloneSucceeded);
}
There are a few things to note here - I am assuming you are using Knockout and needing to set the properties. If you are not using Knockout then you can remove the parans and use equals -
clonedDocument.docId = doc.docId;
I believe this is true for if you are not using Knockout (vanilla js) and if you are using Angular, but I have not used Breeze with Angular yet so bear with me.
And here's another way that works regardless of model library (Angular or KO)
function cloneDocument(doc) {
var manager = doc.entityAspect.entityManager; // get it from the source
// Check this out! I'm using an object initializer!
var clonedDocument = manager.createEntity("Document", {
description: doc.description,
foo: doc.foo,
bar: doc.bar,
baz: doc.baz
});
return clonedDocument;
}
But beware of this:
clonedDocument.docId = doc.docId; // Probably won't work!
Two entities of the same type in the same manager cannot have the same key.
Extra credit: write a utility that copies the properties of one entity to another without copying entityAspect or the key (the id) and optionally clones the entities of a dependent navigation (e.g., the order line items of an order).

EF4.3 Code-First, MVC, Lazy Loading After Attaching in POST Action

I'm using Entity Framework 4.3 with Code-First in an MVC 3 application. I have a POST action that gets an entity as its' parameter, and then marks the entity as modified to update the database. It's a Document entity that has a reference to a File Type.
[HttpPost]
public ActionResult Example(Document model)
{
// fileType is null, as expected
var fileType = model.FileType;
// attach and mark the entity as modified, save changes
Context.Entry(model).State = EntityState.Modified;
Context.SaveChanges();
// fileType is still null?
fileType = model.FileType;
return View(model);
}
After attaching an entity to the context, shouldn't I be able to lazy-load properties on that entity?
Interestingly, when I try this in a console application it seems to work.
static void Main()
{
// create a new context
var context = new Context();
// get the first document and detach it
var doc = context.Documents.First();
context.Entry(doc).State = EntityState.Detached;
// fileType is null, as expected
var fileType = doc.FileType;
// dispose and create a new context
context.Dispose();
context = new Context();
// attach the entity and mark it as modified
context.Entry(doc).State = EntityState.Modified;
// fileType is not null, which is the desired outcome
fileType = doc.FileType;
}
The problem is that the entity passed to the post method is not a proxy, presumably because it was created outside of the Entity Framewortk using the normal "new" operator.
There are a few options here. First, you could modify the MVC controller to create proxy instances by using the DbSet.Create method. I've heard it is possible to modify the MVC controller in this way, but never tried it myself. For example, instead of doing:
var doc = new Document();
in the controller, you would do:
var doc = context.Documents.Create();
The create method lets EF create a proxy for lazy loading, if the entity has appropriate virtual properties, which in your case it looks like it does.
A second and potentially easier option is to not use lazy loading but instead use the explicit loading APIs. For example, to load FileType:
var fileType = context.Entry(doc).Reference(d => d.FileType).Load();
Unlikely lazy loading, this needs an explicit reference to the context, but in your case that should be okay.

What is the best method for updating all changed data in EF 4?

I try to create some method that can update any changed data from changed Data object (this object is generated by ASP.NET MVC) to old Data object (this object is retrieved from current data in DBMS) like the following code.
public static bool UpdateSomeData(SomeEntities context, SomeModelType changedData)
{
var oldData = GetSomeModelTypeById(context, changedData.ID);
UpdateModel(oldData, changedData);
return context.SaveChanges() > 0;
}
I try to create method for saving any changed data without affects other unchanged data like the following source code.
public static void UpdateModel<TModel>(TModel oldData, TModel changedData)
{
foreach (var pi in typeof(TModel).GetProperties()
.Where
(
// Ignore Change ID property for security reason
x => x.Name.ToUpper() != "ID" &&
x.CanRead &&
x.CanWrite &&
(
// It must be primitive type or Guid
x.PropertyType.FullName.StartsWith("System") &&
!x.PropertyType.FullName.StartsWith("System.Collection") &&
!x.PropertyType.FullName.StartsWith("System.Data.Entity.DynamicProxies")
)
)
{
var oldValue = pi.GetValue(oldData, null);
var newValue = pi.GetValue(changedData, null);
if (!oldValue.Equals(newValue))
{
pi.SetValue(oldData, newValue, null);
}
}
}
I am not sure about the above method because it is so ugly method for updating data. From recent bug, it realizes me that if you update some property like Navigation Properties (related data from other table), it will remove current record from database. I don't understand why it happened. But it is very dangerous for me.
So, do you have any idea for this question to ensure me about updating data from ASP.NET MVC?
Thanks,
Have you looked into using a tool like Automapper? You can map the entity type to itself and have automapper copy all the fields over for you. Actually I would prefer to see you use a view model in MVC instead of allowing edits directly to your entities, but that's personal preference.

Resources