How to get the absolute root folder path of a ASP .NET website / MVC website.

 

The following code result in my case to rootFolderPath = "C:\inetpub\wwwroot\MvcApplication1".

Uri uri = new System.Uri(Assembly.GetAssembly(typeof(MvcApplication)).CodeBase);
string binFolderPath = Path.GetDirectoryName(uri.LocalPath);
string rootFolderPath = new DirectoryInfo(binFolderPath).Parent.FullName;

How to set / overwrite the Context.User.IsInRole for debugging/testing purposes in C#

In my case I wanted to debug a ASP .NET MVC application, that used Windows authentication, but my account was not added to the "Administrators" role in development. If you still want to debug the site as an Administrator you can set the role of the authenticated user in the Global.asax.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Context.User != null)
{
var userPrincipal = new GenericPrincipal(Context.User.Identity, new string[] { "Adminstrators" });
Context.User = userPrincipal;
} 
}

Solving: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

I was getting the error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding, when the CloseActivity action was called on a BPT Action.

 

Cause

This was caused by a query in the OnClose action of the BPT action. This query was taking more then 30 seconds resulting in a SQL Server query timeout.

 

Solution

After tweaking the query the error was resolved.

 

4f28f0f1-8d43-4e0b-bc22-3fd624b7f387

Time of Log:

2013-11-11 09:49:09

eSpace:

Test

Tenant:

Users

User:

(7)

Session Id:

ldvw1leqzfsw55ze4zxopmz5

Server:

SERVER001

Module:

Message:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Stack:

