Custom Activity override double-click and disable open Activity in detail - workflow-foundation-4

I'm using custom Activity and overriding OnMouseDoubleClick method. Everything works good but after double click on Activity is that self displayed in designer. It means that in designer is not shown whole workflow but only this Activity. How to disable self-opening Activity in custom designer.
Here is my code in ActivityDesigner.xaml.cs
/// <summary>
/// Raises the <see cref="E:System.Windows.Controls.Control.MouseDoubleClick"/> routed event.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
e.Handled = true;
this.OpenDialogOnDoubleClick();
}

To disable that behabiour you've to use ActivityDesignerOptionsAttribute, in particular its AllowDrillIn property.
Use it on your activity class:
[ActivityDesignerOptions(AllowDrillIn = false)]
public sealed class MyActivity : CodedActivity
{
/* ... */
}
Or if you're using IRegisterMetadata:
internal class Metadata : IRegisterMetadata
{
private AttributeTable attributes;
// Called by the designer to register any design-time metadata.
public void Register()
{
var builder = new AttributeTableBuilder();
builder.AddCustomAttributes(
typeof(MyActivity),
new ActivityDesignerOptionsAttribute{ AllowDrillIn = false });
MetadataStore.AddAttributeTable(builder.CreateTable());
}
}

Related

I have a very strange question with xamarin.form and libvlcsharp

