Custom AnnouncementListItem Visual Web Part in Sharepoint 2010 - c#

I am trying to create a visual web Part to display the latest 5 announcement list items.
I need the Announcement List Item Title to show up as a link and any attachments(only pictures) to be displayed right above it. I am planning on refreshing the web part every 15-20 minutes to be able to show the latest announcement.
I dont know how and what the best asp control and page design would be to display these items.
Here is the CAML Query with the rest of the code I have:
using (SPSite oSPsite = new SPSite("http://mySharePointWebApp:Port#/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList list = oSPWeb.Lists["Announcements"];
SPQuery spQuery = new SPQuery();
//spQuery.Query = "<Where> <Eq> <FieldRef Name='Title' /> <Value Type='Text'></Value> </Eq> </Where>";
spQuery.Query = "";
spQuery.RowLimit = 5;
// Show item in text box
SPListItemCollection oListCollection = list.GetItems(spQuery);
foreach (ListItem oListItem in oListCollection)
{
// **What should I go with here?**
}
}
}

You can use a repeater control like listbox and customize it using item templates.
<asp:ListBox>
<item template>
<div>
<image control/>
<text control/>
</div>
</item template>
</asp:ListBox>
To get the latest 5 announcements, write CAML SPQuery to get top 5 items by ID in descending order.
Check to see if an attachment exist for the announcement. If it does then get the attachment URL and check if it is an image type by looking at the extension.
If image exist then assign the attachment relative url to the image control in the item template. For announcements with no image you can choose to either hide the image control or assign URL to some common image.
You can also use Linq to SharePoint to get the latest 5 announcements. Code should look like this
var top5Announcements = (From a in siteDataContext.Announcements OrderBy a.id descending select a).Take(5)

Related

Web service to retrieve SharePoint List item

We have one SharePoint Server and another server which is having our web service (SharePoint not installed on the machine). We are trying to access SharePoint server list items using our web service. We are getting count of list items but when we go for CAML query, it returns 0 items.
How can we proceed for getting the list item?
here is our code for your reference.
List Device_List = context.Web.Lists.GetByTitle("MasterList");
context.Load(Device_List);
context.ExecuteQuery();
int position = Device_List.ItemCount;
CamlQuery query = new CamlQuery();
query.ViewXml = #"<View><Query><Where><Eq><FieldRef Name='key' /><Value Type='Text'>ConTransDB</Value></Eq></Where></Query></View>";
ListItemCollection itemCollection = Device_List.GetItems(query);
context.Load(itemCollection);
context.ExecuteQuery();
if (itemCollection.Count > 0 && itemCollection != null)
{
string value = itemCollection[0]["value"].ToString();
}
The ViewXml is not complete, it requires you to define the complete view, not just the query. So it would look like:
query.ViewXml = "<View><Query><Where>...</Where></Query></View>";
You can even add more info than just the query, for example:
<View>
<Query>
<Where>...</Where>
<OrderBy>...</OrderBy>
</Query>
<RowLimit>...</RowLimit>
<ViewFields>...</ViewFields>
</View>

CamlQuery - How to use Where clause in C#

I'm very new to CamlQuery and need a bit of help getting this to work.
I installed a tool called CamlDesigner to help me generate the XML needed to filter a collection in Sharepoint, but the XML query that CamlDesigner constructs does not work in my C# codebehind. I have an ID field that I am trying to filter by and I simply want to retrieve an item from Sharepoint where ID = 1 (or 2 or 3 or whatever).
Here is the Caml query generated by the designer:
<Where>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>1</Value>
</Eq>
</Where>
Here is my C# code where I am attempting to incorporate this Caml query. The C# works, but it is returning every item from "My SP Coll" as opposed to only returning the item where ID equals 1.
// Sharepoint web service to retrieve categories items there
ClientContext clientContext = new ClientContext("https://myweb.dev.com/SP");
List oList = clientContext.Web.Lists.GetByTitle("My SP Coll");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<Query><Where><Eq><FieldRef Name='ID'/><Value type='Counter'>" + ID.ToString() + "</Value></Eq></Where></Query>";
Microsoft.SharePoint.Client.ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem oListItem in collListItem) {
string ID = oListItem["ID"].ToString();
}
Thanks for the help!
The query needs to be wrapped in a <View>...</View> element, in addition to the <Query> element.
As per the generated query, the field name is ID not Id.
On a side note, make sure you're disposing of the client context.
And of course, to get an item by ID you can bypass this entire process and just use
var item = list.GetItemById(ID);
The ViewXml property just points to a view within a list and doesn't appear to handle filtering.
If you were to set up an already-filtered view and point the ViewXml to that, then you would still grab all items in the view, but since the view itself is filtered, your result set would match it.

