I am trying to write a simple IDE for C#. I have implemented Building projects like this:
var path = ProjectPath;
var props = new Dictionary<string, string>
{
{"Configuration", "Debug"},
{"Platform", "AnyCPU"},
{"OutputPath", ProjectPath}
};
var pc = new ProjectInstance(path, props, "14.0");
var logger = new ConsoleLogger();
logger.Verbosity = LoggerVerbosity.Diagnostic;
var buildParams = new BuildParameters()
{
DetailedSummary = true,
Loggers = new List<ILogger> { new ConsoleLogger() },
DefaultToolsVersion = "14.0"
};
var targets = new List<string> { "PrepareForBuild", "Build" };
var reqData = new BuildRequestData(pc, targets.ToArray());
BuildManager.DefaultBuildManager.BeginBuild(buildParams);
var buildResult = BuildManager.DefaultBuildManager.BuildRequest(reqData);
I have a TextBox in my XAML file that I would like to bind with ConsoleLogger messages. However, the ConsoleLogger object works on a very different basis than Control objects in WPF. My initial intuitive idea was to simply write an Event Handler to handle errors and messages, but ConsoleLogger doesn't allow me to do that. How would I got about solving this problem?
Note: there are many ConsoleLogger classes around .NET, I am talking specifically about: Microsoft.Build.BuildEngine.ConsoleLogger
Related
Github link for the sample code I'm using
In the AdaptiveBot.cs file,
It creates a list of all the prompts available and takes user input and runs the specified prompt.
I want to modify it such that it loads only one dialog(There are 7 prompts in the sample folder and it gives a choice to load any one )
How would I go about to load only one dialog, for example just the MultiTurnPromptBot is needed to be loaded and the rest are not needed.
private void LoadDialogs()
{
System.Diagnostics.Trace.TraceInformation("Loading resources...");
//For this sample we enumerate all of the .main.dialog files and build a ChoiceInput as our rootidialog.
this.dialogManager = new DialogManager(CreateChoiceInputForAllMainDialogs());
this.dialogManager.UseResourceExplorer(this.resourceExplorer);
this.dialogManager.UseLanguageGeneration();
System.Diagnostics.Trace.TraceInformation("Done loading resources.");
}
private AdaptiveDialog CreateChoiceInputForAllMainDialogs()
{
var dialogChoices = new List<Choice>();
var dialogCases = new List<Case>();
foreach (var resource in this.resourceExplorer.GetResources(".dialog").Where(r => r.Id.EndsWith(".main.dialog")))
{
var name = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(resource.Id));
dialogChoices.Add(new Choice(name));
var subDialog = resourceExplorer.LoadType<AdaptiveDialog>(resource);
dialogCases.Add(new Case($"{name}", new List<Dialog>() { subDialog }));
}
var dialog = new AdaptiveDialog()
{
AutoEndDialog = false,
Triggers = new List<OnCondition>() {
new OnBeginDialog() {
Actions = new List<Dialog>() {
new ChoiceInput() {
Prompt = new ActivityTemplate("What declarative sample do you want to run?"),
Property = "conversation.dialogChoice",
AlwaysPrompt = true,
Style = ListStyle.List,
Choices = new ChoiceSet(dialogChoices)
},
new SendActivity("# Running ${conversation.dialogChoice}.main.dialog"),
new SwitchCondition(){
Condition = "conversation.dialogChoice",
Cases = dialogCases
},
new RepeatDialog()
}
}
}
};
return dialog;
}
You can see that LoadDialogs is instantiating a dialog manager by passing an adaptive dialog into its constructor. So instead of creating the root dialog that starts all the other dialogs, you can just pass in one of those dialogs as the root dialog since they're all adaptive dialogs anyway. You can see that the declarative dialog files are loaded like this:
this.resourceExplorer.GetResources(".dialog")
And then the adaptive dialog instances are created out of them like this:
var subDialog = resourceExplorer.LoadType<AdaptiveDialog>(resource);
So you can do something like this:
private void LoadDialogs()
{
System.Diagnostics.Trace.TraceInformation("Loading resources...");
//For this sample we enumerate all of the .main.dialog files and build a ChoiceInput as our rootidialog.
//this.dialogManager = new DialogManager(CreateChoiceInputForAllMainDialogs());
this.dialogManager = new DialogManager(this.resourceExplorer.LoadType<AdaptiveDialog>(this.resourceExplorer.GetResource("MultiTurnPrompt.main.dialog")));
this.dialogManager.UseResourceExplorer(this.resourceExplorer);
this.dialogManager.UseLanguageGeneration();
System.Diagnostics.Trace.TraceInformation("Done loading resources.");
}
TL;DR: Replace this line:
this.dialogManager = new DialogManager(CreateChoiceInputForAllMainDialogs());
With this line:
this.dialogManager = new DialogManager(this.resourceExplorer.LoadType<AdaptiveDialog>(this.resourceExplorer.GetResource("MultiTurnPrompt.main.dialog")));
I am creating a designer surface and loading the controls to a runtime.
I am having issues when deserializing/loading the controls to the runtime.
All methods I have tried seem to have some type of issue.
Issued faced for example:
Controls are still bound of the design-time
Not all properties deserialize with all the properties, namely nested properties.
Control associations does seem to be followed, i.e. Button in a Panel, will not be in the panel anymore, even though the property is still the parent after loading.
I have created a sample Project on git here: Surface Designer Test
There are the main code snippets:
Serialization from the design-time
private void LoadRuntime(int type)
{
var controls = surface.ComponentContainer.Components;
SerializationStore data = (SerializationStore)surface.
_designerSerializationService.Serialize(controls);
MemoryStream ms = new MemoryStream();
data.Save(ms);
SaveData.Data = ms.ToArray();
SaveData.LoadType = type;
new RuntimeForm().Show();
}
public object Serialize(System.Collections.ICollection objects)
{
ComponentSerializationService componentSerializationService =
_serviceProvider.GetService(typeof(ComponentSerializationService)) as
ComponentSerializationService;
SerializationStore returnObject = null;
using (SerializationStore serializationStore =
componentSerializationService.CreateStore())
{
foreach (object obj in objects)
{
if (obj is Control control)
{
componentSerializationService.SerializeAbsolute(serializationStore, obj);
}
returnObject = serializationStore;
}
}
return returnObject;
}
Deserialization in runtime
Here is attempt with reflection:
MemoryStream ms = new MemoryStream(SaveData.Data);
Designer d = new Designer();
var controls = d._designerSerializationService.Deserialize(ms);
ms.Close();
if (SaveData.LoadType == 1)
{
foreach (Control cont in controls)
{
var ts = Assembly.Load(cont.GetType().Assembly.FullName);
var o = ts.GetType(cont.GetType().FullName);
Control controlform = (Control)Activator.CreateInstance(o);
PropertyInfo[] controlProperties = cont.GetType().GetProperties();
foreach (PropertyInfo propInfo in controlProperties)
{
if (propInfo.CanWrite)
{
if (propInfo.Name != "Site" && propInfo.Name != WindowTarget")
{
try
{
var obj = propInfo.GetValue(cont, null);
propInfo.SetValue(controlform, obj, null);
}
catch { }
}
else { }
}
}
Controls.Add(controlform);
}
}
Here is attempt with loading controls directly (still bound to the design-time):
MemoryStream ms = new MemoryStream(SaveData.Data);
Designer d = new Designer();
var controls = d._designerSerializationService.Deserialize(ms);
foreach (Control cont in controls)
Controls.Add(cont);
I feel like I am missing a concept from the System.ComponentModel.Design framework.
I also do not believe there is a need to write a custom serializer for each control, as surely the already have this has Visual Studio is able to serialize all their properties as they are changed in the PropertyGrid and load them back when you run the program.
I'd love to serialize the designer into a .cs file, but how? How do you serialize controls/form and changed properties to a file like the VS designer, I tried and looked only to find xml and binary serializer. My ideal solution would be build a designer.cs with the CodeDom.
What is the correct way do accomplish this serialization between design-time and run-time?
Assuming you have a DesignSurface to show a Form as root component of the designer and having some components created at run-time by using CreateComponent method of IDesignerHost, here is how I approach the problem:
Get an instance of IDesignerHost from DesignSurface
Create new DesignerSerializationManager
Get an instance of TypeCodeDomSerializer from serialization manager
Serialize the RootComponent of the IDesignerHost
Create an instance of CSharpCodeProvider
Generate code by calling GenerateCodeFromType and passing the serialized root component.
You can also extend the example a bit and use ISelectionService to get notified about selected components and change properties at run-time using a PropertyGrid:
Example - Generate C# code from DesignSurface at runtime
Here in this example, I'll show how you can host a windows forms designer at run-time and design a form containing some controls and components and generate C# code at run-time and run the generated code.
Please note: It's not a production code and it's just an example as a
proof of concept.
Create the DesignSurface and host the designer
You can create the design surface like this:
DesignSurface designSurface;
private void Form1_Load(object sender, EventArgs e)
{
designSurface = new DesignSurface(typeof(Form));
var host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
var root = (Form)host.RootComponent;
TypeDescriptor.GetProperties(root)["Name"].SetValue(root, "Form1");
root.Text = "Form1";
var button1 = (Button)host.CreateComponent(typeof(Button), "button1");
button1.Text = "button1";
button1.Location = new Point(8, 8);
root.Controls.Add(button1);
var timer1 = (Timer)host.CreateComponent(typeof(Timer), "timer1");
timer1.Interval = 2000;
var view = (Control)designSurface.View;
view.Dock = DockStyle.Fill;
view.BackColor = Color.White;
this.Controls.Add(view);
}
Generate C# code using TypeCodeDomSerializer and CSharpCodeProvider
This is how I generate code from design surface:
string GenerateCSFromDesigner(DesignSurface designSurface)
{
CodeTypeDeclaration type;
var host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
var root = host.RootComponent;
var manager = new DesignerSerializationManager(host);
using (manager.CreateSession())
{
var serializer = (TypeCodeDomSerializer)manager.GetSerializer(root.GetType(),
typeof(TypeCodeDomSerializer));
type = serializer.Serialize(manager, root, host.Container.Components);
type.IsPartial = true;
type.Members.OfType<CodeConstructor>()
.FirstOrDefault().Attributes = MemberAttributes.Public;
}
var builder = new StringBuilder();
CodeGeneratorOptions option = new CodeGeneratorOptions();
option.BracingStyle = "C";
option.BlankLinesBetweenMembers = false;
using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
{
using (var codeDomProvider = new CSharpCodeProvider())
{
codeDomProvider.GenerateCodeFromType(type, writer, option);
}
return builder.ToString();
}
}
For example:
var code = GenerateCSFromDesigner(designSurface);
Run the code sing CSharpCodeProvider
Then to run it:
void Run(string code, string formName)
{
var csc = new CSharpCodeProvider();
var parameters = new CompilerParameters(new[] {
"mscorlib.dll",
"System.Windows.Forms.dll",
"System.dll",
"System.Drawing.dll",
"System.Core.dll",
"Microsoft.CSharp.dll"});
parameters.GenerateExecutable = true;
code = $#"
{code}
public class Program
{{
[System.STAThread]
static void Main()
{{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new {formName}());
}}
}}";
var results = csc.CompileAssemblyFromSource(parameters, code);
if (!results.Errors.HasErrors)
{
System.Diagnostics.Process.Start(results.CompiledAssembly.CodeBase);
}
else
{
var errors = string.Join(Environment.NewLine,
results.Errors.Cast<CompilerError>().Select(x => x.ErrorText));
MessageBox.Show(errors);
}
}
For example:
Run(GenerateCSFromDesigner(designSurface), "Form1");
I am trying to exclude Linkedin but when i checked UIActivityType Class, I found only below members.
AddToReadingList
AirDrop
AssignToContact
CopyToPasteboard
Mail
Message
OpenInIBooks
PostToFacebook
PostToFlickr
PostToTencentWeibo
PostToTwitter
PostToVimeo
Print
SaveToCameraRoll
Is there a way we can exclude linkedin?
Update:
I thought this radar concerning third-party values was closed, but it is still open :-(
http://openradar.appspot.com/20170408
...
The ExcludedActivityTypes is just an array of NSStrings that include the bundle id of the share extension. So use com.linkedin.LinkedIn.ShareExtension to exclude linkedin.
Example:
var activityItemsNSUrl = NSUrl.FromString("http://stackoverflow.com");
var activityItemsString = new NSString("StackOverflow");
var activityItems = new NSObject[] { activityItemsString, activityItemsNSUrl };
var activityViewController = new UIActivityViewController(activityItems, null)
{
ExcludedActivityTypes = new NSString[] {
UIActivityType.PostToVimeo,
new NSString("com.linkedin.LinkedIn.ShareExtension"),
UIActivityType.PostToFlickr
}
};
PresentViewController(activityViewController, true, () => { });
Re: https://developer.linkedin.com/docs/ios-sdk
we are working on a project where we are using Storm on HDInsight to analyze real-time data. We are using event hubs as input and output and we are having some problems passing the data through the topology. We are currently having one JavaSpout as input handler, one custom Bolt (Bolt1) that is suppose to do some analysis on the data, and one JavaBolt that is suppose to take the analyzed data and send it to the output event hub. Passing data through the JavaSpout and JavaBolts works like a charm, but when we indroduce the custom Bolt the data gets encapsulated or something, its not showing what it should. the output is supposed to show a JSON string, but is shows some random stuff that looks like: [B#6d645e45
Most part of this is code from this tutorial: http://azure.microsoft.com/sv-se/documentation/articles/hdinsight-storm-develop-csharp-event-hub-topology/
This is our topology builder:
TopologyBuilder topologyBuilder = new TopologyBuilder("EventHubReaderTest");
int partitionCount = Properties.Settings.Default.EventHubPartitionCount;
JavaComponentConstructor constructor = JavaComponentConstructor.CreateFromClojureExpr(
String.Format(#"(com.microsoft.eventhubs.spout.EventHubSpout. (com.microsoft.eventhubs.spout.EventHubSpoutConfig. " +
#"""{0}"" ""{1}"" ""{2}"" ""{3}"" {4} ""{5}""))",
Properties.Settings.Default.EventHubPolicyName,
Properties.Settings.Default.EventHubPolicyKey,
Properties.Settings.Default.EventHubNamespace,
Properties.Settings.Default.EventHubNameInput,
partitionCount,
""));
topologyBuilder.SetJavaSpout(
"EventHubSpout",
constructor,
partitionCount);
List<string> javaSerializerInfo = new List<string>() { "microsoft.scp.storm.multilang.CustomizedInteropJSONSerializer" };
topologyBuilder.SetBolt(
"bolten",
Bolt1.Get,
new Dictionary<string, List<string>>()
{
{Constants.DEFAULT_STREAM_ID, new List<string>(){"Event"}}
},
partitionCount).
DeclareCustomizedJavaSerializer(javaSerializerInfo).
shuffleGrouping("EventHubSpout");
JavaComponentConstructor constructorout =
JavaComponentConstructor.CreateFromClojureExpr(
String.Format(#"(com.microsoft.eventhubs.bolt.EventHubBolt. (com.microsoft.eventhubs.bolt.EventHubBoltConfig. " +
#"""{0}"" ""{1}"" ""{2}"" ""{3}"" ""{4}"" {5}))",
Properties.Settings.Default.EventHubPolicyName,
Properties.Settings.Default.EventHubPolicyKey,
Properties.Settings.Default.EventHubNamespace,
"servicebus.windows.net", //suffix for servicebus fqdn
Properties.Settings.Default.EventHubNameOutput,
"true"));
topologyBuilder.SetJavaBolt(
"EventHubBolt",
constructorout,
partitionCount).
shuffleGrouping("bolten");
return topologyBuilder;
This is the Bolt that is suppose to do some work
public Bolt1(Context ctx)
{
this.ctx = ctx;
Dictionary<string, List<Type>> inputSchema = new Dictionary<string, List<Type>>();
inputSchema.Add("default", new List<Type>() { typeof(string) });
Dictionary<string, List<Type>> outputSchema = new Dictionary<string, List<Type>>();
outputSchema.Add("default", new List<Type>() { typeof(string) });
this.ctx.DeclareComponentSchema(new ComponentStreamSchema(inputSchema, outputSchema));
this.ctx.DeclareCustomizedDeserializer(new CustomizedInteropJSONDeserializer());
}
public static Bolt1 Get(Context ctx, Dictionary<string, Object> parms)
{
return new Bolt1(ctx);
}
//this is there the magic should happen
public void Execute(SCPTuple tuple)
{
string test = "something";
//we are currently just trying to emit a string
ctx.Emit(new Values(test));
}
We hope that we explained the problem good enough, we dont quite grasp how the topology works so its hard to troubleshoot.
EDIT
We solved it by declaring a deserializer in our topology:
List javaSerializerInfo = new List() { "microsoft.scp.storm.multilang.CustomizedInteropJSONSerializer" };
List javaDeserializerInfo = new List() { "microsoft.scp.storm.multilang.CustomizedInteropJSONDeserializer", "java.lang.String" };
topologyBuilder.SetBolt(
"bolten",
Bolt1.Get,
new Dictionary<string, List<string>>()
{
{Constants.DEFAULT_STREAM_ID, new List<string>(){"Event"}}
},
partitionCount).
DeclareCustomizedJavaSerializer(javaSerializerInfo).
DeclareCustomizedJavaDeserializer(javaDeserializerInfo).
shuffleGrouping("EventHubSpout");
And in the custom C# bolt we declared a serializer:
this.ctx.DeclareComponentSchema(new ComponentStreamSchema(inputSchema, outputSchema));
this.ctx.DeclareCustomizedDeserializer(new CustomizedInteropJSONDeserializer());
this.ctx.DeclareCustomizedSerializer(new CustomizedInteropJSONSerializer());
I am trying to access UIActivityViewController from MonoTouch with the following code:
var textToShare = new NSString("hallo there");
var activityItems = new NSObject[] {textToShare};
var excludedActivityTypes = new NSString[] { new NSString("UIActivityTypePostToWeibo"), new NSString("UIActivityTypeMessage") };
var activityViewController = new UIActivityViewController(activityItems, null);
activityViewController.ExcludedActivityTypes = excludedActivityTypes;
this.PresentViewController(activityViewController, true, null)
The iOS action sheet is displayed but the specified activities are not excluded.
Any suggestions what the problem is? Are there any MonoTouch samples for this?
You were close. Change this:
var excludedActivityTypes = new NSString[] {
new NSString("UIActivityTypePostToWeibo"),
new NSString("UIActivityTypeMessage")
};
into:
var excludedActivityTypes = new NSString[] {
UIActivityType.PostToWeibo,
UIActivityType.Message
};
Note: The name of the constant is not always identical to it's value. Also it's common (even if bad practice) for ObjC to compare the NSString pointers (not their values) to detect constant equality - creating your own NSString instance won't work in such cases (anyway the exposed const are much better looking and work better with code completion from the IDE).