Create/Use Codefluent CodeDomSubProducer - dll

I'm attempting to create a CodeFluent SubProducer based on CodeFluent's document at: https://www.softfluent.com/documentation/CustomSubProducer_Topic.html
As the document describes, I've created a Visual Studio (2015) C# class library project named CodeDomSubProducer. Within this project I've added the three references for CodeFluent.Model.dll, CodeFluent.Model.Common.dll and CodeFluent.Producers.CodeDom.dll. I also added an interface, ICodeDomSubProducer, and a class, CodeDomSubProducer, with the code supplied in the document.
After compiling the program, I copied the CodeDomSubProducer.dll to %ProgramFiles(x86)%\SoftFluent\CodeFluent\Modeler.
I've altered my model's CFP file as described in the article.
When I attempt to build the model, the following error is presented:
CF6003: Type 'CodeDomSubProducer.CodeDomLightProducer, CodeDomSubProducer' is not a CodeDomSubProducer.
Any suggestions on how I can resolve this error would be greatly appreciated.
Thanks!
[1]: https://www.softfluent.com/documentation/CustomSubProducer_Topic.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeFluent.Producers.CodeDom;
using System.Collections;
using System.CodeDom;
namespace CodeDomSubProducer
{
interface ICodeDomSubProducer
{
// Methods
void Initialize(CodeDomBaseProducer baseProducer, SubProducer subProducer, IDictionary context);
void Produce(IDictionary context, CodeCompileUnit unit);
void Terminate(IDictionary context);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;
using System.CodeDom;
using CodeFluent.Model;
using CodeFluent.Producers.CodeDom;
//using CodeFluent.Runtime.Utilities;
namespace CodeDomSubProducer
{
public class CodeDomLightProducer : ICodeDomSubProducer
{protected static string namespaceUri = "http://www.softfluent.com/codefluent/producers.lightProducer/2005/1";
public virtual void Initialize(CodeDomBaseProducer baseProducer, CodeFluent.Producers.CodeDom.SubProducer subProducer, IDictionary context)
{baseProducer.CodeDomProduction += new CodeDomProductionEventHandler(OnCodeDomProduction); }
public virtual void Produce(IDictionary context, CodeCompileUnit unit) {}
public virtual void Terminate(IDictionary context) {}
private void OnCodeDomProduction(object sender, CodeDomProductionEventArgs e)
{if (e.EventType == CodeDomProductionEventType.UnitsProducing)
{if (e.Argument == null)
return;
foreach (CodeCompileUnit codeCompileUnit in (CodeCompileUnit[])e.Argument)
{foreach (CodeNamespace codeNamespace in codeCompileUnit.Namespaces)
{foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types)
{BaseType baseType = UserData.GetBaseType(codeTypeDeclaration);
XmlElement xmlElement = (baseType is Set) ? ((Set)baseType).ItemEntity.Element : baseType.Element;
List<string> methodsToHide = new List<string>();
foreach (XmlAttribute xmlAttribute in xmlElement.Attributes)
{if (xmlAttribute.NamespaceURI == namespaceUri)
{if (xmlAttribute.LocalName == "exclude")
{foreach (string method in xmlAttribute.Value.Split('|'))
methodsToHide.Add(method);
} } }
for (int i = 0; i < codeTypeDeclaration.Members.Count; i++)
{if (codeTypeDeclaration.Members[i] is CodeMemberMethod)
{CodeMemberMethod method = codeTypeDeclaration.Members[i] as CodeMemberMethod;
if (methodsToHide.Contains(method.Name))
{if (((method.Attributes & MemberAttributes.Public) == 0) &&
((method.Attributes & MemberAttributes.Static) == 0))
{codeTypeDeclaration.Members.Remove(method);
i--;
} } } } } } } } } }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<cf:project defaultNamespace="TwoCollections"
xmlns:cf="http://www.softfluent.com/codefluent/2005/1"
xmlns:cfx="http://www.softfluent.com/codefluent/modeler/2008/1"
xmlns:cfps="http://www.softfluent.com/codefluent/producers.sqlserver/2005/1"
xmlns:cfom="http://www.softfluent.com/codefluent/producers.model/2005/1"
xmlns:cflp="http://www.softfluent.com/codefluent/producers.lightProducer/2005/1"
defaultTargetFramework="4.6.1"
defaultConnectionString="Database=TwoCollections;Server=\\.\pipe\MSSQL$SQLEXPRESS\sql\query"
createDefaultMethodForms="true"
createDefaultApplication="false"
createDefaultHints="false">
<cf:import path="Default.Surface.cfp" />
<cf:producer name="SQL Server Producer" typeName="CodeFluent.Producers.SqlServer.SqlServerProducer, CodeFluent.Producers.SqlServer">
<cf:configuration
connectionString="Database=TwoCollections;Server=\\.\pipe\MSSQL$SQLEXPRESS\sql\query"
produceViews="true" targetVersion="Sql2008"
targetDirectory="..\TwoCollectionsC.Persistence"
cfx:targetProjectLayout="UpdateItems, DontRemove"
cfx:targetProject="..\TwoCollectionsC.Persistence\TwoCollectionsC.Persistence.sqlproj" />
</cf:producer>
<cf:producer name="BOM Producer" typeName="CodeFluent.Producers.CodeDom.CodeDomProducer, CodeFluent.Producers.CodeDom, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1bb6d7cccf1045ec">
<cf:configuration
compileWithVisualStudio="true"
targetDirectory="..\TwoCollections"
cfx:targetProject="..\TwoCollections\TwoCollections.csproj"
codeDomProviderTypeName="CSharp"
cfx:targetProjectLayout="Update" >
<!-- Custom Sub-Producer -->
<subProducer typeName="CodeDomSubProducer.CodeDomLightProducer, CodeDomSubProducer" />
</cf:configuration>
</cf:producer>
<cf:entity name="SpaceX" cflp:exclude="Input|Save|Delete" namespace="TwoCollections" categoryPath="/TwoCollections">
<cf:property name="GUIDx" key="true" />
<cf:property name="DataX1" />
<cf:property name="DataX2" />
<cf:property name="ParentX" cascadeSave="After" cascadeDelete="Before" typeName="{0}.SpaceYCollection" relationPropertyName="ChildY" />
</cf:entity>
<cf:entity name="SpaceY" namespace="TwoCollections" categoryPath="/TwoCollections">
<cf:property name="GUIDy" key="true" />
<cf:property name="DataY1" />
<cf:property name="DataY2" />
<cf:property name="ChildY" typeName="{0}.SpaceX" relationPropertyName="ParentX" />
</cf:entity>
</cf:project>

A CodeDomSubProducer must implement the CodeFluent.Producers.CodeDom.ICodeDomSubProducer interface from CodeFluent.Producers.CodeDom.dll. In your code, you redeclare the interface. So, the CodeDomLightProducer doesn't implement the expected interface, but another one that has the same methods and the same name.
To make it work you must remove the following code from your producer assembly:
namespace CodeDomSubProducer
{
interface ICodeDomSubProducer
{
// Methods
void Initialize(CodeDomBaseProducer baseProducer, SubProducer subProducer, IDictionary context);
void Produce(IDictionary context, CodeCompileUnit unit);
void Terminate(IDictionary context);
}
}

Great thanks to meziantou, based on his spotting the conditional statement error, and one more tweak, the OnCodeDomProduction function's condition should be <> (!=0) and OrElse (||):
if (((method.Attributes & MemberAttributes.Public) != 0) ||
((method.Attributes & MemberAttributes.Static) != 0))
This removes the three methods of insert, save, and delete.
The resulting library, however, only complains about not having a save and a delete method.

Related

How to create multiple custom renderer with same type?

I wanted to create a page render with ContentPage type. I created so in android and it is working but in IOS there has custom page renderer with same type (ContentPage). It can be removed as this was from nuget package and working on different context.
Here is my code
[assembly: ExportRenderer(typeof(ContentPage), typeof(CustomPageRenderer))]
namespace AlwinInvoiceGenerator.IOS
{
using CoreGraphics;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
public class CustomPageRenderer : PageRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (Element == null || !(Element is ContentPage basePage) || basePage.BindingContext == null ||
!(basePage.BindingContext is BaseViewModel baseViewModel))
{
return;
}
SetCustomBackButton(baseViewModel);
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
OverrideUserInterfaceStyle = UIUserInterfaceStyle.Light;
}
private void SetCustomBackButton(BaseViewModel baseViewModel)
{
var fakeButton = new UIButton {Frame = new CGRect(0, 0, 50, 40), BackgroundColor = UIColor.Clear};
fakeButton.TouchDown += (sender, e) =>
{
baseViewModel.OnBackButtonClicked();
};
NavigationController?.NavigationBar.AddSubview(fakeButton);
}
}
It seems it not registering and that is why not calling.
I have another page renderer that is register in assembly
[assembly: ExportRenderer(typeof(ContentPage), typeof(IOSToolbarExtensions.iOS.Renderers.IOSToolbarExtensionsContentPageRenderer), Priority = short.MaxValue)]
If I removed this line then above code is working but not two in the same time.
Please help
Same type seems not working for multiple renderer.
I have created sub type of my custom renderer and override the methods which needed to. It is working well

Using custom property types in Azure Tables with ASP.NET 5 DNX Core

Azure Table Storage does not support many property types (List<>, TimeSpan, etc).
There are solutions like Lucifure Stash and Lokad.Cloud, but they are not compiling for DNX Core 5.0.
Is there a way to add support for custom property types in Azure Tables with DNX Core?
One solution is to use reflection to iterate through all the “custom” properties of the entity and serialize them to JSON strings.
We can override TableEntity’s ReadEntity and WriteEntity methods to hook de-/serialization:
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public abstract class CustomEntity : TableEntity
{
public override IDictionary<string, EntityProperty> WriteEntity (OperationContext operationContext)
{
var properties = base.WriteEntity(operationContext);
// Iterating through the properties of the entity
foreach (var property in GetType().GetProperties().Where(property =>
// Excluding props explicitly marked to ignore serialization
!property.GetCustomAttributes<IgnorePropertyAttribute>(true).Any() &&
// Excluding already serialized props
!properties.ContainsKey(property.Name) &&
// Excluding internal TableEntity props
typeof(TableEntity).GetProperties().All(p => p.Name != property.Name)))
{
var value = property.GetValue(this);
if (value != null)
// Serializing property to JSON
properties.Add(property.Name, new EntityProperty(JsonConvert.SerializeObject(value)));
}
return properties;
}
public override void ReadEntity (IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
base.ReadEntity(properties, operationContext);
// Iterating through the properties of the entity
foreach (var property in GetType().GetProperties().Where(property =>
// Excluding props explicitly marked to ignore serialization
!property.GetCustomAttributes<IgnorePropertyAttribute>(true).Any() &&
// Excluding props which were not originally serialized
properties.ContainsKey(property.Name) &&
// Excluding props with target type of string (they are natively supported)
property.PropertyType != typeof(string) &&
// Excluding non-string table fields (this will filter-out
// all the remaining natively supported props like byte, DateTime, etc)
properties[property.Name].PropertyType == EdmType.String))
{
// Checking if property contains a valid JSON
var jToken = TryParseJson(properties[property.Name].StringValue);
if (jToken != null)
{
// Constructing method for deserialization
var toObjectMethod = jToken.GetType().GetMethod("ToObject", new[] { typeof(Type) });
// Invoking the method with the target property type; eg, jToken.ToObject(CustomType)
var value = toObjectMethod.Invoke(jToken, new object[] { property.PropertyType });
property.SetValue(this, value);
}
}
}
private static JToken TryParseJson (string s)
{
try { return JToken.Parse(s); }
catch (JsonReaderException) { return null; }
}
}
Now, if we inherit our table entities from the CustomEntity class, we can freely use properties with any types supported by Json.NET.

getting error when I create extension method for UrlHelper

I'm using this class for having clean URLs in my application :
public static class UrlEncoder
{
public static string ToFriendlyUrl(this UrlHelper helper,
string urlToEncode)
{
urlToEncode = (urlToEncode ?? "").Trim().ToLower();
StringBuilder url = new StringBuilder();
foreach (char ch in urlToEncode)
{
switch (ch)
{
case ' ':
url.Append('-');
break;
case '&':
url.Append("and");
break;
case '\'':
break;
default:
if ((ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'z'))
{
url.Append(ch);
}
else
{
url.Append('-');
}
break;
}
}
return url.ToString();
}
}
and I'm using above class with this way :
#item.Name
but I'm getting this error and extension not working:
Compiler Error Message: CS1061: 'System.Web.Mvc.UrlHelper' does not contain a definition for 'ToFriendlyUrl' and no extension method 'ToFriendlyUrl' accepting a first argument of type 'System.Web.Mvc.UrlHelper' could be found (are you missing a using directive or an assembly reference?)
I've added these using directive :
using System;
using System.Text;
using System.Web.Mvc;
I tried this method but still I have same error :
#UrlHelper.ToFriendlyUrl(item.Name)
and used this directive using System.Web.Http.Routing; instead using System.Web.Mvc;but still I have same error.
it seems that UrlHelper belongs to another assembly , I don't know.
any Ideas?
Thanks in your Advise
You also need to include the namespace of UrlEncoder class in your view:
#using Mynamespace
I encountered a similar error when calling a UrlHelper extension method from my view, but the solution was slightly different so I'll share it in case it helps someone else:
In my extension class, I needed to replace using System.Web.Http.Routing; with using System.Web.Mvc;
Both resolve UrlHelper, but the MVC reference is what you need to use it in your view.
Pass the interface(IUrlHelper) instead of class name(UrlHelper) as first parameter.
public static class UrlEncoder
{
public static string ToFriendlyUrl(this **IUrlHelper** helper,
string urlToEncode)
{
//your code
}
}

Some rows are collapsed in DataGrid, I am getting issue in KeyBoard navigation

I am using DataGrid, run time i make visible collapse some rows.
Suppose my 4th row's visibility is collapse, and my focus is on 3rd row, when i try to move on 5th row with the help of Down-Arrow key, it is not working. Same way if my focus on 5th row and want to move on 3rd row with Up-Arrow key, it is also not working.
Now, what should i do?
This is actually a bug in .Net, there is a bug report here.
One workaround is to use Attached behavior to handle the up and down selection. The following example requires the IsSynchronizedWithCurrentItem to be set to true for the DataGrid.
Note! make sure you change the while condition to the appropriate way to determine if the item is collapsed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
namespace DataGridGroupingTest
{
class DataGridKeyboardNavigationAttachedBehavior
{
public static readonly DependencyProperty
KeyboardKey
= DependencyProperty.RegisterAttached(
"IsKeyboardNavigationEnabled",
typeof(bool),
typeof(DataGridKeyboardNavigationAttachedBehavior),
new PropertyMetadata(
false,
OnIsKeyboardNavigationEnabledChanged));
public static bool GetIsKeyboardNavigationEnabled(DependencyObject depObj)
{
return (bool)depObj.GetValue(KeyboardKey);
}
public static void SetIsKeyboardNavigationEnabled(DependencyObject depObj, bool value)
{
depObj.SetValue(KeyboardKey, value);
}
private static void OnIsKeyboardNavigationEnabledChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = depObj as DataGrid;
if (dataGrid != null)
{
dataGrid.PreviewKeyDown += dataGrid_PreviewKeyDown;
dataGrid.IsSynchronizedWithCurrentItem = true;
}
}
static void dataGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
if (dataGrid != null && dataGrid.CurrentCell != null)
{
if (e.Key == System.Windows.Input.Key.Down || e.Key == System.Windows.Input.Key.Up)
{
ICollectionView view = CollectionViewSource.GetDefaultView(dataGrid.Items);
int loopCount = 0;
do
{
if (e.Key == System.Windows.Input.Key.Down)
{
view.MoveCurrentToNext();
if (view.IsCurrentAfterLast)
{
view.MoveCurrentToFirst();
loopCount++;
}
}
if (e.Key == System.Windows.Input.Key.Up)
{
view.MoveCurrentToPrevious();
if (view.IsCurrentBeforeFirst)
{
view.MoveCurrentToLast();
loopCount++;
}
}
} while (((Person)view.CurrentItem).Boss != null && !((Person)view.CurrentItem).Boss.IsExpanded && loopCount < 2);
// We have to move the cell selection aswell.
dataGrid.CurrentCell = new DataGridCellInfo(view.CurrentItem, dataGrid.CurrentCell.Column);
e.Handled = true;
return;
}
}
}
}
}

