Get custom templates programmatically sharepoint 2010 - sharepoint-2010

To get standard templates I do:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetWebTemplates(1033);
foreach (SPWebTemplate template in Templates)
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
I thought I could do:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetCustomWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
To get the custom templates but the dropdown is empty, what am I doing wrong here?
Thanks in advance.
Edit: the templates are activated in the solutions gallery.

I got it to work with
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetAvailableWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
//this gives me all templates, both standard and custom so I filter by name
if(template.name.ToUpper().StartsWith("CUSTOM"))
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
}

SPSite does not contain a GetAvailableWebTemplates method. For those who would like to use the code use the one below. So I have added this line of code:
using(SPWeb web = siteCollection.OpenWeb())
{
SPWebTemplateCollection Templates = web.GetAvailableWebTemplates(1033);
Full code:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
using(SPWeb web = siteCollection.OpenWeb())
{
SPWebTemplateCollection Templates = web.GetAvailableWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
//this gives me all templates, both standard and custom so I filter by name
if(template.name.ToUpper().StartsWith("CUSTOM"))
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
}
}

Related

autodesk design automation

FATAL ERROR: Unhandled Access Violation Reading 0x0008 Exception at 1d8257a5h
Failed missing output
I finally made it work with HostApplicationServices.getRemoteFile in local AutoCAD, then migrated it to Design Automation. It is also working now. The below is the command of .NET plugin.
To have a simple test, I hard-coded the URL in the plugin. you could replace the URL with the workflow at your side (either by an json file, or input argument of Design Automation)
My demo ReadDWG the entities from the remote URL file, then wblock the entities to current drawing (HostDWG), finally save current drawing.
Hope it helps to address the problem at your side.
.NET command
namespace PackageNetPlugin
{
class DumpDwgHostApp: HostApplicationServices
{
public override string FindFile(string fileName,
Database database,
FindFileHint hint)
{
throw new NotImplementedException();
}
public override string GetRemoteFile(Uri url,
bool ignoreCache)
{
//return base.GetRemoteFile(url, ignoreCache);
Database db =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument.Database;
string localPath = string.Empty;
if (ignoreCache)
{
localPath =
Autodesk.AutoCAD.ApplicationServices.Application.
GetSystemVariable("STARTINFOLDER") as string;
string filename =
System.IO.Path.GetFileName(url.LocalPath);
localPath += filename;
using (var client = new WebClient())
{
client.DownloadFile(url, localPath);
}
}
return localPath;
}
public override bool IsUrl(string filePath)
{
Uri uriResult;
bool result = Uri.TryCreate(filePath,
UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp ||
uriResult.Scheme == Uri.UriSchemeHttps);
return result;
}
}
public class Class1
{
[CommandMethod("MyPluginCommand")]
public void MyPluginCommand()
{
try {
string drawingPath =
#"https://s3-us-west-2.amazonaws.com/xiaodong-test-da/remoteurl.dwg";
DumpDwgHostApp oDDA = new DumpDwgHostApp();
string localFileStr = "";
if (oDDA.IsUrl(drawingPath)){
localFileStr = oDDA.GetRemoteFile(
new Uri(drawingPath), true);
}
if(!string.IsNullOrEmpty(localFileStr))
{
//source drawing from drawingPath
Database source_db = new Database(false, true);
source_db.ReadDwgFile(localFileStr,
FileOpenMode.OpenTryForReadShare, false, null);
ObjectIdCollection sourceIds =
new ObjectIdCollection();
using (Transaction tr =
source_db.TransactionManager.StartTransaction())
{
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
SymbolUtilityServices.GetBlockModelSpaceId(source_db),
OpenMode.ForRead);
foreach (ObjectId id in btr)
{
sourceIds.Add(id);
}
tr.Commit();
}
//current drawing (main drawing working with workitem)
Document current_doc =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument;
Database current_db = current_doc.Database;
Editor ed = current_doc.Editor;
//copy the objects in source db to current db
using (Transaction tr =
current_doc.TransactionManager.StartTransaction())
{
IdMapping mapping = new IdMapping();
source_db.WblockCloneObjects(sourceIds,
SymbolUtilityServices.GetBlockModelSpaceId(current_db),
mapping, DuplicateRecordCloning.Replace, false);
tr.Commit();
}
}
}
catch(Autodesk.AutoCAD.Runtime.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString());
}
}
}
}

Windows 8 app, getting data on db change

I´m developing a windows 8 store app in c# and xaml for a website(the website is in .net mvc 4) .In the web site i can create, edit, and delete products (i´m using sql server 2008 r2).
In my w8 app i call a wcf service to get the data and populate the items.
I wanted to know if there is a way to notify or update the data in the w8 app after someone create or edit a product through the website.
One of the posible solution that i thought, was call the wcf service every time that the user click to see the list of products but i dont think is a good practice.
Here is my code:
//App.xaml.cs
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
ServiceProduct serviceData = (ServiceProduct)App.Current.Resources["serviceProducts"];
if (serviceData != null)
{
if (serviceData.ListaIos.Count == 0)
{
try
{
await serviceData.GetListProductsAsync();
}
catch(ServiceException)
{
var messageDialog = new Windows.UI.Popups.MessageDialog("Error");
var result = messageDialog.ShowAsync();
}
}
}
*** code ***
}
//Items page
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
ServiceProduct serviceData = (ServiceProduct)App.Current.Resources["serviceProducts"];
if (serviceData != null)
{
this.DefaultViewModel["Items"] = serviceData.GetProducts;
}
}
public async Task GetListProductsAsync()
{
ProductServiceClient service = new ProductServiceClient();
Product product;
try
{
var wcfCall = await service.GetListaAsync();
foreach (var item in wcfCall.List)
{
map product
this.ListaIos.Add(product);
}
}
catch(Exception)
{
throw new NotImplementedException();
}
}

