Search

Get UnCached version form Ajax file request

While loading external javascript there is problem of caching the general solutionfor this is appending a url parameter like "?rnd=Date.Now()" at the end of the url, so that the url is always unique while making the call. The other way around is to set the IIS ouput caching with FIle change notifications. But the same could be achieve without much effort by setting the response header. We can set the response header to get the modified version from the server instead of the cached one using the following script:
/* Ajax with Un Cached output in MSCRM 4 */
function _LoadIsvScript(execute) {
var JsScriptUrl = "/ISV/customscript.js";
var strServerURL = SERVER_URL.split(ORG_UNIQUE_NAME);
var script_uri = strServerURL[0] + JsScriptUrl;
var ajax = new ActiveXObject("Msxml2.XMLHTTP");
ajax.open('GET', script_uri, false);
//GetUnCachedVersion
ajax.setRequestHeader("If-Modified-Since", "Sat, 01 Jan 2000 00:00:00 GMT");
ajax.setRequestHeader('Cache-Control', 'no-cache');
ajax.send('');
return ajax.responseText;
}

How to define a class in JScript ?

This a common example for JScript(ECMA262) to create a class with defined constructor. The constructor can be parameteries to accent a/multiple parameter.

/* Jscript */
/* Class in JavaScript */
var ClassName = (function () {
// Constructor
function ClassName(message) {
this.variable1 = message;
}
// Method
ClassName.prototype.Greeting = function () {
return "Hello, " + this.variable1;
};
return ClassName;
})();
/* Once a class is created we can define multiple instance of it and use it to called the defined method.*/
// this creates an instance of class and assigns it to greeter.
var g1 = new ClassName("world");
//this calls the greet function
g1.Greeting();

Wiindows Search with batch script

Till last year i was using Windows XP which was quite faster then windows 7 on searching files in the local system. But again windows 7 started giving me hard-time with it’s indexing services. So i started using the old batch script i wrote in the late 90’s. Its’s called windows search.
@Echo off
cls
@echo --==:{[ WINDOWS SEARCH ]}:==--
@Echo Searching... [%1]
dir/b/s %1>search.txt
@echo SearchCompleted: This will open a text file with results
msg "SearchCompleted: This will open a text file with results"
start notepad search.txt


All you have to do, is to copy and save this file as "search.bat" in the user folder(c:\users\).

calling it is even easier cause it supports wildcard(*) characters.

Example:
search *.txt

will search the whole directory for the files with text extension, the query can be modified if you know a part of the file name as
search read*.txt

After pressing enter.. it takes a while and pops up a message window(with instructions), clicking ok in the message window will open notepad with a file search.txt with all the results.

Recycling IIS Application Pools

Recycling IIS app pool are always considered a better option then IISReset to refresh & purge resources. As it Before recycling itself , it invokes a new worker process first and then shutdown the old worker process which makes the IIS still available to take request. Here is the appcmd to recycle appool

%windir%\system32\inetsrv\appcmd recycle apppool /apppool.name:<app pool name>

for Example:

To reset the CRMAppPool( Crm developers know why ;)

%windir%\system32\inetsrv\appcmd recycle apppool /apppool.name:CRMAppPool

will recycle the apppool named "CRMAppPool”.

Web.Config Guide

Important Configuration Tags

There are a lot of configuration tags that are provided by the web.config file, like authentication, authorization, browserCaps, clientTarget etc., but all of these don't have that much importance (and also can't be covered in a single article ), so here, I have only concentrated on the main tags of the config file.

<authentication>

This element is used to verify the client's identity when the client requests a page from the server. This is set at the application level. We have four types of authentication modes: “None”, “Windows”, “Forms”, and “Passport”.
If we don't need any authentication, this is the setting we use:
<authentication mode="None"/>
Normally, Windows authentication is used, for which, we need to check the checkbox: Integrated Windows Authentication.
<authentication mode="Windows"/>
This authentication is handled by IIS. When the user sends a request to the server, IIS authenticates it and sends the authentication identity to the code.
IIS gives us four choices for the authentication modes: Anonymous, Basic, Digest, and Windows Integrated. If the user selects Anonymous, then IIS doesn't perform any authentication. For Basic authentication, the user has to provide a username and password. This authentication is very unsecure, because the user credentials are sent in clear text format over the network. Digest authentication is same as Basic, except it hashes the user's password and transmits the hashed version over the wire. So, it is more secure than Basic. For Windows Integrated authentication, passwords never cross the network. The user must still have a username and password, but the application uses either the Kerberos or a challenge/response protocol to authenticate the user.
Forms authentication uses web application forms to collect user credentials, and on the basis of the credential, it takes action on a web application.
<authentication mode="Forms">
<forms name="Form" loginUrl="index.asp" />
</authentication>
Passport authentication is provided by Microsoft. A redirect URL should be specified, and is used when the requested page is not authenticated, and then it redirects to this URL.
<authentication mode="Passport">
<passport redirectUrl="internal" />
</authentication>
Here, users are authenticated using the information in Microsoft's Passport database. The advantage is, we can use existing user credentials (such as an email address and password) without forcing users to go through a separate registration process. The disadvantage is we need to go through the licensing agreement with Microsoft and pay a yearly fee based on the use.
For using Passport authentication, you first install the Passport Software Development Kit (SDK) on your server. The SDK can be downloaded from here. It includes full details of implementing passport authentication in your own applications.
 

<authorization>

The <authorization> tag controls client access to web page resources. This element can be declared at any level (machine, site, application, subdirectory, or page).
<authorization>
<allow users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
<deny users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
</authorization>
<allow> : Using this tag, we can control access to resources on the basis of the following verbs. In these attributes, we use symbols: ? and *.? means for anonymous users/resources, and * means for all users.
  • users: This contains the list of user names (comma separated) that are allowed to access the resources.
  • roles: This contains the list of roles (comma separated) that are allowed to access the resources.
  • verbs: This contains the list of HTTP verbs to which the action applies (comma separated). It is used to create a rule that applies to a specific type of HTTP request (GET, POST, HEAD, OR DEBUG).
