I have a few generic questions about what are the best practices for SharePoint(2010).
I am currently implementing a feature that requires me to fetch information from a list. I am not quite sure on how to manage these information. I created a class that helps me manage theses information (User.cs). I have a getter in the class that currently searches for a value in a specific list. How should i handle the value ? Should i keep it in a member and refresh only when its subject to changes or should i refresh the value from the list each time i get it ?
private void doesUserHasActivities(){
using(SPSite site = new SPSite("http://vmsharepoint2010/")){
using(SPWeb web = site.openWeb("http://vmsharepoint2010/")){
SPList list = web.list["Users"];
SPListItem user;
/*Information values is refresh each time its accessed, is this bad ?*/
for(int i=0; i < list.items.length; i++){
user = list.item[i];
string accName = user["Acc_Name"];
if(accName == this.providedAccountname){//providedAccountname from a TextBox
//found the user i wanted into the list
//look if the list has data
bool hasActivities = user["Activities"] != null;
}
}
}
}
}
Also, is there other ways to access specific data, in this case the activities list without looping through each rows trying to match the correct user and then looking up the values in the activities list ?
Can i store the row itself as a member for my meta data ? Will my reference still point to the row of the user list i want to if another user is added ?
You'll need to learn CAML and perform a CAML query.
Create an SPQuery object. Set it's Query property to be what you need it to be, then use list.getItems(SPQuery query) to get just the items that match your query.
You can figure out the CAML for it yourself; you'll need to learn it if you want to deal with SharePoint code at all. There is lots of information on basic syntax, and tools for helping auto-generate it based on more user friendly syntax.
The items won't update dynamically when items are added to the list or updated in the list; you will need to re-run the query.
Related
I am trying to select a result set in to a list of object type.
var temp = res.Select(a => new ContentAudit {
locale = a.locale,
product_code = a.product_code, product_name = a.product_name,
image = a.image, product_short_description = a.product_short_description,
product_long_description = a.product_long_description,
items = a.items,
service_articles = GetServiceArticleCount(a.product_id).ToString(),
is_deleted = a.is_deleted, views = a.views,
placed_in_cart = GetPlacedInCartCount(a.product_id).ToString(),
ordered = GetOrderedCount(a.product_id).ToString(),
Importance = GetImportance(a.product_id),
operation = (a.product_id.ToString()) }
).ToList();
I am selecting from 'res' variable which is the result set selected from the database. Which has aroun 65000 records. So because of that the line of code above dosent work and the server get stucked. Is there anyother way i can achieve this? Thank you
There are many problems with this query.
1st You are trying to select 65000 records from DB and use .ToList()
It will iterate all objects.
You should use IEnumerable (or IQueryable), and use lazy loading.
If you do not need all of this objects try to add .Where() statement to limit number of entities.
2nd in query You are using methods wich are trying to make even more request to db. Do You realy need all this data? If yes make sure that everything is using lazy loading. Do not iterate it all in one time!
I can see two solutions. If You don't need all this data, take only data You need from db and limit number of retrived entitiies as much as its posible.
If you realy need all this data, try to use lazy loading, and add pagination (.take() and .skip() methods) to limit number of entites retrived in one call.
i followed this tutorial for setting up an upload/download to/from sql database.
http://dotnetawesome.blogspot.co.uk/2013/11/how-to-upload-and-download-files-tofrom.html
It works just fine. But i want to modify the populate method so that it will only populate files where the fileid exists within a list that i've stored in session state.
The problem is i've looked around and i can't make any sense of the lambda expressions or work out how to do this.
Basically, i keep a list of the fileIDs in the session, (which is renewed on first page load) so it will only show the files uploaded for that form submission. (it's a claim form)
using (Portal_Entities dc = new Portal_Entities()) {
List<WEBSITE_ATTACHMENTS> allFiles = dc.WEBSITE_ATTACHMENTS.ToList()
rptAttachments.DataSource = allFiles;
rptAttachments.DataBind();
}
I'm guessing i need to put a .Where or .Select on the .ToList here, but i'm not sure.
Like i need a sql type statement where field in ('value','value') where there values come from the list in the session.
Can anyone help?
You could try this one:
// Get the list of ints called fileIDs that you have stored in session.
List<int> ids = (List<int>)Session["fileIDs"];
// Declare an enumeration in which only the WEBSITE_ATTACHMENTS
// with an in contained in ids, will be contained.
List<WEBSITE_ATTACHMENTS> allFiles = dc.WEBSITE_ATTACHMENTS
.Where(x=>ids.Contains(x.fileId));
I'm working on a form for user input, and one of the items (a multiple option select) has an inordinate amount of choices (~1600), so it's gotta get filtered down to be digestible. I've got 3 filter fields (dropdowns) that I'm requiring to have completed before I make an AJAX call back to the DB and get an updated list. It's similar to How to filter the options of a drop down list using another drop down list, however I also don't want to lose any items that were previously selected. Here's the signature for the function I've prototyped:
public JsonResult GetContentStandardsForUser(string type, string grade, string subject, List<SelectListItem> selected)
What I want is to return the new list of items (and not lose the ones that were already selected), and have the pick-list update.
What is this AJAX call going to look like (using jquery)? Should I just include the current selected values in my query, or can I pass the SelectListItems like I've written above?
After some thought about the fantasy football example I presented, I came up with a solution. I make two multi-selects, one of available, one of selected. Only the "selected" list gets bound to the model-- the available list is what gets updated as a result of the query.
If someone can come up with a single-select control solution, I'm still interested, but this is a good workaround for me, for now. The reason I was looking for a single-select solution was that I was already using this plugin (http://www.virtuosoft.eu/code/bootstrap-duallistbox/) to filter my selected/available lists.
ETA: I realized I can do this in a single listbox with jquery. Using the ID, loop through the options, if it's not selected, remove it. Then add all new options from the query. Voila!
ETA2: Now with code!
//Filter content standards
$("#csType, #csGrade, #csSubject").change(function(){
var type = $("#csType").val();
var grade = $("#csGrade").val();
var subject = $("#csSubject").val();
if(type != "" && grade != "" && subject != "")
{
$("#csList option:not(:selected)").remove();
var items="";
$.getJSON("#Url.Action("GetContentStandardsForUser","Summary")", {type:type, grade:grade, subject:subject} ,function (data) {
$.each(data,function(index,item){
items+="<option value='"+item.Value+"'>"+item.Text+"</option>"
});
$("#csList").append(items)
$("#csList").trigger('bootstrapduallistbox.refresh', true);
});
}
});
After binding the options, call following function.
$('#csList').multiselect('rebuild');
I need to show the result of a multiple selection and do not know how I can handle, the problem is as follows:
I have a tree, which is multipleselection, selecting the first time, this shows me the correct information, but when I select another node, the information should be displayed for the first and the second selection, but only show the second.
My question is, how I can store the previous selection and link this with the new one ..? I'm working with NHibernate, C # and the MVC model.
I appreciate any help.
Sincerely
you can Query for multiple Selections
IEnumerable<Entity> results = Enumerable.Empty<Entity>();
foreach (var node in selectedNodes)
{
results = results.Concat(Session.Query<Entity>().Where(...).Future<Entity>());
}
Show(results);
Or cache the results of selections
Dictionary<node, IEnumerable<Entity>> _nodeResults; // somewhere
foreach (var node in selectedNodes)
{
if (!_nodeResults.ContainsKey(node))
_nodeResults.Add(node, Session.Query<Entity>().Where(...).Future<Entity>());
results = results.Concat(_nodeResults[node]);
}
if you need distinct results use Intersect instead of Concat or use Show(results.Distinct());
can anyone show me how to get the users within a certain group using sharepoint?
so i have a list that contains users and or groups. i want to retrieve all users in that list. is there a way to differentiate between whether the list item is a group or user. if its a group, i need to get all the users within that group.
im using c#, and im trying to do thins by making it a console application.
im new to sharepoint and im really jumping into the deep end of the pool here, any help would be highly appreciated.
cheers..
The first thing you need to know is that when you have a list with a User / Group field you must be aware of its type. When you have one user or group within the item value, the field type is SPFieldUserValue. However, if the field has multiple user / group selection the field type is SPFieldUserValueCollection.
I'll assume that your field allows a single user / group selection and you already has the following objects:
SPSite site;
SPWeb web;
SPListItem item;
Now, we'll check the field value for a user / group and retrieve a list of users, independant of which kind it is (the field's name is "Users").
SPFieldUserValue usersField = new SPFieldUserValue(mainWeb, item["Users"].ToString());
bool isUser = SPUtility.IsLoginValid(site, usersField.User.LoginName);
List<SPUser> users = new List<SPUser>();
if (isUser)
{
// add a single user to the list
users.Add(usersField.User);
}
else
{
SPGroup group = web.Groups.GetByID(usersField.LookupId);
foreach (SPUser user in group.Users)
{
// add all the group users to the list
users.Add(user.User);
}
}
I hope it helps you.
Tks,
Pedro José Batista
note: an SPUser object can also be an AD Group (that is to say, an SPUser object might exist for "DOMAIN\Domain Users"... which is why the SPUser object also contains the property IsDomainGroup.
From this information you can start to traverse through AD groups using the SPPrincipalInfo objects... however it's not always pleasant.
One thing worth keeping in mind is that the SPGroup object includes the ContainsCurrentUser property which can traverse AD groups... this assumes you've got an SPGroup object to work from, however.
Enjoy.
-Scott
private bool IsMember()
{
bool isMember;
SPSite site = new SPSite(SiteURL);
SPWeb web = site.OpenWeb();
isMember = web.IsCurrentUserMemberOfGroup(web.Groups["GroupName"].ID);
web.Close();
site.Close();
return isMember;
}
This is better to use web.SiteGroups instead of web.Groups as a group might be inherited by that site.