Find subsolution items - c#

I am trying to find subsolution and add items into that solution programmatically. But code that i use is not searching for subfolders.
I use code on github: See code here please
Method that i search for solution is:
public static IEnumerable<EnvDTE.Project> GetAllProjects(EnvDTE.DTE dte)
{
List<EnvDTE.Project> projectList = new List<EnvDTE.Project>();
var folders = dte.Solution.Projects.Cast<EnvDTE.Project>().Where(p=>p.Kind == EnvDTE80.ProjectKinds.vsProjectKindSolutionFolder);
foreach (EnvDTE.Project folder in folders)
{
if (folder.ProjectItems == null) continue;
foreach (EnvDTE.ProjectItem item in folder.ProjectItems)
{
if (item.Object is EnvDTE.Project)
projectList.Add(item.Object as EnvDTE.Project);
}
}
var projects = dte.Solution.Projects.Cast<EnvDTE.Project>().Where(p=>p.Kind != EnvDTE80.ProjectKinds.vsProjectKindSolutionFolder);
if (projects.Count() > 0)
projectList.AddRange(projects);
return projectList;
}
But this is searching only main solution and sub solution. But solution that i want to find has a longer path like "MainFolder\SubFolder1\SubFolder2\SubFolder3\SubSolution"

Related

Differentiate iTunes internal playlists and user playlist

Following my previous question
When I fetch Playlists in iTunes library I get some entries which seems to be default playlists for iTunes
Here is my code:
App = new iTunesAppClass();
IITSourceCollection sources = App.Sources;
foreach (IITSource src in sources)
{
if (src.Name == "Library")
{
IITPlaylistCollection pls = src.Playlists;
foreach (IITPlaylist pl in pls)
{
// add pl.Name to a List<string> and them show them on TreeView
}
}
}
This is the result:
You see that I have created a playlist named "Music". There is also a default entry named "Music". How can I differentiate these two playlist ? Is there any property in iTunesLib which says which one is the default one and which is the one I have created?
Using Kind and SpecialKind properties, I was able to implement a solution:
App = new iTunesAppClass();
IITSourceCollection sources = App.Sources;
foreach (IITSource src in sources)
{
if (src.Name == "Library")
{
IITPlaylistCollection pls = src.Playlists;
foreach (IITPlaylist pl in pls)
{
/* here is the trick */
if (p is IITUserPlaylist)
{
var upl = (IITUserPlaylist)p;
if (upl.SpecialKind != ITUserPlaylistSpecialKind.ITUserPlaylistSpecialKindNone)
continue;
}
/* and this one */
if (p.Kind == ITPlaylistKind.ITPlaylistKindLibrary)
continue;
// add pl.Name to a List<string> and them show them on TreeView
}
}
}

How to validate if a folder already exists

I want to create folders and add classes within the folders. I can create the folder once, but once I have created it, I just want to add classes. My code gives error because I'm trying to create a folder several times, which is not right. So before adding a class to the folder, I want to check if the folder already exists and if it exists I just want to add the class.
ProjectItem rootFolder = project.ProjectItems.AddFolder(folder);
ProjectItem item = rootFolder.ProjectItems.AddFromTemplate(itemPath, className);
According to documentation, there is no kind of Exists function which would tell us if a folder already existed.
So you have at least two options:
1. Try and ignore
Simply:
try
{
var rootFolder = project.ProjectItems.AddFolder(folder);
}
catch
{
/* folder already exists, nothing to do */
}
2. Solution folders can only occur in the first level below the solution root node, so we can get away with a non-recursive solution.
public static bool CheckIfSolutionFolderExists(ProjectItems projectItems, string foldername)
{
foreach(var projectItem in projectItems)
{
if(projectItem.Kind == EnvDTE.vsProjectItemKindVirtualFolder)
{
if(projectItem.Name == foldername)
{
return true;
}
}
}
return false;
}
For a recursive solution, I found this, which boils down to:
public static bool CheckIfFileExistsInProject(ProjectItems projectItems, string fullpath)
{
foreach(ProjectItem projectItem in projectItems)
{
if(projectItem.Name == fullpath)
{
return true;
}
else if ((projectItem.ProjectItems != null) && (projectItem.ProjectItems.Count > 0))
{
/* recursive search */
return CheckIfFileExistsInProject(projectItem.ProjectItems, fullpath);
}
}
return false;
}
A robust pattern for solution and project folder management would use AddFromDirectory whenever you want to mirror the file system hierarchy in the project tree, and AddFolder only for virtual folders that have no representation in the file system.
ProjectItem item;
if(Directory.Exists(itemname))
{
item = project.AddFromDirectory(itemname);
}
else
{
item = project.AddFolder(itemname);
}
(source: inspired from this)
You can use method Directory.Exists
and in your code it'll be look like there
if(!Directory.Exists(folder)) {
ProjectItem rootFolder = project.ProjectItems.AddFolder(folder);
}
ProjectItem item = rootFolder.ProjectItems.AddFromTemplate(itemPath, className);
You need to do the following:
if(Directory.Exists(path))
{
// The folder already exists
}
else
{
//Create a new folder here ...
}
Please check this out for more details on Directory.Exists