<deny> : Using this tag, we can control access to resources on the basis of the following verbs:
  • users: This contains the list of users names (comma separated) that are denied access to the resources.
  • roles: This contains the list of roles (comma separated) that are denied access to the resources.
  • verbs: This contains the list of HTTP verbs to which the action applies (comma separated). It is used to create a rule that applies to a specific type of HTTP request (GET, POST, HEAD, OR DEBUG).

<compilation>

In this section, we can configure the settings of the compiler. Here, we can have lots of attributes, but the most common ones are debug and defaultLanguage. Setting debug to true means we want the debugging information in the browser, but it has a performance tradeoff, so normally, it is set as false. And, defaultLanguage tells ASP.NET which language compiler to use: VB or C#.
 

<customErrors>

This tags includes the error settings for the application, and is used to give custom error pages (user-friendly error pages) to end users. In the case that an error occurs, the website is redirected to the default URL. For enabling and disabling custom errors, we need to specify the mode attribute.
<customErrors defaultRedirect="url" mode="Off">
<error statusCode="403" redirect="/accesdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
</customErrors>
  • "On" means this settings is on, and if there is any error, the website is redirected to the default URL.
  • "Off" means the custom errors are disabled.
  • "RemoteOnly" shows that custom errors will be shown to remote clients only.
<error statusCode="403" redirect="/accesdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
This means if there is an error of 403, then the website will redirected to the custom page accessdenied.html. Similarly for 404 as defined above.
Note: If an error occurs in the custom error page itself, ASP.NET won't able to handle it. It won't try to reforward the user to the same page. Instead, it'll show the normal default client error page with a generic message.
 

<globalization>

This section is used when we want to use encoding or specify a culture for the application. This is a very vast topic, and can take an article itself for explaining it. Here, we define the character set for the server to send the response to the client, which is by default is UTF-8, and the settings of which the server should use to interpret and display culturally specific strings, such as numbers and dates.
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
 

<httpRuntime>

This section can be used to configure the general runtime settings of the application. The main two are:
<httpRuntime appRequestQueueLimit="50" executionTimeout="300" />
As the name suggests, the attribute appRequestQueueLimit defines the number of requests that can be queued up on the server for processing. If there are 51 or more requests, then server would return the 503 error ("Server too busy").
The attribute executionTimeout defines the number of minutes ASP.NET will process a request before it gets timeout.
 

<trace>

As the name suggestz, it is used for tracing the execution of an application. We have here two levels of tracing: page level and application level. Application level enables the trace log of the execution of every page available in the application. IfpageOutput="true", trace information will be displayed at the bottom of each page. Else, we can view the trace log in the application root folder, under the name trace.axd.
<trace enabled="false" requestLimit="10" pageOutput="false"
traceMode="SortByTime" locaOnly="true" />
Set the attribute localOnly to false for not viewing the trace information from the client.
For enabling trace at page level, set Trace="True" in the Page tag (on the top of the page).
 

<identity>

Using this tag, we can control the identity of the application. By default, Impersonation is disabled. Using Impersonation, an ASP.NET application can execute optionally with the identity of a client on whose behalf they are operating.
<identity impersonate="false" userName="domain\username" password="password" />
 

<sessionState>

In this section, we tell ASP.NET where to store the session. By default, it's inproc which means storing the session values on the server. But we have four options:
  • "Off" means session is not enabled for the application.
  • "inproc" means storing the session values on the server.
  • "StateServer" means session states are stored in a remote server.
  • "SQLServer" means session states are stored in a SQL Server database. For this, we need to install the InstallSQLState.sql script in the SQL Server database. It is mainly used when the we use web farms (an application deployed on multiple servers), but it makes the performance slow as compared to "inproc".
Here are the other settings:
  • "cookieless": when it is true, it means the session used is without cookies.
  • “timeout” specifies after how much time the session would expire if the application is not accessed during that period.
  • "stateConnectionString" needs to be specified when the session mode is StateServer.
  • "sqlConnectionString" is the connection string of the SQL Server database if the session mode is sqlserver.
  • "stateNetworkTimeout" attribute, when using the StateServer mode to store session state, specifies the number of seconds the TCP/IP network connection between the web server and the state server can be idle before the session is abandoned. The default is 10.
<sessionState mode="Off"
cookieless="true"
timeout="100"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>
 

<appSettings>

This section is used to store custom application configuration like database connection strings, file paths etc. This also can be used for custom application-wide constants to store information over multiple pages. It is based on the requirements of the application.
<appSettings>
<add key="Emailto" value="me@microsoft.com" />
<add key="cssFile" value="CSS/text.css" />
</appSettings>
It can be accessed from code like:
ConfigurationSettings.AppSettings("Emailto");


Reflector - C# reflection over console