When I create LibVLC and MediaPlayer objects in the constructor and play the video, there is only sound but no image. When I create LibVLC and MediaPlayer objects in the'Play' function, there are sounds and images. I don't want to create a MediaPlayer object every time the play function is called. what should I do?
using System;
using System.ComponentModel;
using System.Windows.Input;
using LibVLCSharp.Shared;
using static Xamarin.Essentials.Permissions;
namespace MediaElement
{
/// <summary>
/// Represents the main viewmodel.
/// </summary>
public class MainViewModel : INotifyPropertyChanged
{
/// <summary>
/// Property changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Initializes a new instance of <see cref="MainViewModel"/> class.
/// </summary>
public MainViewModel()
{
Core.Initialize();
LibVLC = new LibVLC();
MediaPlayer = new MediaPlayer(LibVLC) { EnableHardwareDecoding = true };
}
private LibVLC _libVLC;
/// <summary>
/// Gets the <see cref="LibVLCSharp.Shared.LibVLC"/> instance.
/// </summary>
public LibVLC LibVLC
{
get => _libVLC;
private set => Set(nameof(LibVLC), ref _libVLC, value);
}
private MediaPlayer _mediaPlayer;
/// <summary>
/// Gets the <see cref="LibVLCSharp.Shared.MediaPlayer"/> instance.
/// </summary>
public MediaPlayer MediaPlayer
{
get => _mediaPlayer;
private set => Set(nameof(MediaPlayer), ref _mediaPlayer, value);
}
/// <summary>
/// Initialize LibVLC and playback when page appears
/// </summary>
public void Play(String path)
{
MediaPlayer.Play(new LibVLCSharp.Shared.Media(LibVLC, new Uri(path)));
}
private void Set<T>(string propertyName, ref T field, T value)
{
if (field == null && value != null || field != null && !field.Equals(value))
{
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
You only sent half of your code, we don't know how you are using your VideoView control.
As a general rule of thumb:
How do you attach the MediaPlayer to your view?
Do you properly wait for the view to be visible before calling Play?
Have a look at the samples here and compare to see what you did wrong.

Upgrading Unity to 5.11.1

I'm trying do upgrade Unity from version 3.0.1304.1 to the latest, 5.11.1. Unsurprisingly, there are some issues (3.0.1304.1 is quite old). The code below accomplished two things:
Use a ContainerControlledLifetimeManager for all classes deriving from some base class X, without specifying that for every class derived from X.
Use the default constructor when resolving for all classes deriving from base class Y, without specifying that for every class derived from Y.
Unity documentation is scarce nowadays, and lacks examples. I've read the upgrade notes and regular documentation but I can't make this work with the new version.
So far I have:
Replaced IConstructorSelectorPolicy with ISelect<ConstructorInfo>
Replaced IBuilderContext with BuilderContext (or ref BuilderContext in the PreBuildUp function)
But what to do with the LifetimeManagerFactory? Should I derive IOCConstructorSelectorPolicy from ISelect<ConstructorInfo> and should IOCConstructorSelectorPolicy.SelectConstructor then be replaced by Select (as per the ISelect interface) and how to implement this Select function?
I know this is a very long shot, and I'll post this on the unity github as well (as a request for documentation of sorts), but hopefully there is someone who can give me some pointers.
/// <summary>
/// This class merely exists for readability: avoid having to write the class it derives from.
/// </summary>
public class IOCConfigLifetimeExtension : DefaultLifetimeManagerExtension<ContainerControlledLifetimeManager, X>
{}
/// <summary>
/// An IOC strategy to use a specific LifetimeManager (<typeparamref name="TLifetimeManager"/>) for subclasses of <typeparamref name="TBaseClass"/>.
/// </summary>
public class DefaultLifetimeManagerExtension<TLifetimeManager, TBaseClass> : UnityContainerExtension where TLifetimeManager : LifetimeManager, new()
{
protected override void Initialize()
{
var theFactory = new LifetimeManagerFactory(Context, typeof(TLifetimeManager));
Context.Strategies.Add(new DefaultLifetimeManagerStrategy(theFactory, TypePredicate), UnityBuildStage.TypeMapping);
}
private bool TypePredicate(Type type)
{
return typeof (TBaseClass).IsAssignableFrom(type);
}
}
public class DefaultLifetimeManagerStrategy : BuilderStrategy
{
public DefaultLifetimeManagerStrategy(LifetimeManagerFactory factory, Predicate<Type> typePredicate)
{
mFactory = factory;
mTypePredicate = typePredicate;
}
public override void PreBuildUp(IBuilderContext context)
{
if (context.Existing == null) {
var theLifetime = context.Policies.GetNoDefault<ILifetimePolicy>(context.BuildKey, false);
if (theLifetime == null && mTypePredicate(context.BuildKey.Type)) {
theLifetime = mFactory.CreateLifetimePolicy();
context.PersistentPolicies.Set(theLifetime, context.BuildKey);
}
}
}
private readonly LifetimeManagerFactory mFactory;
private readonly Predicate<Type> mTypePredicate;
}
/// <summary>
/// A Unity extension that prioritizes the default constructor for classes derived of Y when available, otherwise the default resolve method is used.
/// </summary>
public class IOCExtension : UnityContainerExtension
{
protected override void Initialize()
{
var theDefaultConstructorSelectorPolicy = Context.Policies.Get<IConstructorSelectorPolicy>(null);
Context.Policies.SetDefault<IConstructorSelectorPolicy>(new IOCConstructorSelectorPolicy(theDefaultConstructorSelectorPolicy));
}
public class IOCConstructorSelectorPolicy : IConstructorSelectorPolicy
{
public IOCConstructorSelectorPolicy(IConstructorSelectorPolicy defaultConstructorSelectorPolicy)
{
mDefaultConstructorSelectorPolicy = defaultConstructorSelectorPolicy;
}
public SelectedConstructor SelectConstructor(IBuilderContext context, IPolicyList resolverPolicyDestination)
{
Type theType = context.BuildKey.Type;
if (typeof(DataNode).IsAssignableFrom(theType)) {
ConstructorInfo theDefaultConstructorInfo = theType.GetConstructor(Type.EmptyTypes);
if (theDefaultConstructorInfo != null && theDefaultConstructorInfo.IsPublic) {
return new SelectedConstructor(theDefaultConstructorInfo);
}
}
return mDefaultConstructorSelectorPolicy.SelectConstructor(context, resolverPolicyDestination);
}
private readonly IConstructorSelectorPolicy mDefaultConstructorSelectorPolicy;
}
}

dynamic load recive activity wf

I'm trying to load and invoke activityes from custom activity as follows:
Imagine I have a xamlx like this:
--Sequence
|----- LoadActiviy
|--Initialize dictionary with input data of activitity
|----- Invoke
This works when activity NOT CONTAINS receive/send messages. But when i try with activity wich contains receive/send messages the result is a exception
WorkflowApplicationUnhandledExceptionEventArgs: Only registered bookmark scopes can be used for creating scoped bookmarks.
The code:
1-Load xaml: (Load activity)
public sealed class LoadActivity : CodeActivity<Activity>
{
#region Properties
/// <summary>
/// Gets or sets Path.
/// </summary>
[RequiredArgument]
public InArgument<string> Path { get; set; }
#endregion
#region Methods
/// <summary>
/// The execute method.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <returns>
/// An activity loaded from a file
/// </returns>
protected override Activity Execute(CodeActivityContext context)
{
return ActivityXamlServices.Load(this.Path.Get(context));
}
#endregion
}
2- Run activity:
public class SynchronousSynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
d(state);
}
}
public sealed class Invoke : CodeActivity
{
#region Properties
/// <summary>
/// Gets or sets Activity.
/// </summary>
/// <remarks>
/// The activity that will be invoked. Can be loaded from XAML.
/// </remarks>
[RequiredArgument]
public InArgument<Activity> Activity { get; set; }
public OutArgument<IDictionary<string, object>> Output { get; set; }
/// <summary>
/// Gets or sets Input.
/// </summary>
/// <remarks>
/// The input arguments you want to pass to the other workflow
/// </remarks>
public InArgument<IDictionary<string, object>> Input { get; set; }
#endregion
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
try
{
IDictionary<string,object> _input= this.Input.Get(context);
foreach (KeyValuePair<string,object> item in _input )
{
Debug.WriteLine(string.Format("{0} {1}", item.Key, item.Value));
}
// AutoResetEvent idleEvent = new AutoResetEvent(false);
WorkflowApplication app = new WorkflowApplication(this.Activity.Get(context),this.Input.Get(context));
app.SynchronizationContext = new SynchronousSynchronizationContext();
app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
{
// idleEvent.Set();
};
app.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
{
// Display the unhandled exception.
Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}",
e.InstanceId, e.UnhandledException.Message);
Console.WriteLine("ExceptionSource: {0} - {1}",
e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId);
// Instruct the runtime to terminate the workflow.
// Other choices are Abort and Cancel. Terminate
// is the default if no OnUnhandledException handler
// is present.
return UnhandledExceptionAction.Terminate;
};
app.Idle = e => Console.WriteLine("WorkflowApplication.Idle called");
Console.WriteLine("Before WorkflowApplication.Run()");
app.Run();
}
catch
{
throw;
}
}
}
Any ideas?
You can only use a Receive activity in a workflow hosted in a WorkflowServiceHost. Even if your main workflow is hosted in a WorkflowServiceHost the child workflow is hosted in a WorkflowApplication and can't contain a Receive activity because it isn't running as part of the WCF infrastructure.

