Getting DefaultView through client object model - sharepoint

I want to load fields of the default view for Sharepoint list through client object model (I am using Silverlight). Here are some relevant things I've found (on msdn here):
class List has property DefaultViewUrl [of type string]
class List has method GetView(Guid)
class List has property Views [of type ViewCollection]
class ViewCollection has method GetById(Guid)
class ViewCollection has method GetByTitle(string)
class View has property DefaultView [of type bool]
That's everything I was able to find. As you can see there is no direct way of getting DefaultView (there is missing DefaultViewId property on List or GetByUrl(string) method on ViewCollection).
Seems to me as the only solution is to iterate through List.Views collection and check DefaultView property on each View. Which is kind of...well, inefficient...
Did I miss something? Anyone see some straigh solition?
Thanks for ideas.

Try LoadQuery using a LINQ statement
For Example:
private IEnumerable<View> viewQuery = null;
public void LoadDefaultView()
{
using (ClientContext ctx = ClientContext.Current)
{
list = ctx.Web.Lists.GetByTitle("YourList");
viewQuery = ctx.LoadQuery(list.Views
.Include(v => v.Title) // include more lamda statements here to populate View Properties
.Where(v => v.DefaultView == true));
ctx.ExecuteQueryAsync(LoadDefaultViewSuccess, LoadDefaultViewFailure);
}
}
private void LoadDefaultViewSuccess(object sender, ClientRequestSucceededEventArgs args)
{
// should only be one View in views
View defaultView = viewQuery.FirstOrDefault();
// use default.Title here
}
private void LoadDefaultViewFailure(object sender, ClientRequestFailedEventArgs args)
{
// handle failure here
}
MSDN SharePoint 2010 Silverlight COM article here
http://msdn.microsoft.com/en-us/library/ee538971.aspx

What about SPList.DefaultView? The SPList DefaultView member is an SPView object (not bool)

Related

X++ Dialog Field Lookup Override Error DialogControl.Control Cannot be Called From Server

