WF4 Ready Instances - workflow-foundation-4

How can I find out what items in the database are ready to be ran. In other words, I want to query the persistence tables to identify what items have the lock that expired. I can't seem to find any fields that would show this.

I've never worked it out either.
I've used workflow.Load and caught the exception; which is nasty but worked.

On an WorkflowApplication instance, you can use the LoadRunnableInstance method which automatically loads the next available workflow in the instance store whose lock has expired.
AutoResetEvent sync = new AutoResetEvent(false);
Workflow1 myWorkflow = new Workflow1();
SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore("<my connection string>");
WorkflowApplication wfApp = new WorkflowApplication(myWorkflow);
wfApp.InstanceStore = instanceStore;
wfApp.Completed += (eventArgs) => sync.Set();
wfApp.LoadRunnableInstance();
wfApp.Run();
sync.WaitOne();

Related

Need to setup SqlDependency per-user

System Scope
I have a database with a lot of users (over 50,000). At any time there may be 100-200 people logged in and actively using the system. The system is ASP.NET MVC 4, with Sql Server 2008 backend. For data access we are using Dapper.
Requirements
I am trying to build a notification component that has the following attributes:
When a new record is created in the [dbo.Assignment] table (with OwnerId = [Currently logged in user]), I need to update the Cache inside of an asp.net application.
I don't want to receive any notifications for users who are not actively online, as this would be a massive waste of resources)
Specific Questions:
Should I be using SqlDependency, SqlCacheDependency, or SqlNotification?
Assuming that we are using SqlDependency, how would I remove the Dependency.OnChange handler when user has logged out.
Any code samples would be much appreciated, as this has consumed the whole part of my day trying to figure it out.
Here is the current code
public IList<Notification> GetNotifications(string userName)
{
Cache o = HttpContext.Current.Cache;
if (o["Notifications_" + userName] == null)
{
var notifications = new List<Notification>();
using (var cn = new SqlConnection(getSQLString()))
{
using (var cmd = cn.CreateCommand())
{
var parameter = new SqlParameter("Employee_Cd", SqlDbType.Char, 30) { Value = userName };
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Notifications.Assignments";
cmd.Parameters.Add(parameter);
cmd.Notification = null;
var dependency = new SqlCacheDependency(cmd);
cn.Open();
using (var dr = cmd.ExecuteReader())
{
// this is where you build your cache
while (dr.Read())
{
var obj = new Notification();
obj.Name = dr["Name"].ToString();
notifications.Add(obj);
}
dr.Close();
}
HttpContext.Current.Cache.Insert("Notifications_" + userName,
notifications,
dependency,
DateTime.Now.AddDays(1D),
Cache.NoSlidingExpiration);
}
}
}
return (List<Notification>) o["Notifications_" + userName];
}
Note: I am not experienced with using SqlDependencies, as I have never really needed to use them until today. It's very possible that I am overlooking something important.
I didn’t really use any of these techniques but here are some alternatives that you can create yourself that will do the job just as good.
If you need to update cache every time new record is inserted into dbo.Assignment table why not create OnInserted event in your data access layer that will notify the cache object to refresh?
Another thing you can to is to create INSERT trigger in Assignemt table and another table that can look like this dbo.Cache (LastUpdate datetime). Trigger will insert value into Cache table and your application cache can ping this table like every X mins or X seconds to see if cache update is required.
If you need to refresh the cache immediately after record is inserted triggers might be an overkill because you’d have to ping Cache table probably every second but if you have 200 online users at a time that probably won’t make much of a difference in DB performance.
There is a lot of work if you want to implement these for a lot of tables but since this is only one table this might turn out to be faster way than implementing built in cache mechanisms.

Publishing failing in final stage of workflow

