Image Custom Webpart - sharepoint

I have custom List which has image field. I have to display the image through the object modelling code.
Which Control I need to use to display the image in a webpart and which property I need to assign it for.
[Guid("207cea76-b1ee-4b86-9638-00c22d3d9398")]
public class News : System.Web.UI.WebControls.WebParts.WebPart
{
Label lblTitle;
ImageField imgNews;
Label lblDescription;
public News()
{
}
protected override void CreateChildControls()
{
base.CreateChildControls();
lblTitle = new Label();
imgNews = new ImageField();
lblDescription = new Label();
string siteURL = "http://my-dev-box-har";
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPListItemCollection list = web.Lists["News"].Items ;
foreach (SPListItem item in list)
{
lblTitle.Text = item["Title"].ToString();
lblDescription.Text = item["Description"].ToString();
imgNews. = item[""].ToString();
Controls.Add(lblTitle);
Controls.Add(lblDescription);
}
}
}
}
}
}
I don't know wheather to use image or Imagefield control to display my image form the sharepoint custom list.
Could anybody point me in right direction please.
Thank you
Hari

This is the most simple example I could come up with:
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace TestPictureWebPart.PicWebPart
{
[ToolboxItemAttribute(false)]
public class PicWebPart : WebPart
{
protected override void CreateChildControls()
{
SPList list = SPContext.Current.Web.Lists["ImageList"];
SPListItemCollection items = list.Items;
foreach (SPListItem item in items)
{
string title = item[SPBuiltInFieldId.Title].ToString(); // or string title = item.Title;
SPFieldUrlValue picture = new SPFieldUrlValue(item["MyPicture"].ToString());
Image image = new Image();
image.ToolTip = title;
image.ImageUrl = picture.Url;
Controls.Add(image);
}
}
}
}
Just a tip: it's always better to use SPBuiltInFieldId to access out-of-the-box columns in SharePoint.
Also, in your example code... if you have more than one listitem in your list, you are in trouble. You will use the same web controls (the labels for example) for each listitem and add them to the Controls collection in every iteration.

Related

error : is a field but used as a type

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication5
{
public class ClientContext
{
private string p;
public ClientContext(string p)
{
// TODO: Complete member initialization
this.p = p;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//First construct client context, the object which will be responsible for
//communication with SharePoint:
private ClientContext context = new ClientContext("#url");
//then get a hold of the list item you want to download, for example
public List list;
public ClientContext
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
}
//note that data has not been loaded yet. In order to load the data
//you need to tell SharePoint client what you want to download:
context.Load(result, items=>items.Include(
item => item["Title"],
item => item["FileRef"]
));
//now you get the data
context.ExecuteQuery();
//here you have list items, but not their content (files). To download file
//you'll have to do something like this:
var item = items.First();
//get the URL of the file you want:
var fileRef = item["FileRef"];
//get the file contents:
FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());
using (var memory = new MemoryStream())
{
byte[] buffer = new byte[1024 * 64];
int nread = 0;
while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
memory.Write(buffer, 0, nread);
}
memory.Seek(0, SeekOrigin.Begin);
// ... here you have the contents of your file in memory,
// do whatever you want
}
}
}
this is the complete code.
I don't know why it is showing error. I searched for the error "is a field but used as a type" and I tried that but it didn't help. Please help with a solution Code to this since I am new to this. Thank you in advance.
What are you trying to achieve by this lines of code?
public partial class Form1 : Form
{
...
public ClientContext
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
}
}
What is public ClientContext {} inside class Form1 ?
It seems that you intended to create constructor to a class in another class and for compiler it looks more like a property but without accessors (get, set) as if it is a Type or smth like this.
Try to put get; set; accessors inside if you intended to create property:
public List Context
{
get
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
return list;
}
}
Or change it to method instead :
public void GetClientContext()
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
}

Custom Filter Web Part to filter/update ListView Web Part

