DNX: C#: Delegate, Func and Action

As you may know, Microsoft is getting into the open source community with the ASP.NET and DNX with the mono project.
The .NET Execution Environment (DNX) is a software development kit which allows you to run .NET applications on Windows, Mac, and Linux using different frameworks such as .NET framework, .NET Core, and Mono. However, everything are not roses. There are many incomplete libraries, incompatibilities, lack of documentation, and most of the examples such as doing SQL or SOAP do not work depending on which the library targets you are planning to code for. Therefore, I decided to test the basics on all the library targets. I am starting with DNX451.

Delegate seems to be working fine in DNX451 with C#. Below is a code example for those who wish to play with it.

Program.cs

using System;

namespace ConsoleApp1 {
	
	public class Program {
		
		public void Main(string[] args){			
			Console.WriteLine("Main()");
			
			displayWhichDnxIsCompilingOn();
			
			new DelegateExample();
			
		}
		
		private void displayWhichDnxIsCompilingOn(){
			#if DNX451
			Console.WriteLine("Compiled on DNX451: .NET Framework");
			#endif
			
			#if DNXCORE50
			Console.WriteLine("Compiled on DNXCORE50: .NET Core 5");
			#endif						
		}
		
	}
	
}
DelegateExample.cs

using System;

namespace ConsoleApp1 {

	public class DelegateExample {
		
		delegate void SomeDelegate();
		
		delegate void Operation(int number);
		
		public DelegateExample() {
			Console.WriteLine("\nDelegateExample()");
			
			// Calling directly
			SampleMethod();
			
			// Calling using delegate 
			SomeDelegate del = new SomeDelegate(SampleMethod);
			del.Invoke();
			
			// Another way to use delegate
			SomeDelegate del2 = SampleMethod;
			del2();
			
			// Calling delegate within method
			CallingDelegate(del2);
			
			// Getting a delegate
			del2 = GetDelegate();
			CallingDelegate(del2);

			Console.WriteLine("----");
						
			// Displaying Values						
			Operation op = DisplaySquare;
			ExecuteOperation(2, op);
			
			op = DisplayCube;
			ExecuteOperation(2, op);
			
			Console.WriteLine("----");
			
			// Add Methods to execute
			op = DisplaySquare;
			op = op + DisplayCube;
			ExecuteOperation(2, op);
			
			Console.WriteLine("----");
						
			// Add and substract methods to execute
			op = DisplaySquare;
			op += DisplayCube;
			op += DisplayCube;
			op += DisplayCube;
			ExecuteOperation(2, op);
			
			Console.WriteLine("----");
						
			// Instead of displaying square once and cube three times, we wish to do square once and cube double.
			// Lets remove one
			op -= DisplayCube;			
			ExecuteOperation(2, op);
			
			Console.WriteLine("----");
							
			// Action is like delegates for functions that doesn't return something.
			Action<int> actionOp = number => { 
				Console.WriteLine("{0} x {0} x {0} = {1}", number, number * number * number);				
			};
			actionOp(2);
			
			Console.WriteLine("------");
			
			// Action is like delegate for function that accept parameters and have a return value.
			Func<int, int> funcOp = number => { return number * number * number * number; };
			Console.WriteLine("{0} x {0} x {0} x {0} = {1}", 2, funcOp(2));
								
		}
		
		private void SampleMethod(){
			Console.WriteLine("\tSampleMethod()");
		}
				
		private void CallingDelegate(SomeDelegate sDel){
			sDel();
		}
		
		private SomeDelegate GetDelegate(){
			return new SomeDelegate(SampleMethod);
		}
		
		private void DisplaySquare(int number){
			Console.WriteLine("{0} x {0} = {1}", number, number * number);
		} 

		private void ExecuteOperation(int num, Operation operation){
			operation(num);			
		}
		
		private void DisplayCube(int number){
			Console.WriteLine("{0} x {0} x {0} = {1}", number, number * number * number);
		}
			
	}

}
Output:

AGCRM-MacBook-Pro:Examples user$ dnx . me
Main()
Compiled on DNX451: .NET Framework

DelegateExample()
    SampleMethod()
    SampleMethod()
    SampleMethod()
    SampleMethod()
    SampleMethod()