Our final automatic activity is publishing component to live target. We have below code written in Edit script.
' Script for Automatic Activity Content Manager Workflow
Set oTDSE = CreateObject("TDS.TDSE")
Call oTDSE.Initialize
Set oWorkItem = CurrentWorkItem.GetItem(3)
sDestinationServer = "tcm:0-18-65538"
Set oComp = oTDSE.GetObject(oWorkItem.ID, 3)
Call oComp.Publish(sDestinationServer, True, True, True)
FinishActivity "Automatic Activity ""Process Complete"" Finished"
set oWorkItem = Nothing
set oComp = Nothing
set oTDSE = Nothing
This code is executing successfully but when we check publishing queue component is getting failed with error The item tcm:34-20615-16-v0 does not exist.
Same code is working fine when we are publishing the component to staging in earlier activity.
The problem is that while in the script you are publishing dynamic version (-v0) of component. As publishing is asynchronous operation, item is not published straightaway, but publish transaction is created (which is linking to dynamic version).
After this, your script is done and item get checked-in. Now, publisher is starting with processing your publish transaction and discovers that there's no dynamic version anymore, hence your exception.
When publish activity is not last, publisher has enough time to get dynamic version of an item.
Workaround can be to wait for publish transaction to complete in your automatic activity, or do something with OnCheckIn event
Yes this is frequent one I faced at clients place. Especially when your last activity in workflow is automatic and Publish to Live.
Simplest way I did is:
First FinishActivity in automatic code
Then Publish workflow=false.
PublishCoreServiceClient.FinishActivity(activityInstance.Id, finishData, publishoptions);
}
//Now Publish
ComponentData component = (ComponentData)PublishCoreServiceClient.Read(componentid, publishoptions);
if (GetConfigurationValues(component, PublishCoreServiceClient))
{
PublishInstructionData publishInstructionData = new PublishInstructionData();
publishInstructionData.MaximumNumberOfRenderFailures = 100;
publishInstructionData.RollbackOnFailure = true;
ResolveInstructionData resolveInstructionData = new ResolveInstructionData();
resolveInstructionData.IncludeWorkflow = false;
resolveInstructionData.IncludeChildPublications = true;
resolveInstructionData.IncludeComponentLinks = true;
publishInstructionData.ResolveInstruction = resolveInstructionData;
RenderInstructionData renderInstructionData = new RenderInstructionData();
publishInstructionData.RenderInstruction = renderInstructionData;
List<string> ItemToPublish = new List<string>();
ItemToPublish.Add(component.Id);
if (!String.IsNullOrEmpty(Utilities.LIVE_URI))
{
PublicationTargetData pubtarget = (PublicationTargetData)PublishCoreServiceClient.Read(Utilities.LIVE_URI, publishoptions);
List<string> target = new List<string>();
target.Add(pubtarget.Id);
PublishCoreServiceClient.Publish(ItemToPublish.ToArray(), publishInstructionData, target.ToArray(), PublishPriority.Normal, publishoptions);
Logger.Debug("ElapsedMilliseconds Publish [" + _watch.ElapsedMilliseconds + " ms]");
}
Issue is resolved after setting activateWorkflow parameter of Publish method to False.
We had the same error and we have solved it by sending the component to publish with a few seconds delay:
Call oComp.Publish("tcm:0-1-65538", False, False, True, dateAdd("s",10,Now))

The underlying provider failed on Open

I made 3 Ajax processes to run the below code at the same time.
but one of the processes throw exception that message says "The underlying provider failed on Open."
try{
orderRepository orderRepo = new orderRepository(); // get context (Mysql)
var result = (from x in orderRepo.orders
where x.orderid == orderno
select new {x.tracking, x.status, x.charged }).SingleOrDefault();
charged = result.charged;
}catch(Exception e){
log.Error(e.Message); // The underlying provider failed on Open.
}
And, I run the 1 Ajax call that failed before, then It passes through.
It happen to 1 of 3 (Ajax) process, sometimes, 2 of 5 process.
I guess it because all process try to using Database same time. but I couldn't find the solution.
This is my connection string,
<add name="EFMysqlContext" connectionString="server=10.0.0.10;User Id=root;pwd=xxxx;Persist Security Info=True;database=shop_db" providerName="Mysql.Data.MySqlClient" />
Anybody know the solution or something I can try, please advise me.
Thanks
It sounds like a problem because of concurrent connection with SQL Server using same username. Have you tried destroying/disposing the repository(or connection) object after using it?
Give it a try:
try{
using( orderRepository orderRepo = new orderRepository()) // get context (Mysql)
{
var result = (from x in orderRepo.orders
where x.orderid == orderno
select new {x.tracking, x.status, x.charged }).SingleOrDefault();
charged = result.charged;
} // orderRepo object automatically gets disposed here
catch(Exception e){
log.Error(e.Message); // The underlying provider failed on Open.
} }
Not sure if it matters, but your provider name is Mysql.Data.MySqlClient and not MySql.Data.MySqlClient (if it is case-sensitive, this could be the cause).

Newly Created Session doesn't retain session contents

The system I am working on does not use standard ASP.NET Auth/ Membership facilities for logging users in/ out. Therefore after logging the user in I want to issue a new Session ID to the user in order to prevent Session trapping/ Hijacking. The problem i have is that although I have been able to successfully create a new session with a new ID and copy the various components to the newly created session eg. session["value"]. By the end of the code excerpt below the newly created session is the current HTTPContext's session, and has the session values that were copied accross. However after performing a Response.Redirect the new session is in action, but none of the session["values"] have persisted across the two requests. As you can see from the code below i've tried adding the values to a number of collections to avail.
Any help would be amazing!! Thanks in advance
bool IsAdded = false;
bool IsRedirect = false;
HttpSessionState state = HttpContext.Current.Session;
SessionIDManager manager = new SessionIDManager();
HttpStaticObjectsCollection staticObjects = SessionStateUtility.GetSessionStaticObjects(HttpContext.Current);
SessionStateItemCollection items = new SessionStateItemCollection();
foreach (string item in HttpContext.Current.Session.Contents)
{
var a = HttpContext.Current.Session.Contents[item];
items[item] = a;
}
HttpSessionStateContainer newSession = new HttpSessionStateContainer(
manager.CreateSessionID(HttpContext.Current),
items,
staticObjects,
state.Timeout,
true,
state.CookieMode,
state.Mode,
state.IsReadOnly);
foreach (string item in HttpContext.Current.Session.Contents)
{
var a = HttpContext.Current.Session.Contents[item];
newSession.Add(item,a);
}
SessionStateUtility.RemoveHttpSessionStateFromContext(HttpContext.Current);
SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, newSession);
manager.RemoveSessionID(HttpContext.Current);
manager.SaveSessionID(HttpContext.Current, newSession.SessionID, out IsRedirect, out IsAdded);
return newSession.SessionID;
Maybe I'm missing something here but won't this work:
Session["mysession"] = mySessionObject;
Basically it appears it's not possible since you can only add session variables once there has been one round trip to the client to create the corresponding session cookie. Therefore I had to create the new new session (with new ID) so that by the time I came to adding session variables, the client cookie had the appropriate session id: annoying since this in reality is issuing the new session ID before the user is authenticated.
Interestingly, it seems a little strange that issuing a new Session ID is exactly what the standard asp.net authentication/ membership functionality does but is able to maintain session variables, and yet doing it manually it doesn't....are there some methods for this that are not being exposed to us mere developers maybe....

