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.
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)
I'm working with the revit api, and one of its problems is that it locks the .dll once the command's run. You have to exit revit before the command can be rebuilt, very time consuming.
After some research, I came across this post on GitHub, that streams the command .dll into memory, thus hiding it from Revit. Letting you rebuild the VS project as much as you like.
The AutoReload Class impliments the revit IExteneralCommand Class which is the link into the Revit Program.
But the AutoReload class hides the actual source DLL from revit. So revit can't lock the DLL and lets one rebuilt the source file.
Only problem is I cant figure out how to implement it, and have revit execute the command. I guess my C# general knowledge is still too limited.
I created an entry in the RevitAddin.addin manifest that points to the AutoReload Method command, but nothing happens.
I've tried to follow all the comments in the posted code, but nothing seems to work; and no luck finding a contact for the developer.
Found at: https://gist.github.com/6084730.git
using System;
namespace Mine
{
// helper class
public class PluginData
{
public DateTime _creation_time;
public Autodesk.Revit.UI.IExternalCommand _instance;
public PluginData(Autodesk.Revit.UI.IExternalCommand instance)
{
_instance = instance;
}
}
//
// Base class for auto-reloading external commands that reside in other dll's
// (that Revit never knows about, and therefore cannot lock)
//
public class AutoReload : Autodesk.Revit.UI.IExternalCommand
{
// keep a static dictionary of loaded modules (so the data persists between calls to Execute)
static System.Collections.Generic.Dictionary<string, PluginData> _dictionary;
String _path; // to the dll
String _class_full_name;
public AutoReload(String path, String class_full_name)
{
if (_dictionary == null)
{
_dictionary = new System.Collections.Generic.Dictionary<string, PluginData>();
}
if (!_dictionary.ContainsKey(class_full_name))
{
PluginData data = new PluginData(null);
_dictionary.Add(class_full_name, data);
}
_path = path;
_class_full_name = class_full_name;
}
public Autodesk.Revit.UI.Result Execute(
Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message,
Autodesk.Revit.DB.ElementSet elements)
{
PluginData data = _dictionary[_class_full_name];
DateTime creation_time = new System.IO.FileInfo(_path).LastWriteTime;
if (creation_time.CompareTo(data._creation_time) > 0)
{
// dll file has been modified, or this is the first time we execute this command.
data._creation_time = creation_time;
byte[] assembly_bytes = System.IO.File.ReadAllBytes(_path);
System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(assembly_bytes);
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass && type.FullName == _class_full_name)
{
data._instance = Activator.CreateInstance(type) as Autodesk.Revit.UI.IExternalCommand;
break;
}
}
}
// now actually call the command
return data._instance.Execute(commandData, ref message, elements);
}
}
//
// Derive a class from AutoReload for every auto-reloadable command. Hardcode the path
// to the dll and the full name of the IExternalCommand class in the constructor of the base class.
//
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
public class AutoReloadExample : AutoReload
{
public AutoReloadExample()
: base("C:\\revit2014plugins\\ExampleCommand.dll", "Mine.ExampleCommand")
{
}
}
}
There is an easier approach: Add-in Manager
Go to Revit Developer Center and download the Revit SDK, unzip/install it, the check at \Revit 2016 SDK\Add-In Manager folder. With this tool you can load/reload DLLs without having to modify your code.
There is also some additional information at this blog post.
this is how you can use the above code:
Create a new VS class project; name it anything (eg. AutoLoad)
Copy&Paste the above code in-between the namespace region
reference revitapi.dll & revitapiui.dll
Scroll down to AutoReloadExample class and replace the path to point
your dll
Replace "Mine.ExampleCommand" with your plugins namespace.mainclass
Build the solution
Create an .addin manifest to point this new loader (eg.
AutoLoad.dll)
your .addin should include "FullClassName" AutoLoad.AutoReloadExample
This method uses reflection to create an instance of your plugin and prevent Revit to lock your dll file! You can add more of your commands just by adding new classes like AutoReloadExample and point them with seperate .addin files.
Cheers
Following the example of the following KB article we have implemented the AssemblyResolve event in order to point .Net to the correct folder to load assemblies from: http://support.microsoft.com/kb/837908
This is our current implementation:
public static class AssemblyLoader
{
/// <summary>
/// A custom AssemblyResolver that will search for missing assemblies in the root and subfolders of the executing assembly
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <returns></returns>
public static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string assemblyPath = string.Empty;
string assemblyFileName = string.Empty;
try
{
// This handler is called only when the common language runtime tries to bind to the assembly and fails.
string rootProbingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
// Loop through the referenced assembly names.
assemblyFileName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
// Search for the filename in the root and subfolders of the rootProbingPath
string[] matchingAssemblies = Directory.GetFiles(rootProbingPath, assemblyFileName, SearchOption.AllDirectories);
// If a match is found, awesomeness was achieved!
if (matchingAssemblies.Length > 0)
assemblyPath = matchingAssemblies[0];
// Throw a clear exception when the assembly could not be found.
if (string.IsNullOrEmpty(assemblyPath))
throw new FileNotFoundException(string.Format("AssemblyLoader: Could not find assembly '{0}' in '{1}' or its subfolders.", assemblyFileName, rootProbingPath));
Console.WriteLine(string.Format("[" + DateTime.Now.ToString() + "] AssemblyLoader: Assembly '{0}' found at '{1}'", assemblyFileName, assemblyPath));
// Load the assembly from the specified path.
return Assembly.LoadFrom(assemblyPath, AppDomain.CurrentDomain.Evidence);
}
catch (Exception ex)
{
throw new Exception(string.Format("[" + DateTime.Now.ToString() + "] The assemblyloader could not load the assembly '{0}' from path '{1}': " + ex.Message, assemblyFileName, assemblyPath), ex);
}
}
}
We use this in all of our batch procedures which often run in parallel and using mostly the same assemblies.
Periodically a batch will crash leaving the following trail:
[26/04/2013 12:35:01] AssemblyLoader: Assembly
'COMPANY.DistributieOrderFacade.dll' found at
'C:\COMPANY_Batch\MDS\Executables\MDS\FACADE\COMPANY.DistributieOrderFacade.dll'
[26/04/2013 12:35:01] AssemblyLoader: Assembly
'COMPANY.DOCUMENTCENTERDOCS.dll' found at
'C:\COMPANY_Batch\MDS\Executables\MDS\CLIENT\COMPANY.DOCUMENTCENTERDOCS.dll'
26/04/2013 12:35:01: Create COMPANYDocument...in
queue:\rug.adroot\dfsroot\mds\Data\queue_new\ 26/04/2013 12:35:01
Could not load file or assembly 'COMPANY.DistributieOrderBRDA,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its
dependencies. General Exception (Exception from HRESULT: 0x80131500)
The assembly in the error is indeed located in one of the folders which the AssemblyLoader searches. And if I run the procedure again, it does succeed.
I've tried to see if the dll's are getting locked by using this assembly loader in two console apps and access the same dll's at the same time, but this did not seem to be a problem.
I should also mention that this is just a log from one of the batches. There are others, and it's rarely the same assembly that is not being loaded.
I don't know where to start looking for a solution next.
It was due to an update script that updated the dll's before each batch was running. When two batches were running at the same and there was a dll that needed updating, locks were occurring on the dll's which was causing the problem.
We've removed this script for a week now and haven't seen any problems yet. So our conclusion is that this was the problem.
I created an unit test case for displaying error messages in a different language than English but it doesn't seem to work and I don't know what I am missing.
Here are the details:
I am using attributes.
app.config (I excluded the nhibernate cfg):
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
<section name="nhv-configuration" type="NHibernate.Validator.Cfg.ConfigurationSectionHandler, NHibernate.Validator" />
</configSections>
<nhv-configuration xmlns="urn:nhv-configuration-1.0">
<property name='apply_to_ddl'>false</property>
<property name='autoregister_listeners'>true</property>
<property name='default_validator_mode'>OverrideExternalWithAttribute</property>
</nhv-configuration>
Initialization of the validator:
private void InitializeValidator()
{
var provider = new NHibernateSharedEngineProvider();
provider.GetEngine().Configure();
NHibernate.Validator.Cfg.Environment.SharedEngineProvider = provider;
}
The test function (EntityDescription is my entity class and the Repository follows the sharp architecture design with Repository classes):
[Test]
public void TestNhValidationSp()
{
CultureInfo ci = CultureInfo.GetCultureInfo("fr");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
TestNhValidation();
}
private void TestNhValidation()
{
IEntityDescriptionRepository repository = GetObject<IEntityDescriptionRepository>();
ISession session = NHibernateSession.Current;
EntityDescription entityDescription=
(from kpad in session.Query<EntityDescription>()
select kpad).FirstOrDefault();
entityDescription.Title = "012345678901234567890123456789012345678901234567890123456789";
try
{
repository.SaveOrUpdateWithTransaction(entityDescription);
Assert.IsTrue(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Assert.IsTrue(ex is InvalidStateException);
InvalidStateException isex = (InvalidStateException) ex;
foreach (InvalidValue invalidValue in isex.GetInvalidValues())
{
Console.WriteLine("PropertyName={0} Message={1}", invalidValue.PropertyName, invalidValue.Message);
}
}
}
Setting
entityDescription.Title = "012345678901234567890123456789012345678901234567890123456789";
will trigger a validation error because the title can have up to 50 chars.
The problem is that the message always comes in English. Any thoughts?
One thing I want to add is that my test project has a dependency on the SharpArchitecture project (1.9.5). I wonder if somehow this screws up my nhibernate validator cnfiguration.
Found this message: NHibernate Validation Localization with S#arp Architecture that reports a similar problem.
I think it was my own fault due to a dll versions mix-up.
SharpArchitecture 1.9.5 uses NHV 1.2.0 which in turn has been compiled with NH 2.1.0.
My test above used NHV 1.3.1 (I wanted to upgrade to the latest version of NHV) and it didn't work, the messages didn't show in the right language.
I recompiled NHV 1.2.0 to use NH 3.1.0, I switched to NHV 1.2.0 and now the test works fine.
I have been trying to follow this example (download the source code from a link on the site or here, but I keep running into an error that seems embedded in the example.
My procedure has been as follows (after installing the AppFabric SDK and other dependencies):
Download the source
Create a Service Namespace on the AppFabric.
Import the project into a new Windows Azure project with one Worker Role, make sure that it all compiles and that the default Worker Role Run() method starts and functions.
Configure the method GetInterRoleCommunicationEndpoint in InterRoleCommunicationExtension.cs with the ServiceNameSpace and IssuerSecret from my AppFabric Service Namespace (IssuerName and ServicePath stay default). This is a hard-wiring of my own parameters.
Copy/paste the initialization logic from the "SampleWorkerRole.cs" file in the demo into the OnStart() method of my project's Worker Role
Comment-out references to Tracemanager.* as the demo code does not have the Tracemanager methods implemented and they're not crucial for this test to work. There are about 7-10 of these references (just do a Find -> "Tracemanager" in entire solution).
Build successfully.
Run on local Compute Emulator.
When I run this test, during the initialization of a new InterRoleCommunicationExtension (the first piece of the inter-role communication infrastructure to be initialized, this.interRoleCommunicator = new InterRoleCommunicationExtension();), an error is raised: "Value cannot be null. Parameter name: contractType."
Drilling into this a bit, I follow the execution down to the following method in ServiceBusHostFactory.cs (one of the files from the sample):public static Type GetServiceContract(Type serviceType)
{
Guard.ArgumentNotNull(serviceType, "serviceType");
Type[] serviceInterfaces = serviceType.GetInterfaces();
if (serviceInterfaces != null && serviceInterfaces.Length > 0)
{
foreach (Type serviceInterface in serviceInterfaces)
{
ServiceContractAttribute serviceContractAttr = FrameworkUtility.GetDeclarativeAttribute<ServiceContractAttribute>(serviceInterface);
if (serviceContractAttr != null)
{
return serviceInterface;
}
}
}
return null;
}
The serviceType parameter's Name property is "IInterRoleCommunicationServiceContract," which is one of the classes of the demo, and which extends IObservable. The call to serviceType.GetInterfaces() returns the "System.IObservable`1" interface, which is then passed into FrameworkUtility.GetDeclarativeAttribute(serviceInterface);, which has the following code:
public static IList GetDeclarativeAttributes(Type type) where T : class
{
Guard.ArgumentNotNull(type, "type");
object[] customAttributes = type.GetCustomAttributes(typeof(T), true);
IList<T> attributes = new List<T>();
if (customAttributes != null && customAttributes.Length > 0)
{
foreach (object customAttr in customAttributes)
{
if (customAttr.GetType() == typeof(T))
{
attributes.Add(customAttr as T);
}
}
}
else
{
Type[] interfaces = type.GetInterfaces();
if (interfaces != null && interfaces.Length > 0)
{
foreach (object[] customAttrs in interfaces.Select(iface => iface.GetCustomAttributes(typeof(T), false)))
{
if (customAttrs != null && customAttrs.Length > 0)
{
foreach (object customAttr in customAttrs)
{
attributes.Add(customAttr as T);
}
}
}
}
}
return attributes;
}</code><br>
It is here that the issue arises. After not finding any customAttributes on the "IObservable1" type, it calls type.GetInterfaces(), expecting a return. Even though type is "System.IObservable1," this method returns an empty array, which causes the function to return null and the exception with the above message to be raised.
I am extremely interested in getting this scenario working, as I think the Publish/Subscribe messaging paradigm is the perfect solution for my application. Has anyone been able to get this demo code (from the AppFabric CAT Team itself!) working, or can spot my error? Thank you for your help.
Answered in the original blog post (see link below). Please advise if you are still experiencing problems. We are committed to supporting our samples on best effort basis.
http://blogs.msdn.com/b/appfabriccat/archive/2010/09/30/implementing-reliable-inter-role-communication-using-windows-azure-appfabric-service-bus-observer-pattern-amp-parallel-linq.aspx#comments