I was trying to read a C# source file and parse it using Resharper. I wanted to get the list of namespaces used in the file but I had an exception in this line.
ICSharpFile file = CSharpParserUtil.Parse(sCode);
Exception Details:
A first chance exception of type 'System.InvalidOperationException' occurred in
JetBrains.Platform.ReSharper.Shell.dll
The thread 0x1020 has exited with code 0 (0x0).
The thread 0x14c0 has exited with code 0 (0x0).
static void Main()
{
String sCode = File.ReadAllText(#"D:\ResharperTries\TestFile.cs");
try
{
ICSharpFile file = CSharpParserUtil.Parse(sCode);
IList<ICSharpNamespaceDeclaration> x = file.NamespaceDeclarations;
foreach (ICSharpNamespaceDeclaration value in x)
{
Console.WriteLine(value.ContainingNamespace.ShortName);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Need some help regarding this issue.
Thanks
It is possible to do this with the parsers that are part of DXCore and CodeRush.
In version 10.2 we released stand-alone parser libraries for C# and VB (part of the freely downloadable DXCore), so referencing the parser libraries will make it very easy to do what you’re looking for.
If you need help with this, simply email support#devexpress.com with any questions.
Here is sample of code, which can be used to fill ListBox with namespaces, used in some file:
string filePath = #"InsertFilePathHere";
CSharp30Parser parser = new CSharp30Parser();
SourceFile fileNode = parser.ParseFile(filePath) as SourceFile;
if (fileNode == null || fileNode.UsingList == null)
return;
lbUsedNamespaces.Items.Clear();
for (int i = 0; i < fileNode.UsingList.Count; i++)
{
string strUsing = fileNode.UsingList.GetKey(i) as String;
if (String.IsNullOrEmpty(strUsing))
continue;
lbUsedNamespaces.Items.Add(strUsing);
}
Currently, it's impossible to use ReSharper API without Visual Stdio as in your example with console app.
You need to write R# plugin and it will be loaded into R# in Visual Studio.
Take a look at http://resharperpowertoys.codeplex.com/
Related
i came from Microsoft course on edx, the template 10 is not working even after installing the NuGet Package, it gives me this error while compilling:
Error CS0103 The name 'PropertyChanged_ViewModel' does not exist in the current context.
and with double clicking on it, it takes me to the DetailPage.g.cs and the error is in this function :
public void UpdateChildListeners_ViewModel(global::solarizer.ViewModels.DetailPageViewModel obj)
{
if (obj != cache_ViewModel)
{
if (cache_ViewModel != null)
{
((global::System.ComponentModel.INotifyPropertyChanged)cache_ViewModel).PropertyChanged -= PropertyChanged_ViewModel;
cache_ViewModel = null;
}
if (obj != null)
{
cache_ViewModel = obj;
((global::System.ComponentModel.INotifyPropertyChanged)obj).PropertyChanged += PropertyChanged_ViewModel;
}
}
}
}
i deleted those if blocks and the error disappeared and the app ran but without the Hamburger Menu, any idea on how to fix this ??
Please consider updating the Template 10 Visual Studio Extension to at least version 1.7 and the NuGet package to at least 1.1.2. Then, create your project using the Hamburger template and let me know if it works.
takes me to the DetailPage.g.cs
Those .g.cs files are auto generated, and you shouldn't be modifying them. I think a clean build here would solve this issue, (especially after you've upgraded to a new version of T10)
we are developing a GUI Plug-In Framework using Catel.MVVM.
Single Plugins should be loaded dynamically using the "ServiceLocatorRegistration" Attribute.
Example:
[ServiceLocatorRegistration(typeof(IInitializable), ServiceLocatorRegistrationMode.SingletonInstantiateWhenRequired, "SamplePlugin")]
In our bootstrapper we load all Plugin assemblies into the default AppDomain:
Catel.Windows.Controls.MVVMProviders.Logic.UserControlLogic.DefaultSkipSearchingForInfoBarMessageControlValue = true;
Catel.Windows.Controls.MVVMProviders.Logic.UserControlLogic.DefaultCreateWarningAndErrorValidatorForViewModelValue = false;
IoCConfiguration.DefaultServiceLocator.AutoRegisterTypesViaAttributes = true;
IoCConfiguration.DefaultServiceLocator.CanResolveNonAbstractTypesWithoutRegistration = true;
foreach (
var file in
BaseDirectory.GetFiles("*.dll", SearchOption.AllDirectories)
.Where(f => IsNetAssembly(f.FullName))
.Where(f => !f.FullName.EndsWith("resources.dll"))
.AsParallel())
{
try
{
var asm = Assembly.ReflectionOnlyLoadFrom(file.FullName);
}
catch { }
}
Then we try to initialize them by calling
var initializables = ServiceLocator.Default.ResolveTypes();
foreach(var initializable in initializables)
initializable.Initialize();
But even if we have the plugin assemblies loaded in the AppDomain, we dont get all Classes with the ServiceLocatorRegistration attribute.
Is there any was to resolve all classes that have the example attribute set as above?
Thanks in advance!
The problem is probably because the assemblies containing the types that use the registration are not loaded into the AppDomain yet. There are a few things you can consider:
1) Use AppDomainExtensions.PreloadAssemblies
2) Use the type somehow (like Console.WriteLine(typeof(TypeFromAssembly).FullName))
I wouldn't recommend the second one because it goes against your plug-in architecture.
Resolved this issue myself. Mistake was probably the linevar asm = Assembly.ReflectionOnlyLoadFrom(file.FullName);
After replacing this line withAppDomain.CurrentDomain.LoadAssemblyIntoAppDomain(file.FullName); everything works as expected.
Thanks Geert for pointing to the right direction!
I have a very similar question to this SO post: TFS Build 2010 - Custom Binary Location and SharePoint WSP. There's no marked answer, but the only answer provided seemed to be the path to go.
I'm building several solutions and need the solutions and projects to be placed into their own folders. This lead to the build output change to the MSBuild call in the template that I'm using. I've been using this for sometime without any issues.
Recently a developer complained that the .wsp files were not being generated in our daily build. I looked into this and came across the fore mentioned SO post.
I followed the instructions and now have a new error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets (411): Method not found: 'Boolean Microsoft.VisualStudio.SharePoint.PathUtils.HasIllegalDeploymentPathCharacters(System.String)'.
I've looked at this line (411) in the targets file:
<PackageFiles LayoutPath="$(LayoutPath)%(EnumeratedFiles.Package)\" PackagePath="$(BasePackagePath)%(EnumeratedFiles.Package).$(PackageExtension)" />
The PackageFiles target is defined:
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="PackageFiles" />
I checked the GAC and didn't see it there so I added it. The TFS 2010 Build machine has Visual Studio 2010 and Sharepoint 2010 installed on it. I don't think I need to do anything other than changing this task:
<CreateSharePointProjectService Configuration="$(Configuration)"
Platform="$(Platform)"
ProjectFile="$(MSBuildProjectFile)"
ProjectReferences="#(SharePointProjectReference)"
OutDir="$(TargetDir)">
<Output PropertyName="ProjectService" TaskParameter="ProjectService" />
</CreateSharePointProjectService>
So that OutDir points to $(TargetDir).
Am I missing something as to why I'm getting this error where now a method cannot be found? This error is very exasperating as there is no information on the web regardless of the Google Fu employed!
Update
I've pulled apart the Microsoft.VisualStudio.SharePoint.dll that's on the build server. There is no PathUtils class or Namespace. Could I possibly have a bad version of this file? How can I detect this? Should I install the Sharepoint SDK on the build server. It already has Sharepoint 2010 installed on it.
Update 2
I checked the GAC. The Microsoft.VisualStudio.Sharepoint assembly shows up. However, I can only find it when I'm running the x64 version of the Visual Studio Command Prompt. When I run the normal one I get no assembly back. I'm assuming that is because the Sharepoint assembly is 64 bit. As far as I know TFS is setup to be 64bit. Is this going to be my problem?
The PathUtils.HasIllegalDeploymentPathCharacters method is present in version 10.0.40219.1 of Microsoft.VisualStudio.SharePoint.Designers.Models.dll and not in version 10.0.30319.1 (where I was seeing this error).
You are missing the assembly "Microsoft.VisualStudio.SharePoint.Designers.Models.dll"
The following assemblies must be copied to the GAC of the build system:
Microsoft.VisualStudio.SharePoint.Designers.Models.dll
Microsoft.VisualStudio.SharePoint.Designers.Models.Features.dll
Microsoft.VisualStudio.SharePoint.Designers.Models.Packages.dll
Microsoft.VisualStudio.SharePoint.dll
Please refer to the following article for more information about the required assemblies:
http://msdn.microsoft.com/en-us/ff622991.aspx
Regards,
Wes MacDonald
I found a solution to this issue. I don't think anyone has ever encountered this so I'm doubtful there will be a "correct" solution. I will post here what I have done to allow my .wsp files to build in the solution.
By all means, please post an answer (or comment on either this answer or the original question) if you think there is a better solution or if my manner of solving the problem is not up to par.
I will explain this in steps that I came up with to solve the problem.
First Step
The task PackageFiles was giving me the issue. This task was unable to find a method to invoke. Looking at the file C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets we can find this on line 56:
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="PackageFiles" />
I know knew where to look for the PackageFiles task/class.
Step Two
After knowing where to look I decompiled the task. I used Telerik's JustDecompile but I also came up with the same code in Reflector.
I could clearly see the line:
if (PathUtils.HasIllegalDeploymentPathCharacters(str2))
Which was erroring.
Step Three
I ended up deciding that the PathUtils.HasIllegalDeploymentPathCharacters method was just there as a safety check. I could recreate this task in my own custom library and then insert it into a custom targets file.
Here was the class I came up with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using Microsoft.VisualStudio.SharePoint.Tasks;
using Microsoft.Build.Framework;
namespace SharepointTaskLibrary
{
public class PackageFiles : BuildTask
{
[Required]
public ITaskItem LayoutPath
{
get;
set;
}
[Required]
public ITaskItem PackagePath
{
get;
set;
}
public PackageFiles()
{
}
protected override void OnCheckParameters()
{
if (this.LayoutPath == null)
{
throw new InvalidOperationException(Strings.GetString("LayoutPathNotSpecified"));
}
if (this.PackagePath == null)
{
throw new InvalidOperationException(Strings.GetString("PackagePathNotSpecified"));
}
}
protected override void OnExecute()
{
object[] objArray;
object[] objArray2;
object[] objArray3;
string metadata = this.LayoutPath.GetMetadata("FullPath");
string str1 = this.PackagePath.GetMetadata("FullPath");
Assembly sharepointTasksAss = Assembly.Load("Microsoft.VisualStudio.SharePoint.Tasks");
if (sharepointTasksAss != null)
base.Log.LogMessage(MessageImportance.High, "Found Tasks assembly!");
else
{
base.Log.LogError("Couldn't find the tasks assembly");
return;
}
if (!Directory.Exists(metadata))
{
base.Log.LogErrorFromResources("LayoutPathDoesNotExist", new object[] { metadata });
}
else
{
MethodInfo createCabMethod = GetStaticMethod(sharepointTasksAss, "Microsoft.VisualStudio.SharePoint.Tasks.Utilities.CabCreator", "CreateCabinet");
if (createCabMethod == null)
{
base.Log.LogError("the method could not be retrieved on type.");
return;
}
else
base.Log.LogMessage(MessageImportance.High, "Found method: " + createCabMethod.Name);
IEnumerable<string> strs = createCabMethod.Invoke(null, new object[] { metadata, str1 }) as IEnumerable<string>;
/*
* The following code would error in the original task.
*/
//foreach (string str2 in strs)
//{
// if (PathUtils.HasIllegalDeploymentPathCharacters(str2))
// {
// base.Log.LogWarningFromResources("FileNameContainsIllegalDeploymentPathCharacters", new object[] { str2 });
// }
//}
base.Log.LogMessage(MessageImportance.High, Strings.GetString("PackageCreatedSuccessfully"), new object[] { str1 });
}
Type codeMarkersType = null;
try
{
codeMarkersType = sharepointTasksAss.GetType("Microsoft.Internal.Performance.CodeMarkers", true);
}
catch (Exception e)
{
base.Log.LogErrorFromException(e, true);
}
if (codeMarkersType == null)
{
base.Log.LogError("Couldn't get the CodeMarkers class!");
return;
}
else
base.Log.LogMessage(MessageImportance.High, "Found the type: " + codeMarkersType.FullName);
/*
* This has yet to be added back in.
*/
//CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfSharePointPackageWspPackageEnd);
}
private MethodInfo GetStaticMethod(Assembly assembly, string typeName, string methodName)
{
Type type = null;
try
{
type = assembly.GetType(typeName, true);
}
catch (Exception e)
{
base.Log.LogErrorFromException(e, true);
}
if (type == null)
{
base.Log.LogError("Couldn't get the type: " + typeName);
return null;
}
else
base.Log.LogMessage(MessageImportance.High, "Found the type: " + type.FullName);
MethodInfo methodInfo = type.GetMethod(methodName, BindingFlags.Static);
if (methodInfo == null)
{
MethodInfo[] methods = type.GetMethods().Union(type.GetMethods(BindingFlags.Static)).ToArray();
base.Log.LogWarning(string.Format("Wasn't able to find {0} directly. Searching through the static {1} method(s) on {2}", methodName, methods.Length, type.FullName));
foreach (MethodInfo info in methods)
{
if (info.Name == methodName && methodInfo == null)
methodInfo = info;
}
if (methodInfo == null)
{
MemberInfo[] members =
type.GetMembers().Union(type.GetMembers(BindingFlags.Static | BindingFlags.NonPublic)).Union(type.GetMembers(BindingFlags.NonPublic)).ToArray();
base.Log.LogWarning(string.Format("Wasn't able to find {0}. Searching through the {1} members(s) on {2}", methodName, methods.Length, type.FullName));
MemberInfo createCabMember = null;
foreach (MemberInfo member in members)
{
if (member.Name == methodName)
{
createCabMember = member;
break;
}
else
base.Log.LogMessage(MessageImportance.High, "Found member: " + member.Name);
}
if (createCabMember == null)
base.Log.LogError("Still wasn't able to find " + methodName + " in the members!");
}
}
return methodInfo;
}
}
}
Since most of the classes and methods are marked as internal I had to make use reflection to get the type and method needed to actually build the cab/wsp files. This is done in the method: GetStaticMethod
Step Four
If you read over the decompiled code and my custom version of the class you'll notice the Strings class. It appears to be a resource accessor class. I decided that I'd just decompile that code as well and use it in my solution that makes the custom task instead of reflecting every time I wanted to access a string resource. This file ended up not being a straight decompile as it has a line this.GetType().Assembly it uses to get the current assembly containing the resources. This works fine within the original assembly but causes a problem in this custom assembly.
The original line:
internal Strings()
{
this.resources = new ResourceManager("Strings", this.GetType().Assembly);
}
This line had to be changed to:
Assembly sharepointTasksAss = Assembly.Load("Microsoft.VisualStudio.SharePoint.Tasks");
this.resources = new ResourceManager("Strings", sharepointTasksAss);
Step Five
After I had a custom build task that mimics the original I needed to now place that into the targets file. I then backed up the original targets file and made a custom one replacing the UsingTask section like this:
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="CreateSharePointProjectService" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumerateFiles" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumerateFeature" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumeratePackage" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="EnumerateProjectItem" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="LayoutFiles" />
<!-- The next task is a mimic of the one from the other assembly. I decompiled it and recreated it so it wouldn't error. LOL -->
<UsingTask AssemblyFile="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\SharepointTaskLibrary.dll" TaskName="PackageFiles" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="ResolveProjectMember" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="SetPackagingProperties" />
<UsingTask AssemblyFile="Microsoft.VisualStudio.SharePoint.Tasks.dll" TaskName="ValidatePackage" />
This made the task point to my DLL which contained the custom task. Specifically, this line:
<UsingTask AssemblyFile="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools\SharepointTaskLibrary.dll" TaskName="PackageFiles" />
FINALLY
I dropped the compiled DLL and edited targets file into the C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools directory (again backing up the original targets file).
This allowed me to build via TFS 2010 with custom outputs the wsp files generated by the SharePoint solutions!
I used this site as a resource:
http://blogs.like10.com/2011/08/04/team-build-2010-customized-output-directories-sharepoint-2010-wsps/
(I may have used another one or two sites as a resource, but I can find them in the browser history at the moment).
Your mileage may vary, but please let me know if anyone has this similar issue and is able to fix it in a non "hacked" way.
UPDATE
This whole issue seems to have came from the original TFS install I was administering. I recently moved our team to a proper TFS server (2012) with a completely fresh OS install and a new database server. Once I migrated the databases over and ran the upgrade tasks in TFS I was able to do some small build edits to make my build work with 2012 and I did not encounter this issue a second time. I believe that because the original 2010 TFS was on a converted dev machine it caused this problem.
I checked SO for the xmlpullparser exception but it's giving me others questions with Android and SOUP. I am using J2me and normal HTTPrequest to get my XML and I am using kXMl to parser the xml text. Below is the code that I am working on. And above it is more parsing code and they work perfectly.
if (parser.getName().equals("comments")) {
event = parser.next();
boolean flag = false;
if (parser.getName().equals("comment")) {
flag = true;
System.out.println("Flag is true");
}
while (flag) {
event = parser.next();
Questioncomments.addComponent(new Label(parser.nextText()));
event = parser.next();
System.out.println("Inside the While");
if (!parser.getName().equals("comment")) {
flag = false;
System.out.println("Flag is false");
}
}
Questioncomments.repaint();
}
XML I am sending this side - <comments><comment>Awesome Question #dulitha<idComment></idComment></comment></comments>
The error is -
org.xmlpull.v1.XmlPullParserException: precondition: START_TAG
(position:TEXT Awesome Question...#1:399 in
java.io.InputStreamReader#f828ed68)
at org.kxml2.io.KXmlParser.exception(+47)
at org.kxml2.io.KXmlParser.nextText(+14)
at
com.petmill.mobile.view.qanda.QuestionCanvas.setData(QuestionCanvas.java:189)
at
com.petmill.mobile.view.qanda.QuestionsList$5$1$1.actionPerformed(QuestionsList.java:119)
The error comes up at the line where I am trying to get the text - parser.nextText(). How can I parse the xml to get the data required... Thanks in advance.
It looks like you are not on the START_TAG event when you call parser.nextText(). Check that you are on a START_TAG event when you call parser.nextText() with the parser.getEventType(). I suspect that you have some whitespace between <comments> and <comment> tag and therefore your parser is not at the event that you expect it to be.
Perhaps you should also consider a safer approach for parsing this xml.
<comments>
<comment>Awesome Question #dulitha
<idComment></idComment>
</comment>
</comments>
this is not valid xml
I'm trying to test a multi-threaded IO class using MbUnit. My goal is to have the test fixture constructor execute 3 times, once for each row on the class. Then, for each instance, execute the tests multiple times on parallell threads.
However, Icarus blows up with an 'index out of range' on TaskRunner. I can't get the full stack, it spawns message boxes too fast.
What am I doing wrong, or is this a bug in MbUnit/Gallio?
using System;
using System.Collections.Generic;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using System.IO;
namespace ImageResizer.Plugins.DiskCache.Tests {
[TestFixture]
[Row(0,50,false)]
[Row(0,50,true)]
[Row(8000,100,true)]
public class CustomDiskCacheTest {
public CustomDiskCacheTest(int subfolders, int totalFiles, bool hashModifiedDate) {
char c = System.IO.Path.DirectorySeparatorChar;
string folder = System.IO.Path.GetTempPath().TrimEnd(c) + c + System.IO.Path.GetRandomFileName();
cache = new CustomDiskCache(folder,subfolders,hashModifiedDate);
this.quantity = totalFiles;
for (int i = 0; i < quantity;i++){
cache.GetCachedFile(i.ToString(),"test",delegate(Stream s){
s.WriteByte(32); //Just one space
},defaultDate, 10);
}
}
int quantity;
CustomDiskCache cache = null;
DateTime defaultDate = new DateTime(2011, 1, 1);
[ThreadedRepeat(150)]
[Test(Order=1)]
public void TestAccess() {
CacheResult r =
cache.GetCachedFile(new Random().Next(0, quantity).ToString(), "test",
delegate(Stream s) { Assert.Fail("No files have been modified, this should not execute"); }, defaultDate, 100);
Assert.IsTrue(System.IO.File.Exists(r.PhysicalPath));
Assert.IsTrue(r.Result == CacheQueryResult.Hit);
}
volatile int seed = 0;
[Test (Order=2)]
[ThreadedRepeat(20)]
public void TestUpdate() {
//try to get a unique date time value
DateTime newTime = DateTime.UtcNow.AddDays(seed++);
CacheResult r =
cache.GetCachedFile(new Random().Next(0, quantity).ToString(), "test",
delegate(Stream s) {
s.WriteByte(32); //Just one space
}, newTime, 100);
Assert.AreEqual<DateTime>(newTime, System.IO.File.GetLastWriteTimeUtc(r.PhysicalPath));
Assert.IsTrue(r.Result == CacheQueryResult.Miss);
}
[Test(Order=3)]
public void TestClear() {
System.IO.Directory.Delete(cache.PhysicalCachePath, true);
}
}
}
I wont answer direct question about bug but I think following steps will help find the error and not get lost in popping message boxes
decrease numbers of totalfiles ,
subfolders to much lower values to
see if error persists in 2 or even 1
file counts
your tests code isn't
super easy, as it should be,
write tests for tests
so you know they are running
correct, maybe those random nexts
are the problem, maybe something
else, tests should be easy.
figure out what test breaks the
system, your code contains 3 tests,
and constructor, comment two other
tests and see which one produces
error
your threaded repeat 150
looks pretty sick, maybe try smaller
number like 2 or 3 if error is basic
even 2 threads might break, if you
run 150 threads I can understand
your trouble with message boxes
add logging and try catch - catch
that index exception and log your
class state carefully, after
inspecting it I think youll see
problem much more clearly.
Right now you cant figure out the problem I think, you got too many variables , not to mention you didnt provide code for your Cache class which might contain some simple error that is causing it, before MBunit features even begin to show up.