Sharepoint 2010 DocumentSets - How to Manage Programatically?

I am new to Sharepoint 2010 but not new to .Net programming. Here is a my situation, i have a large set of files to be uploaded into Sharepoint 2010 with metadata. I have decided to write a C# class library to handle the documentsets programatically. I have to use to DocumentSets and i was able to successfully create a documentset. Now i am stuck with the following:
How do i check if a documentset already exists?
How do i remove a documentSet?
Here is my code to create the documentset:
using (SPSite site = new SPSite(spURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList docs = web.Lists["Documents"];
if (docs != null)
{
SPContentType docSetCT = docs.ContentTypes["Document Set"];
if (docSetCT != null)
{
Hashtable docsetProps = new Hashtable();
docsetProps.Add("New Docset", "New Docset");
DocumentSet docSet = DocumentSet.Create(docs.RootFolder, documentSetName, docSetCT.Id, docsetProps, true);
docs.Update();
}
}
}
}
The list of helper methods for working with Document Sets:
How do I check if a document set already exists?
private static bool IsDocumentSetExist(SPList list,string docSetName)
{
var folderUrl = SPUrlUtility.CombineUrl(list.RootFolder.ServerRelativeUrl, docSetName);
var folder = list.ParentWeb.GetFolder(folderUrl);
return folder.Exists;
}
Usage:
var docSetExists = IsDocumentSetExist(docs, "New Docset");
How do I remove a document set?
private static void DeleteDocumentSet(DocumentSet docSet)
{
docSet.Folder.Delete();
}

How to search file from a document library using client object model sharepoint 2010

At the moment i am struggling to programatically enable the search functionality to search file from a document library using client object model sharepoint 2010,
Can you please help me with the code
Thanks
Kajal
List list = clientcontext.Web.Lists.GetByTitle(ListName);
clientcontext.Load(list);
clientcontext.ExecuteQuery();
FileCollection files = list.RootFolder.Files;
clientcontext.Load(files);
clientcontext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.File file in files)
{
if(file.Name == txtSearch)
{
// your logic
}
}
private string searchDoc(string name)
{
try
{
ClientContext clientContext = new ClientContext("YOUR SERVER");
SP.List oList = clientContext.Web.Lists.GetByTitle("YOUR DOC");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='Recursive'/>";
Microsoft.SharePoint.Client.ListItemCollection collListItem1 = oList.GetItems(camlQuery);
clientContext.Load(collListItem1, items => items.Include(item => item.DisplayName, item => item["Comments"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem oListItem1 in collListItem1)
{
if (oListItem1.DisplayName == name)
{
XXXXXXXXXXXXXX
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message, "Exception");
}
}
Recursive's search!

Set the value of custom webpart property in c#

How to set the value of custom webpart property Programatically in C#.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite SiteCollection = new SPSite(mySiteGuid))
{
SPWeb myWeb = SiteCollection.OpenWeb(myWebGuid);
myWeb .AllowUnsafeUpdates = true;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = myWeb.GetLimitedWebPartManager ("default.aspx",System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
{
if (myWebPart.Title == "Other Webpart Name")
{
myWebPart.Visible = ! myWebPart.Visible;
myWeb.Update();
break;
}
}
}
});
I have a custom property in the webpart of type string to get the input from the user.
I wanted to updated the value of the property from c#.
Is there any way to set the value?
TIA
Try myWebPart.Update() instead of myWeb.Update().
Maybe it's a bit late for the answer, but here i let a piece of code i used for this.
var webCollection = new SPSite("http://mySharePointSite").AllWebs;
foreach (SPWeb web in webCollection)
{
var landingPageReference = #"/Pages/default.aspx";
var page = web.GetFile(landingPageReference);
if (!page.Exists)
continue;
page.CheckOut();
var spLimitedWebPartManager = web.GetLimitedWebPartManager(page.ServerRelativeUrl, PersonalizationScope.Shared);
foreach (WebPart webPartItem in spLimitedWebPartManager.WebParts)
{
if (webPartItem.Title.Equals("myWebPartTitle"))
{
// Specify Properties to change here
webPartItem.ChromeType = PartChromeType.Default;
webPartItem.Description = "AGAIN CHANGED";
// Save made changes
spLimitedWebPartManager.SaveChanges(webPartItem);
break;
}
}
page.CheckIn("Add Comment if desired");
page.Publish("Add Comment if desired");
web.Update();
web.Dispose();
}