----
2 x 2 = 4
2 x 2 x 2 = 8
----
2 x 2 = 4
2 x 2 x 2 = 8
----
2 x 2 = 4
2 x 2 x 2 = 8
2 x 2 x 2 = 8
2 x 2 x 2 = 8
----
2 x 2 = 4
2 x 2 x 2 = 8
2 x 2 x 2 = 8
----
2 x 2 x 2 = 8
------
2 x 2 x 2 x 2 = 16
Cite this article as: Alejandro G. Carlstein Ramos Mejia, "DNX: C#: Delegate, Func and Action," in Alejandro G. Carlstein Ramos Mejia Blog, September 1, 2015, http://www.acarlstein.com/?p=3158.
Share

DNX: C#: Reflection

As you may know, Microsoft is getting into the open source community with the ASP.NET and DNX with the mono project.
The .NET Execution Environment (DNX) is a software development kit which allows you to run .NET applications on Windows, Mac, and Linux using different frameworks such as .NET framework, .NET Core, and Mono. However, everything are not roses. There are many incomplete libraries, incompatibilities, lack of documentation, and most of the examples such as doing SQL or SOAP do not work depending on which the library targets you are planning to code for. Therefore, I decided to test the basics on all the library targets. I am starting with DNX451.

Reflection seems to be working fine in DNX451 with C#. Below is a code example for those who wish to play with it.

ReflectionExample.cs

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1 {

	public class ReflectionExample {

		public ReflectionExample() {
			
			Console.WriteLine("ReflectionExample()");
			
			// Option 1
			Assembly assm = typeof(ReflectionExample).Assembly;
			Console.WriteLine("Assembly: {0}", assm);
			Console.WriteLine("Assembly Full Name: {0}", assm.FullName);
					
			// Option 2
			var asm = Assembly.GetExecutingAssembly();
			Console.WriteLine("Assembly Full Name: {0}", asm.FullName);
			
			// Getting info
			var asmTypes = asm.GetTypes();
			foreach (var type in asmTypes){
				Console.WriteLine("\tType: " + type.Name);
				
				var properties = type.GetProperties();
				foreach (var prop in properties){
					Console.WriteLine("\t\tProperty: " + prop.Name + " [Type: " + prop.PropertyType + "]");
				}
				
				var fields = type.GetFields();
				foreach (var f in fields){
					Console.WriteLine("\t\tField: " + f.Name);
				}
				
				var methods = type.GetMethods();
				foreach (var m in methods){
					Console.WriteLine("\t\tMethod: "+ m.Name);
				}
				
			}
			
			// Accessing to properties and methods
			var rs = new ReflectionSample() { Name = "Alejandro", Age = 35 };
			var rsType = typeof(ReflectionSample);

			var nameProperty = rsType.GetProperty("Name");
			Console.WriteLine("Property: " + nameProperty.GetValue(rs));

			var ms = rsType.GetMethod("MethodSample");
			ms.Invoke(rs, null);
					
			Console.WriteLine("Methods:");
			MethodInfo[] methodInfos = rsType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			Console.WriteLine("-> Number of methods: {0}", methodInfos.Length);
			foreach (MethodInfo mi in methodInfos){
				Console.WriteLine("\t-> Name: {0}", mi.Name);
				Console.WriteLine("\t - Number of parameters: {0}", mi.GetParameters().Length);
				if (mi.GetParameters().Length < 1){
					mi.Invoke(rs, null);
				}
				
			}	
			
			// Accessing attributes
			var types = asm.GetTypes().Where(t => t.GetCustomAttributes<ThisClassAttribute>().Count() > 0);
			foreach(var type in types){
				Console.WriteLine("\nClass with ThisClassAttribute: {0}", type.Name);
				
				var methods = type.GetMethods().Where(m => m.GetCustomAttributes<ThisMethodAttribute>().Count() > 0);
				foreach(var method in methods){
					Console.WriteLine("\t Method with ThisMethodAttribute: {0}", method.Name);
				}
			}		
		
		}
		
		[ThisClass]
		public class ReflectionSample{
			
			public string Name { get; set; }
			
			public int Age;
			
			[ThisMethod]
			public void MethodSample(){
				Console.WriteLine("MethodSample()\n\tRun...");
			}
			
			public void MethodSample2(){
				Console.WriteLine("MethodSample2()\n\tRun...");
			}
		}
		
		[AttributeUsage(AttributeTargets.Class)]
		public class ThisClassAttribute : Attribute { }
		
		[AttributeUsage(AttributeTargets.Method)]
		public class ThisMethodAttribute : Attribute { }
		
	}	
		
}

Since the output may varied depending on all the classes you may have in your project, I decided to not include to not include it]

 