ASP.NET MVC - Using Ninject bindings outside of controllers

I'm using ASP.NET MVC3, and Ninject. I've set up the standard code implementation in "AppStart_NinjectMVC3.cs" that sets up the bindings and adds a kernel to the DependencyResolver like this:
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepository>();
...
}
public static void Start() {
IKernel kernel = new StandardKernel();
RegisterServices(kernel);
DependencyResolver.SetResolver(new NinjectServiceLocator(kernel));
}
All is working well in my controllers - dependencies are being resolved fine.
I'd like to be able to use Ninject and these bindings outside of controllers, and outside of the MVC stack. For example, I have a bunch of regular aspx pages in which I'd like to use my ninject kernel, and some code hanging off global.asax too.
Can I re-use my Ninject kernel in these other places, or do I need to also register a kernel in my Global.asax appstart?
The current development release found on http://teamcity.codebetter.com provides support for side a side usage of ordinary aspx pages, mvc and wcf. You might want to have a look at this.
Be aware this is a development version and it is not tested very well. Nevertheless, I think it should be pretty much stable. But as it is work in progress it the interface can change. Also I won't give a lot of support before I have written the Ninject 2.4 preview blog about this change.
You need
Ninject
Ninject.Web.Common
Ninject.Web
Ninject.Web.MVC3
I've used the Ninject MVC Extension within my ASP.NET MVC application.
Here is the manner in which I've achieved what I think you're trying to accomplish.
Global.asax.cs:
public class MvcApplication : NinjectHttpApplication
{
/// <summary>
/// Overridden Ninject method that is called once the application has started and is initialized
/// </summary>
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
// Tell the MVC Framework to use our implementation of metadataprovider.
ModelMetadataProviders.Current = new XXX.myNamespace.MetadataProvider();
// Tell the MVC Framework to use our CartModelBinder class
ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());
}
/// <summary>
/// Establish a reference to our DIFactory object
/// <remarks>
/// This application currently uses Ninject for dependency injection.
/// </remarks>
/// </summary>
/// <returns></returns>
protected override IKernel CreateKernel()
{
return DIFactory.GetNinjectFactory();
}
// snip... additional global.asax.cs methods
}
DIFactory.cs:
/// <summary>
/// This class is used as a container for dependency injection throughout the entire application
/// </summary>
public class DIFactory
{
public static IKernel _kernel = null;
/// <summary>
/// Method used to create a single instance of Ninject's IKernel
/// </summary>
/// <returns>IKernel</returns>
public static IKernel GetNinjectFactory()
{
if (_kernel == null)
{
var modules = new INinjectModule[]
{
new ServiceModule()
};
_kernel = new StandardKernel(modules);
}
return _kernel;
}
/// <summary>
/// Method used as a service locator for the IConfiguration interface
/// </summary>
/// <returns></returns>
public static IConfiguration CreateConfigurationType()
{
return _kernel.Get<IConfiguration>();
}
// snip....additional public static methods for all other Interafaces necessary
}
ServiceModule.cs:
/// <summary>
/// Configures how abstract service types are mapped to concrete implementations
/// </summary>
internal class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<IConfiguration>().To<XXX.myNamespace.Configuration>();
// snip... all other bindings to interfaces
}
}
Use in other classes besides Controllers:
UserInteraction.cs:
public class UserInteraction : IUserInteraction
{
private IConfiguration configuration;
public bool SubmitFeedback(Feedback feedback)
{
try
{
this.configuration = DIFactory.CreateConfigurationType();
// snip additional logic...
}
catch(Exception ex)
{
// snip
}
}
}

Custom Authorize Attribute additional Param?

im looking for a way to customize my Authorize Attribute so that i can implement it correctly with my own MembershipProvider.
What i need is to have the IsInRoles(string role, int perm) for example, in other word, i want to have it replace with a new IsinRoles or maybe create another method to archive this result.
Is it possible? or i need to write a different authorize attribute?
Thank you very much for your concern...
PS: im working on ASP.net MVC, so i need to have the [Authorize] filter up and running.
I think you can just add a public property to your custom AuthorizeAttribute.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
/// <summary>
/// Add the allowed roles to this property.
/// </summary>
public YourCustomRoles RequiredRole;
public int YourCustomValue;
/// <summary>
/// Checks to see if the user is authenticated and has the
/// correct role to access a particular view.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
// Make sure the user is authenticated.
if (httpContext.User.Identity.IsAuthenticated == false) return false;
// Can use your properties if needed and do your checks
bool authorized = DoSomeCustomChecksHere();
return authorized;
}
}
Usage I think would be (haven't tried it though):
[CustomAuthorizeAttribute (RequiredRole=MyCustomRole.Role1 | MyCustomRole.Role2, YourCustomValue=1234)]

Resources