Programmatically adding a mix of standard and hyperlink list items to a bulletlist in ASP.NET

I'm trying to build a list from a datatable, and the function also needs to add group headers. Currently I have it checking to see if a row has a new group header and adding a list item with a CSS class to differentiate it from the rest of the list items. What I'd like to do is make the non-header list items show up as normal hyperlinks. I know you can add DisplayMode="HyperLink" to the .aspx, but that applies to every element, including the header items. I'm looking for suggestions on the best way to add link styling to the items that should have them while leaving the group headers as normal text.
Here is the code so far:
The aspx:
<asp:BulletedList ID="reportsList" runat="server"></asp:BulletedList>
The function:
protected void BuildReportList(DataTable dt)
{
string groupHeader = "";
foreach (DataRow row in dt.Rows)
{
if (row["su2_description"].ToString().Trim() != groupHeader)
{
groupHeader = row["su2_description"].ToString().Trim();
ListItem myHeader = new ListItem();
myHeader.Text = row["su2_description"].ToString();
myHeader.Attributes.Add("Class", "groupHeader");
reportsList.Items.Add(myHeader);
}
ListItem myItem = new ListItem();
myItem.Text = row["prg_menu"].ToString();
myItem.Attributes.Add("title", row["prg_description"].ToString());
myItem.Attributes.Add("onClick", "runReport(this);");
myItem.Attributes.Add("value", row["prg_path"].ToString().Trim());
reportsList.Items.Add(myItem);
}
}
You can see from the code that the list items are using onClick, so they ARE links, but they don't have the standard styling to accompany a link. Rather than writing CSS for the group headers to negate all the HTML styling caused by DisplayMode="HyperLink" on the BulletedList, is there a way to add an attribute to the appropriate items to make them dynamically be recognized as links?
This is a long shot since I haven't tried it but I imagine this would work:
The items that are not headers, add a style attribute and set both, text-decoration to underline and any color you'd like for the hyperlink appearance:
myItem.Attributes.Add("style", "text-decoration:underline; color:blue;");

Updating a field on list items based on the value selected from drop down "choice" column

