Roslyn Run Code in AppDomain - c#

I added Roslyn my project.
Roslyn can run script from string like
using Roslyn.Scripting.CSharp;
namespace RoslynScriptingDemo
{
class Program
{
static void Main(string[] args)
{
var engine = new ScriptEngine();
engine.Execute(#"System.Console.WriteLine(""Hello Roslyn"");");
}
}
}
but I wanna access the controls,properties,variables in the form.
For Example There is a textbox in form.
var engine = new ScriptEngine();
engine.Execute(#" textbox1.Text="SK"; ");
Can I access controls in Roslyn?

You could set up a host object for your script session that has a public property for the controls you want to access.

Related

How to properly setup CodeContext of IronPython to directly invoke IO from C#?

I am trying to directly invoke IronPython's built-in modules from C#. It looks like I'm missing some important initialization, that I can't find anywhere in the code.
Here's what I do:
namespace py.consoleio
{
using IronPython.Runtime;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Hosting.Providers;
using Microsoft.Scripting.Runtime;
public static class consoleio
{
public static string name;
static void Main()
{
var setup = new ScriptRuntimeSetup();
setup.LanguageSetups.Add(
IronPython.Hosting.Python.CreateLanguageSetup(null));
var dlrRuntime = new ScriptRuntime(setup);
var scriptDomainManager = HostingHelpers.GetDomainManager(dlrRuntime);
var pythonContext = new PythonContext(scriptDomainManager, null);
var context = new CodeContext(new PythonDictionary(), new ModuleContext(new PythonDictionary(), DefaultContext.DefaultPythonContext));
name = IronPython.Modules.Builtin.input(context, "What is your name?\n");
IronPython.Modules.Builtin.print(context, "Hi, %s.", consoleio.name);
System.GC.KeepAlive(pythonContext);
}
}
}
That properly outputs "What is your name?", but then crashes trying to decode input: unknown encoding: cp437.
Now I've already found, that encodings are initialized in Src/StdLib/Lib/encodings/init.py
I can't find how it gets to loading this module in a normal IronPython run (e.g. a console host), so I can't reproduce it in C# program.
My goal here is to invoke IronPython functions without dynamic dispatch.
UPD. Now I also tried to do this:
var engine = Python.CreateEngine();
this.ScriptDomainManager = HostingHelpers.GetDomainManager(engine.Runtime);
to the same result
Figured that one out: encodings module is implemented in Python in IronPython (core modules are in C#). It always worked with IronPythonConsole project, because it implicitly adds IronPython source for standard libraries to Python path. I just had to explicitly specify path like this:
var options = new Dictionary<string, object> { ["SearchPaths"] = path };
var engine = Python.CreateEngine(options);

Total number of labels inside a module of TFS repository

I need to find out how many labels are there inside each module of a collection in Team Foundation repository.
I am using TFS 2013.
I know we can get it from Visual Studio. But we need a script which gets us the number of labels as output.
Can anyone help me out in getting a C# or a Powershell code to obtain the same?
TIA
You can use .NET Client Libraries to get this: .NET client libraries for Visual Studio Team Services (and TFS)
Code sample:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace GetLabels
{
class Program
{
static void Main(string[] args)
{
string tfscollection = "http://xxx:8080/tfs/defaultcollection";
TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(tfscollection));
VersionControlServer vcs = ttpc.GetService<VersionControlServer>();
string labelname = null;
string labelscope = "$/";
string owner = null;
bool includeitem = false;
int labelnumber;
VersionControlLabel[] labels = vcs.QueryLabels(labelname,labelscope,owner,includeitem);
labelnumber = labels.Length;
Console.WriteLine(labelnumber);
Console.ReadLine();
}
}
}

How can I export my c# code logic (if-else-loops) in to text files (e.g XML) and later import it back and run?

I have these requirements coming from client every week for some new logic or verification. For which I have to code new logic (basically some if-else and loops) and launch a new build for him. I want to avoid it by simply coding my logic in visual studio then writing a utility to export it to XML or something and send it to client via e-mail. He just have to place this file in some appropriate folder and the application will behave considering this logic.
Please suggest some solutions. My platform is C# Asp.Net.
Thanks
Using .NET 4.6 and the NuGetPackage Microsoft.CodeAnalysis.Scripting you could implement a scripting engine to run your c# code residing in a textfile without building an assembly.
Install NuGet Package:
Install-Package Microsoft.CodeAnalysis.Scripting.CSharp
Implement TestClass with some basic C#-Code-Content:
class Program
{
static void Main(string[] args)
{
TestScript();
}
private static async void TestScript()
{
// Code snippet: a class with one string-property.
string codeContent = #" using System;
public class ScriptedClass
{
public string HelloWorld { get; set; }
public ScriptedClass()
{
HelloWorld = ""Hello Roslyn!"";
}
}
new ScriptedClass().HelloWorld";
// Instanciate CSharpScriptEngine
var engine = new CSharpScriptEngine();
// Execute code and return string property (HelloWorld)
var scriptingState = await engine.ExecuteAsync(codeContent);
// Print return value from CSharpScript
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
Implement a ScriptingEngine:
internal sealed class CSharpScriptEngine
{
public async Task<ScriptState<object>> ExecuteAsync(string codeContent)
{
// Add references from calling assembly
ScriptOptions options = ScriptOptions.Default.AddReferences(Assembly.GetExecutingAssembly());
// Run codeContent with given options
return await CSharpScript.RunAsync(codeContent, options);
}
}
Read ScriptCode from textfile:
So basically you could read some csharpcode from a textfile of your choice and run them on the fly:
private static async void TestScript()
{
// Read in script file
string codeContent = File.ReadAllText(#"C:\Temp\CSharpScriptTest.cs");
var engine = new CSharpScriptEngine();
// Run script
var scriptingState = await engine.ExecuteAsync(codeContent);
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
In case you are wondering how all of this works under the hood, Roslyn will create a so called submission from your script code. A submission is an in memory assembly containing the types generated around your script code, which can be identified among the assemblies in the current AppDomain by a ℛ prefix in the name.
The precise implementation details are not important here (though, for example, scriptcs heavily relies on understanding in detail how Roslyn works to provide its extra features), but it's important to know that submissions can be chained together. When they are chained, variables, methods or classes defined in an earlier submission are available to use in subsequent submissions, creating a feature of a C# REPL (read-evaluate-print loop).
C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Hope it helps

Programmatically add user role to COM+ component (C#)

I wish to know the way to add ASP.NET ("Machine_Name"\IIS_IUSRS) to user role in COM+ component programmatically using C#. So whenever my COM+ component is being installed, ASP.NET user is created under Role.
Here's the code. You've got to reference C:\windows\system32\com\comadmin.dll.
using System;
using COMAdmin;
using Microsoft.VisualBasic;
namespace TesteAdicionaRole
{
class Program
{
static void Main(string[] args)
{
string packageName = "TRICOLOR";
ICOMAdminCatalog catalog = (ICOMAdminCatalog)Interaction.CreateObject("COMAdmin.COMAdminCatalog", string.Empty);
ICatalogCollection packages = (ICatalogCollection)catalog.GetCollection("Applications");
packages.Populate();
foreach (ICatalogObject package in packages)
if (package.Name.ToString().Equals(packageName))
{
ICatalogCollection roles = (ICatalogCollection)packages.GetCollection("Roles", package.Key);
roles.Populate();
ICatalogObject role = (ICatalogObject)roles.Add();
role.set_Value("Name", "MyRoleName");
roles.SaveChanges();
ICatalogCollection users = (ICatalogCollection)roles.GetCollection("UsersInRole", role.Key);
users.Populate();
ICatalogObject user = (ICatalogObject)users.Add();
user.set_Value("User", "MV0266\\IUSR_MV0266");
users.SaveChanges();
break;
}
}
}
}
[]'s

How do I programmatically close an InfoPath form in C#?

Is it possible to close an InfoPath form programmatically? I know that it can be configured as a form rule / action but I want to close the form via code.
Use the ApplicationClass.XDocuments.Close method and pass it your document object:
using System;
using Microsoft.Office.Interop.InfoPath;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var app = new ApplicationClass();
var uri = #".\form1.xml";
var doc = app.XDocuments.Open(uri, 0);
app.XDocuments.Close(doc);
}
}
}

Categories

Resources