Cite this article as: Alejandro G. Carlstein Ramos Mejia, "DNX: C#: Reflection," in Alejandro G. Carlstein Ramos Mejia Blog, August 31, 2015, http://www.acarlstein.com/?p=3155.
Share

DNX: C#: Serialization: Binary & SOAP Formatter

As you may know, Microsoft is getting into the open source community with the ASP.NET and DNX with the mono project.
The .NET Execution Environment (DNX) is a software development kit which allows you to run .NET applications on Windows, Mac, and Linux using different frameworks such as .NET framework, .NET Core, and Mono. However, everything are not roses. There are many incomplete libraries, incompatibilities, lack of documentation, and most of the examples such as doing SQL or SOAP do not work depending on which the library targets you are planning to code for. Therefore, I decided to test the basics on all the library targets. I am starting with DNX451.

Only binary serialization seems to be working in DNX451 with C#. SOAP serialization was not included in the library, I am assuming that such library is available for DNXCORE5.
Below is a code example for those who wish to play with it.

Program.cs

using System;

namespace ConsoleApp1 {
	
	public class Program {
		
		public void Main(string[] args){			
			Console.WriteLine("Main()");
			
			displayWhichDnxIsCompilingOn();
			
			serializationExample();
			
		}
		
		private void displayWhichDnxIsCompilingOn(){
			#if DNX451
			Console.WriteLine("Compiled on DNX451: .NET Framework");
			#endif
			
			#if DNXCORE50
			Console.WriteLine("Compiled on DNXCORE50: .NET Core 5");
			#endif						
		}
				
		private void serializationExample(){
			SerializationExample bse = new SerializationExample();						
		}
			
	}
	
}
SerializationExample.cs

using System;
using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

#if DNXCORE50
	// Assuming Soap formatter is available in DNXCORE50
	using System.Runtime.Serialization.Formatters.Soap;
#endif

using System.Runtime.Remoting.Messaging;

namespace ConsoleApp1 {

	class SerializationExample {
		
		public SerializationExample(){
			Console.WriteLine("SerializationExample()");
	
			ComputerModel[] computerModels = getComputerModels();		
			
			var filename = @"/Users/User/Documents/Projects/Visual Studio Projects/Examples/Serialization Example/computer.bin";		
			IRemotingFormatter formatter = new BinaryFormatter();
			saveComputerModelsInFile(filename, computerModels, formatter);
			displayComputerModelsFromFile(filename, formatter);
			
			// There is not SOAP formatter in DNX451 right now, so this code doesn't work.
			// This code need to be tested with DNXCORE50
			#if DNXCORE50
			filename = @"/Users/User/Documents/Projects/Visual Studio Projects/Examples/Serialization Example/computer.soap";
			formatter = new SoapFormatter();					
			saveComputerModelsInFile(filename, computerModels, formatter);
			displayComputerModelsFromFile(filename, formatter);
			#endif
		}
		
		private ComputerModel[] getComputerModels(){
			ComputerModel[] cm = {
				new ComputerModel(1, "MacBook Pro 6.1"),
				new ComputerModel(2, "MacMini")			
			};
			return cm;
		}
	
		private void saveComputerModelsInFile(String filename, ComputerModel[] computerModels, IRemotingFormatter usingFormatter){
			FileStream fs = new FileStream(filename, FileMode.Create);						
			usingFormatter.Serialize(fs, computerModels); 		
			fs.Close();
		}
		
		private void displayComputerModelsFromFile(String filename, IRemotingFormatter usingFormatter){
			
			FileStream fs = new FileStream(filename, FileMode.Open);
			
			ComputerModel[] serializedData = (ComputerModel[]) usingFormatter.Deserialize(fs);
			
			fs.Close();
			
			foreach (ComputerModel cm in serializedData){
				Console.WriteLine("Description: " + cm.description);
			}
		}
		
	}

}

 

 ComputerModel.cs

using System;

[Serializable]
public class ComputerModel {
	
	private int _id;
	private string _description;
	
	public int id {
		get { return _id; }
		set { _id = value; }		
	}
	
	public string description {
		get { return _description; }
		set { _description = value; }
	}
	
	public ComputerModel(){}
	
	public ComputerModel(int id, string description){
		_id = id;
		_description = description;
	}
}


 Output file: computer.bin

 

Cite this article as: Alejandro G. Carlstein Ramos Mejia, "DNX: C#: Serialization: Binary & SOAP Formatter," in Alejandro G. Carlstein Ramos Mejia Blog, August 31, 2015, http://www.acarlstein.com/?p=3149.
Share