I have the following problem I have two list "TestUsers" amd "TestGroups". The "TestUsers" list has two columns [Group - Choice], [User - Single line of text]. The "TestGroups" list has two columns [Group - Single line of text], [CheckedOut - Single line of text].
The data in both lists are the following:
TestUsers (List):
User: testuser1
Group: groupA
User: testuser2
Group: groupB
TestGroups (List):
Group: groupA
CheckedOut: testuser1
The requirement is that when a user in the "TestUsers" lists gets its "Group" changed for example from "groupA" to "groupB" than this should also be reflected and automatically updated in the "TestGroups" list. So for example in the "TestUsers" list if I were to change the "Group" for "testuser1" to "groupB" then in the "TestGroups" list the "Group" of "testuser1" has to also change/update to "groupB".
I hope the above is clear enough in describing what the requirement is.
I have tried doing this using worklflows and having lookup column as well as calculated columns. But both the calculated columns and the lookup columns does not seem to be work.
How would I go about achieving this using code in c#. I know how to update list items but what I am not sure is how to update listitems from a list when a value is changed on a separate list as mentioned earlier.
I am stuck with this issue and thought I post it here so I can get some quick and accurate suggestions on how to procceed.
Many thanks, any help with this will be greatly appreciated.
you can try this In event receiver use ItemUpdating Event method just check it out item changed or not and create your logic
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
if (properties.ListTitle == "TestUsers")
{
SPWeb web = properties.OpenWeb();
SPList list = web.Lists[properties.ListTitle];
SPListItem litemUser = list.GetItemById(properties.ListItemId);
SPList objFeatureList = web.Lists["TestGroups"];
SPQuery objParentQuery = new SPQuery();
string user = properties.AfterProperties["User"].ToString();
//in Caml query just find it out listitem which contain Users and than update its listitem.
objParentQuery.Query = "<Where><Eq><FieldRef Name='Check_x0020_it_x0020_out'/><Value Type='Integer'>"+You should set Userid in Field From litemUser +"</Value></Eq></Where>";
SPListItemCollection liitemcol = objFeatureList.GetItems(objParentQuery);
foreach (SPListItem litemGroup in liitemcol)
{
litemGroup["Group"] = litemUser["Group"];
litemGroup.Update();
// or if you want to using Workflow just startWorflow when item has match over here.
}
}
}

Batch Element in Sharepoint to Delete a List item when you do not know the ID

