‏הצגת רשומות עם תוויות c#. הצג את כל הרשומות
‏הצגת רשומות עם תוויות c#. הצג את כל הרשומות

יום חמישי, 6 ביוני 2013

Executing java jar from C-sharp

The following code execute a java jar from C# environment and capture back the standard output the jar generate.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Diagnostics;
  4: using System.IO;
  5: using System.Linq;
  6: using System.Text;
  7: using System.Threading.Tasks;
  8: 
  9: namespace SendTheEvent
 10: {
 11:     class Program
 12:     {
 13:         static void Main(string[] args)
 14:         {
 15:             ProcessStartInfo thePsi = new ProcessStartInfo ();
 16: 
 17:             thePsi.WorkingDirectory = @"C:\projects\myProjectWorkingDirectory";
 18: 
 19:             thePsi.FileName =@"C:\Program Files\Java\jre7\bin\java.exe";
 20: 
 21:             thePsi.RedirectStandardOutput = true;
 22: 
 23:             thePsi.UseShellExecute = false;
 24: 
 25:             thePsi.Arguments = "-jar ActiveMQNotifier.jar";
 26:        
 27:       using (Process process = Process.Start(thePsi))
 28:       {
 29:         //
 30:         // Read in all the text from the process with the StreamReader.
 31:         //
 32:         using (StreamReader reader = process.StandardOutput)
 33:         {
 34:           string result = reader.ReadToEnd();
 35:           Debug.Write(result);
 36:         }
 37:       }
 38:        }
 39:     }
 40: }

יום שבת, 1 ביוני 2013

Very simple web api call part 1

Create a new project based of web api template.
The view
Replace all the content of Index.cshtml with the following code

  1: <!DOCTYPE html>
  2: <html lang="en">
  3: <head>
  4:     <title>Routes Web API</title>
  5:     <link href="../../Content/Site.css" rel="stylesheet" />
  6:  
  7: </head>
  8: <body id="body" >
  9:     <div class="main-content">
 10:         <div>
 11:             <h1>All Routes</h1>
 12:             <ul id="RoutesList"/>
 13:         </div>
 14:         <div>
 15:             <input type="button" id="CallWebApi" value="Call web api" />
 16:             <p id="product" />
 17:         </div>
 18:     </div>
 19:       <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 20:        <script>
 21:          
 22:            $(document).ready(function () {
 23:                
 24:                $("#CallWebApi").on("click", function (event) {
 25:                    // Send an AJAX request
 26:                    $.getJSON("api/values/",
 27:                    function (data) {
 28:                        // On success, 'data' contains a list of products.
 29:                        $.each(data, function (key, val) {
 30: 
 31:                            // Format the text to display.
 32:                            var theRouteName = val.Name ;
 33: 
 34:                            // Add a route for the routes list.
 35:                            $('<li/>', { text: theRouteName })
 36:                            .appendTo($('#RoutesList'));
 37:                        });
 38:                    });
 39:                });
 40:          });
 41:         
 42:        </script>
 43: </body>
 44: </html>

The modal
Create a simple Route modal

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: 
  6: namespace MvcApplication1.Models
  7: {
  8:     public class Route
  9:     {
 10:         public Route()
 11:         {
 12: 
 13:         }
 14:         public int Id { get; set; }
 15:         public string Name { get; set; }
 16:     }
 17: }

The controller
change the values controller as follow


  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Net;
  5: using System.Net.Http;
  6: using System.Web.Http;
  7: using MvcApplication1.Models;
  8: 
  9: namespace MvcApplication1.Controllers
 10: {
 11:     public class ValuesController : ApiController
 12:     {
 13:         Route[] Routes = new Route[] 
 14:         { 
 15:             new Route { Id = 1, Name = "To Scoll" }, 
 16:             new Route { Id = 2, Name = "To Home" } 
 17:         };
 18:         public ValuesController()
 19:         {
 20: 
 21:         }
 22:         // GET api/values
 23:         public IEnumerable<Route> Get()
 24:         {
 25:             return Routes; 
 26:         }
 27: 
 28:         // GET api/values/5
 29:         public string Get(int id)
 30:         {
 31:             return "value";
 32:         }
 33: 
 34:         // POST api/values
 35:         public void Post([FromBody]string value)
 36:         {
 37:         }
 38: 
 39:         // PUT api/values/5
 40:         public void Put(int id, [FromBody]string value)
 41:         {
 42:         }
 43: 
 44:         // DELETE api/values/5
 45:         public void Delete(int id)
 46:         {
 47:         }
 48:     }
 49: }

The Result after clicking the button:
Capture22

יום חמישי, 30 במאי 2013

wcf calls thread affinity

A week ago we have notice that many WCF service calls are executing in the UI thread context.
We wish to eliminate this behavior in order to void blocking the UI thread by WCF service calls.
Because the WCF service calls execution time is very long we wants that every call will be execute in a new thread and not using a thread pool .
The solution for this problem was :