First off, the code displayed below, extracted from where it is sitting in our AX, WORKS. Both the class creating the dialog and the class containing the lookup are set to run on "Called From". The class where the dialog method sits is an abstract class. Could that cause this error? The parent class also does not extend RunBase. Not sure if that makes a difference or not.
I am receiving this error, "The method DialogControl.control cannot be called from the server; use methods on the DialogField class instead", when attempting to add a lookup override to a dialog field.
Any help or workarounds would be greatly appreciated.
protected boolean dialog()
{
Dialog dialog = new Dialog("My Dialog", this);
DialogField myField;
boolean ok;
myField = dialog.addFieldValue(extendedTypeStr(MyStringType),
"DefaultValue", "FieldCaption", "FieldHelp");
myField.registerOverrideMethod(
methodStr(FormStringControl, lookup),
methodStr(MyClassName, MyLookupMethod),
new MyClassName());
ok = dialog.run();
}
private void MyLookupMethod(FormStringControl _control)
{
SysTableLookup sysTableLookup;
QueryBuildDataSource queryBuildDataSource;
Query query = new Query();
queryBuildDataSource = query.addDataSource(tablenum(CustTable));
sysTableLookup = SysTableLookup::newParameters(tablenum(CustTable), _control);
sysTableLookup.addLookupfield(fieldnum(CustTable, AccountNum), true);
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
Ok, I finally found this. Thought I'd post the answer to help others.
While the class is set to Called From, as is the action menu item that calls it, it was re-instantiating itself using a construct method. The static Construct method was set as a server method.

Need to verify Autommaper implemented correctly in Asp.Net MVC

I have implemented Automapper in my MVC project but not sure if it is been done correctly. I am currently using Entity Framework Database First Approach and retrieving data using stored procedures. As you would be aware Entity Framework creates complex type object which is a wrapper around Stored Procedures.So I have created two classes for mapping purpose. One is used in the repository class to map the complex type to Entity class and second is the viewmodel that is used to map the entity class to view model in the controller. I havent explicitly mapped my entity class to viewmodel in the controller. So I am wondering how is the data bound to the grid as the grid is expecting viewmodel. I am looking forward for suggestions in terms of the approach that I have taken.
spGetUserProfileByUserProfileID_Result - Complex type object
UserProfile - Entity class.
UserProfileViewModel - ViewModel
AutoMapperConfiguration Class
public static void Configure()
{
Assembly[] assemblies = BuildManager.GetReferencedAssemblies().OfType<Assembly>().ToArray();
Mapper.Initialize(cfg =>
cfg.AddProfiles(AllClasses.FromAssemblies(assemblies)
.Where(
a =>
a.FullName.EndsWith("Mapping"))));
}
Mapping class
public class DomainToModelMapping : Profile
{
public DomainToModelMapping()
{
CreateMap<spGetUserProfileByUserProfileID_Result, UserProfile>().ReverseMap();
CreateMap<UserProfileViewModel, UserProfile>().ReverseMap();
}
}
Repository
public List<UserProfile> GetUserProfileById(int id)
{
if (MCRHelper.UserValidate() == 1)
{
var userProfiles = db.spGetUserProfileByUserProfileID(id);
return Mapper.Map<List<UserProfile>>(userProfiles);
}
else
{
return null;
}
}
Controller
public ActionResult UserProfile_Read([DataSourceRequest]DataSourceRequest request)
{
var response = mcrRepository.GetUserProfileById(0).ToDataSourceResult(request);
return Json(response, JsonRequestBehavior.AllowGet);
}
If I add the following , to my controller to map to viewmodel, I get an error Missing type map configuration or unsupported mapping.
Mapping types:
DataSourceResult -> UserProfile
Kendo.Mvc.UI.DataSourceResult -> CC.GRP.MCRequest.Models.UserProfile
var userProfile = mcrRepository.GetUserProfileById(0).ToDataSourceResult(request);
return Json(Mapper.Map<UserProfile>(userProfile), JsonRequestBehavior.AllowGet);
If your question is how to return the viewmodel instead of the entity model from your controller using Automapper, then use Automapper Queryable Extensions:
using Automapper.QueryableExtensions;
...
public JsonResult UserProfile_Read([DataSourceRequest]DataSourceRequest request)
{
var users = mcrRepository.GetUserProfileById(0).Project().To<UserProfileViewModel>();
var response = users.ToDataSourceResult(request);
return Json(response, JsonRequestBehavior.AllowGet);
}

Using "Content" view as EditorFor template in an "Embedded Resource" view

I have an "Embedded Resource" view. In this view I am using the following model
public class TestModel
{
public TestModel()
{
CustomModel1 = new CustomModel1 ();
CustomModel2 = new CustomModel2();
}
public CustomModel1 CustomModel1 { get; set; }
public CustomModel2 CustomModel2{ get; set; }
}
In this view I have a form and inside it I am using #Html.EditorFor instead of #Html.Partial, because when I use #Html.Partial the CustomModel1 passed to the action (when the form is submitted) is empty.
#Html.EditorFor(m => m.CustomModel1, Constants.CustomEmbeddedView1)
However when I use #Html.EditorFor and pass as a template a "Content" view
#Html.EditorFor(m => m.CustomModel1, "~/Views/Common/_CustomPartialView.cshtml")
I get the following error:
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.Int32'.
If I set the "Content" view to be an "Embedded Resource" everything works fine.
Is there any way to resolve this problem? Perhaps there is another solution to the model binding problem instead of using #Html.EditorFor.
I found a solution to my problem. I still do not know why the error is thrown, but at least I fixed the model binding.
The problem with the model binding, is that when you call #Html.Partial
#Html.Partial("~/Views/Common/_CustomPartialView.cshtml", Model.CustomModel1)
The elements that are dispayed (I use #Html.EditorFor(m => m.Name) for example in the partial view) have an id="Name". So the model binding tries to find a "Name" property inside the TestModel, but the name property is inside the CustomModel1 property. This is why the model binding does not work, and the Name property is an empty string when the form is submitted.
The fix is to set the HtmlFieldPrefix.
var dataDictCustomModel1 = new ViewDataDictionary { TemplateInfo = { HtmlFieldPrefix = "CustomModel1" } };
#Html.Partial("~/Views/Common/_CustomPartialView.cshtml", Model.CustomModel1, dataDictCustomModel1 )
This way the id of the Name property becomes id="CustomModel1_Name", thus allowing the model binder to properly set the value of the Name property.
There may be a better solution for this, but so far this is the best, that I have come up with.

Create SharePoint (2010) ToolPart usable for more than one WebPart

I am using the basic instructions (here) for creating a property driven by a custom ToolPart.
All is good, except for the part where, in order to access the webpart property within the ApplyChanges method I must cast the "this.ParentToolPane.SelectedWebPart" back to a concrete "SimpleWebPart" class.
public override void ApplyChanges()
{
SimpleWebPart wp1 = (SimpleWebPart)this.ParentToolPane.SelectedWebPart;
// Send the custom text to the Web Part.
wp1.Text = Page.Request.Form[inputname];
}
Doing this means that I must pair each toolpart with a specific webpart. Is there a better way?
I cannot create an interface as there is no way of specifying a property in one.
I ineptly tried an passing an event/eventhandler during toolpart creation, but that did not update the webpart property when called.
I could create a base class for all the webparts that have a public "Text" property, but that is fugly.
I could also get desperate and crack open the this.ParentToolPane.SelectedWebPart reference with Reflection and call any properties named "Text" that way.
Either way, I am staring down the barrel of a fair bit of faffing around only to find out each option is a dead end.
Has anyone done this and can recommend the correct method for creating a reusable toolpart?
I have used an interface instead of a specific instance of a webpart.
private class IMyProperty
{
void SetMyProperty(string value);
}
public override void ApplyChanges()
{
IMyProperty wp1 = (IMyProperty)this.ParentToolPane.SelectedWebPart;
// Send the custom text to the Web Part.
wp1.SetMyProperty(Page.Request.Form[inputname]);
}
But this does not give a compile time warning that the toolpart requires the parent webpart to implement the IMyProperty interface.
The simple solution to that is to add a property of the IMyProperty interface in the toolpart constructor and call this reference instead of the this.ParentToolPane.SelectedWebPart property.
public ToolPart1(IContentUrl webPart)
{
// Set default properties
this.Init += new EventHandler(ToolPart1_Init);
parentWebPart = webPart;
}
public override void ApplyChanges()
{
// Send the custom text to the Web Part.
parentWebPart.SetMyProperty(Page.Request.Form[inputname]);
}
public override ToolPart[] GetToolParts()
{
// This is the custom ToolPart.
toolparts[2] = new ToolPart1(this);
return toolparts;
}
This works fine, but I cannot get over the feeling that there is something nasty in the underlying SharePoint code that may trip me up later.

creating fields programmatically in featureactivated

I need help creating a method that allows me to create a bunch of fields during featureactivated. C#. There are about 15 different fields, of varying types, and I'd like to be able to pass in all of the necessary attributes to create each field.
Anyone have any sample code or guidance on this?
Okay I found part of the answer...quite a bit to go though. I found the following utility method here:
public void AddCustomField(SPWeb web, string fieldType, string fieldName, bool isRequired, string defaultValue, string fieldGroup)
{
//Check if the field is there or not already
if (!web.Fields.ContainsField(fieldName))
{
//Initializing a SPField instance
SPField customField;
//Creating a new filed
customField = web.Fields.CreateNewField(fieldType, fieldName);
//Assigning a group
customField.Group = fieldGroup;
//Sets this field is required field
customField.Required = isRequired;
//Assigning a default value
customField.DefaultValue = defaultValue;
//Adding the newly created field to SPweb
web.Fields.Add(customField);
}
}
However, I'm not sure how to call this method, could someone give me an example?

Resources