I want to programmatically create a Webpart page (.aspx file) for Sharepoint 2010. I already found this code snippet:
public static PublishingPage CreatePage(string fileName, string title)
{
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(Web);
PageLayout[] layouts = pWeb.GetAvailablePageLayouts();
PageLayout layout = layouts[0];
foreach (PageLayout p in layouts)
{
if (p.Name.Equals("BlankWebPartPage.aspx"))
{
layout = p;
break;
}
}
try
{
PublishingPage newPage = pWeb.GetPublishingPages().Add(fileName, layout);
newPage.Title = title;
newPage.Update();
return newPage;
}
catch (Exception)
{
return null;
}
}
But my problem is SharePoint Foundation Server does not have the Publishing part but I have to run it on a SharePoint Foundation Server.
Is it possible to create a Webpart Page without PublishingWeb?
greets
Publishing Infrastructure is one of the features that is only avaialble in SharePoint Server Standard or Enterprise. It is not included in SharePoint Foundation 2010. It wasn't included in Windows SharePoint Servives (WSS) either. Publishing has always required the purchased version of the product.
Related
I have a problem with updating properties of sharepoint 2010 feature
this is my code :
using (SPSite site = new SPSite("http://vm-pc:2000"))
{
foreach (SPFeatureDefinition def in SPFarm.Local.FeatureDefinitions)
{
if (def.Scope == SPFeatureScope.WebApplication)
{
if (def.GetTitle(System.Threading.Thread.CurrentThread.CurrentCulture) == "Configure Site Settings")
{
((SPFeatureProperty)def.Properties[0]).Value = "5";
def.Properties.Update();
def.Update();
}
}
}
}
The problem with def.Properties.Update();
It throws an exception :
Updating the properties of a feature definition is not supported.
Why dont you use the Property bag?
SPSite site = new SPSite("URL");
SPWeb web = site.RootWeb;
web.Properties.Add("Key", "Value");
web.Properties.Update();
and get value:
web.AllProperties["Key"]
I have created a Site Named Application Test. In this site i again Create a Sub site Named Sub Application.
I add in site url "http://SP2010:2222/" in Visual Studio Project
Project Scope is Site.
Now i when i try to access the List ( TestList ) From Sub site ( Sub Application ) it give error List Does not Exist.
Following Code to Access the List( TestList ):
using (SPSite sites = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = sites.OpenWeb())
{
SPList CurrentList = web.Lists["TestList"]; // Error comes here
}
}
anybody have solution?
Try this,
using (SPSite sites = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = sites.OpenWeb())
{
SPWebCollection subsites= web.GetSubwebsForCurrentUser(); //get subsites
for (int i= 0; i< subsites.Count; i++)
{
SPWeb subSiteWeb= subsites[i];
SPList CurrentList = subSiteWeb.Lists["TestList"];
if (CurrentList != null)
break;
}
}
}
Well SPContext.Current.Site is the current site you deployed your thing to - whatever it is. But when you do sites.OpenWeb() without any parameters is opens the RootWeb and if the root web doesn't have your list you won't find it there.
Try to open the web and the site explicitly by using their respective URLs e.g. http://SP2010:2222/
webpart is working on local server but not working on production server when "SPSite" class is uesd in the web part. On the production server it throws error. If I do not use that class in the webpart the web part also works on live machine.
Any idea what might be causing the error?
the code in the webpart is this:
namespace CompanyNews
{
[Guid("40de3c60-9e30-4050-b9f3-01e71868f522")]
public class CompanyNews : System.Web.UI.WebControls.WebParts.WebPart
{
private HtmlTextWriter writer;
public CompanyNews()
{
}
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
string listName = "News Display";
writer.Write(listName);
SPList list = null;
foreach (SPList currentList in web.Lists)
{
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase))
{
list = currentList;
break;
}
}
writer.WriteBeginTag("ul");
foreach (SPListItem item in list.Items)
{
writer.Write("<li style=\"font-size:12px;padding:1px\">");
writer.Write(item["Title"].ToString() + "... ");
writer.Write("<a class=\"smallerred\" href=\"#\">Read More</a>");
writer.Write("</li>");
}
writer.WriteEndTag("ul");
}
}
}
}
}
The dll of the webpart is in the bin folder and in the web.config file there is an entry for the web par as a safe control.
Other webpart which displays a "hellow world" message is also uploaded to production the same way.
I i guess its the code that is causing the problem.
The error message is: "An error occurred while previewing the web part"
just something I noticed, you shouldn't wrap objects from the Current Context in a using statement. Good article here Clicky
Better practice would be to use the following
using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
{
...
}
Also you should look at packaging up your solution in a WSP, allowing stsadm to deploy it. Dragging into the GAC isn't very good practice.
Shane
The SPSite object isn't getting reference anywhere that I can see. Why don't you remove it anyway as it's superflous to your needs?
SPWeb web = SPContext.Current.Web;
string listName = "News Display";
writer.Write(listName);
SPList list = null;
foreach (SPList currentList in web.Lists)
{
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase))
{
list = currentList;
break;
}
}
writer.WriteBeginTag("ul");
foreach (SPListItem item in list.Items)
{
writer.Write("<li style=\"font-size:12px;padding:1px\">");
writer.Write(item["Title"].ToString() + "... ");
writer.Write("<a class=\"smallerred\" href=\"#\">Read More</a>");
writer.Write("</li>");
}
writer.WriteEndTag("ul");
am working on a project where I want to pull data from different lists in SharePoint and have these data imported into a single list. The list has the same attribute everywhere; it is located in different sites.
I have a list which contains all the site names and URL to those sites. The idea is to read from this list all the site names and then go to each one of those sites and try and pull the information from the list under that particular site, in synchronies matter. Data that are pulled from last week’s process do not need to be pulled again.
Can someone guide me in explaining what would be the best way to doing this solution?
Am using SharePoint 2007
You may be better off looking at the Data View Web Part (DVWP) and rollups
A common topic that is asked about in
SharePoint, is how to roll up
information from sub-sites to a top
level site, and just generally how to
show data from one site on another
site.
I have this scenario. I made a webpart that sends the information for my consolidation list, through the sharepoint web services.
I installed the webpart in each sharepoint site, this webpart get the data (when it's outdated) and make a insert in the consolidation list through the lists.asmx webservice. See http://msdn.microsoft.com/en-us/library/lists(v=office.12).aspx. Then a I create a user with permission to write in the consolidation list in my consolidation site, and used this to authenticate my webpart when it will do the insert on the list.
I did something like this, in Visual Studio 2005, with Sharepoint dll referenced.
public void InsertToPainel(string strID, string user, string password)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
//WSPainel is the WebReference to http://<site>/_vti_bin/Lists.asmx.
using (WSPainel.Lists lstPainel = new webPartSender.WSPainel.Lists())
{
lstPainel.UseDefaultCredentials = true;
lstPainel.Credentials = new System.Net.NetworkCredential(user, password);
#region Make the fields in consolidation list
Dictionary<string, string> fieldsNamesAndValues = new Dictionary<string, string>();
fieldsNamesAndValues.Add("ID", strID);//Recuperar quando for atualizar ou incluir New
fieldsNamesAndValues.Add("URL", SPContext.Current.Web.Url + ", " + splInfGerItems[0]["Title"].ToString()); //The link of the actual site that is sending the information
fieldsNamesAndValues.Add("Comments", splStatusItems[0]["Title"].ToString());//In my case, I just need the last result.
#endregion
//It will make the register in CAML format and updates the lists.
lstPainel.UpdateListItems(_listaPainel, NewCAMLRegister(fieldsNamesAndValues, strID));
}
}
catch (Exception e)
{
//Exception
}
});
}
private XmlNode NewCAMLRegister(Dictionary<string, string> FieldsNamesAndValues, string strID)
{
try
{
XmlDocument xdMensagem = new XmlDocument();
XmlElement xeBatch = xdMensagem.CreateElement("Batch");
XmlNode xnMethod = xdMensagem.CreateElement("Method");
xdMensagem.AppendChild(xeBatch);
xeBatch.AppendChild(xnMethod);
XmlAttribute xaID = xdMensagem.CreateAttribute("ID");
XmlAttribute xaCmd = xdMensagem.CreateAttribute("Cmd");
xaID.Value = "1"; //Id do comando no Batch.
if (strID == "New")
{
xaCmd.Value = "New";
}
else
{
xaCmd.Value = "Update";
}
xnMethod.Attributes.Append(xaID);
xnMethod.Attributes.Append(xaCmd);
foreach (KeyValuePair<string, string> strfieldname in FieldsNamesAndValues)
{
XmlNode xnField = xdMensagem.CreateElement("Field");
XmlAttribute xaName = xdMensagem.CreateAttribute("Name");
xaName.Value = strfieldname.Key;//Nome do Campo
xnField.Attributes.Append(xaName);
xnField.InnerText = strfieldname.Value;//Valor do Campo
xnMethod.AppendChild(xnField);
}
//"<Method ID=\"1\" Cmd=\"New\">" + "<Field Name=\"ID\">New</Field>" + "<Field Name=\"Title\">This is a test</Field>" + "</Method>";
return xdMensagem;
}
catch (Exception e)
{
//Exception
return null;
}
}
I hope it helps.
I am trying to get a list of webparts deployed on a web page in sharepoint 3.0. Is there way I can retrieve it from sharepoint content database or can I do it programmatically?
You can use the SPWebPartManager to iterate thru a list of web part in a page.
See this MSDN example.
EDIT:
This is maybe a better example:
private static void GetWebParts()
{
using (SPSite site = new SPSite("<YOUR SITE URL>"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("default.aspx"); // or what ever page you are interested in
using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
foreach (WebPart wp in wpm.WebParts)
{
Console.WriteLine("Web part: {0}", wp.Title);
}
}
}
}
}
Adding web parts programmatically is simple:
SPWeb site = SPContext.Current.Web;
SPFile page = web.GetFile("Pages/somepage.aspx");
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
// logic to get web parts here.
ContentEditorWebPart webPart = new ContentEditorWebPart();
webPart.Title = "Test Web Part";
webPartManager.AddWebPart(webPart, "Zone 1", 0);
}
finally
{
// SPLimitedWebPartManager has known memory leak where it does not dispose SPRequest object in its SPWeb, so dispose it
webPartManager.Web.Dispose();
}
}