I want to delete an item in a list when it matches some critera using UpdateListItems web service. I dont know the ID of the list item that I want to delete but do know the criteria.
For example in SQL I could do:
DELETE FROM listName WHERE LastName='Bauer' AND FirstName='Jack'
How would you write a Batch Element to do this?
Update
Would it be something like this?
<Batch PreCalc='TRUE' OnError='Continue'>
<Method ID='1' Cmd='Delete'>
<Field Name='LastName'>Bauer</Field>
<Field Name='FirstName'>Jack</Field>
</Method>
</Batch>
Is the ID for the Method or the ID of the thing you wish to delete?
Update
I have tried the following code and the error that is returned is
Invalid URL Parameter
The URL provided contains an invalid Command or Value. Please check the URL again.
My guessing is that it is not possible to do without the ID...
As an addition to ChrisB's answer (formatting a CAML query in a comment didn't seem to work out), you'd make the query something like this:
SPQuery query = new SPQuery();
query.Query = "<Where><And>"+
"<Eq><FieldRef Name='LastName'/><Value Type='Text'>Bauer</Value></Eq>"
"<Eq><FieldRef Name='FirstName'/><Value Type='Text'>Jack</Value></Eq>"
"</And></Where>";
SPListItemCollection items = list.GetItems(query);
(this is the object model specification, but it extends naturally into the webservices call)
Then you'd loop through the listitems and build up your batch.
This does not look possible.
My way round this was to query the list and get the id's. Loop for the response pull out the id's then create a method for each ID to delete it.
Similarly, to get list item returned from the the Sharepoint 2010 object model that can be used in C# corresponding value of a key node in xml we have to get rid of that additional character attached at position 1 in the xml. This can be done as follows:
// Code to decipher XML string returned from SharePoint Server 2010 object model list item. - Courtesy - Rajiv Kapoor - ideals.co.in. View http://www.ideals.co.in/estore/code.php for complete solution.
string sRetVal = "";
string myXMLStr = "​<robot><Key>ConstSigned</Key><Value>Rad Is Signed</Value><Key>CodeAddChangeReqSub</Key><Value>ACRS</Value><Key>CodeAddChangeReqInit</Key><Value>ACRI</Value><Key>CodeSupTaskComp</Key><Value>STC</Value><Key>CodeSupApprComp</Key><Value>SAC</Value><Key>CodeSupRejComp</Key><Value>SAR</Value><Key>CodeOperAppr</Key><Value>OPA</Value><Key>CodeOperRej</Key><Value>OPR</Value><Key>Oper1TaskCreated</Key><Value>OTC</Value><Key>Oper2TaskCreated</Key><Value>QCTC</Value><Key>Oper2TaskAppr</Key><Value>QCRA</Value><Key>Oper2TaskRej</Key><Value>QCRR</Value><Key>ApprPending</Key><Value>Approval Pending</Value><Key>PendingProcessing</Key><Value>Pending Processing</Value><Key>PendingReview</Key><Value>Pending Review</Value><Key>Approved</Key><Value>Approved</Value><Key>GroupOperation</Key><Value>Operation</Value><Key>WorkFlowHistoryList</Key><Value>/Lists/Workflow History</Value><Key>ColInitDateTime</Key><Value>Initiated Date Time</Value><Key>ColWorkFlowHistoryParentInst</Key><Value>Workflow History Parent Instance</Value><Key>ColWorkflowAssId</Key><Value>Workflow Association ID</Value><Key>ColListId</Key><Value>List ID</Value><Key>ColPrimaryItemId</Key><Value>Primary Item ID</Value><Key>ColDate</Key><Value>Date Occurred</Value><Key>ColOutcome</Key><Value>Outcome</Value><Key>ColDesc</Key><Value>Description</Value><Key>ColCreated</Key><Value>Created</Value><Key>ColTaskStatus</Key><Value>TaskStatus</Value><Key>ServiceReqList</Key><Value>Service Request</Value><Key>CAUEventList</Key><Value>Events</Value><Key>ReqStatus1</Key><Value>Request Status</Value><Key>ReqStatCode</Key><Value>Request Status Code</Value><Key>ColumnCode</Key><Value>Code</Value><Key>SuperUser</Key><Value>SuperUser</Value><Key>AssignedTo</Key><Value>AssignedTo</Value><Key>TaskListId</Key><Value>ID</Value><Key>DocLibId</Key><Value>List</Value><Key>WorkflowInstanceId</Key><Value>WorkflowInstanceID</Value><Key>TaskTitle</Key><Value>Title</Value><Key>Priority</Key><Value>Priority</Value><Key>ReqStatusCode</Key><Value>Request Status Code</Value><Key>ServiceRequestList</Key><Value>Service Request</Value><Key>CAUEventList</Key><Value>Events</Value><Key>ColumnDesc</Key><Value>Description</Value><Key>ColumnStatus</Key><Value>Status</Value><Key>Completed</Key><Value>Completed</Value><Key>ReqStatus</Key><Value>Request Status</Value><Key>ColumnTaskStatus</Key><Value>TaskStatus</Value><Key>ColumnPerComp</Key><Value>PercentComplete</Value><Key>Rejected</Key><Value>Rejected</Value><Key>CodeSupTaskCreated</Key><Value>STC</Value><Key>CodeSupTaskInit</Key><Value>SAI</Value><Key>Oper1TaskInit</Key><Value>OPI</Value><Key>Oper2TaskInit</Key><Value>QCRI</Value><Key>ColActedBy</Key><Value>Acted By</Value><Key>WorkFlowCode</Key><Value>Workflow Code</Value><Key>ProcCode</Key><Value>Process Code</Value></robot>";
string myXMLStr1 = myXMLStr;
int ln = myXMLStr.Length;
int lnMinus1 = ln - 1;
char[] myst = { ' ', ' ', ' '};// create a long array enough to fit the xml
string mys = "";
object m1 ;
string m2 = "";
myXMLStr.CopyTo(0, myst, 0, ln); m1 = myst.Clone();
m2 = new string(myst);// m1;// ToString();
m2.TrimStart();
m2.TrimEnd();
m2 = m2.Substring(1);
sRetVal = GetConfigVal(m2, "ProcCode");
Console.WriteLine("****#*" + sRetVal + "*#******");
I am not that familiar with using the web services, but I assume there is one for searching. Using the API you would create an SPQuery and use CAML to get the list items you wanted to remove.

Categories