What hinders NetStream.onPeerConnect from being triggered?

I'm using Adobe Stratus (now renamed to Cirrus) to build a p2p application. Inside the application, I used NetStream.onPeerConnect callback function and expected it to be triggered every time when a peer is connected. However, it always failed with my friend A while strangely friend B managed to have the function called without any problem.
I was wondering what could be the cause to this issue?
Here are how the code pieces look like.
First of all, create a NetConnection.
netConnection = new NetConnection();
netConnection.addEventListener(NetStatusEvent.NET_STATUS, netConnectionHandler);
netConnection.connect(SERVER_ADDRESS+DEVELOPER_KEY);
Secondly, create NetStream upon NetConnection successfully connected.
private function netConnectionHandler(event:NetStatusEvent):void{
switch (event.info.code){
case "NetConnection.Connect.Success":
sendStream = new NetStream(netConnection, NetStream.DIRECT_CONNECTIONS);
sendStream.addEventListener(NetStatusEvent.NET_STATUS, netStreamHandler);
var sendObj:Object = new Object();
sendObj.onPeerConnect = function(subscriber:NetStream) : Boolean {
trace("[onPeerConnect] far id: " + subscriber.farID);
return true;
}
sendStream.client = sendObj;
sendStream.publish("file");
......
Thirdly, here's how I build the connection between two peers
receivedStream = new NetStream(netConnection, farId);
receivedStream.client = this;
receivedStream.addEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
receivedStream.play("file");
Please help enlighten me. Thanks!
It turns out my friend A is behind a symmetric NAT. I'm thinking to setup a TURN server for us to build a successful connection.

Resources