at OutSystems.HubEdition.RuntimePlatform.Processes.ProcessBase.ThrowSpecificException(String failureMessage)
at OutSystems.HubEdition.RuntimePlatform.GenericExtendedActions.#Reb(HeContext heContext, Int32 activityId, Boolean advanceProcess, Boolean skip, Boolean skipAll, Action`4 activityChecks, List`1 inputs)
at OutSystems.HubEdition.RuntimePlatform.GenericExtendedActions.ActivityClose(HeContext heContext, Int32 activityId, String requiredssKey, String actionName, List`1 inputs, Int32& nextHumanActivityId)
at OutSystems.HubEdition.RuntimePlatform.GenericExtendedActions.ActivityClose(HeContext heContext, Int32 activityId, Int32& nextHumanActivityId)
at ssHRCallRegistration.Actions.ActionCloseActivityCustomAction(HeContext heContext, Int32 inParamActivityId)
at ssHRCallRegistration.Flows.FlowMainFlow.WBlkEnlistmentCreateDocuments.CommandDone(HeContext heContext)
-Env-
eSpaceVer: 725 (Id=2492, PubId=2461, CompiledWith=8.0.0.8)
RequestUrl: http://12.0.0.1/Test/Activity_View.aspx (Method: POST)
AppDomain: /LM/W3SVC/1/ROOT/Test-55-130286322452188885
FilePath: C:\…\PS\running\Test.0862112041\Activity_View.aspx
Locale: nl-NL
DateFormat: yyyy-MM-dd
PID: 1692 (‘w3wp’, Started=’11/8/2013 7:33:37 AM’, Priv=517Mb, Virt=5661Mb)
TID: 66
Thread Name:
.NET: 2.0.50727.6407

Fontawesome is awesome!

 

Fontawesome can be found at: http://fontawesome.io

Icons based on a font, gives you infinite scale, icon color adjustment with CSS etc.:

 

image

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Font awesome</title>
<link href="css/font-awesome.css" rel="stylesheet" />
</head>
<body>
<h3>Small icons</h3>
<i class="fa fa-check" style="color:black"></i>
<i class="fa fa-check" style="color:orange"></i>
<i class="fa fa-check" style="color:green"></i>
<h3>Large icons</h3>
<i class="fa fa-5x fa-check" style="color:black"></i>
<i class="fa fa-5x fa-check" style="color:orange"></i>
<i class="fa fa-5x fa-check" style="color:green"></i>
<p></p>
<h3>Rotated icon</h3>
<i class="fa fa-5x fa-info-circle fa-rotate-180" style="color:blue"></i>
</body>
</html>

How to dynamically call an action in Outsystems, based on the eSpace name and Action name.

This post describes how to call an action in Outsystems, based on a given eSpace name and action name.

 

Lets says you want the user to select a action name from a dropdownlist and execute this action, then you can create a big switch statement to call the actions supplied in the dropdownlist, but if you don’t want to change this switch statement each time a new action is added to the list, then you have to create an Outsystems actions and write some C# code, to dynamically execute the action based on a given eSpace name and action name.

 

Extension

image

 

Visual Studio

image

 

C# code

namespace OutSystems.NssDynamicExtension {
using System;
using System.Collections;
using System.Data;
using OutSystems.HubEdition.RuntimePlatform;
using GotDotNet.ApplicationBlocks;
using System.Text;
using System.Linq;
using System.Reflection;
public class CssDynamicExtension: IssDynamicExtension {
/// <summary>
/// 
/// </summary>
/// <param name="ssresult"></param>
/// <param name="sseSpaceName"></param>
/// <param name="ssactionName"></param>
public void MssInvokeAction(out string ssresult, string sseSpaceName, string ssactionName) {
ssresult = string.Empty;
var messages = new StringBuilder(string.Empty);
try
{
// Get all assemblies in current AppDomain.
AppDomain currentDomain = AppDomain.CurrentDomain;
Assembly[] assemblies = currentDomain.GetAssemblies();
// Log all assemblynames.
assemblies.ToList()
.OrderBy(x => x.FullName).ToList()
.ForEach(x => { messages.AppendLine(x.GetName().Name); });
// Get eSpace assembly.
Assembly eSpaceAssemlby = assemblies.ToList()
.First(x => x.GetName().Name.Equals(sseSpaceName, StringComparison.InvariantCultureIgnoreCase));
// Get assembly that contians the "HeContext" type.
Assembly runtimePlatform = assemblies.ToList()
.First(x => x.GetName().Name.Equals("OutSystems.HubEdition.RuntimePlatform"));
// Get the type that contains all actions from an eSpace.
Type actionsType = eSpaceAssemlby.GetType(string.Format("ss{0}.Actions", sseSpaceName));
// Get "HeContext" type (curent HttpContext object).
Type contextType = runtimePlatform.GetType("OutSystems.HubEdition.RuntimePlatform.HeContext");
// Create an instance of the "HeContext" type.
object contextInstance = Activator.CreateInstance(contextType);
// Invoke the given action and supply as first parameter the "HeContext" (curent HttpContext) object.
actionsType.InvokeMember(string.Format("Action{0}", ssactionName), 
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, 
null, null, new object[] { contextInstance });
}
catch (Exception ex)
{
messages.AppendLine(ex.ToString());
}
ssresult = messages.ToString();
} // MssInvokeAction
} // CssDynamicExtension
} // OutSystems.NssDynamicExtension

 

Use the action in Outsystems

image

 

Result

image

 

The action that was dynamically invoked, inserted a record in the database and I could see this record was created, so everything worked just fine.

 

So instead of:

image

 

My code now looks like this:

 

image

 

 

Sometimes, reflection is your friend Smile.

How to dynamically bind data to Content Controls in a Microsoft Word document by using OpenXml and C#.

 

Create a new Microsoft Word document add two content controls with the names:

  • Employee_Firstname
  • Employee_Lastname

Like:

image

 

Employee_Lastname

 

image

 

Now when you run the unittest below, the following the result will be:

 

image

 

 

namespace EndToEndTest
{
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.CustomXmlDataProperties;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
[TestClass]
public class RliResearch
{
private List<string> _tagNames = new List<string>();
private List<string> _uniqueTagNames = new List<string>();
[TestMethod]
public void Test_with_duration()
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
InitialiseDatabinding();
watch.Stop();
System.Console.WriteLine(watch.Elapsed.TotalMilliseconds);
}
public void InitialiseDatabinding()
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Temp\Test.docx", true))
{
CustomXmlPart customXmlPart = doc.MainDocumentPart.CustomXmlParts.FirstOrDefault();
if (customXmlPart == null)
{
customXmlPart = doc.MainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
}
if (customXmlPart.CustomXmlPropertiesPart == null)
{
customXmlPart.AddNewPart<CustomXmlPropertiesPart>();
}
var propertiesPart = customXmlPart.CustomXmlPropertiesPart;
if(propertiesPart.DataStoreItem == null)
{
var dataStoreItem = new DataStoreItem() { ItemId = Guid.NewGuid().ToString("B") };
propertiesPart.DataStoreItem = dataStoreItem;
}
string dataStoreId = customXmlPart.CustomXmlPropertiesPart.DataStoreItem.ItemId;
var names = new List<string>();
foreach (var cc in doc.ContentControls())
{
SdtProperties props = cc.Elements<SdtProperties>().FirstOrDefault();
if (props != null)
{
string name = string.Empty;
try
{
Tag tag = props.Elements<Tag>().FirstOrDefault();
if (tag != null)
{
name = tag.Val.ToString();
names.Add(name);
tag.Val = name;
DocumentFormat.OpenXml.Wordprocessing.SdtAlias alias = props.Elements<DocumentFormat.OpenXml.Wordprocessing.SdtAlias>().FirstOrDefault();
if (alias != null)
{
alias.Val = name;
}
// Update databinding
DocumentFormat.OpenXml.Wordprocessing.DataBinding dataBinding = props.Elements<DocumentFormat.OpenXml.Wordprocessing.DataBinding>().FirstOrDefault();
if (dataBinding == null)
{
dataBinding = new DataBinding();
dataBinding.XPath = string.Format("/Root[1]/{0}[1]", name);
dataBinding.StoreItemId = dataStoreId;
props.Append(dataBinding);
}
else
{
dataBinding.XPath = string.Format("/Root[1]/{0}[1]", name);
dataBinding.StoreItemId = dataStoreId;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(string.Format("Exception found during processing of tag [{0}].", name), ex);
}
}
}
List<string> uniqueTagNames = names.Distinct(StringComparer.CurrentCultureIgnoreCase).OrderBy(x => x).ToList();
XDocument xdoc = CreateXmlDocument("Root", uniqueTagNames);
SaveCustomXmlPart(customXmlPart, xdoc);
}
}
/// <summary>
/// Create a XDocument, with a root element based on the given "rootName", containing child elements based on the given "tagnames".
/// </summary>
public XDocument CreateXmlDocument(string rootName, List<string> tagNames)
{
var document = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(rootName,
tagNames.Select(x => 
{
XElement xe = new XElement(x, string.Empty);
if(string.Compare(x, "Employee_Firstname", true) == 0)
{
xe = new XElement(x, "Johny");
}
if (string.Compare(x, "Employee_Lastname", true) == 0)
{
xe= new XElement(x, "Droptables");
}
return xe;
}
)
)
);
return document;
}
public void SaveCustomXmlPart(CustomXmlPart part, XDocument xdoc)
{
using (var stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite))
{
// Reset stream position to 0, to prevent errors.
stream.Position = 0;
using (XmlWriter xw = XmlWriter.Create(stream))
{
xdoc.Save(xw);
}
}
}
}
/// <summary>
/// Code from: http://openxmldeveloper.org/blog/b/openxmldeveloper/archive/2011/04/11/137383.aspx
/// </summary>
public static class ContentControlExtensions
{
public static IEnumerable<OpenXmlElement> ContentControls(
this OpenXmlPart part)
{
return part.RootElement
.Descendants()
.Where(e => e is SdtBlock || e is SdtRun);
}
public static IEnumerable<OpenXmlElement> ContentControls(
this WordprocessingDocument doc)
{
foreach (var cc in doc.MainDocumentPart.ContentControls())
yield return cc;
foreach (var header in doc.MainDocumentPart.HeaderParts)
foreach (var cc in header.ContentControls())
yield return cc;
foreach (var footer in doc.MainDocumentPart.FooterParts)
foreach (var cc in footer.ContentControls())
yield return cc;
if (doc.MainDocumentPart.FootnotesPart != null)
foreach (var cc in doc.MainDocumentPart.FootnotesPart.ContentControls())
yield return cc;
if (doc.MainDocumentPart.EndnotesPart != null)
foreach (var cc in doc.MainDocumentPart.EndnotesPart.ContentControls())
yield return cc;
}
}
}

How to create an XML document that contains tags for all content control names in a Microsoft Word document, with Open XML and C#

 

If you want to bind content controls in a Microsoft Word document to data, you might want to use a CustomXmlPart. This is a XML document that binds content controls to xml tag names.

 

The xml produced will look like:

<?xml version="1.0" encoding="utf-8"?>
<Root>
<Employee_EmployeeCity></Employee_EmployeeCity>
<Employee_CompetitionAttachment></Employee_CompetitionAttachment>
<Employee_FirstName></Employee_FirstName>
<Employee_FormattedName></Employee_FormattedName>
<Employee_HandinDate></Employee_HandinDate>
<Employee_HouseNumber></Employee_HouseNumber>
<Employee_HouseSuffix></Employee_HouseSuffix>
<Employee_PostalCode></Employee_PostalCode>
<Employee_RelationAttachment></Employee_RelationAttachment>
<Employee_Salutation></Employee_Salutation>
<Employee_Street></Employee_Street>
<Enlistment_CompetitionClause></Enlistment_CompetitionClause>
<Enlistment_EmployeeFirstDay></Enlistment_EmployeeFirstDay>
<Enlistment_RelationshipClause></Enlistment_RelationshipClause>
<Enlistment_TraineeTravel></Enlistment_TraineeTravel>
<Function_CurrentDate></Function_CurrentDate>
<Function_GetManager></Function_GetManager>
<ServiceRequest_Id></ServiceRequest_Id>
</Root>

 

To produce that XML document based on all content control names in a Microsoft Word document, you can use the following code:

namespace EndToEndTest
{
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
[TestClass]
public class RliResearch
{
[TestMethod]
public void Test_with_duration()
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
string sourcePath = @"C:\Temp\Test.docx";
string destinationPath = string.Format(@"C:\Temp\{0}_Test.xml", Guid.NewGuid());
Create_XML_file_for_CustomXmlPart(sourcePath, destinationPath);
watch.Stop();
System.Console.WriteLine(watch.Elapsed.TotalMilliseconds);
}
public void Create_XML_file_for_CustomXmlPart(string sourcePath, string destinationPath)
{
var names = new List<string>();
using (Stream content = GetFileContent(sourcePath))
{
names = GetUniqueContentControlNames(content);
}
XDocument document = CreateXmlDocument("Root", names);
document.Save(destinationPath);
}
/// <summary>
/// Gets the contents of the file as a stream, don't forget to use this function in a "using" statement.
/// </summary>
public Stream GetFileContent(string path)
{
byte[] contentBytes = File.ReadAllBytes(path);
var stream = new MemoryStream(contentBytes);
return stream;
}
/// <summary>
/// Create a XDocument, with a root element based on the given "rootName", containing child elements based on the given "tagnames".
/// </summary>
public XDocument CreateXmlDocument(string rootName, List<string> tagNames)
{
var document = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(rootName,
tagNames.Select(x => new XElement(x, string.Empty)
)
)
);
return document;
}
/// <summary>
/// Gets all unique content control names in the given document.
/// </summary>
public List<string> GetUniqueContentControlNames(Stream content)
{
var names = new List<string>();
using (WordprocessingDocument doc =
WordprocessingDocument.Open(content, false))
{
foreach (var cc in doc.ContentControls())
{
SdtProperties props = cc.Elements<SdtProperties>().FirstOrDefault();
Tag tag = props.Elements<Tag>().FirstOrDefault();
if (tag != null)
{
names.Add(tag.Val);
}
}
}
// Makes names unique and order by name.
var uniqueNames = names.Distinct(StringComparer.CurrentCultureIgnoreCase).OrderBy(x => x).ToList();
return uniqueNames;
}
}
/// <summary>
/// Code from: http://openxmldeveloper.org/blog/b/openxmldeveloper/archive/2011/04/11/137383.aspx
/// </summary>
public static class ContentControlExtensions
{
public static IEnumerable<OpenXmlElement> ContentControls(
this OpenXmlPart part)
{
return part.RootElement
.Descendants()
.Where(e => e is SdtBlock || e is SdtRun);
}
public static IEnumerable<OpenXmlElement> ContentControls(
this WordprocessingDocument doc)
{
foreach (var cc in doc.MainDocumentPart.ContentControls())
yield return cc;
foreach (var header in doc.MainDocumentPart.HeaderParts)
foreach (var cc in header.ContentControls())
yield return cc;
foreach (var footer in doc.MainDocumentPart.FooterParts)
foreach (var cc in footer.ContentControls())
yield return cc;
if (doc.MainDocumentPart.FootnotesPart != null)
foreach (var cc in doc.MainDocumentPart.FootnotesPart.ContentControls())
yield return cc;
if (doc.MainDocumentPart.EndnotesPart != null)
foreach (var cc in doc.MainDocumentPart.EndnotesPart.ContentControls())
yield return cc;
}
}
}