void RunWithRedirect(string cmdPath) { var proc = new Process(); proc.StartInfo.FileName = cmdPath; // set up output redirection proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.EnableRaisingEvents = true; proc.StartInfo.CreateNoWindow = true; // see below for output handler proc.ErrorDataReceived += proc_DataReceived; proc.OutputDataReceived += proc_DataReceived; proc.Start(); proc.BeginErrorReadLine(); proc.BeginOutputReadLine(); proc.WaitForExit(); } void proc_DataReceived(object sender, DataReceivedEventArgs e) { // output will be in string e.Data }
Search
RunWithRedirect
C#: DATE-TIME FUNCTIONS
// DATE FUNCTIONS // Get Current Year protected int _currentYear() { DateTime dtn = DateTime.Now; int ret= dtn.Year; return ret; }//** // Get Current Month protected int _currentMonth() { DateTime dtn = DateTime.Now; int ret = dtn.Month; return ret; }//** // Get current month in string protected string _curMonthStr() { string thismonth = String.Format("{0:MMMM}", DateTime.Now).ToString(); return thismonth; } // Get Current Day protected int _currentDay() { DateTime dtn = DateTime.Now; int ret = dtn.Day; return ret; }//** // Get Sundays for this month protected int[] getSundays(int year, int month, DayOfWeek dayName) { int[] _sunday = new int[4]; CultureInfo ci = new CultureInfo("en-US"); int ai = 0; for (int i = 1; i <= ci.Calendar.GetDaysInMonth(year, month); i++) { if (new DateTime(year, month, i).DayOfWeek == dayName) { //Response.Write(i.ToString()); _sunday[ai] = i; ai += 1; } } return _sunday; }//**
C#: Get num of days in month
DateTime.DaysInMonth(int year, int month); //or static int GetDaysInMonth(int year, int month) { DateTime dt1 = new DateTime(year, month, 1); DateTime dt2 = dt1.AddMonths(1); TimeSpan ts = dt2 - dt1; return (int)ts.TotalDays; }
C#: Get sundays in month
using System.Globalization; protected void PrintSundays(int year, int month, DayOfWeek dayName) { CultureInfo ci = new CultureInfo("en-US"); for (int i = 1 ; i <= ci.Calendar.GetDaysInMonth (year, month); i++) { if (new DateTime (year, month, i).DayOfWeek == dayName) Response.Write (i.ToString() + " "); } }
C#: HttpWebRequest example with error handling using C#
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; } }
C#: Using inline code in ASP.NET
Using this syntax, you can use inline code in ASP.NET (.aspx) pages. The server-side code will be automatically compiled by the .NET framework the first time the page is requested on the server. The compiled .dll file is stored in the "Temporary ASP.NET Files" system folder. Changing the code in .aspx files will trigger a new compilation, generating new .dll files. The old .dll files are phased out by the framework and eventually deleted.
<%@ Import Namespace="System" %>
<%@ Page Language="c#"%>
<script runat="server">
public string ServerSideFunction(string input)
{
return "Hello " + input;
}
</script>
<% string pageVariable = "world"; %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>ASP.NET inline</title>
</head>
<body>
<% =ServerSideFunction(pageVariable) %>
</body>
</html>
C#: Create Bitmap Image
private Bitmap CreateBitmapImage(string sImageText)
{
Bitmap objBmpImage = new Bitmap(1, 1);
int intWidth = 0;
int intHeight = 0;
// Create the Font object for the image text drawing.
Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
// Create a graphics object to measure the text's width and height.
Graphics objGraphics = Graphics.FromImage(objBmpImage);
// This is where the bitmap size is determined.
intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;
// Create the bmpImage again with the correct size for the text and font.
objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
// Add the colors to the new bitmap.
objGraphics = Graphics.FromImage(objBmpImage);
// Set Background color
objGraphics.Clear(Color.White);
objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
objGraphics.Flush();
return (objBmpImage);
}
List All Assembly exceptions
using System; using System.Collections; using System.Reflection; using System.Text; namespace ExceptionReflection { class Program { static void Main(string[] args) { // load the assemblies to analyze LoadAssemblies(); ArrayList ExceptionTree = new ArrayList(); foreach (Assembly Assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (Type Type in Assembly.GetTypes()) { if (!Type.IsClass || !Type.IsPublic) continue; StringBuilder TypeHierarchy = new StringBuilder(Type.FullName, 5000); Boolean IsDerivedFromException = false; Type BaseType = Type.BaseType; while ((BaseType != null) && !IsDerivedFromException) { TypeHierarchy.Append("-" + BaseType); IsDerivedFromException = (BaseType == typeof(Exception)); BaseType = BaseType.BaseType; } if (!IsDerivedFromException) continue; String[] Hierarchy = TypeHierarchy.ToString().Split('-'); Array.Reverse(Hierarchy); ExceptionTree.Add(String.Join ("-", Hierarchy, 1, Hierarchy.Length - 1)); ExceptionTree.Sort(); foreach (String Identifier in ExceptionTree) { String[] Trace = Identifier.Split('-'); Console.WriteLine(new String(' ', 3*Trace.Length) + Trace[Trace.Length-1]); } } } Console.ReadLine(); } static void LoadAssemblies() { String[] Assemblies = { /* uncomment as needed */ //"System, PublicKeyToken={0}", //"System.Data, PublicKeyToken={0}", //"System.Design, PublicKeyToken={1}", //"System.DirectoryServices, PublicKeyToken={1}", //"System.Drawing, PublicKeyToken={1}", //"System.Drawing.Design, PublicKeyToken={1}", //"System.EnterpriseServices, PublicKeyToken={1}", //"System.Management, PublicKeyToken={1}", //"System.messaging, PublicKeyToken={1}", //"System.Runtime.Remoting, PublicKeyToken={0}", //"System.Security, PublicKeyToken={1}", //"System.serviceProcess, PublicKeyToken={1}", //"System.Web, PublicKeyToken={1}", //"System.Web.RegularExpressions, PublicKeyToken={1}", //"System.Web.Services, PublicKeyToken={1}", //"System.Windows.Forms, PublicKeyToken={0}", //"System.Xml, PublicKeyToken={0}", "MSCorLib, PublicKeyToken={0}" }; // change this if you want to use assemblies that are not from microsoft String EcmaPublicKeyToken = "B77A5C561934E089"; String MSPublicKeyToken = "B03F5F7F11D50A3A"; // get the newest version Version Version = typeof(System.Object).Assembly.GetName().Version; // load the assemblies foreach (String AssemblyName in Assemblies) { String AssemblyIdentity = String.Format(AssemblyName, EcmaPublicKeyToken, MSPublicKeyToken) + ", Culture=neutral, Version=" + Version; Assembly.Load(AssemblyIdentity); } } } }
Host DLL as WCF Service
Using .Net framework 4 we can host a DLL as WebServiceand here is how to do it. All you have to do is the following: Create an Interface for the DLL Code Add Reference to "using System.ServiceModel" in the code
Service Interface
// an interface as contract
namespace killercodes_in.Dll_as_WS
{
[ServiceContract()]
interface IWS_Class1
{
[OperationContract()]
int AddNum(int one, int two);
}
}
then you should implement the interface like
using System.ServiceModel;
using System.ServiceModel.Description;
// class implementing the contract(interface)
namespace killercodes_in.Dll_as_WS
{
// Service Implementation
public class WS_Class1:IWS_Class1
{
public int AddNum(int one, int two)
{
return one + two;
}
}
}
The reason using "System.ServiceModel.Description" reference is because we Need a host application to host this DLL as WS. So Add a new Class call it "Host_WS_Class1"
// Hosting WS
namespace killercodes_in.Dll_as_WS
{
public class Host_WS_Class1
{
public Uri httpUrl { get; set; }
public string Status { get; set; }
private ServiceHost WsSvcHost;
public bool IsLive { get; set; }
public Host_WS_Class1(string HostingURL)
{
//Create a URI to serve as the base address
httpUrl = new Uri(HostingURL);
//Create ServiceHost
WsSvcHost = new ServiceHost(typeof(killercodes_in.Dll_as_WS.WS_Class1), httpUrl);
//Add a service endpoint
WsSvcHost.AddServiceEndpoint(typeof(killercodes_in.Dll_as_WS.IWS_Class1), new WSHttpBinding(), "");
//Enable metadata exchange
ServiceMetadataBehavior svcMetaBehaviour = new ServiceMetadataBehavior();
svcMetaBehaviour.HttpGetEnabled = true;
WsSvcHost.Description.Behaviors.Add(svcMetaBehaviour);
IsLive = false;
}
public string Start()
{
//Start the Service
WsSvcHost.Open();
IsLive = true;
Status = string.Format("Service started at {0}", DateTime.Now.ToString().Replace('/', ':'));
return Status;
}
public string Stop()
{
//Start the Service
WsSvcHost.Close();
IsLive = false;
Status = string.Format("Service stopped at {0}", DateTime.Now.ToString().Replace('/', ':'));
return Status;
}
}
}
Now all you need is an application to call/host this DLL.
killercodes_in.Dll_as_WS.Host_WS_Class1 hostCls = new Host_WS_Class1("http://localhost:5000/NewSvc");
Console.WriteLine(hostCls.Start());
Console.ReadKey();
Business Delegate
In business tier we've following entities.
Client - Presentation tier code may be JSP, Asp, servlet or UI code.using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate { class Client { BusinessDelegate businessService; public Client(BusinessDelegate businessService) { this.businessService = businessService; } public void doTask() { businessService.doTask(); } } }Business Delegate - A single entry point class for client entities to provide access to Business Service methods.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate { public class BusinessDelegate { private BusinessLookUp lookupService = new BusinessLookUp(); private BusinessService businessService; private String serviceType; public void setServiceType(String serviceType) { this.serviceType = serviceType; } public void doTask() { businessService = lookupService.getBusinessService(serviceType); businessService.doProcessing(); } } }LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate { class BusinessLookUp { public BusinessService getBusinessService(String serviceType) { if (serviceType.Equals("EJB")) { return new Services.Service1(); } else { return new Services.Service2(); } } } }Business Service - Business Service interface. Concrete classes implements this business service to provide actual business implementation logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate { interface BusinessService { void doProcessing(); } }and services as Service1
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate.Services { class Service1:BusinessService { public void doProcessing() { Console.WriteLine("Service 1 invoked"); } } }and Service2
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate.Services { class Service2:BusinessService { public void doProcessing() { Console.WriteLine("Service 2 invoked"); } } }
To use these we need a main methods as
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business_Delegate { class BusinessDelegatePatternDemo { public static void main(String[] args) { BusinessDelegate businessDelegate = new BusinessDelegate(); businessDelegate.setServiceType("WCF"); Client client = new Client(businessDelegate); client.doTask(); businessDelegate.setServiceType("EJB"); client.doTask(); } } }
Using Dynamic Object
Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly.
CGI using C++
The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.
make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable.
By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin.
#include <iostream>
using namespace std;
int main ()
{
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Hello World - First CGI Program</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<h2>Hello World! This is my first CGI program</h2>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable.
Write then read a text file
using System; using System.IO; public class WriteReadClass { public static void Main() { // write a text file TextWriter tws = new StreamWriter ("test.txt"); // write the current datetime to the stream tws.WriteLine (DateTime.Now); // write test strings to the stream tws.Write (" Test string 1 to write to file.\n"); tws.Write (" Test string 2 to write to file.\n"); tws.Close(); // close the stream // now, read in the text file TextReader trs = new StreamReader ("test.txt"); // read the first line of text Console.WriteLine (trs.ReadLine()); // read the rest of the text lines Console.WriteLine (trs.ReadToEnd()); trs.Close(); // close the stream Console.Write ("\nPress \"Enter\" to exit ..."); Console.Read(); } }
Make Record Inactivate using C# in CRM 2011
//Inactive Recordes C# public bool InactiveRecord ( string entity, Guid id ) { try{ SetStateRequest req = new SetStateRequest(); //the entity you want to change the state of req.EntityMoniker = new EntityReference(entity,id); //what should the new state be\ req.State = new OptionSetValue((int)AccountState.Inactive); //Pick an option from the status reason picklist to specify reason for state change req.Status = new OptionSetValue (2); this.Service.Execute (req); return true; } catch ( SoapException ex ){ return false; } }
C# Preprocessor
C# actually has almost all the standard preprocessor directives - it just happens to be that the functionality of some of them (specifically the #define directive) is quite reduced. The one notable directive that is missing is #include - and it makes sense that C# wouldn't have it, because C# gets the same sort of functionality from the using statements (although there is the fact that #include refers to files and using refers to assemblies - so they are definitely not equivalent). So let's start at the beginning: #define and #undef. The directive #define gives you the ability to define a symbol, and #undef lets you un-define it. For instance:
#define MY_SYMBOL /* Do Stuff */ #undef MY_SYMBOL However, while you can define a symbol, you cannot assign a value to it (which is where that major difference from C/C++ comes into play): #define MY_SYMBOL 42 //Error: Single-line comment or end-of-line expectedSo what good is defining a symbol when you can't actually give it a value? Because in C/C++, giving it a value was really the whole point. Well, now that you can't give it a value, the only place to use them are in the #if and #elif directives:
#define SYMBOL_A #define SYMBOL_B using System; public class Foo { static void Main() { #if (SYMBOL_A && !SYMBOL_B) Console.WriteLine("SYMBOL_A!!"); #elif (!SYMBOL_A && SYMBOL_B) Console.WriteLine("SYMBOL_B!!"); #elif (SYMBOL_A && SYMBOL_B) Console.WriteLine("SYMBOL_A and SYMBOL_B!!"); #else Console.WriteLine("Neither!!"); #endif } }That code sample pretty much covers all the craziness that you can do with the conditional directives. This particular code block would end up printing out "SYMBOL_A and SYMBOL_B!!", because both symbols were defined. If, say, I had thrown an #undef in there, we might get something else:
#define SYMBOL_A #define SYMBOL_B #undef SYMBOL_A using System; public class Foo { static void Main() { #if (SYMBOL_A && !SYMBOL_B) Console.WriteLine("SYMBOL_A!!"); #elif (!SYMBOL_A && SYMBOL_B) Console.WriteLine("SYMBOL_B!!"); #elif (SYMBOL_A && SYMBOL_B) Console.WriteLine("SYMBOL_A and SYMBOL_B!!"); #else Console.WriteLine("Neither!!"); #endif } } Now, this code block would end up printing "SYMBOL_B!!". But now on to my favorite two directives: #error and #warning. They essentially allow you to inject compile errors and warnings into the code. For example: using System; public class Foo { static void Main() { #error My Best Error Ever!! #warning A Little Tiny Warning } } //Error: #error: 'My Best Error Ever!!' //Warning: #warning: 'A Little Tiny Warning'Simple, and yet quite effective. I use them as almost a to-do list - whenever I'm leaving a section of code that I know is wrong, I'll leave some #error or #warning directives so that the compiler will remind me to come back later and fix it. Next up: #pragma. The #pragma directive is kind of a catch-all in C/C++, and it is the same here in C#. But there is one #pragma varient that is probably useful to know: #pragma warning.
using System; public class Foo { static void Main() { int foo; Console.WriteLine("Hi"); } } //Warning: The variable 'foo' is declared but never usedGenerally, the code above would throw the warning that you see there. But say you want to ignore that warning - you can use the #pragma warning directive to get rid of it:
using System; public class Foo { static void Main() { #pragma warning disable 0168 int foo; #pragma warning restore 0168 Console.WriteLine("Hi"); } }Essentially, what that does is disable the warning number CS0168 between the disable and restore directives. You should be careful when using this directive, because if you don't restore the warning, it will be disabled for the rest of the file. This #pragma warningdirective is actually quite a bit more powerful than displayed here, and if you'd like to learn more, you should read about it at MSDN. Well, that concludes a nice overview of C#'s preprocessor directives. We did not cover everything, because some things (like #line) could probably get a whole tutorial on their own. Also, if you would like to know more about what can be done with the #pragmadirective, you can check out this MSDN page (there is a lot of stuff). As always, feel free to leave any questions or comments below.
What is WCF RIA service?
WCF RIA service is a framework to develop n-tier application for Rich Internet Application (RIA). It is mainly used in RIA applications like Silverlight, AJAX client, etc. It solves the major problem while developing business application like decoupling the resource access, application logic and presentation layer. WCF RIA service was introduced in Silverlight 4 with .net framework 4, and it can be developed using visual studio2010.
Main problem developer are facing while developing the n-tier RIA application will be coordinating the application logic between middle tier and presentation tier. This problem will be solved by using WCF RIA service, it will synchronize the code between middle and presentation tier.
WCF RIA service will allow developer to write the set of service code and this server code will be available to the client side without manually duplicate that programming logic. RIA service client will be updated with business rule and entity present at the server side, when your recompile your project solution.
WCF RIA service will generate the code at the client side related to the service and domain entities declared at the server side.
RIA service exposes the data from server side to client side using Domain service, RIA service framework implements the each domain service as WCF service to access the data as business entity.
-
WCF RIA Domain Service
-
Problems solved in RIA Service
-
Query/Update process in RIA
-
How to create Silverlight-WCF RIA service
fig: WCF RIA Serive architecture
Domain Service
Domain services are WCF services that expose the business logic of a WCF RIA Services application. Domain service contains set of business related data operation and it is exposed as WCF service.
Below diagram explains integration of the RIA service with WCF
The DomainService class is the base class for all classes that serve as domain services.
- DomainServiceHost is the hosting class for domain service; internally
- DomainServiceHost uses the WCF ServiceHost class to host the application.
A domain service class must be marked with the EnableClientAccessAttribute attribute to make the service available to the client project. The EnableClientAccessAttributeattribute is automatically applied to a domain service when you select the Enable client access check box in the Add New Domain Service Class dialog box. When the EnableClientAccessAttribute attribute is applied to a domain service, RIA Services generates the corresponding classes for the client project.
//Example: [EnableClientAccess()] public class EmployeeDomainService : DomainService { private EmployeeData data = EmployeeData.Instance; public IEnumerable < Employee> GetEmployees() { return data.EmployeeList; } }
DomainContext class at the client side is used to consume the Domain service by using DomainClient object. DomainContext class available inside the name space "System.ServiceModel.DomainServices.Client"
fig: WCF RIA Domain Serive architecture
Problem solved in RIA
- To have best performance of the RIA application, app logic need to be available in client and server side. This problem is solved by auto generating the code at the client side while recompiling the project.
- Asynchronous call – Asynch service call are supported in Domain service by using WCF infrastructure
- Handling large data and data across different tier – Large amount of data can be access and filter using IQueryable object. Since entity objects used in domain service are serializable and so it can be access across different layer
- Security/Access control – ASP.Net membership frameworks are integrated with RIA service to provide security systems to RIA service
- Validation – Entity can be validated based using adding attribute to the class members
//Example: public class Member { [Key] public int MemberId { get; set; } public string Fname { get; set; } [Required] public string Lname { get; set; } public DateTime JoinDate { get; set; } [Range(30,90, ErrorMessage="sorry, you are either too young or too old for our club!")] public int Age { get; set; } }
Querying/Updating data in RIA Service
The below diagram are self explanatory to discuss about the querying or updating the data using RIA service
fig: WCF RIA to Query data
fig: WCF RIA to update data
How to Create WCF RIA Service
Download:
Silverlight_WCF_RIA_Service.zipLet us understand more about the WCF RIA service by creating Silverlight client application which read and updated the Employee details from WCF RIA Service.
Step 1:Start the Visual Studio 2010 and click File -> New-> Project. Enter the project name and click “Create”
Step 2:Select “Enable WCF RIA Services”. This will make your Silverlight application to user WCF RIA service
Step 3:Create “Data” folder and add DataModel” class as shown below. This is the data class which will return list of Employee and update the employee list
Data Model class:
1: public class Employee
2: {
3: [Key]
4: public int EmpId { get; set; }
5: public string Fname { get; set; }
6: public string Lname { get; set; }
7: public DateTime JoinDate { get; set; }
8: public int Age { get; set; }
9: }
10:
11:
12: public partial class EmployeeData
13: {
14: private static readonly EmployeeData _instance = new EmployeeData();
15: private EmployeeData() { }
16: public static EmployeeData Instance
17: {
18: get
19: {
20: return _instance;
21: }
22: }
23:
24:
25: private List < Employee > empList = new List < Employee>()
26: {
27: new Employee() { EmpId = 1, Fname = "Sam", Lname = "kumar",
28: JoinDate=new DateTime(2010,7, 21), Age=30},
29: new Employee() { EmpId = 2, Fname = "Ram", Lname = "kumar",
30: JoinDate=new DateTime(2009,6,8), Age=35},
31: new Employee() { EmpId = 3, Fname = "Sasi", Lname = "M",
32: JoinDate=new DateTime(2008,3,5), Age=39},
33: new Employee() { EmpId = 4, Fname = "Praveen", Lname = "KR",
34: JoinDate=new DateTime(2010, 5,1), Age=56},
35: new Employee() { EmpId = 5, Fname = "Sathish", Lname = "V",
36: JoinDate = new DateTime(2006,12,15), Age=72},
37: new Employee() { EmpId = 6, Fname = "Rosh", Lname = "A",
38: JoinDate=new DateTime(2009,2,2), Age=25}
39: };
40:
41: public IEnumerable< Employee > EmployeeList
42: {
43: get
44: {
45: return empList;
46: }
47: }
48:
49:
50: public void Update(Employee updEmployee)
51: {
52: Employee existing = empList.Find(p => p.EmpId == updEmployee.EmpId);
53: if (existing == null)
54: throw new KeyNotFoundException("Specified Employee cannot be found");
55:
56: existing.Fname = updEmployee.Fname;
57: existing.Lname = updEmployee.Lname;
58: existing.JoinDate = updEmployee.JoinDate;
59: existing.Age = updEmployee.Age;
60: }
61: }
Step 4:To expose the Employee related operation to the client side, Create domain service class. By right click project file and select Add new item.
Step 5:Add code to return the Employee list
Domain Service class:
1: // TODO: Create methods containing your application logic.
2: [EnableClientAccess()]
3: public class EmployeeDomainService : DomainService
4: {
5: //Create instance of the Data access layer
6: private EmployeeData data = EmployeeData.Instance;
7:
8: public IEnumerable< Employee> GetEmployee()
9: {
10: return data.EmployeeList ;
11: }
12:
13: public void UpdateEmployee(Employee emp)
14: {
15: data.Update(emp);
16: }
17: }
Step 6:Compile the solution – After compilation RIA service will generate the application logic at the client side using DomainContext object. Enable show all files option for the solution and view the auto generated code.
Step 7:View the DomainContext class are created at the client side.
Domain Context class at client:
1: ///
2: /// The DomainContext corresponding to the 'EmployeeDomainService' DomainService.
3: ///
4: public sealed partial class EmployeeDomainContext : DomainContext
5: {
6:
7: #region Extensibility Method Definitions
8:
9: ///
10: /// This method is invoked from the constructor once initialization is complete and
11: /// can be used for further object setup.
12: ///
13: partial void OnCreated();
14:
15: #endregion
16:
17:
18: ///
19: /// Initializes a new instance of the < see cref="EmployeeDomainContext"/> class.
20: ///
21: public EmployeeDomainContext() :
22: this(new WebDomainClient< IEmployeeDomainServiceContract>(new
23: Uri("MyFirstRIAApplication-Web-EmployeeDomainService.svc",
24: UriKind.Relative)))
25: {
26: }
27:
28: ........
29: ........
Step 8:Add DataGrid to Main.xaml file to display the employee details query from DataModel and add two buttons to update and reject the data changed from client side.
Main.xaml
< Grid x:Name="LayoutRoot" Background="White">
< StackPanel Orientation="Vertical" HorizontalAlignment="Left" >
< sdk:DataGrid x:Name="EmployeeGrid" AutoGenerateColumns="True"
RowEditEnded="EmployeeGrid_RowEditEnded" />
< Button Content="Accept" Height="23" Name="btnAccept"
Width="75" Margin="5" Click="btnAccept_Click" />
< Button Content="Reject" Height="23" Name="btnReject"
Width="75" Margin="5" Click="btnReject_Click"/>
</StackPanel>
</Grid>
Main.xaml.vb
1: public partial class MainPage : UserControl
2: {
3: //create instance of Doman context class
4: EmployeeDomainContext ctx = new EmployeeDomainContext();
5:
6: public MainPage()
7: {
8: InitializeComponent();
9: //Load query data , Read data from DAL layer to UI
10: EntityQuery< Employee> query = ctx.GetEmployeeQuery();
11: LoadOperation< Employee> lo = ctx.Load< Employee>(query);
12: EmployeeGrid.ItemsSource = lo.Entities;
13: }
14:
15: private void EmployeeGrid_RowEditEnded(object sender,
16: DataGridRowEditEndedEventArgs e)
17: {
18:
19: }
20:
21: private void btnAccept_Click(object sender, RoutedEventArgs e)
22: {
23: //Update the DAL with user changes
24: ctx.SubmitChanges();
25: }
26:
27: private void btnReject_Click(object sender, RoutedEventArgs e)
28: {
29: //Roll back the user changes
30: ctx.RejectChanges();
31: }
32: }
Step 9:Run the application and see the output as shown below
Basic Linq to XML
XElement root2 = XElement.Parse(xmlString);
IEnumerabletests =
from el in root2.Elements("Root")
where (string)el.Element("elementName") == "searchPattern"
select el.Element("pickElement");
string cc= tests.Single().Value;
Parse connection string
using System.Text.RegularExpressions; ... const string CONNECTION_STRING_PATTERN = @"=(?The following is an alternative method:.+);Initial Catalog=(? \w+);"; static readonly Regex ConnectionString_Regex = new Regex (CONNECTION_STRING_PATTERN, RegexOptions.IgnoreCase); static GroupCollection ParseConnectionString (string inputString) { Match match = ConnectionString_Regex.Match (inputString); return match.Groups; }
static void ParseConnectionString(string inputString) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(inputString); // retrieve Data source and Db name ; even user id and password using builder instance // like builder.DataSource(Server name);builder.InitialCatalog(DB Name); // builder.UserID(User Id);builder.Password(Password) }
Create Account in Active Directory
using System.DirectoryServices; using System.DirectoryServices.ActiveDirectory; using System.DirectoryServices.AccountManagement; namespace ActiveDirectory_User { class Program { public class User { public string Firstname; public string Lastname; public string LoginId; public string Office; public string EmailAddress; public bool IsDisabled; public User() {} public User(string firstName, string lastName) { Firstname = firstName; Lastname = lastName; } public User(string firstName, string lastName, string office = "London",) { Firstname = firstName; Lastname = lastName; Office = office; } } static void Main(string[] args) { } public static void CreateOU(string ou) { try { if (!DirectoryEntry.Exists("LDAP://PLABDC01/ou=" + ou + ",dc=PRACTICELABS,dc=COM")) { try { DirectoryEntry ActiveDirectory = new DirectoryEntry("LDAP://PLABDC01/dc=PRACTICELABS,dc=COM", "Administrator", "Passw0rd"); DirectoryEntry NewOU = ActiveDirectory.Children.Add("OU=" + ou, "OrganizationalUnit"); NewOU.CommitChanges(); ActiveDirectory.CommitChanges(); Console.WriteLine("Created OU:{0}", ou); } catch (Exception error) { Console.WriteLine("An error occured while creating group:{0} :\n{1}", ou, error.Message); } } else { Console.WriteLine("OU already exists"); } } catch (Exception error) { Console.WriteLine("We couldnt connect to AD! Is the server powered on?. Exception generated was\n{0}", error.Message); } } public bool CreateAccount() { // wrap our connection in a try catch block which will safeguard us against application crash if for example we can't connect to AD try { string FullPath = "LDAP://PLABDC01/ou=" + Department + ",dc=PRACTICELABS,dc=COM"; // Active directory connection DirectoryEntry Directory = new DirectoryEntry(FullPath, "Administrator", "Passw0rd"); // New user DirectoryEntry NewUser = Directory.Children.Add("CN=" + LoginId, "user"); // givenName is first name NewUser.Properties["givenName"].Value = Firstname; // sn is last name NewUser.Properties["sn"].Value = Lastname; // login id NewUser.Properties["sAMAccountName"].Value = LoginId; // office NewUser.Properties["physicalDeliveryOfficeName"].Value = Office; // commit the new user NewUser.CommitChanges(); // update the user to be enabled, here we CAST the value as an integer (i.e. we instruct the compiler that the return type value will be an int. // casting this will cause exceptions if the return type is not what you specify so beware! int val = (int)NewUser.Properties["userAccountControl"].Value; NewUser.Properties["userAccountControl"].Value = val & ~0x2; NewUser.CommitChanges(); // everything worked ok, return a value of true return true; } catch (Exception error) { // an error occured, write the error message out and return a value of false Console.Write("An error occured while creating user:{0} {1}: \n{2}", Firstname, Lastname, error.Message); return false; } } public bool DisableAccount() { try { DirectoryEntry Directory = new DirectoryEntry("LDAP://dc=PRACTICELABS,dc=COM"); DirectorySearcher SearchAD = new DirectorySearcher(Directory); SearchAD.Filter = "(SAMAccountName=" + LoginId + ")"; SearchAD.CacheResults = false; SearchResult result = SearchAD.FindOne(); Directory = result.GetDirectoryEntry(); Directory.Properties["userAccountControl"].Value = 0x0002; Directory.CommitChanges(); return true; } catch (Exception error) { Console.WriteLine("An error occured when disabling this user:{0}\n{1}", LoginId, error.Message); return false; } }// } }
Convert JavaScript date to ISO date format
There is not functions yet available to display the JS date object in the ISO UTC format, although there is a workaround.