Determine if CodeElement belongs to project

I'm trying to develop a plugin for Visual Studio 2015. I have command that gets added to the context menu when a project is right clicked and I can get the project that was right clicked. Now what I am trying to do is determine if the project contains a class that implements a certain interface. So my first step is to get the classes in the project. So I did something like this:
protected IEnumerable<EnvDTE.CodeClass> GetClasses(EnvDTE.CodeElements elements,
EnvDTE.Project project)
{
foreach (EnvDTE.CodeElement element in elements)
{
System.Diagnostics.Debug.WriteLine(element.InfoLocation);
var cls = element as EnvDTE.CodeClass;
if (cls != null)
{
yield return cls;
}
var ns = element as EnvDTE.CodeNamespace;
if (ns != null)
{
foreach (var childCls in GetClasses(ns.Members, project))
{
yield return childCls;
}
}
}
}
So this will go through and pull out classes. The problem is that it will go through everything that is referenced include BCL classes. I thought using InfoLocation might help, but everything returns vsCMInfoLocationExternal (presumably because in the context where the plugin is running, they are external). I've tried things like element.ProjectItem and element.ProjectItem.ContainingProject and element.Parent with the hope of comparing that to the parent project, but those all throw System.Runtime.InteropServices.COMException. So is there a way, given that I know the project, to determine if a particular CodeElement is part of the project, or just referenced by the project?
EDIT: The best I've been able to come up with so far is to do this, first get the default namespace for the project:
var defaultNS = project.Properties.Item("DefaultNamespace").Value.ToString();
And then I can do this:
if (ns != null && ns.Name == defaultNS)
So now I won't go drilling down into System, which is good. The only problem would be if a project had multiple namespaces that I wanted to search. I can't figure out if there is a way to get a list of namespaces that are defined in the project.
Edit: The suggested dupe deals with Type so isn't entirely relevant.
This may suit your needs or it may not but this is what I used to parse code elements and figure out if the definition is in the solution or if it comes in via a reference. There is no way to know if the reference is 3rd party vs BCL however. Some code removed for brevity since this is inside an API and hard to fully break out. You could add a trick once you have the types full name and know its a reference where you reflect all dlls that are signed with the Microsoft key for the type name, if you find one its bcl, otherwise it probably is not.
public static string CodeElementAsTypeFullName(EnvDTE80.CodeElement2 element)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (element.Kind == vsCMElement.vsCMElementClass
|| element.Kind == vsCMElement.vsCMElementEnum
|| element.Kind == vsCMElement.vsCMElementStruct)
return element.FullName;
else
return ((dynamic)element).Type.AsFullName;
}
protected void FlattenElement(EnvDTE80.CodeElement2 element)
{
try
{
string varType = CodeElementAsTypeFullName(element);
switch (element.Kind)
{
case vsCMElement.vsCMElementVariable:
case vsCMElement.vsCMElementProperty:
{
EnvDTE80.CodeElement2 defined = null;
///this is API, basically a collection of all the files in the solution with all class/enum/stuct defs parsed out into collections.
foreach (SquishFile file in this.solutionFiles)
{
//next line goes through each solution file one by one to figure out if the file defines the class/enum/struct definition.
defined = file.ContainsCodeElement(varType);
if (defined != null)
break;
}
if (defined != null)
{
if (defined.Kind == vsCMElement.vsCMElementClass
|| defined.Kind == vsCMElement.vsCMElementStruct
|| defined.Kind == vsCMElement.vsCMElementEnum)
//THE ITEM IS DEFINED LOCALLY!
}else
//the item is a reference
}
}
}
public class SquishFile
{
public ConcurrentBag<CodeClass> ClassDefinitions = new ConcurrentBag<CodeClass>();
public ConcurrentBag<CodeEnum> EnumDefinitions = new ConcurrentBag<CodeEnum>();
public ConcurrentBag<CodeStruct> StructDefinitions = new ConcurrentBag<CodeStruct>();
protected ProjectItem _projectItem;
public ProjectItem ProjectItem { get { return _projectItem; } }
public SquishFile(ProjectItem projectItem)
{
if (projectItem.FileCodeModel == null)
throw new Exception("Cannot make a squish file out of a project item with no FileCodeModel!");
_projectItem = projectItem;
foreach (EnvDTE80.CodeElement2 ele in projectItem.FileCodeModel.CodeElements)
Discovery(ele);
}
public EnvDTE80.CodeElement2 ContainsCodeElement(string fullName)
{
foreach(EnvDTE80.CodeElement2 ele in ClassDefinitions)
if (ele.FullName.Equals(fullName))
return ele;
foreach (EnvDTE80.CodeElement2 ele in EnumDefinitions)
if (ele.FullName.Equals(fullName))
return ele;
foreach (EnvDTE80.CodeElement2 ele in StructDefinitions)
if (ele.FullName.Equals(fullName))
return ele;
return null;
}
protected void Discovery(EnvDTE80.CodeElement2 element)
{
if (element.IsCodeType && element.Kind == vsCMElement.vsCMElementClass)
this.ClassDefinitions.Add(element as EnvDTE80.CodeClass2);
else if (element.IsCodeType && element.Kind == vsCMElement.vsCMElementEnum)
this.EnumDefinitions.Add(element as EnvDTE.CodeEnum);
else if (element.IsCodeType && element.Kind == vsCMElement.vsCMElementStruct)
this.StructDefinitions.Add(element as EnvDTE80.CodeStruct2);
foreach (EnvDTE80.CodeElement2 ele in element.Children)
Discovery(ele);
}
}

Resharper - Go To Implementation listing reference twice

In one of my solutions, when I right click a symbol and choose "Go To Implementation" for an object defined in one of the other solution projects, it lists the reference twice and forces me to choose one.
Based on the icons, it appears that one of the items in the list represents the project, and the other represents a dll. It doesn't matter which one I click - it goes to the same source file.
I only have the library reference once in this particular project - it is referencing the project.
What would cause this to happen? Some sort of circular reference issue perhaps?
As far as I can tell, this can also happen if you have a solution with several projects, where a certain project is referenced as project and also as pure file by two other projects in the solution.
Another advice that I can give if something is broken with ReSharper, is to clear the cache.
I had this problem and I just fixed it.
First, try do a Clean Solution and then a Build.
In my case, one rogue Project in my solution was compiled using an older version of the .NET framework than the other Projects, so when Resharper added a reference to my other Projects for me, it must have added it as a dll reference instead of as a Project reference.
My fix was
Upgrade old Project to the same version of .NET framework as the other Projects
Remove references to other Projects from that old Project
Add references to the other Projects again (as Project references this time)
Clean solution
Build solution
Done.
I've found a couple different cases that cause this problem, and got so annoyed that I wrote a little console app to scan my solution and find the problems for me. Here it is for anyone who might find this useful. To run it pass it the path to your solution folder and it will print out the issues on the console. It's very "quick and dirty" but it found the issues for me.
class Program
{
static void Main(string[] args)
{
if (args != null && args.Any())
{
foreach (var s in args)
{
Console.WriteLine("Checking " + s);
DirectoryInfo dir = new DirectoryInfo(s);
var files = dir.GetFiles("*.csproj", SearchOption.AllDirectories);
var projects = files.Select(x => new Project(x)).ToList();
var grouped = projects.GroupBy(x => x.TargetFrameworkVersion);
if(grouped.Count()>1)
{
Console.WriteLine("Solution contains multiple versions of Target Frameworks, this may cause duplicate assemblies in R# cache");
foreach (var group in grouped)
{
Console.WriteLine(group.Key);
foreach (var project in group)
{
Console.WriteLine(project.AssemblyName);
}
}
}
//loop through for debugging
foreach (var project in projects)
{
foreach (var reference in project.References)
{
foreach (var checkProject in projects)
{
if (checkProject.AssemblyName == reference)
{
Console.WriteLine("Reference in" + project.FileName + " referencing " +
reference+" that should be a ProjectReference, this may cause duplicate entries in R# Cache");
}
}
}
}
}
Console.WriteLine("Complete");
Console.ReadLine();
}
else
{
Console.WriteLine("You must provide a path to scan for csproj files");
}
}
}
public class Project
{
public string FileName { get; set; }
public string AssemblyName { get; set; }
public string ProjectGuid { get; set; }
public string TargetFrameworkVersion { get; set; }
public IList<string> References { get; set; }
private FileInfo _file;
private XmlDocument _document;
private XmlNamespaceManager _namespaceManager;
public Project(FileInfo file)
{
_file = file;
FileName = _file.FullName;
_document = new XmlDocument();
_document.Load(_file.FullName);
_namespaceManager = new XmlNamespaceManager(_document.NameTable);
_namespaceManager.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
var projectGuidNode = _document.SelectSingleNode("//msbld:ProjectGuid", _namespaceManager);
ProjectGuid = projectGuidNode.InnerText;
var assemblyNameNode = _document.SelectSingleNode("//msbld:AssemblyName", _namespaceManager);
AssemblyName = assemblyNameNode.InnerText;
var targetFrameworkNode = _document.SelectSingleNode("//msbld:TargetFrameworkVersion", _namespaceManager);
TargetFrameworkVersion = targetFrameworkNode.InnerText;
References = new List<string>();
var referenceNodes = _document.SelectNodes("//msbld:Reference", _namespaceManager);
foreach (var node in referenceNodes)
{
var element = (XmlElement) node;
//file references
if (element.HasChildNodes)
{
foreach (var child in element.ChildNodes)
{
var childElement = (XmlElement)child;
if (childElement.Name == "HintPath")
{
var value = childElement.InnerText;
value = value.Substring(value.LastIndexOf("\\") + 1);
value = value.Replace(".dll", "");
References.Add(value);
}
}
}
//gac references
else
{
foreach (var attr in element.Attributes)
{
var attribute = (XmlAttribute)attr;
if (attribute.Name == "Include")
{
var value = attribute.Value;
string reference = value;
if (value.Contains(','))
{
reference = value.Substring(0, value.IndexOf(','));
}
References.Add(reference);
break;
}
}
}
}
}
}

copy list items from one list to another in sharepoint

In Sharepoint how can you copy a list item from one list to another list
eg copy from "List A" to "List B" (both are at the root of the site)
I want this copying to occur when a new list item is added to "List A"
I tried using the CopyTo() method of an SPListItem inside the ItemAdded event receiver but couldnt figure out the url to copy to.
Here is the code I use. Pass it a SPlistItem and the name of the destination list as seen in Sharepoint(Not the URL). The only restriction is that both list must be in the same site:
private SPListItem CopyItem(SPListItem sourceItem, string destinationListName) {
//Copy sourceItem to destinationList
SPList destinationList = sourceItem.Web.Lists[destinationListName];
SPListItem targetItem = destinationList.Items.Add();
foreach (SPField f in sourceItem.Fields) {
//Copy all except attachments.
if (!f.ReadOnlyField && f.InternalName != "Attachments"
&& null != sourceItem[f.InternalName])
{
targetItem[f.InternalName] = sourceItem[f.InternalName];
}
}
//Copy attachments
foreach (string fileName in sourceItem.Attachments) {
SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
byte[] imageData = file.OpenBinary();
targetItem.Attachments.Add(fileName, imageData);
}
return targetItem;
}
Indeed as Lars said, it can be tricky to move items and retain versions and correct userinfo. I have done similar things with that before so if you need some code examples, let me know through a comment and can supply you with some guidance.
The CopyTo method (if you decide to go with that) need an absolute Uri like:
http://host/site/web/list/filename.doc
So, if you are performing this in an event receiver you need to concatinate a string containing the elements needed. Something like (note that this can be done in other ways to):
string dest=
siteCollection.Url + "/" + site.Name + list.Name + item.File.Name;
Copying and moving files, items and folders in SharePoint can be tricky if you want to retain all metadata, timestamps, author info and version history. Take a look a CopyMove for SharePoint - it also has a Web Service API.
There's many tools on the market for copying a list item to another list (avepoint, metavis, etc.) but they are pretty expensive if you're planning to do this on only one list.
If you can do this manually once a week for example, look at the following tool : http://en.share-gate.com/sharepoint-tools/copy-move-sharepoint-list-items-with-metadata-and-version-history
Here is a powershell equivalent of Sylvian's that does allow for cross-site copy. His code could be modified similarly as well...
param([string]$sourceWebUrl, [string]$sourceListName, [string]$destWebUrl, [string]$destListName)
$sourceWeb = get-spweb $sourceWebUrl;
$sourceList = $sourceWeb.Lists[$sourceListName];
$destWeb = get-spweb $destWebUrl;
$destList = $destWeb.Lists[$destListName];
$sourceList.Items |%{
$destItem = $destList.Items.Add();
$sourceItem = $_;
$sourceItem.Fields |%{
$f = $_;
if($f.ReadOnlyField -eq $false -and $f.InternalName -ne "Attachments" -and $sourceItem[$f.InternalName] -ne $null){
$destItem[$f.InternalName] = $sourceItem[$f.InternalName];
}
}
$destItem.Update();
}
To use, copy and past to a file copy-listitems.ps1 and run using Sharpoint powerhsell commandline...
Make sure you call CopyTo(url) method on SPFile, not on SPListItem.
for example:
ItemUpdated(SPItemEventProperties properties)
{
//...
string url = properties.Web.Site.Url + "/" + properties.Web.Name + "Lists/ListName/" + properties.ListItem.File.Name;
//properties.ListItem.File.MoveTo(url);
properties.ListItem.File.CopyTo(url);
//...
}
private void CopyAttachmentsToList(SPListItem srcItem, SPListItem tgtItem)
{
try
{
//get source item attachments from the folder
SPFolder srcAttachmentsFolder =
srcItem.Web.Folders["Lists"].SubFolders[srcItem.ParentList.Title].SubFolders["Attachments"].SubFolders[srcItem.ID.ToString()];
//Add items to the target item
foreach (SPFile file in srcAttachmentsFolder.Files)
{
byte[] binFile = file.OpenBinary();
tgtItem.Update();
tgtItem.Attachments.AddNow(file.Name, binFile);
tgtItem.Update();
}
}
catch
{
//exception message goes here
}
finally
{
srcItem.Web.Dispose();
}
}
Don't forget to add this line, tgtItem.Update();, else you will get an err.
So, the lists have the exact same or similar columns? Either way, you could create a simple workflow that runs automatically when an item is created in "List A". Since the workflow in question is relatively simple, I'd recommend using SharePoint Designer (which is free) to create it, since you can easily match up the columns from the two lists. The walk through below should be able to help you get started.
Create a Workflow - SharePoint Designer
I had the same problem.
After experimenting a bit instead of
targetItem[f.InternalName] = sourceItem[f.InternalName];
I used:
targetItem[childField.Title] = sourceItem[parentField.Title];
How to copy field and save versions:
public static SPListItem CopyItem(SPListItem sourceItem, SPList destinationList)
{
SPListItem targetItem = destinationList.AddItem();
//loop over the soureitem, restore it
for (int i = sourceItem.Versions.Count - 1; i >= 0; i--)
{
//set the values into the archive
foreach (SPField sourceField in sourceItem.Fields)
{
SPListItemVersion version = sourceItem.Versions[i];
if ((!sourceField.ReadOnlyField) && (sourceField.InternalName != "Attachments"))
{
SetFields(targetItem, sourceField, version);
}
}
//update the archive item and
//loop over the the next version
targetItem.Update();
}
foreach (string fileName in sourceItem.Attachments)
{
SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
targetItem.Attachments.Add(fileName, file.OpenBinary());
}
targetItem.SystemUpdate();
return targetItem;
}
private static bool SetFields(SPListItem targetItem, SPField sourceField, SPListItemVersion version)
{
try
{
targetItem[sourceField.InternalName] = version.ListItem[sourceField.InternalName];
return true;
}
catch (System.ArgumentException)//field not filled
{
return false;
}
catch (SPException)//field not filled
{
return false;
}
}
Copy List Items from one SharePoint List or library to Another SharePoint list or library using c# server side code
//Itecollection is a collection of data from source list
public void CopyItemsFromOneListToAnotherList(SPListItemCollection itemCollection)
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
//Get destination list/library
//destListName - Destination list/library name
SPList destList = web.Lists.TryGetList(destListName);
foreach (SPListItem sourceItem in itemCollection)
{
//Add new Item to list
SPListItem destItem = destList.Items.Add();
foreach (SPField field in sourceItem.Fields)
{
if (!field.ReadOnlyField && !field.Hidden && field.InternalName != "Attachments")
{
if (destItem.Fields.ContainsField(field.InternalName))
{
//Copy item to destination library
destItem[field.InternalName] = sourceItem[field.InternalName];
}
}
}
//Update item in destination library or list
destItem.Update();
Console.WriteLine("Copied " + sourceItem["ID"] + "to destination list/library");
}
}
}
}

Categories

Resources