AppFabric: Could not contact the cache service

Update: I have now implemented this properly. For more information see my blog post about it.
I'm trying to use AppFabric with NHibernate as my second level cache provider but I'm getting the following error: ErrorCode:Initialization: Could not contact the cache service. Contact administrator and refer to product help documentation for possible reasons.
I presume that the problem is with my configuration in web.config:
<section name="dcacheClient"
type="Microsoft.ApplicationServer.Caching.DataCacheClientSection, Microsoft.ApplicationServer.Caching.Core"
allowLocation="true"
allowDefinition="Everywhere"/>
...
<dcacheClient deployment="routing" localCache="False">
<localCache isEnabled="false" sync="TimeoutBased" ttlValue="300" />
<hosts>
<host name="localhost" cachePort="22233" cacheHostName="AppFabricCachingService" />
</hosts>
</dcacheClient>
I've downloaded the NHibernate.Caches source code to try and discover where the problem lies and the exception is being thrown in the VelocityClient constructor when the GetCache method is called:
public VelocityClient(string regionName, IDictionary<string, string> properties)
{
region = regionName.GetHashCode().ToString(); //because the region name length is limited
var cacheCluster = new CacheFactory();
cache = cacheCluster.GetCache(CacheName);
try
{
cache.CreateRegion(region, true);
}
catch (CacheException) {}
}
If I add a watch to the cacheCluster variable, I can find a _servers private variable which has one System.Data.Caching.EndpointID which has the MyURI property set to net.tcp://localhost:22234/AppFabricCachingServive which I presume has come from the configuration in web.config.
If you don't know the exact cause of the problem but have some ideas on how to go about troubleshooting this problem, that would be much appreciated as well.
Additional Info
I get the following results from the command, Get-CacheHostConfig -HostName tn-staylor-02 -CachePort 22233:
HostName : tn-staylor-02
ClusterPort : 22234
CachePort : 22233
ArbitrationPort : 22235
ReplicationPort : 22236
Size : 3001 MB
ServiceName : AppFabricCachingService
HighWatermark : 90%
LowWatermark : 70%
IsLeadHost : True
So I think the values I've got configured in web.config are OK.
Googling this problem and investigating how to set up AppFabric in the first place, I have come across two slightly different ways of how to configure the cache in web.config. The way I have described above and the way Hanselman has it in his AppFabric blog post
I actually started with it like this however, I got the following error which is how I came to have it configured how I have it now:
ErrorCode:"dcacheClient" tag not specified in the application configuration file. Specify valid tag in configuration file.
Full stack trace of the exception that gets thrown in VelocityClient:
System.Data.Caching.CacheException occurred
Message="ErrorCode:\"dcacheClient\" tag not specified in the application configuration file. Specify valid tag in configuration file."
Source="CacheBaseLibrary"
ErrorCode="ERRCMC0004"
StackTrace:
at System.Data.Caching.ClientConfigFile.ThrowException(String errorCode, String param)
at System.Data.Caching.ClientConfigReader.GetDeployementMode()
at System.Data.Caching.ClientConfigurationManager.InitializeDepMode(ClientConfigReader cfr)
at System.Data.Caching.ClientConfigurationManager.Initialize(String path)
at System.Data.Caching.ClientConfigurationManager..ctor()
at System.Data.Caching.CacheFactory.InitCacheFactory()
at System.Data.Caching.CacheFactory.GetCache(String cacheName)
at NHibernate.Caches.Velocity.VelocityClient..ctor(String regionName, IDictionary`2 properties) in C:\Source\Projects\NHibernate.contrib\trunk\src\NHibernate.Caches\Velocity\NHibernate.Caches.Velocity\VelocityClient.cs:line 67
InnerException:
EDIT: Added output from get-cachehost as requested by #PhilPursglove
Output from get-cachehost:
HostName : CachePort Service Name Service Status Version Info
-------------------- ------------ -------------- ------------
tn-staylor-02:22233 AppFabricCachingService UP 1 [1,1][1,1]
SOLUTION: #PhilPursglove was spot on. The NHibernate velocity provider was using old dll's so upgrading them and making a few code changes resolved my problems. I thought I would include my complete solution here.
Downloaded the NHibernate.contrib source from the SVN repository at https://nhcontrib.svn.sourceforge.net/svnroot/nhcontrib/trunk
Opened up the NHibernate.Caches.Everything solution and removed the references to the old velocity dll's from the NHibernate.Caches.Velocity project.
Added references to the App Fabric dll's which were installed when I installed App Fabric. This isn't the normal case of adding a reference to an assembly in the GAC, but this article describes how to do it.
Adding the new references meant that the VelocityClient class no longer compiled. With a little bit of help from this I came up with the version of VelocityClient.cs below.
I added a reference to the new version of NHibernate.Caches.Velocity to my project, made the changes below to my configuration and everything worked.
VelocityClient.cs
using System;
using System.Collections.Generic;
using Microsoft.ApplicationServer.Caching;
using log4net;
using NHibernate.Cache;
using CacheException = Microsoft.ApplicationServer.Caching.DataCacheException;
using CacheFactory = Microsoft.ApplicationServer.Caching.DataCacheFactory;
namespace NHibernate.Caches.Velocity
{
public class VelocityClient : ICache
{
private const string CacheName = "nhibernate";
private static readonly ILog log;
private readonly DataCache cache;
private readonly string region;
private Dictionary<string, DataCacheLockHandle> locks = new Dictionary<string, DataCacheLockHandle>();
static VelocityClient()
{
log = LogManager.GetLogger(typeof (VelocityClient));
}
public VelocityClient() : this("nhibernate", null) {}
public VelocityClient(string regionName) : this(regionName, null) {}
public VelocityClient(string regionName, IDictionary<string, string> properties)
{
region = regionName.GetHashCode().ToString(); //because the region name length is limited
var cacheCluster = new CacheFactory();
cache = cacheCluster.GetCache(CacheName);
try
{
cache.CreateRegion(region);
}
catch (CacheException) {}
}
#region ICache Members
public object Get(object key)
{
if (key == null)
{
return null;
}
if (log.IsDebugEnabled)
{
log.DebugFormat("fetching object {0} from the cache", key);
}
DataCacheItemVersion version = null;
return cache.Get(key.ToString(), out version, region);
}
public void Put(object key, object value)
{
if (key == null)
{
throw new ArgumentNullException("key", "null key not allowed");
}
if (value == null)
{
throw new ArgumentNullException("value", "null value not allowed");
}
if (log.IsDebugEnabled)
{
log.DebugFormat("setting value for item {0}", key);
}
cache.Put(key.ToString(), value, region);
}
public void Remove(object key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (log.IsDebugEnabled)
{
log.DebugFormat("removing item {0}", key);
}
if (Get(key.ToString()) != null)
{
cache.Remove(region, key.ToString());
}
}
public void Clear()
{
cache.ClearRegion(region);
}
public void Destroy()
{
Clear();
}
public void Lock(object key)
{
DataCacheLockHandle lockHandle = null;
if (Get(key.ToString()) != null)
{
try
{
cache.GetAndLock(key.ToString(), TimeSpan.FromMilliseconds(Timeout), out lockHandle, region);
locks.Add(key.ToString(), lockHandle);
}
catch (CacheException) {}
}
}
public void Unlock(object key)
{
DataCacheLockHandle lockHandle = null;
if (Get(key.ToString()) != null)
{
try
{
if (locks.ContainsKey(key.ToString()))
{
cache.Unlock(key.ToString(), locks[key.ToString()], region);
locks.Remove(key.ToString());
}
}
catch (CacheException) {}
}
}
public long NextTimestamp()
{
return Timestamper.Next();
}
public int Timeout
{
get { return Timestamper.OneMs * 60000; } // 60 seconds
}
public string RegionName
{
get { return region; }
}
#endregion
}
}
NHibernate.config:
...
<property name="cache.provider_class">NHibernate.Caches.Velocity.VelocityProvider, NHibernate.Caches.Velocity</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
...
web.config
...
<section name="dataCacheClient"
type="Microsoft.ApplicationServer.Caching.DataCacheClientSection, Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
allowLocation="true"
allowDefinition="Everywhere"/>
...
<dataCacheClient>
<!-- cache host(s) -->
<hosts>
<host
name="localhost"
cachePort="22233"/>
</hosts>
</dataCacheClient>
...
I didn't make any further changes to my App Fabric configuration or anything.
I think there are two possible culprits here:
In your web.config under the hosts element, you're listing localhost - I'd try swapping that out for the actual server name tn-staylor-02
That exception stack trace refers to CacheBaseLibrary - I don't know a great deal (read: anything!) about NHibernate but I would hazard a guess that that cache might not be built with the release version of AppFabric - CacheBaseLibrary was an assembly that appeared in the CTPs and betas but I didn't think it was used in the RTM version. Note that in the section element for dcacheclient, it refers to the Microsoft.ApplicationServer.Caching.Core assembly.