Create custom SynchronizationContext that overrides the send and post methods

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Threading;
  6: 
  7: namespace WcfInfra
  8: {
  9:     public class NewThreadForEachCallSyncContext: SynchronizationContext
 10:     {
 11:         public NewThreadForEachCallSyncContext ()
 12: 	    {
 13: 
 14: 	    }
 15:         public override void Send(SendOrPostCallback d, object state)
 16:         {
 17:             new Thread(new ThreadStart(() =>
 18:             {
 19:                 d(state);
 20:             })).Start();
 21:         }
 22:         public override void Post(SendOrPostCallback d, object state)
 23:         {
 24:             new Thread (new ThreadStart (()=>
 25:             {
 26:                 d(state);
 27:             })).Start ();
 28:         }
 29: 
 30:     }
 31: }

Create a wcf service attribute that implements the IContractBehavior .In the applydispatchbehavior attach to the dispatchRuntime.SynchronizationContext  an instance of our custom SynchronizationContext .

  1: public class NewThreadForEachCallInterceptorAttribute : Attribute, IContractBehavior
  2: {
  3: 	public NewThreadForEachCallInterceptorAttribute()
  4: 	{
  5: 
  6: 	}
  7: 
  8: 	public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
  9: 	{
 10: 		
 11: 	}
 12: 
 13: 	public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
 14: 	{
 15: 		
 16: 	}
 17: 
 18: 	public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)
 19: 	{
 20: 		dispatchRuntime.SynchronizationContext = new TrainerSyncContext();
 21: 	}
 22: 
 23: 	public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
 24: 	{
 25: 
 26: 	}
 27: }

Adore the wcf service with the new attribute


  1: [ServiceBehavior(IncludeExceptionDetailInFaults = true ,InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
  2:     [NewThreadForEachCallInterceptor()]
  3:     [ErrorBehavior(typeof(ApplicationException))]
  4:     public class DoThingsLongTimeService : IDoThing

יום חמישי, 16 במאי 2013

Generated .net code on the fly

Sometimes I need to provide the end user capabilities that require dynamic compilation.
For an example a signal generator with option to allow the user to write a complicated phrase that express the Y value according to a given x (time ) value.
.net Code dom is used in order to generate on the fly the code based on the user pharse.

First declare and interface to be implement using the user dynamic code for an example:
public interface ISignalGenerator
    {
        double GetYValue(double pTime);
    }

Then declare the template of the interface  implementer.
The following code should be store as a string

  public class SignalGeneratorT%ClassName% : ISignalGenerator
{
public double GetYValue(double pTime)
{
return %UserCode%;
}
}
The program responsibility to switch the %ClassName% with the name of the function given by the user or generated randomly.
And to switch the %UserCode% with the phrase the user entered.

The following code is used to generate a .net assembly by the code , a list of reference assemblies and the programing language.

 public static System.Reflection.Assembly CompileTemplatedCode (string Code, string Language, params string[] ReferencedAssemblies)
{

Debug.Assert (System.String.IsNullOrEmpty(Code) == false );
            Debug.Asser(System.CodeDom.Compiler.CodeDomProvider.IsDefinedLanguage(Language))
using (System.CodeDom.Compiler.CodeDomProvider cdp =
System.CodeDom.Compiler.CodeDomProvider.CreateProvider(Language))
{
System.CodeDom.Compiler.CompilerParameters cp =
System.CodeDom.Compiler.CodeDomProvider.GetCompilerInfo
(Language).CreateDefaultCompilerParameters();

cp.ReferencedAssemblies.Add("System.dll");

if (ReferencedAssemblies != null)
{
cp.ReferencedAssemblies.AddRange(ReferencedAssemblies);
}
                cp.GenerateInMemory = true;

System.CodeDom.Compiler.CompilerResults cr =
cdp.CompileAssemblyFromSource(cp,
Code
);
if (cr.Errors.HasErrors)
{

System.Exception err = new System.Exception("Compilation failure" + cr.Errors[0].ErrorText);
err.Data["Errors"] = cr.Errors;
err.Data["Output"] = cr.Output;
throw (err);
}

return (cr.CompiledAssembly);
}
}

Note that a reference to the assembly that declare the ISignalGenerator interface should be include in the method assemblies list.

The current assembly cannot be referenced implicitly by the generated code but should be added to the assemblies list explicitly .
After call to generate the code and checking that there are no errors an assembly reference is returned .
The following code generate and instance of the class
Assembly theAssembly = CompileTemplatedCode (pTheTemplatedSource, "C#", "MyExtraAssembly");
ISignalGenerator theISignalGenerator = (ISignalGenerator)theAssembly.CreateInstance(
<TheClassName>, false, BindingFlags.CreateInstance,
null, null, null, null);
 
Note:
The class name should be unique for every generation phase.
The generated assembly residents in memory until the hosting application is shut down this may cause a memory leak issue if a a lot of classes are generated in a working session.