Scenario : I need Refresh/Filter the Items/records displayed in List View Web Part on the same page based on selected filters. So I created Visual Web Part and tried to modify the View of List View Web Part Programmatically. So far i have reached till here :
string spListName = "Job";
protected void BtnSearchClick(object sender, EventArgs e)
{
try
{
SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists[spListName];
XsltListViewWebPart xsltWP = null;
SPWebPartManager wpManager = WebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
//Code to Find List View Web Part on Page
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpManager.WebParts)
{
if (wp.GetType().Name == "XsltListViewWebPart")
xsltWP = wp as XsltListViewWebPart;
}
oWebsite.AllowUnsafeUpdates = true;
StringBuilder strbPreQuery = new StringBuilder("<Where><Eq>");
StringBuilder strbPostQuery = new StringBuilder("</Value></Eq></Where>");
string strQueryKeyword = "<FieldRef Name='Customer' /><Value Type='Lookup'>";
SPQuery oQuery = new SPQuery();
oQuery.Query = strbPreQuery.ToString() + strQueryKeyword + txtCustomer.Text + strbPostQuery.ToString();
SPListItemCollection itemCol = oWebsite.Lists[spListName].GetItems(oQuery);
PropertyInfo pi = xsltWP.GetType().GetProperty("ContextView", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
SPView view = (SPView)(pi.GetValue(xsltWP, null));
view.Query = oQuery.Query;
view.Update();
wpManager.SaveChanges(xsltWP);
xsltWP.DataBind();
oWebsite.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
Response.Write(ex);
}
}
The Above code works but now I am facing following problems :
The results updation requires page refresh so If I add following code, results are updated but filter values in visual web part is lost.
this.Context.Response.Redirect(this.Context.Request.Url.ToString());
Filtered applied by one user is also reflected to another user.
Can some please help in to address these two problems I have ? that is I want
To preserve the filter values and results to be modified at the same time
The filtering should be only for one user and not for all.
Any help in this regards will be appreciated.
Create a SPQuery that will hold the default value of the view.
then after passing the value,
Use this to revert back the default query of the view.
SPView _view;
protected void Page_Unload(object sender, EventArgs e)
{
//your code
SPView view = (SPView)(pi.GetValue(xsltWP, null));
view.Query = _view.Query;
view.Update();
}

EventReceiver to Create folder sharepoint 2010

I have this event receiver c# class that I am trying to implement on a Sharepoint site. It did not work. I have deployed it from visual studio 2010 after it was build ok. Does anyone see what is the problem? Is the code ok? or is the problem on the SP? Thank you.
- here is the new code
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace EventReceiverCFolder.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
if (properties.ListTitle == "CF") // list where the item was added
{ // if item was added to this list then create a folder on - Dlib - list
UpdateFolder(properties);
}
}
catch (Exception ex)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
}
}
private void UpdateFolder(SPItemEventProperties properties)
{
string foldername = properties.ListItem["Title"].ToString();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//inside RunWithElevatedPriviliges I need to open a new site (an elevated site)
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("DLib"); // this is doc Library where the new folder will be created
//note that we are creating a list item, not a folder - a folder IS a list item
SPListItem createdFolder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
if (createdFolder != null)
{
createdFolder["Name"] = foldername;
createdFolder.Update();
}
list.Update();
}
}
});
}
finally { }
}
}
}
Don't do this: SPUser privilegedAccount = properties.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
Read up on using SPSecurity.RunWithElevatedPrivileges. See the MSDN documentation here.
Also don't do a using (SPSite... and inside the using block you try to get the web via SPContext.Current - that web won't be elevated anymore.
The correct way is something along these lines (I didn't try this, so it' just to give you an idea where you are headed):
private void UpdateFolder(SPItemEventProperties properties)
{
string foldername = properties.ListItem["Title"].ToString();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//inside RunWithElevatedPriviliges I need to open a new site (an elevated site)
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("ListTitle"); //is that really the list title?
//note that we are creating a list item, not a folder - a folder IS a list item
SSPListItem createdFolder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
if (newFolder != null)
{
createdFolder["Name"] = foldername;
createdFolder.Update();
}
list.Update();
}
}
});
}
Also try to debug your code, set breakpoints etc.
I had to get folder name like this:
string foldername = Convert.ToString(properties.AfterProperties["Title"]);
Did you try to debug it? try to debug and tell us what error you are getting.
BUT before you debug first use sharepoint manager to see if your event receiver is attached properly.
If you dont know how to debug sharepoint event receiver then please see this

Passing Multiple parameters from Custom WebPart to Reporting services Report Viewer webpart