A custom C# reflection over console

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace killercodes_in
{
class Reflector
{
const string usage = "prints assembly reflection information over console. \nUsage: Reflector [assmblyName] ...";
static public void Main(string[] args)
{
if ((args.Length == 1 &amp;&amp; (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
{
Console.WriteLine(usage);
}
else
{
Assembly assembly = Assembly.LoadFrom(args[0]);
Reflect(assembly);
String xml = ReflectXml(assembly);
//Console.Write(xml);
}
}
/// Exports the reflection information as XML
static String ReflectXml(Assembly assembly)
{
StringBuilder xmlDoc = new StringBuilder();
Func&lt;string, string, string&gt; tagIt = (tag, value) =&gt;
{
return string.Format("&lt;{0}&gt;{1}&lt;/{0}&gt;", tag, value);
};
xmlDoc.AppendLine(tagIt("assembly", assembly.FullName));
foreach (string s in assembly.GetManifestResourceNames())
{
xmlDoc.AppendLine(tagIt("resource", s));
}
foreach (AssemblyName a in assembly.GetReferencedAssemblies())
{
xmlDoc.AppendLine(tagIt("references", a.Name));
}
foreach (Module m in assembly.GetModules())
{
xmlDoc.AppendLine(tagIt("module", m.Name));
foreach (Type t in m.GetTypes())
{
xmlDoc.AppendLine(tagIt("class", t.Name));
foreach (MethodInfo mtd in t.GetMethods())
{
StringBuilder parameters = new StringBuilder();
foreach (ParameterInfo pra in mtd.GetParameters())
{
if (mtd.GetParameters().Count() == 1)
parameters.Append(pra.ParameterType);
else
parameters.Append(pra.ParameterType + ",");
}
xmlDoc.AppendLine(tagIt(mtd.MemberType.ToString(), (String.Format("{0} {1}({2}) ", mtd.ReturnParameter.ParameterType.Name, mtd.Name, parameters.ToString()))));
}
}
}
return xmlDoc.ToString();
}
//Prints the Reflection information which includes class, method &amp; parameters
static void Reflect(Assembly assembly)
{
Printer(" Assembly: " + assembly.FullName + "/" + assembly.GetName() + "/" + assembly.EntryPoint);
foreach (string s in assembly.GetManifestResourceNames())
{
Printer(" Resource: " + s);
}
foreach (AssemblyName a in assembly.GetReferencedAssemblies())
{
Printer(" ReferencedAssembly: " + a.Name);
}
foreach (Module m in assembly.GetModules())
{
Printer(" Module: " + m);
foreach (Type t in m.GetTypes())
{
Printer(" Class: " + t);
foreach (MethodInfo mtd in t.GetMethods())
{
StringBuilder parameters = new StringBuilder();
foreach (ParameterInfo pra in mtd.GetParameters())
{
if (mtd.GetParameters().Count() == 1)
parameters.Append(pra.ParameterType);
else
parameters.Append(pra.ParameterType + ",");
}
PrintMethod(String.Format(" {0}:{1} {2}({3}) ", mtd.MemberType, mtd.ReturnParameter.ParameterType.Name, mtd.Name, parameters.ToString()));
}
}
}
}
private static void Printer(String message)
{
String[] print = message.Split(':');
if (print.Count() &gt; 1)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(print[0] + ":");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(print[1]);
}
else
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(message);
}
}
private static void PrintMethod(String message)
{
String[] print = message.Split(':');
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(print[0] + ": ");
String[] returnType = print[1].Split(' ');
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write(returnType[0] + " ");
Console.ForegroundColor = ConsoleColor.Magenta;
string[] para = (returnType[1]).Split('(');
Console.Write(para[0]);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("(" + para[1]);
}
}
}
view raw Reflector.cs hosted with ❤ by GitHub

Syntax highlight using RichTextBox

This example uses the RegEx to search the keywords and highlight them with different color

//Synatx Highlight inside Rich Text box
private void HighLightSyntax()
{
//rtbCommand.Enabled = false;
//rtbCommand.ReadOnly = true;
//rtbCommand.Cursor = Cursors.No;
rtbCommand.BorderStyle = BorderStyle.None;
//Add RichTextBox
// private System.Windows.Forms.RichTextBox rtbCommand;
//define the JScript keywords
string jSkeywords = "abstract|arguments|boolean|break|byte";
jSkeywords = jSkeywords.Replace("|", "\\b|\\b");
// create regular Expression
Regex regExp = new Regex( "\\b" +jSkeywords + "\\b",
RegexOptions.Compiled | RegexOptions.Multiline);
//find all the matches in match collection
MatchCollection _matches = regExp.Matches(rtbCommand.Text);
// process all the matched keywords
foreach (Match match in _matches)
{
rtbCommand.Select(match.Index, match.Length);
rtbCommand.SelectionColor = Color.Red;
//de-select word and move cursor to the end
rtbCommand.DeselectAll();
rtbCommand.SelectionStart = rtbCommand.Text.Length;
}
}
/*It can be called onKeyUp event like
if(e.KeyCode == Keys.Enter)
{
HighLightSyntax();
}*/

Referencing DLL from GAC in Visual Studio

Long back i wrote about it http://www.killercodes.in/2010/09/how-to-reference-assemblies-in-gac.html but this requires some registry editing and generally developers don't have privileges to do that in the production system. I too face the similar issue and i found that the GAC for .Net framework resides at

"C:\Windows\assembly\"
. So the first thing is to put your DLL there. Then

  • GoTo Projects --> Properties

  • Click Reference Path and browse the GAC folder(for 3.5 it's "C:\Windows\assembly\")


Now remove any of the local references that can conflict with the GAC version of DLL and Buld.

Why it works beacuse during the build Visaul studio will try to resolve the references and since we have specified a reference path to the Framework 3.5 GAC folder, it will resolve the reference by taking it from the GAC folder and since the folder structure remains same across windows system there will be no errors.



although i have tested it with framework 3.5 but it will work with any other framwork also.
..keep coding

Logging JScript Errors to windows event log

Writing Jscript is a tough task, there were no errors if the data is well structured, but somtimes i wish to log all those information & exception in some place to review/analyse. Yes we can log all them in browser event log, but that is temprorary and will be all gone when the window is closed. Still there is something that you can do with Windows Event Logger. Here is a small script that uses activeXObject to write the log to eventviewer. Later you can view the log by running "eventvwer" in the cmd prompt.


/* Jscript - event logger */
// Creates a Eventlog object
function EvntLog(){
this.about = "This will log all the messages to system event log on a IE browser";
}
// adds functions to it
EvntLog.prototype = {
Error:function(ErrorMsg){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(1,Error);
},
Success:function(SuccessMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(0,Message);
},
Warn:function(WarningMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(2,Message);
},
Info:function(InformationMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(4,Information);
},
AuditSuccess:function(AuditSuccessMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(8,Message);
},
AuditFailure:function(AuditFailureMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(16,Message);
}
}

And this is how you can call it:
 
// Calling the log to write error
EvntLog.Err("error in script");

Note: Due to inconsistent ActiveX use, it works only with InternetExplorer browser family :(
..keep coding

Creating a System Restore point using VBScript

Create a VBScript file (*.vbs) and paste the below code, it will create a system Restore point.


' Create a System Restore Point
' supported on: Windows XP

dim spi
Set spi = Createobject("sapi.spvoice")
spi.speak "Well come napstr"
spi.speak "Initialising Automated Restore"
Const DEVICE_DRIVER_INSTALL = 10
Const BEGIN_SYSTEM_CHANGE = 100

strComputer = "."
Set objWMI = GetObject("winmgmts:" _
& "\\" & strComputer & "\root\default")

Set objItem = objWMI.Get("SystemRestore")
errResults = objItem.CreateRestorePoint _
("AUTOMATED NAPSTR RESTORE", DEVICE_DRIVER_INSTALL, BEGIN_SYSTEM_CHANGE)

spi.speak "Automated Restore point Created"

Kill a process using c#

The following class is a process manager, that helps to find and kill process with Id or name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace killercodes_in.ProcKiller
{
//Process Killer
class IProcKiller
{
public void I_KillByName(string ProcName)
{
try
{
Process[] processByName = Process.GetProcessesByName(ProcName);
//Process pogo = Process.GetProcesses();
foreach (Process pr in processByName)
{
pr.Kill();
}
}
catch
{
Console.WriteLine("Cannot terminate " + ProcName + "\n");
}
}
public void I_KillByWinName(string WindowName)
{
//bool res;
try
{
Process[] pro = Process.GetProcesses();
foreach (Process p in pro)
{
if (p.MainWindowTitle.Equals(WindowName))
{
p.Kill();;
}
else
{
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Cannot terminate " + WindowName + "\n Process Not found", "Erraor:");
}
//return true;
}
}
}

HttpWebRequest example with error handling using C#

This is an example of simple HttpWebRequest with error handling module
using System;
using System.IO;
using System.Net;
using System.Text;
public class HttpWebRequestTool
{
public static void Main(String[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Missing argument. Need a URL and a filename");
}
else
{
StreamWriter sWriter = new StreamWriter(args[1]);
sWriter.Write(WRequest(args[0], "GET", ""));
sWriter.Close();
}
}
public static string WRequest(string URL, string method, string postData)
{
string responseData = "";
try
{
System.Net.HttpWebRequest hwrequest =
(System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
hwrequest.Accept = "*/*";
hwrequest.AllowAutoRedirect = true;
hwrequest.UserAgent = "http_requester/0.1";
hwrequest.Timeout= 60000;
hwrequest.Method = method;
if (hwrequest.Method == "POST")
{
hwrequest.ContentType = "application/x-www-form-urlencoded";
// Use UTF8Encoding instead of ASCIIEncoding for XML requests:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] postByteArray = encoding.GetBytes(postData);
hwrequest.ContentLength = postByteArray.Length;
System.IO.Stream postStream = hwrequest.GetRequestStream();
postStream.Write(postByteArray, 0, postByteArray.Length);
postStream.Close();
}
System.Net.HttpWebResponse hwresponse =
(System.Net.HttpWebResponse) hwrequest.GetResponse();
if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
{
System.IO.Stream responseStream = hwresponse.GetResponseStream();
System.IO.StreamReader myStreamReader =
new System.IO.StreamReader(responseStream);
responseData = myStreamReader.ReadToEnd();
}
hwresponse.Close();
}
catch (Exception e)
{
responseData = "An error occurred: " + e.Message;
}
return responseData;
}
}

Matrix falling number - animation

This will create the green matrix falling numbers animation in a c# console with green text

using System;
namespace Killercodes.matrix
{
class Program
{
static int Counter;
static Random rand = new Random();
static int Interval = 100; // Normal Flowing of Matrix Rain
static int FullFlow = Interval + 30; // Fast Flowing of Matrix Rain
static int Blacking = FullFlow + 50; // Displaying the Test Alone
static ConsoleColor NormalColor = ConsoleColor.DarkGreen;
static ConsoleColor GlowColor = ConsoleColor.Green;
static ConsoleColor FancyColor = ConsoleColor.White;
//static String TextInput = "Matrix";
static char AsciiCharacter//Randomised Inputs
{
get
{
int t = rand.Next(10);
if (t <= 2)
return (char)('0' + rand.Next(10));
else if (t <= 4)
return (char)('a' + rand.Next(27));
else if (t <= 6)
return (char)('A' + rand.Next(27));
else
return (char)(rand.Next(32, 255));
}
}
static void Main()
{
Console.ForegroundColor = NormalColor;
Console.WindowLeft = Console.WindowTop = 0;
Console.WindowHeight = Console.BufferHeight = Console.LargestWindowHeight;
Console.WindowWidth = Console.BufferWidth = Console.LargestWindowWidth;
Console.SetWindowPosition(0, 0);
Console.CursorVisible = false;
int width, height;
int[] y;
Initialize(out width, out height, out y);//Setting the Starting Point
while (true)
{
Counter = Counter + 1;
UpdateAllColumns(width, height, y);
if (Counter > (3 * Interval))
Counter = 0;
}
}
private static void UpdateAllColumns(int width, int height, int[] y)
{
int x;
if (Counter < Interval)
{
for (x = 0; x < width; ++x)
{
if (x % 10 == 1)//Randomly setting up the White Position
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = GlowColor;
Console.SetCursorPosition(x, y[x]);
Console.Write(AsciiCharacter);
if (x % 10 == 9)
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = NormalColor;
int temp = y[x] - 2;
Console.SetCursorPosition(x, inScreenYPosition(temp, height));
Console.Write(AsciiCharacter);
int temp1 = y[x] - 20;
Console.SetCursorPosition(x, inScreenYPosition(temp1, height));
Console.Write(' ');
y[x] = inScreenYPosition(y[x] + 1, height);
}
}
else if (Counter > Interval && Counter < FullFlow)
{
for (x = 0; x < width; ++x)
{
Console.SetCursorPosition(x, y[x]);
if (x % 10 == 9)
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = NormalColor;
Console.Write(AsciiCharacter);//Printing the Character Always at Fixed position
y[x] = inScreenYPosition(y[x] + 1, height);
}
}
else if (Counter > FullFlow)
{
for (x = 0; x < width; ++x)
{
Console.SetCursorPosition(x, y[x]);
Console.Write(' ');//Slowly blacking out the Screen
int temp1 = y[x] - 20;
Console.SetCursorPosition(x, inScreenYPosition(temp1, height));
Console.Write(' ');
if (Counter > FullFlow && Counter < Blacking)// Clearing the Entire screen to get the Darkness
{
if (x % 10 == 9)
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = NormalColor;
int temp = y[x] - 2;
Console.SetCursorPosition(x, inScreenYPosition(temp, height));
Console.Write(AsciiCharacter);//The Text is printed Always
}
Console.SetCursorPosition(width / 2, height / 2);
//Console.Write(TextInput);
y[x] = inScreenYPosition(y[x] + 1, height);
}
}
}
public static int inScreenYPosition(int yPosition, int height)
{
if (yPosition < 0)//When there is negative value
return yPosition + height;
else if (yPosition < height)//Normal
return yPosition;
else// When y goes out of screen when autoincremented by 1
return 0;
}
private static void Initialize(out int width, out int height, out int[] y)
{
height = Console.WindowHeight;
width = Console.WindowWidth - 1;
y = new int[width];
Console.Clear();
for (int x = 0; x < width; ++x)//Setting the cursor at random at program startup
{
y[x] = rand.Next(height);
}
}
}
}

Clock application with hourly beeping function



//this is a clock application with infinite-loop and hourly beeping function
while(start)
{
DateTime dtn = DateTime.Now;
if (dtn.Minute == 59 && dtn.Second == 59)
{
Console.Beep(5500, 250);
Console.Beep(3500, 250);
Console.Beep(5500, 250);
}
else if (dtn.Minute == 30 && dtn.Second == 59)
{
Console.Beep(5500, 250);
}
}




Transforming XML to HTML on the fly

Here is the simple source code needed transform the XML file to HTML on the client (try it yourself):

<html>
<body>
<script language="javascript">

xml.async = false
xml.load("cd_catalog.xml")

// Load the XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load("cd_catalog.xsl")

// Transform
document.write(xml.transformNode(xsl));

</script>

</body>
</html>

Using window.console in JScript

just to log messages in browser console, the console must be visible, the below function is a foolproof way to implement it, regardless of the browser.
 
/* Jscript */
//console
(function() {
if (!window.console) {
window.console = {};
}
// union of Chrome, FF, IE, and Safari console methods
var m = [
"log", "info", "warn", "error", "debug", "trace", "dir", "group",
"groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
"dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
];
// define undefined methods as noops to prevent errors
for (var i = 0; i < m.length; i++) {
if (!window.console[m[i]]) {
window.console[m[i]] = function() {};
}
}
})();


now in you can write anywhere
 window.console.warn(" this is warning");

to print in the console, this is quite useful with the old IE browsers.

Redirecting errors to Errors.aspx page

Although everyone wants to code bugfree, but exception are generated with the change of environment. Here is a sample as how to setup an error.aspx to

// This is the error page looking for message & stack over the http context
public partial class Errors : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.Items.Contains("Title") && !HttpContext.Current.Items.Contains("Message"))
{
Response.Redirect("/");
}
else
{
//these can me a string literal or asp.net label
msgtitle.Text = "<br/><span class='mtitle'>" + (String)HttpContext.Current.Items["Title"] + "</span><br/>";
msgcontent.Text = "<span class='mcontent'>" + (String)HttpContext.Current.Items["Message"] + "<span/>";
msgStack.Text = "<b>Stack:</b><br/>" + (String) HttpContext.Current.Items["Stack"];
}
}
}



according to MSDN.. Server.Transfer acts as an efficient replacement for the Response.Redirect method. Response.Redirect specifies to the browser to request a different page. Because a redirect forces a new page request, the browser makes two requests to the Web server, so the Web server handles an extra request. IIS 5.0 introduced a new function, Server.Transfer, which transfers execution to a different ASP page on the server. This avoids the extra request, resulting in better overall system performance, as well as a better user experience.

so we aregoing to use it to throw the error, you can make use of this action delegate in every page to throw the exception


// setup for error message for other page -pass the title/message to the error page
Action RedirectError = (title, message,stack) =>
{
//adds the title,message & stack from the passed parameter to the HttpContext
HttpContext.Current.Items.Add("Title", title);
HttpContext.Current.Items.Add("Message",message);
// adds the stacktrace to httpcontext if it's not null
if(stack != null)
HttpContext.Current.Items.Add("Stack", stack);

//transfers the execution to a different aspx page
Server.Transfer("Errors.aspx");
};




Serialize/ De-Serialize

Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called de-serialization.
It allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
    /// 
    /// Serializes an Object
    /// 
    /// Object to SerializedObject
    /// serialized string(xml)
    public string SerializeObject(Object objectInstance)
    {
        System.IO.StringWriter stringwriter = new System.IO.StringWriter();
        System.Xml.Serialization.XmlSerializer serilizer = new System.Xml.Serialization.XmlSerializer(objectInstance.GetType());
        serilizer.Serialize(stringwriter, objectInstance);
        return stringwriter.ToString();
    }
To de-serialize it back to the object,
    /// 
    /// De-Serializes an Object
    /// 
    /// serialized string(xml)
    /// 
    public Object DeSerializeObject(string serializedObject)
    {
        var stringReader = new System.IO.StringReader(serializedObject);
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Object));
        return serializer.Deserialize(stringReader) as Object;
    }

FeedForwardProgram Neural Network Demo

public class NeuralNetwork
{
public delegate void PrintEventHandler(object message);
public event PrintEventHandler Cout;
private int numInput;
private int numHidden;
private int numOutput;
private double[] inputs;
private double[][] ihWeights; // input-to-hidden
private double[] ihBiases;
private double[][] hoWeights; // hidden-to-output
private double[] hoBiases;
private double[] outputs;
public void SelfDemo()
{
try
{
Console.WriteLine("\nBegin neural network feed-forward demo\n");
Console.WriteLine("Creating a 3-input, 4-hidden, 2-output neural network");
Console.WriteLine("Using log-sigmoid function for input-to-hidden and hidden-to-output activation");
const int numInput = 3;
const int numHidden = 4;
const int numOutput = 2;
NeuralNetwork nn = new NeuralNetwork(numInput, numHidden, numOutput);
nn.Cout += message => Console.Write("{0}", message);
const int numWeights = (numInput * numHidden) + (numHidden * numOutput) + numHidden + numOutput; // (3*4)+(4*2)+4+2 = 26
double[] weights = new double[numWeights] {
0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2,
-2.0, -6.0, -1.0, -7.0,
1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0,
-2.5, -5.0 };
Console.WriteLine("\nWeights and biases are:");
nn.ShowVector(weights, 2);
Console.WriteLine("Loading neural network weights and biases");
nn.SetWeights(weights);
Console.WriteLine("\nSetting neural network inputs:");
double[] xValues = new double[] { 2.0, 3.0, 4.0 };
nn.ShowVector(xValues, 2);
Console.WriteLine("Loading inputs and computing outputs\n");
double[] yValues = nn.ComputeOutputs(xValues);
Console.WriteLine("\nNeural network outputs are:");
nn.ShowVector(yValues, 4);
Console.WriteLine("\nEnd neural network demo\n");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
Console.ReadLine();
}
public void Write(string format, object[] args)
{
string message = string.Format(format, args);
if (this.Cout != null)
{
this.Cout(message);
}
}
public void Write(string message)
{
if (this.Cout != null)
{
this.Cout(message);
}
}
public NeuralNetwork(int numInput, int numHidden, int numOutput)
{
this.numInput = numInput;
this.numHidden = numHidden;
this.numOutput = numOutput;
inputs = new double[numInput];
ihWeights = MakeMatrix(numInput, numHidden);
ihBiases = new double[numHidden];
hoWeights = MakeMatrix(numHidden, numOutput);
hoBiases = new double[numOutput];
outputs = new double[numOutput]; // aka hoOutputs
}
/*public int numWeights()
{
int numWeights = (numInput * numHidden) + (numHidden * numOutput) + numHidden + numOutput; // (3*4)+(4*2)+4+2 = 26
return numWeights;
}*/
private static double[][] MakeMatrix(int rows, int cols)
{
double[][] result = new double[rows][];
for (int i = 0; i < rows; ++i)
result[i] = new double[cols];
return result;
}
public void SetWeights(double[] weights)
{
// order: ihWeights (row-col order), ihBiases, hoWeights, hoBiases
int numWeights = (numInput * numHidden) + (numHidden * numOutput) + numHidden + numOutput;
if (weights.Length != numWeights)
throw new Exception("The weights array length: " + weights.Length + " does not match the total number of weights and biases: " + numWeights);
int k = 0; // points into weights param
for (int i = 0; i < numInput; ++i)
for (int j = 0; j < numHidden; ++j)
ihWeights[i][j] = weights[k++];
for (int i = 0; i < numHidden; ++i)
ihBiases[i] = weights[k++];
for (int i = 0; i < numHidden; ++i)
for (int j = 0; j < numOutput; ++j)
hoWeights[i][j] = weights[k++];
for (int i = 0; i < numOutput; ++i)
hoBiases[i] = weights[k++];
}
public void ShowMatrix(double[][] matrix, int numRows)
{
Write("\n");
int ct = 0;
if (numRows == -1) numRows = int.MaxValue; // if numRows == -1, show all rows
for (int i = 0; i < matrix.Length && ct < numRows; ++i)
{
for (int j = 0; j < matrix[0].Length; ++j)
{
if (matrix[i][j] >= 0.0) Write(" "); // blank space instead of '+' sign
Write(matrix[i][j].ToString("F2") + " ");
}
Write("\n");
++ct;
}
Write("\n");
}
public void ShowVector(double[] vector, int decimals)
{
Write("\n");
for (int i = 0; i < vector.Length; ++i)
{
if (i > 0 && i % 12 == 0) // max of 12 values per row
Write("\n");
if (vector[i] >= 0.0) Console.Write(" ");
Write(vector[i].ToString("F" + decimals) + " "); // 2 decimals
}
Console.WriteLine("\n");
}
public double[] ComputeOutputs(double[] xValues)
{
if (xValues.Length != numInput)
throw new Exception("Inputs array length " + inputs.Length + " does not match NN numInput value " + numInput);
double[] ihSums = new double[this.numHidden]; // these scratch arrays could be class members
double[] ihOutputs = new double[this.numHidden];
double[] hoSums = new double[this.numOutput];
for (int i = 0; i < xValues.Length; ++i) // copy x-values to inputs
this.inputs[i] = xValues[i];
//Console.WriteLine("Inputs:");
//FeedForwardProgram.ShowVector(this.inputs, 2);
Write("input-to-hidden weights:");
ShowMatrix(this.ihWeights, -1);
for (int j = 0; j < numHidden; ++j) // compute input-to-hidden weighted sums
for (int i = 0; i < numInput; ++i)
ihSums[j] += this.inputs[i] * ihWeights[i][j];
Write("input-to-hidden sums before adding i-h biases:");
ShowVector(ihSums, 2);
Write("input-to-hidden biases:");
ShowVector(this.ihBiases, 2);
for (int i = 0; i < numHidden; ++i) // add biases to input-to-hidden sums
ihSums[i] += ihBiases[i];
Write("input-to-hidden sums after adding i-h biases:");
ShowVector(ihSums, 2);
for (int i = 0; i < numHidden; ++i) // determine input-to-hidden output
ihOutputs[i] = LogSigmoid(ihSums[i]);
Write("input-to-hidden outputs after log-sigmoid activation:");
ShowVector(ihOutputs, 2);
Console.WriteLine("hidden-to-output weights:");
ShowMatrix(hoWeights, -1);
for (int j = 0; j < numOutput; ++j) // compute hidden-to-output weighted sums
for (int i = 0; i < numHidden; ++i)
hoSums[j] += ihOutputs[i] * hoWeights[i][j];
Write("hidden-to-output sums before adding h-o biases:");
ShowVector(hoSums, 2);
Write("hidden-to-output biases:");
ShowVector(this.hoBiases, 2);
for (int i = 0; i < numOutput; ++i) // add biases to input-to-hidden sums
hoSums[i] += hoBiases[i];
Write("hidden-to-output sums after adding h-o biases:");
ShowVector(hoSums, 2);
for (int i = 0; i < numOutput; ++i) // determine hidden-to-output result
this.outputs[i] = LogSigmoid(hoSums[i]);
double[] result = new double[numOutput]; // copy hidden-to-output to this.outputs
this.outputs.CopyTo(result, 0);
return result;
} // ComputeOutputs
private static double LogSigmoid(double z)
{
if (z < -20.0) return 0.0;
else if (z > 20.0) return 1.0;
else return 1.0 / (1.0 + Math.Exp(-z));
}
//extend
private static int CalculateWeight(int inputNodeCount, int hiddenNodeCount, int outputNodeCount)
{
int numWeights = (inputNodeCount * hiddenNodeCount) + (hiddenNodeCount * outputNodeCount) + hiddenNodeCount + outputNodeCount; //count the total weights
return numWeights;
}
} // class

Generating class through C# code




namespace killercodes_in.CodeGeneration
{
public class GenerateClass
{
public void Generate()
{
//output file name
string fileName = "HelloWorld.cs";

//text writer to write the code
TextWriter tw = new StreamWriter(new FileStream(fileName, FileMode.Create));

//code generator and code provider
ICodeGenerator codeGenerator = new CSharpCodeProvider().CreateGenerator();
CSharpCodeProvider cdp = new CSharpCodeProvider();
codeGenerator = cdp.CreateGenerator();

//namespace and includes
CodeNamespace Samples = new CodeNamespace("Samples");
Samples.Imports.Add(new CodeNamespaceImport("System"));

//declare a class
CodeTypeDeclaration Class1 = new CodeTypeDeclaration("HelloWorld");
Samples.Types.Add(Class1);
Class1.IsClass = true;

//reference to a method - writeHelloWorld
CodeMethodReferenceExpression Method1Ref = new CodeMethodReferenceExpression();
Method1Ref.MethodName = "writeHelloWorld";
CodeMethodInvokeExpression mi1 = new CodeMethodInvokeExpression();
mi1.Method = Method1Ref;

//constructor for the class
CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.Statements.Add(mi1);
Class1.Members.Add(cc);

//method - writeHelloWorld
CodeMemberMethod Method1 = new CodeMemberMethod();
Method1.Name = "writeHelloWorld";
Method1.ReturnType = new CodeTypeReference(typeof(void));
//Method1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "text"));
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!!"));
Method1.Statements.Add(cs1);
Class1.Members.Add(Method1);

//method - Main
CodeEntryPointMethod Start = new CodeEntryPointMethod();
Start.Statements.Add(new CodeSnippetStatement("HelloWorld hw = new HelloWorld();"));
Class1.Members.Add(Start);

//generate the source code file
codeGenerator.GenerateCodeFromNamespace(Samples, tw, null);

//close the text writer
tw.Close();

RunClass sampleRun = new RunClass();
}
}
}



Creating custom workflow in CRM 2015

Creating custom workflow in CRM 2015

This sample shows how to write a custom workflow activity that can create an account and a task for the account. This sample uses early binding.

using System;
using System.Activities;
using System.Collections.ObjectModel;

using Microsoft.Crm.Sdk.Messages;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;

namespace Microsoft.Crm.Sdk.Samples
{
	public sealed class SimpleSdkActivity : CodeActivity
	{
		protected override void Execute(CodeActivityContext executionContext)
		{
			//Create the tracing service
			ITracingService tracingService = executionContext.GetExtension<ITracingService>();

			//Create the context
			IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
			IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
			IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

			tracingService.Trace("Creating Account");

			Account entity = new Account();
			entity.Name = AccountName.Get<string>(executionContext);
			Guid entityId = service.Create(entity);

			tracingService.Trace("Account created with Id {0}", entityId.ToString());

			tracingService.Trace("Create a task for the account");
			Task newTask = new Task();
			newTask.Subject = TaskSubject.Get<string>(executionContext);
			newTask.RegardingObjectId = new EntityReference(Account.EntityLogicalName, entityId);

			Guid taskId = service.Create(newTask);

			tracingService.Trace("Task has been created");

			tracingService.Trace("Retrieve the task using QueryByAttribute");
			QueryByAttribute query = new QueryByAttribute();
			query.Attributes.AddRange(new string[] { "regardingobjectid" });
			query.ColumnSet = new ColumnSet(new string[] { "subject" });
			query.EntityName = Task.EntityLogicalName;
			query.Values.AddRange(new object[] { entityId });

			tracingService.Trace("Executing the Query for entity {0}", query.EntityName);

			//Execute using a request to test the OOB (XRM) message contracts
			RetrieveMultipleRequest request = new RetrieveMultipleRequest();
			request.Query = query;
			Collection<Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

			//Execute a request from the CRM message assembly
			tracingService.Trace("Executing a WhoAmIRequest");
			service.Execute(new WhoAmIRequest());

			if (1 != entityList.Count)
			{
				tracingService.Trace("The entity list was too long");
				throw new InvalidPluginExecutionException("Query did not execute correctly");
			}
			else
			{
				tracingService.Trace("Casting the Task from RetrieveMultiple to strong type");
				Task retrievedTask = (Task)entityList[0];

				if (retrievedTask.ActivityId != taskId)
				{
					throw new InvalidPluginExecutionException("Incorrect task was retrieved");
				}

				tracingService.Trace("Retrieving the entity from IOrganizationService");

				//Retrieve the task using Retrieve
				retrievedTask = (Task)service.Retrieve(Task.EntityLogicalName, retrievedTask.Id, new ColumnSet("subject"));
				if (!string.Equals(newTask.Subject, retrievedTask.Subject, StringComparison.Ordinal))
				{
					throw new InvalidPluginExecutionException("Task's subject did not get retrieved correctly");
				}

				//Update the task
				retrievedTask.Subject = UpdatedTaskSubject.Get<string>(executionContext);
				service.Update(retrievedTask);
			}
		}

		[Input("Account Name")]
		[Default("Test Account: {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
		public InArgument<string> AccountName { get; set; }

		[Input("Task Subject")]
		[Default("Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
		public InArgument<string> TaskSubject { get; set; }

		[Input("Updated Task Subject")]
		[Default("UPDATED: Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
		public InArgument<string> UpdatedTaskSubject { get; set; }
	}

	public sealed class SdkWithLooselyTypesActivity : CodeActivity
	{
		protected override void Execute(CodeActivityContext executionContext)
		{
			//Create the tracing service
			ITracingService tracingService = executionContext.GetExtension<ITracingService>();

			//Create the context
			IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
			IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
			IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

			tracingService.Trace("Creating Account");

			tracingService.Trace("Creating Account");

			Entity entity = new Entity("account");
			entity.Attributes["name"] = AccountName.Get<string>(executionContext);
			Guid entityId = service.Create(entity);

			tracingService.Trace("Account created with Id {0}", entityId.ToString());

			tracingService.Trace("Create a task for the account");
			Entity newTask = new Entity("task");
			newTask["subject"] = TaskSubject.Get<string>(executionContext);
			newTask["regardingobjectid"] = new EntityReference("account", entityId);

			Guid taskId = service.Create(newTask);

			tracingService.Trace("Task has been created");

			Entity updateTask = new Entity("task");
			updateTask.Id = taskId;
			updateTask["subject"] = UpdatedTaskSubject.Get<string>(executionContext);
			service.Update(updateTask);

			tracingService.Trace("Task has been updated");
		}

		[Input("Account Name")]
		[Default("Test Account: {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
		public InArgument<string> AccountName { get; set; }

		[Input("Task Subject")]
		[Default("Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
		public InArgument<string> TaskSubject { get; set; }

		[Input("Updated Task Subject")]
		[Default("UPDATED: Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
		public InArgument<string> UpdatedTaskSubject { get; set; }
	}

	public sealed class SimpleSdkWithRelatedEntitiesActivity : CodeActivity
	{
		protected override void Execute(CodeActivityContext executionContext)
		{
			//Create the tracing service
			ITracingService tracingService = executionContext.GetExtension<ITracingService>();

			//Create the context
			IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
			IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
			IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

			Relationship primaryContactRelationship = new Relationship("account_primary_contact");

			Guid primaryContactId = service.Create(new Contact() { LastName = RootContactLastName.Get<string>(executionContext) });

			//tracingService.Trace("Create an Account with an existing primary contact");
			Account rootAccount = new Account() { Name = RelatedAccountName.Get<string>(executionContext) };
			Contact primaryContact = new Contact()
			{
				EntityState = EntityState.Changed,
				Id = primaryContactId,
				FirstName = RootContactFirstName.Get<string>(executionContext)
			};

			rootAccount.RelatedEntities[primaryContactRelationship] =
				new EntityCollection(new Entity[] { primaryContact }) { EntityName = Contact.EntityLogicalName };

			tracingService.Trace("Execute the Create/Update");
			rootAccount.Id = service.Create(rootAccount);

			//Create the related entities query
			RelationshipQueryCollection retrieveRelatedEntities = new RelationshipQueryCollection();
			retrieveRelatedEntities[primaryContactRelationship] = new QueryExpression(Account.EntityLogicalName)
			{
				ColumnSet = new ColumnSet("name"),
				Criteria = new FilterExpression()
			};

			//Create the request
			RetrieveResponse response = (RetrieveResponse)service.Execute(new RetrieveRequest()
			{
				ColumnSet = new ColumnSet("firstname"),
				RelatedEntitiesQuery = retrieveRelatedEntities,
				Target = new EntityReference(primaryContact.LogicalName, primaryContact.Id)
			});

			tracingService.Trace("Retrieve the record with its related entities");
			Contact retrievedContact = (Contact)response.Entity;
			Account retrievedAccount = (Account)retrievedContact.RelatedEntities[primaryContactRelationship][0];

			tracingService.Trace("Ensure the first name was updated");
			if (retrievedContact.FirstName == primaryContact.FirstName)
			{
				tracingService.Trace("Primary Contact name is correct");
			}
			else
			{
				tracingService.Trace("First Name is \"{0}\", expected \"{1}\".", retrievedContact.FirstName, primaryContact.FirstName);
				throw new InvalidPluginExecutionException("The first name was not changed");
			}
		}

		[Input("Related Account Name")]
		[Default("Related Account")]
		public InArgument<string> RelatedAccountName { get; set; }

		[Input("Root Contact First Name")]
		[Default("New FirstName")]
		public InArgument<string> RootContactFirstName { get; set; }

		[Input("Root Contact Last Name")]
		[Default("Root LastName")]
		public InArgument<string> RootContactLastName { get; set; }
	}
}

LINQ to Lambda

As we know the LINQ is a language integrated query introduced in visual studio 2008 which offered an compact, and intelligible syntax for manipulating data & objects. Also Lambda expressions are introduced which is like an anonymous function that can be used to write local functions, delegates and expression tree. The below are few examples as how to modify the LINQ expression to Lambda.

Filtering

//Linq
    var column = from o in Orders
                 where o.CustomersId = 45
                 select o;
/* can be converted to Lambda as */
//Lambda
    var column = Orders.Where(o => o.CustomersId == 45);


Compile On Fly

This class compiles and executes a dot.net snippets on the fly in memory. Although this is a basic example, but it can be extended with xml inside Completecode();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.CodeDom;
using System.IO;
namespace killercodes_in.CompileOnFly
{
public class Compile
{
string _codeStatement;
string _completeCode;
public Compile(string Code)
{
this._codeStatement = Code;
}
private string CompleteCode()
{
StringBuilder sb = new StringBuilder("using System;");
sb.AppendLine("namespace killercodes_in.CompileOnFly");
sb.AppendLine("{");
sb.AppendLine("public class Program");
sb.AppendLine("{");
sb.AppendLine("public static void Main()");
sb.AppendLine("{").Append(this._codeStatement).Append("}");
sb.AppendLine("}").AppendLine("}");
return sb.ToString();
}
public bool Execute()
{
try
{
_completeCode = CompleteCode();
CompilerParameters compilerParameters = new CompilerParameters();
// Reference to System.Drawing library
compilerParameters.ReferencedAssemblies.Add("System.Drawing.dll");
compilerParameters.ReferencedAssemblies.Add("system.dll");
//rest of the references can be added as compilerParameters.ReferencedAssemblies.Add("System.Console");
// True - memory generation, false - external file generation
compilerParameters.GenerateInMemory = true;
// True - exe file generation, false - dll file generation
compilerParameters.GenerateExecutable = true;
CodeNamespace _nameSpace = new CodeNamespace("CompileOnFly");
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, _completeCode);
if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
}
throw new InvalidOperationException(sb.ToString());
}
//Get assembly, type and the Main method:
Assembly assembly = results.CompiledAssembly;
Type program = assembly.GetType("killercodes_in.CompileOnFly.Program");
MethodInfo main = program.GetMethod("Main");
//runti
main.Invoke(null, null);
return true;
}
catch
{
return false;
}
}
}