Skip to main content

Reusing Templates and Code Tutorials

Tutorial HomeReuse

Reuse code with .cs files (new in 2sxc 10.01)

Starting with 2sxc 10.01 CreateInstance() can also be used with .cs files, from both razor pages as well as WebApi controllers. This allows you to create shared code which can be used in Razor and WebApi controllers.


Using shared library of simple functions

The example takes a cs file FunctionsBasic.cs with shared code in a class FunctionsBasic. This example uses a simple C# class, so the code only has what's in it.

Hello from FunctionsBasic: Hello from shared functions!

Using a different Class from a library files

The example takes a cs file with shared code, but gets the class Second.

Hello from FunctionsBasic: Hello from the second class!

Using shared code with context

Often you may need context - like the Dnn or App objects. We made this easy by defining a base class you can inherit from, called ToSic.Sxc.Dnn.DynamicCode. If you use that as your base-class, all existing context is automatically attached, allowing you to access variables like App.


Using shared libraries in WebApi Controllers

The mechanism above also works in WebApi Controllers (if you have 2sxc 10.01+). Note that specifically in WebApi you can only use CreateInstance(...) for .cs files.

Click to see the result of a WebApi call with the shared code:

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials.

@inherits ToSic.Sxc.Dnn.RazorComponent
<!-- unimportant stuff, hidden -->

Reuse code with .cs files (new in 2sxc... <!-- unimportant stuff, hidden -->

<hr>
<h2>Using shared library of simple functions</h2>
The example takes a cs file... <!-- unimportant stuff, hidden -->
@{
  var lib = CreateInstance("FunctionsBasic.cs");
}
<div>Hello from FunctionsBasic: @lib.SayHello()</div>

<hr>
<h2>Using a different Class from a library files</h2>
The example takes a cs file with shared... <!-- unimportant stuff, hidden -->
@{
  var lib2 = CreateInstance("FunctionsBasic.cs", name: "Second");
}
<div>Hello from FunctionsBasic: @lib2.SayHello()</div>

<hr>
<h2>Using shared code with context</h2>
Often you may need context - like the... <!-- unimportant stuff, hidden -->
@{
  var powerLib = CreateInstance("FunctionsWithContext.cs");
}
<div>
  <img src='@powerLib.QrPath("https://2sxc.org")' width="75px">
</div>

<!-- unimportant stuff, hidden -->

@* tell 2sxc that we'll use the js API *@
@Edit.Enable(js:true)

<blockquote>
  Click to see the result of a WebApi call with the shared code:
  <button type="button" class="btn btn-primary" onclick="callApiWithSharedCode(this)">
    Call WebApi
  </button>
</blockquote>

<script>
  function callApiWithSharedCode(context) {
    $2sxc(context).webApi.get('app/auto/reuse/api/sharedcode/hello')
      .then(function (results) {
        console.log(results);
        alert(results);
      });
    return false;
  }
</script>

<!-- unimportant stuff, hidden -->

Source Code of FunctionsBasic.cs

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials.

// Important notes: 
// - This class should have the same name as the file it's in
public class FunctionsBasic {

  public string SayHello() {
    return "Hello from shared functions!";
  }
}

// Example for another class in the same file
public class Second {
  public string SayHello() {
    return "Hello from the second class!";
  }
}

Source Code of FunctionsWithContext.cs

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials.

// Important notes: 
// - This class should have the same name as the file it's in
// - This inherits from ToSic.Sxc.Code.WithDnnContext
//   which will automatically provide the common objects like App, Dnn etc.
//   from the current context to use in your code
public class FunctionsWithContext: ToSic.Sxc.Dnn.DynamicCode {

  public string QrPath(string link) {
        // path to qr-code generator
        var qrPath = "//api.qrserver.com/v1/create-qr-code/?color={foreground}&bgcolor={background}&qzone=0&margin=0&size={dim}x{dim}&ecc={ecc}&data={link}"
            .Replace("{foreground}", App.Settings.QrForegroundColor.Replace("#", ""))
            .Replace("{background}", App.Settings.QrBackgroundColor.Replace("#", ""))
            .Replace("{dim}", App.Settings.QrDimension.ToString())
            .Replace("{ecc}", App.Settings.QrEcc)
            .Replace("{link}", link)
            ;
        return qrPath;
    }

}

Source Code of /reuse/api/SharedCodeController.cs

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials.

using System.Web.Http;
using ToSic.SexyContent.WebApi;
using DotNetNuke.Web.Api;

[AllowAnonymous]
[ValidateAntiForgeryToken]
public class SharedCodeController : SxcApiController
{
	[HttpGet]
	[AllowAnonymous]
	public string Hello()
	{
		var shared = CreateInstance("../FunctionsBasic.cs");
		return shared.SayHello();
	}
}