I working with Reporting services in Sharepoint Mode, I am able to show the report in Sql Server Reporting services report viewer , the report has multiple parameters , My question is how do I pass more than one parameter from a custom web part to this report.
I am able to pass one parameter by implementing the ITransformableFilterValues interface in the custom webpart , what I want to do is pass more than one parameter .
Ex: If there are 2 parameters on report then i should able to map each from the control in webpart.
Here is the Code for Custom Webpart:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using aspnetwebparts = System.Web.UI.WebControls.WebParts;
//using Microsoft.Office.Server.Utilities;
using wsswebparts = Microsoft.SharePoint.WebPartPages;
//using Microsoft.SharePoint.Portal.WebControls;
using System.Collections.ObjectModel;
using Microsoft.SharePoint.Utilities;
using System.Data;
using System.Collections;
namespace CustomWebPart
{
/// <summary>
/// Used to provide filter values for the status report.
/// </summary>
public class StatusReportFiler : aspnetwebparts.WebPart, wsswebparts.ITransformableFilterValues
{
DropDownList ddlCategory;
ListItem lstItem;
Label lblCaption;
public virtual bool AllowMultipleValues
{
get
{
return false;
}
}
public virtual bool AllowAllValue
{
get
{
return true;
}
}
public virtual bool AllowEmptyValue
{
get
{
return false;
}
}
public virtual string ParameterName
{
get
{
return "Category";
}
}
public virtual ReadOnlyCollection<string> ParameterValues
{
get
{
string[] values = this.GetCurrentlySelectedCategory();
return values == null ?
null :
new ReadOnlyCollection<string>(values);
}
}
protected override void CreateChildControls()
{
lblCaption = new Label();
lblCaption.Text = " Category: ";
Controls.Add(lblCaption);
ddlCategory = new DropDownList();
ddlCategory.AutoPostBack = true;
lstItem = new ListItem();
lstItem.Text = "Select All Category";
lstItem.Value = "0";
ddlCategory.Items.Add(lstItem);
lstItem = null;
lstItem = new ListItem();
lstItem.Text = "BING";
lstItem.Value = "Bing";
ddlCategory.Items.Add(lstItem);
lstItem = null;
lstItem = new ListItem();
lstItem.Text = "Google";
lstItem.Value = "Google";
ddlCategory.Items.Add(lstItem);
lstItem = null;
Controls.Add(ddlCategory);
// base.CreateChildControls();
}
[aspnetwebparts.ConnectionProvider("Category Filter", "ITransformableFilterValues", AllowsMultipleConnections = true)]
public wsswebparts.ITransformableFilterValues SetConnectionInterface()
{
return this;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
public string[] GetCurrentlySelectedCategory()
{
string[] selCategory = new string[1];
selCategory[0] = ddlCategory.SelectedValue;
return selCategory;
}
protected override void RenderContents(HtmlTextWriter htmlWriter)
{
/*htmlWriter.Write("<table border=\"0\" width=\"100%\">");
htmlWriter.Write("<tr><td>");
lblCaption.RenderControl(htmlWriter);
htmlWriter.Write("</td></tr>");
htmlWriter.Write("<tr><td>");
lblCaption.RenderControl(htmlWriter);
htmlWriter.Write("</td></tr>");
htmlWriter.Write("</table>");*/
this.EnsureChildControls();
RenderChildren(htmlWriter);
}
}
}
Once you build this Webpart deploy it to SharePoint.
Create a Webpart page in Sharpoint , Add the Custom Web Part to the page .
Once you add it you will be able to see the dropdownlist with values on the Webpart .
In another Add Webpart Section add a Sql Server Reporting Sevices ReportViewer web part and set the report URL in the properties section and click apply , this report should have the same parameter name as in Custom Webpart.
In the Custom Webpart click on Edit -> Connections-> Send Category Filter To -> ReportViewer - AAAA(This is the ReportName I Guess). This will popup a Window with the mapping section , Map the Filer Category to Filtered parameter on the Report and click Finish . This will pass the value from the Webpart to the Report.
Hope this helps.
I'm not sure about SharePoint integrated mode, but ReportServer correctly accept parameters passed via URL string.

Filter a SharePoint list by audience

Using the SharePoint SDK, I'm attempting to retrieve a list and display the contents in a composite control. The list is audience aware and I'd like to maintain that in my control. How can I go about getting this list, filtered by audience, using the SharePoint SDK? Here's some of the code I'm working with:
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
SPList shortcuts = currentWeb.Lists["Shortcuts"];
Here's some of the code I'm using now, and it's not quite working for me. According to how the audiences are set up, I should be getting results:
protected override void CreateChildControls()
{
dropdown = new DropDownList();
dropdown.Items.Add(new ListItem("Select...", ""));
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
SPList shortcuts = currentWeb.Lists["Shortcuts"];
ServerContext context = ServerContext.GetContext(currentWeb.Site);
AudienceManager audManager = new AudienceManager(context);
AudienceCollection audiences = audManager.Audiences;
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
foreach (SPListItem listItem in shortcuts.Items)
{
string audienceFieldValue = (string)listItem["Target Audiences"];
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false))
{
dropdown.Items.Add(new ListItem(listItem.Title, listItem.Url));
}
}
Controls.Add(dropdown);
base.CreateChildControls();
}
On:
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false))
It's never returning true, even when it should be.
Here's a more succinct code snippet. Main changes are removal of unused objects, and a more efficient version of the foreach loop.
protected override void CreateChildControls()
{
dropdown = new DropDownList();
dropdown.Items.Add(new ListItem("Select...", ""));
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
SPListItemCollection scItems = currentWeb.Lists["Shortcuts"].Items;
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
// Iterate over a copy of the collection to prevent multiple queries to the list
foreach (SPListItem listItem in scItems)
{
string audienceFieldValue = (string)listItem["Target Audiences"];
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false))
{
dropdown.Items.Add(new ListItem(listItem.Title, listItem.Url));
}
}
Controls.Add(dropdown);
base.CreateChildControls();
}
Here's a code snippet that maybe could be of use, to determine each items audience:
SPList shortcuts = currentWeb.Lists["Shortcuts"];
SPListItemCollection items = list.Items;
Audience siteAudience;
ServerContext context = ServerContext.GetContext(site);
AudienceManager audManager = new AudienceManager(context);
foreach (SPListItem item in items)
{
string ID = item["Target Audiences"].ToString();
string NewID = ID.Remove(36);
Guid guid = new Guid(NewID);
siteAudience = audManager.GetAudience(guid);
}

Resources