Get role list from Web.Config


var res = new List<string>();
var conf = WebConfigurationManager.GetSection("system.web/authorization");
if (conf != null)
{
    var sec = (AuthorizationSection)conf;
    foreach (AuthorizationRule r in sec.Rules)
    {
        if (r.Action == AuthorizationRuleAction.Allow)
        {
            var p = r.ElementInformation.Properties["roles"];
            if (p != null)
            {
                if (p.ValueOrigin != PropertyValueOrigin.Inherited)
                {
                    string val = p.Value.ToString();
                    if (!string.IsNullOrEmpty(val))
                    {
                        string[] roles = val.Split(',');
                        foreach (string roleStr in roles)
                        {
                            string roleVal = roleStr.Trim();
                            if (roleVal != string.Empty)
                            {
                                res.Add(roleVal);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
}

Workflow Tracking DB Monitor

A sample console application that lists workflows information from the WorkflowTracking database:

Workflow Tracking DB Monitor Project

Using SharpBITS to transfer (download) file

1. Add a reference to the SharpBITS.dll on your project (download from SharpBITS.NET).
2. Add multi-line TextBox named “output” to your form.
3. Add following piece of code to your form code:

public partial class BITStester : Form
{

BitsManager manager = null;
object jobTransferredSync = new object();
object jobFailedSync = new object();
const string fromURL = @"http://localhost/download/test.txt";
const string fileTo = @"c:/temp/test.txt";

private void BITStester_Load(object sender, EventArgs e)
{
	manager = new BitsManager();
	manager.OnJobTransferred += new EventHandler(OnJobTransferred);
	manager.OnJobError += new EventHandler(OnJobError);
	manager.EnumJobs(JobOwner.AllUsers);	

	FileInfo file = new FileInfo(fileTo);

	BitsJob job = manager.CreateJob(file.Name, JobType.Download);

	job.NotificationFlags = NotificationFlags.JobTransferred;

	// The default retry delay was 600 seconds (10 minutes).
	job.MinimumRetryDelay = 60; // 1 min
	job.Priority = JobPriority.High;
	job.Description = "Created by BITStester";
	job.AddFile(fromURL, fileTo);
	job.Resume();

	AddToOutput("File {0} added to BITS pool", file.Name);
}

private void OnJobTransferred(object sender, NotificationEventArgs e)
{
	lock (jobTransferredSync)
	{
		BitsJob job = e.Job;
		job.Complete();
		AddToOutputHelper(string.Format("File {0} downloaded", job.DisplayName));
	}
}

private void OnJobError(object sender, NotificationEventArgs e)
{
	lock (jobFailedSync)
	{
		BitsJob job = e.Job;
		string errorMessage = string.IsNullOrEmpty(job.Description) ? 
				"Error description not provided" : job.Error.Description;

		AddToOutputHelper(string.Format("File download {0} failed: {1}", 
				job.DisplayName, errorMessage));
		job.Cancel();
	}
}

#region Output

private delegate void UpdateOutputHandler(string line);

// To call also from another thread
private void AddToOutputHelper(string line)
{
	if (output.InvokeRequired)
	{
		output.Invoke(new UpdateOutputHandler(AddToOutput), line);
	}
	else
	{
		AddToOutput(line);
	}
}

private void AddToOutput(string line)
{
	output.AppendText(line + Environment.NewLine);
}

private void AddToOutput(string line, params object[] param)
{
	output.AppendText(string.Format(line, param) + Environment.NewLine);
}

#endregion Output
} // class

 

Useful links when using BITS technology:

Posted in BITS, C#. Tags: , , , , . Leave a Comment »

Remove Workflow Instance from WorkflowTracking & WorkflowPersistence

To remove from WorkflowTracking:

declare @guid uniqueidentifier
set @guid = 'd37ef09d-fd95-4550-aac7-7d467286f3f3';
declare @id bigint;

set @id =
	(select workflowinstanceinternalid from workflowinstance
	where workflowinstanceid = @guid)

delete from workflowinstance
	where workflowinstanceinternalid = @id

delete from workflowinstanceevent
	where workflowinstanceinternalid = @id

delete from userevent
	where workflowinstanceinternalid = @id

delete from activityinstance
	where workflowinstanceinternalid = @id

delete from activityexecutionstatusevent
	where workflowinstanceinternalid = @id

To remove from WorkflowPersistence:

declare @guid uniqueidentifier
set @guid = 'd37ef09d-fd95-4550-aac7-7d467286f3f3';

DELETE FROM [WorkflowPersistence].[dbo].[InstanceState]
      WHERE uidInstanceID = @guid;

Specify to Run Server Garbage Collection (gcServer)

To enable Garbage Collector to work in server mode put follwing section in config:

<runtime>
  <gcServer enabled="true" />
</runtime>

When to use:

  • On computers with more  than two cores.
  • You have multithreaded service not hosted in IIS.

Typical candidate: self-hosted WCF service.
This option improves service performance and consumes more memory.

For details see:

Encrupt/Protect Custom Configuration Section

Illustrates how to encrypt custom configuration section in the service OnStart event:

protected override void OnStart(string[] args)
{
	try
	{			    
		string sectionName = "SectionNameToSecure";
		
		Configuration config = 
				ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
		ConfigurationSection section = config.GetSection(sectionName);
		if (!section.SectionInformation.IsProtected)
		{
			section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
			section.SectionInformation.ForceSave = true;
			config.Save(ConfigurationSaveMode.Full);

			// Reset configuration object!
			ConfigurationManager.RefreshSection(sectionName);
		}                
	}
	catch (Exception ex)
	{
		// Do exception tracing here
		this.Stop();
	}
}