Wednesday, 22 December 2010

CRM Wait Condition

1. select wait condition - > select work flow -> select timeout -> select duration -> select time or days

Tuesday, 14 December 2010

ASP.NET Cashing

Wow its fantastic

1. ASP.NET Tutorial - Caching - Part1
http://www.youtube.com/watch?v=Emxyt4dAf5g

2. ASP.NET Tutorial - Caching - Part2
http://www.youtube.com/watch?v=kLgyUaSmlFI&feature=related

3. ASP.NET Tutorial - Caching - Part3
http://www.youtube.com/watch?v=lZvMuYJQ75E&feature=related

Monday, 6 December 2010

WEB PARTS

You Tube Link - http://www.youtube.com/watch?v=RHcyILkdrQ4&feature=related

Name of the Video - ASP.NET Tutorial - Web Parts and Personalization - Part1

Wednesday, 1 December 2010

CRM DATE TIME ISSUE

Link - http://blogs.infinite-x.net/2009/08/17/using-crm-4-0s-built-in-function-part-1-of-5/



dbo.fn_UTCToLocalTime

Converts a UTC datetime value into a local date and time value. Using modifications of our examples above:

select dbo.fn_UTCToLocalTime(dbo.fn_BeginOfHour(GetUTCDate()))
select dbo.fn_UTCToLocalTime(dbo.fn_BeginOfLastXHour(GetUTCDate(), 1))
select dbo.fn_UTCToLocalTime(dbo.fn_EndOfNextXHour(GetUTCDate(), 1))

Returns:

Beginning of Hour: 2009-08-16 12:00:00.000

Beginning of Last X Hour: 2009-08-16 11:00:00.000

Beginning of Next X Hour: 2009-08-16 14:00:00.000

dbo.fn_LocalTimeToUTC

Just the opposite of dbo.fn_UTCToLocalTime, this function converts local time to UTC time.

select dbo.fn_LocalTimeToUTC(GetDate())

Returns: 2009-08-16 20:56:56.827

Conclusion

Today we started covering the user-defined SQL functions found inside CRM 4.0 database. Granted, sometimes the data that is returned doesn’t quite look right because all dates and times are in UTC format. I just have to say that you need to trust the results because this is what CRM uses on an everyday basis.

If you are ever confused by the results, I would suggest wrapping your query in a dbo.fn_UTCToLocalTIme() function to see what is returned. Like this:

select dbo.fn_UTCToLocalTime(dbo.fn_BeginOfLastSevenDay(GetUTCDate()))

Returns: 2009-08-09 00:00:00.000

Tuesday, 7 September 2010

Triggers

USE [Akash_MSCRM]
GO
/****** Object: Trigger [dbo].[UpdateStateEndInShipStatusHistory] Script Date: 09/07/2010 15:54:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[UpdateStateEndInShipStatusHistory]
ON [dbo].[Akash_ShipStatusHistoryExtensionBase]
AFTER INSERT
AS
DECLARE @CurrentRecordStateStartDate datetime
DECLARE @CurrentRecordShipStatusHistoryId uniqueidentifier --RecordID
DECLARE @CurrentRecordShiphistoryShipid uniqueidentifier --MemberID

DECLARE @LastUpdatedShipStatusHistoryId uniqueidentifier

SELECT @CurrentRecordStateStartDate = Akash_StateStartDate ,
@CurrentRecordShipStatusHistoryId = Akash_ShipStatusHistoryId,
@CurrentRecordShiphistoryShipid = Akash_ShiphistoryShipid
FROM INSERTED

SELECT TOP 1 @LastUpdatedShipStatusHistoryId = Akash_ShipStatusHistoryId
FROM Akash_ShipStatusHistory
WHERE Akash_ShiphistoryShipid = @CurrentRecordShiphistoryShipid AND
Akash_ShipStatusHistoryId != @CurrentRecordShipStatusHistoryId AND
Akash_StateStartDate < GETDATE() AND
DeletionStateCode = '0' AND
Akash_StateEndDate IS NULL
ORDER BY Akash_StateStartDate DESC

IF (@LastUpdatedShipStatusHistoryId IS NOT NULL)
BEGIN
UPDATE Akash_ShipStatusHistoryExtensionBase SET Akash_StateEndDate =@CurrentRecordStateStartDate
WHERE Akash_ShipStatusHistoryId = @LastUpdatedShipStatusHistoryId
END



DECLARE @ShipStatus int --Ship Status
DECLARE @PreviousAwaitingFirstPaymentStatusHistory uniqueidentifier

SELECT @ShipStatus = Akash_ShipStatus ,
@CurrentRecordShiphistoryShipid = Akash_ShiphistoryShipid,
@CurrentRecordShipStatusHistoryId = Akash_ShipStatusHistoryid
FROM INSERTED--Akash_ShipStatusHistory where Akash_ShipStatusHistoryid = 'A6C1BFBB-1C9F-DF11-9AFD-0050569F7F2C'

IF (@ShipStatus IS NOT NULL)
BEGIN

IF (@ShipStatus = 5)
BEGIN

SELECT TOP 1 @PreviousAwaitingFirstPaymentStatusHistory = Akash_ShipStatusHistoryId
FROM Akash_ShipStatusHistory
WHERE Akash_ShiphistoryShipid = @CurrentRecordShiphistoryShipid
AND CreatedOn < GETDATE()
AND Akash_ShipStatusHistoryId != @CurrentRecordShipStatusHistoryId
AND Akash_ShipStatus = 5
ORDER BY CreatedOn DESC

IF(@PreviousAwaitingFirstPaymentStatusHistory IS NOT NULL)
BEGIN



DECLARE @CursorShipStatusHistoryId uniqueidentifier

DECLARE StatusHistoryDeleteCursor
CURSOR FOR SELECT Akash_ShipStatusHistoryid
FROM Akash_ShipStatusHistory
WHERE Akash_ShiphistoryShipid = @CurrentRecordShiphistoryShipid
AND CreatedOn < DATEADD(n,-3,GETDATE())
AND Akash_ShipStatusHistoryId != @PreviousAwaitingFirstPaymentStatusHistory

OPEN StatusHistoryDeleteCursor
FETCH NEXT FROM StatusHistoryDeleteCursor INTO @CursorShipStatusHistoryId
WHILE @@FETCH_STATUS = 0
BEGIN

DELETE FROM Akash_ShipStatusHistoryExtensionBase WHERE Akash_ShipStatusHistoryId = @CursorShipStatusHistoryId
DELETE FROM Akash_ShipStatusHistoryBase WHERE Akash_ShipStatusHistoryId = @CursorShipStatusHistoryId

FETCH NEXT FROM StatusHistoryDeleteCursor INTO @CursorShipStatusHistoryId
END

CLOSE StatusHistoryDeleteCursor
DEALLOCATE StatusHistoryDeleteCursor

UPDATE Akash_ShipStatusHistoryExtensionBase SET Akash_StateEndDate = NULL WHERE Akash_ShipStatusHistoryId = @PreviousAwaitingFirstPaymentStatusHistory
COMMIT TRANSACTION


DELETE FROM Akash_ShipStatusHistoryExtensionBase WHERE Akash_ShipStatusHistoryId = @CurrentRecordShipStatusHistoryId
DELETE FROM Akash_ShipStatusHistoryBase WHERE Akash_ShipStatusHistoryId = @CurrentRecordShipStatusHistoryId



END

END

END

Friday, 3 September 2010

Visual Studio 2010 Short Cut Keys

http://channel9.msdn.com/posts/NicFill/Sara-Fords-101-Visual-Studio-Tips-in-55-Minutes-Challenge/

very good one.

Wednesday, 1 September 2010

Visual Studio 2010 Java Script Debugging

1. Make the internet explorer your default browser

2. uncheck the “Disable Java script” in Advance option in internet explore

3. make the break point and run the program

http://www.youtube.com/watch?v=kzalJRdHro8

Friday, 27 August 2010

javascript

1. getElementById Method

var productElement = document.getElementById("product");

if (productElement != null) {
alert(productElement.innerHTML);
}
else {
alert("its null");
}

2. JavaScript Try...Catch Statement

function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}


3.Link to JS File

JavaScript DateTime

Included in JavaScript is a Date Object. This object is a part of the overall specification of JavaScript and is available to any page that can include JavaScript (these days, that pretty much means any page.) To use it, you create a new date object instance by setting a variable as follows:

ourDate = new Date( )

"ourDate" can be any variable name you wish. This statement (known as a Date Constructor) creates an instance of the Date Object, named ourDate. In its raw form like this, it contains the exact time (as accurately as the local computer knows it) represented in milliseconds past 00:00 on January first, 1970. It's quite a big number! By handling dates and times in this manner, the arithmetic involved in date calculations is greatly simplified. All you need is an easy way to convert back and forth -- and the Date( ) object includes methods for just that purpose. Through these methods, the Date( ) object understands the following date and time fields:

year, month, day, hours, minutes, seconds, milliseconds

The Date( ) object doesn't have properties that can be directly read and written. Instead it has methods that are used to work with the data value in the object. This is a technical difference that stems from the way the date and time is stored. It's not possible to read the month directly, for example, it must be derived from the data by calculation. Calculation requires a method. The Date( ) object includes quite a lot of methods; here's an alphabetically ordered list:
getDate( ) return the day of the month
getDay( ) return the day of the week
getFullYear( ) return the four digit year
getHours( ) return the hours
getMilliseconds( ) return the milliseconds
getMinutes( ) return the minutes
getMonth( ) return the month
getSeconds( ) return the seconds
getTime( ) return the internal representation of the time
getTimezoneOffset( ) return the offset from GMT
getUTCDate( ) return the Universal Time day of the month
getUTCDay( ) return the Universal Time day of the week
getUTCFullYear( ) return the Universal Time four digit year
getUTCHours( ) return the Universal Time hours
getUTCMilliseconds( ) return the Universal Time milliseconds
getUTCMinutes( ) return the Universal Time minutes
getUTCMonth( ) return the Universal Time month
getUTCSeconds( ) return the Universal Time seconds


setDate( ) set the day of the month
setDay( ) set the day of the week
setFullYear( ) set the four digit year
setHours( ) set the hours
setMilliseconds( ) set the milliseconds
setMinutes( ) set the minutes
setMonth( ) set the month
setSeconds( ) set the seconds
setTime( ) set the date and time using the millisecond format
setUTCDate( ) set the Universal Time day of the month
setUTCDay( ) set the Universal Time day of the week
setUTCFullYear( ) set the Universal Time four digit year
setUTCHours( ) set the Universal Time hours
setUTCMilliseconds( ) set the Universal Time milliseconds
setUTCMinutes( ) set the Universal Time minutes
setUTCMonth( ) set the Universal Time month
setUTCSeconds( ) set the Universal Time seconds


toGMTstring( ) return the date and time as a string, using the GMT time zone
toLocaleString( ) return the date and time as a string, using the local time zone
toString( ) return the date and time as a string
toUTCString( return the date and time as a string, using Universal Time


valueOf( ) convert a date to the internal millisecond format

Two other methods, getYear( ) and setYear( ), also exist but are deprecated in favor of the "Full" versions listed above.

The constructor also has two methods that you can invoke. These are Date.parse( ) and Date.UTC( )



small Example as follows

function ak() {
ourDate = new Date();
alert("ak");
document.write(ourDate.getDate());


var myDate = new Date();
var today = new Date();

myDate.setFullYear(2010, 7, 27);

today.setMilliseconds(001);
myDate.setMilliseconds(001);

document.write("My Date" + myDate.getMilliseconds());
document.write("Today" + "
" + today.getMilliseconds() + "
");

document.write("My Date" + myDate + "
");
document.write("Today" + today + "
");

var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
document.write("tomorrow" + tomorrow + "
");
tomorrow.setHours(0);
tomorrow.setMinutes(0, 0, 0);


document.write("tomorrow" + tomorrow + "
");


if (myDate == tomorrow) {
alert("equal");
}

if (myDate >= tomorrow) {
alert("my date is greate than or equel today");
}
else {
alert("my date is less than today");
}


}






Date Object ourDate =
new Date(); - Fri Aug 27 2010 10:28:40 GMT+0100 (GMT Daylight Time)


ourDate.toLocaleString() - 27 August 2010 11:34:36

ourDate.toString() - Fri Aug 27 2010 11:36:13 GMT+0100 (GMT Daylight Time)

ourDate.toGMTstring() -

Thursday, 19 August 2010

Lambda Expressions

Visual Studio 2010Other Versions Visual Studio 2008

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:

VBC#C++F#JScriptCopydelegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
To create an expression tree type:

VBC#C++F#JScriptCopyusing System.Linq.Expressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Expression myET = x => x * x;
}
}
}
The => operator has the same precedence as assignment (=) and is right-associative.

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.

When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func. A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions.Expression where Func is any Func delegates with up to sixteen input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the Where calls to look similar although in fact the type of object created from the lambda is different.

In the previous example, notice that the delegate signature has one implicitly-typed input parameter of type int, and returns an int. The lambda expression can be converted to a delegate of that type because it also has one input parameter (x) and a return value that the compiler can implicitly convert to type int. (Type inference is discussed in more detail in the following sections.) When the delegate is invoked by using an input parameter of 5, it returns a result of 25.

Lambdas are not allowed on the left side of the is or as operator.

All restrictions that apply to anonymous methods also apply to lambda expressions. For more information, see Anonymous Methods (C# Programming Guide).

Expression Lambdas
--------------------------------------------------------------------------------

A lambda expression with an expression on the right side is called an expression lambda. Expression lambdas are used extensively in the construction of Expression Trees (C# and Visual Basic). An expression lambda returns the result of the expression and takes the following basic form:

Copy(input parameters) => expression
The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:

Copy(x, y) => x == y
Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:

Copy(int x, string s) => s.Length > x
Specify zero input parameters with empty parentheses:

Copy() => SomeMethod()
Note in the previous example that the body of an expression lambda can consist of a method call. However, if you are creating expression trees that will be consumed in another domain, such as SQL Server, you should not use method calls in lambda expressions. The methods will have no meaning outside the context of the .NET common language runtime.

Statement Lambdas
--------------------------------------------------------------------------------

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:

Copy(input parameters) => {statement;}
The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.

Copydelegate void TestDelegate(string s);

TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");
Statement lambdas, like anonymous methods, cannot be used to create expression trees.

Lambdas with the Standard Query Operators
--------------------------------------------------------------------------------

Many Standard query operators have an input parameter whose type is one of the Func family of generic delegates. The Func delegates use type parameters to define the number and type of input parameters, and the return type of the delegate. Func delegates are very useful for encapsulating user-defined expressions that are applied to each element in a set of source data. For example, consider the following delegate type:

Copypublic delegate TResult Func(TArg0 arg0)
The delegate can be instantiated as Func myFunc where int is an input parameter and bool is the return value. The return value is always specified in the last type parameter. Func defines a delegate with two input parameters, int and string, and a return type of bool. The following Func delegate, when it is invoked, will return true or false to indicate whether the input parameter is equal to 5:

Copy Func myFunc = x => x == 5;
bool result = myFunc(4); // returns false of course
You can also supply a lambda expression when the argument type is an Expression, for example in the standard query operators that are defined in System.Linq.Queryable. When you specify an Expression argument, the lambda will be compiled to an expression tree.

A standard query operator, the Count method, is shown here:

Copy int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
The compiler can infer the type of the input parameter, or you can also specify it explicitly. This particular lambda expression counts those integers (n) which when divided by two have a remainder of 1.

The following method will produce a sequence that contains all the elements in the numbers array that are to the left of the “9” because that is the first number in the sequence that does not meet the condition:

Copy var firstNumbersLessThan6 = numbers.TakeWhile(n => n <>) with the greater than or equal operator (>=).

Copy var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
Type Inference in Lambdas
--------------------------------------------------------------------------------

When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as described in the C# Language Specification. For most of the standard query operators, the first input is the type of the elements in the source sequence. So if you are querying an IEnumerable, then the input variable is inferred to be a Customer object, which means you have access to its methods and properties:

Copycustomers.Where(c => c.City == "London");
The general rules for lambdas are as follows:

•The lambda must contain the same number of parameters as the delegate type.

•Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.

•The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

Note that lambda expressions in themselves do not have a type because the common type system has no intrinsic concept of "lambda expression." However, it is sometimes convenient to speak informally of the "type" of a lambda expression. In these cases the type refers to the delegate type or Expression type to which the lambda expression is converted.

Variable Scope in Lambda Expressions
--------------------------------------------------------------------------------

Lambdas can refer to outer variables that are in scope in the enclosing method or type in which the lambda is defined. Variables that are captured in this manner are stored for use in the lambda expression even if variables would otherwise go out of scope and be garbage collected. An outer variable must be definitely assigned before it can be consumed in a lambda expression. The following example demonstrates these rules:

Copydelegate bool D();
delegate bool D2(int i);

class Test
{
D del;
D2 del2;
public void TestMethod(int input)
{
int j = 0;
// Initialize the delegates with lambda expressions.
// Note access to 2 outer variables.
// del will be invoked within this method.
del = () => { j = 10; return j > input; };

// del2 will be invoked after TestMethod goes out of scope.
del2 = (x) => {return x == j; };

// Demonstrate value of j:
// Output: j = 0
// The delegate has not been invoked yet.
Console.WriteLine("j = {0}", j);

// Invoke the delegate.
bool boolResult = del();

// Output: j = 10 b = True
Console.WriteLine("j = {0}. b = {1}", j, boolResult);
}

static void Main()
{
Test test = new Test();
test.TestMethod(5);

// Prove that del2 still has a copy of
// local variable j from TestMethod.
bool result = test.del2(10);

// Output: True
Console.WriteLine(result);

Console.ReadKey();
}
}

The following rules apply to variable scope in lambda expressions:

•A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.

•Variables introduced within a lambda expression are not visible in the outer method.

•A lambda expression cannot directly capture a ref or out parameter from an enclosing method.

•A return statement in a lambda expression does not cause the enclosing method to return.

•A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function

Implement and Call a Custom Extension Method

Visual Studio 2010Other Versions Visual Studio 2008

This topic shows how to implement your own extension methods for any type in the .NET Framework Class Library, or any other .NET type that you want to extend. Client code can use your extension methods by adding a reference to the DLL that contains them, and adding a using directive that specifies the namespace in which the extension methods are defined.

To defining and call the extension method
1.Define a static class to contain the extension method.

The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).

2.Implement the extension method as a static method with at least the same visibility as the containing class.

3.The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.

4.In the calling code, add a using directive to specify the namespace that contains the extension method class.

5.Call the methods as if they were instance methods on the type.

Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.

Example
--------------------------------------------------------------------------------

The following example implements an extension method named WordCount in the MyExtensions.StringExtension class. The method operates on the String class, which is specified as the first method parameter. The MyExtensions namespace is imported into the application namespace, and the method is called inside the Main method.

VBC#C++F#JScriptCopy
using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
//Extension methods must be defined in a static class
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Simple
{
//Import the extension method namespace.
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}


Compiling the Code
--------------------------------------------------------------------------------

To run this code, copy and paste it into a Visual C# console application project that has been created in Visual Studio. By default, this project targets version 3.5 of the .NET Framework, and it has a reference to System.Core.dll and a using directive for System.Linq. If one or more of these requirements are missing from the project, you can add them manually. For more information, see How to: Create a LINQ Project.

Covariance and Contravariance in Generics

.NET Framework 4

Covariant and contravariant generic type parameters provide greater flexibility in assigning and using generic types. For example, covariant type parameters enable you to make assignments that look much like ordinary polymorphism. Suppose you have a base class and a derived class, named Base and Derived. Polymorphism enables you to assign an instance of Derived to a variable of type Base. Similarly, because the type parameter of the IEnumerable interface is covariant, you can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable, as shown in the following code.

Windows Azure

link - http://channel9.msdn.com/learn/courses/Azure/WindowsAzure/IntroToWindowsAzureLab/Overview/

Windows Azure
1. Windows Azure services

Web Role - ASP.NET Web application accessible via an HTTP or HTTPS endpoint and is commonly the front-end for an application

User Role - Background-processing applications and are typically found in the back-end

2. Windows Azure storage services

lob services - text and binary data
table services - structured storage that can be queried,
queue services - reliable and persistent messaging between services.


Structure of the Solution

1. Configuration project –

a. olds the configuration for the web and worker roles that compose the cloud application

1. ServiceDefinition.csdef, which contains metadata needed by the Windows Azure fabric to understand the requirements of your application, such as which roles are used,
their trust level, the endpoints exposed by each role, the local storage requirements and the certificates used by the roles. The service definition also establishes
configuration settings specific to the application
2. ServiceConfiguration.cscfg, specifies the number of instances to run for each role and sets the value of configuration settings defined in the service definition file.
3. The Roles node in the cloud service project enables you to configure what roles the service includes (Web, worker or both) as well as which projects to associate with
these roles. Adding and configuring roles through the Roles node will update the ServiceDefinition.csdef and ServiceConfiguration.cscfg files

2. Web Project –

a. standard ASP.NET Web Application project template modified for the Windows Azure environment. It contains an additional class that provides the entry point for the web role and
contains methods to manage the initialization, starting, and stopping of the role.



Data Storage

http://channel9.msdn.com/learn/courses/Azure/Storage/WindowsAzureStorageOverview/

Tuesday, 17 August 2010

Avoid Form Close Alerts in CRM

crmForm.detachCloseAlert();

Windows ServiceController to control the behavior of the service

.NET Framework Class Library
ServiceController Class

Represents a Windows service and allows you to connect to a running or stopped service, manipulate it, or get information about it.

Namespace: System.ServiceProcess
Assembly: System.ServiceProcess (in System.ServiceProcess.dll)
Syntax

[ServiceProcessDescriptionAttribute("ServiceControllerDesc")]
public class ServiceController : Component
Remarks

You can use the ServiceController class to connect to and control the behavior of existing services. When you create an instance of the ServiceController class, you set its properties so it interacts with a specific Windows service. You can then use the class to start, stop, and otherwise manipulate the service.

You will most likely use the ServiceController component in an administrative capacity. For example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. This would be useful, because the Service Control Manager (SCM) Microsoft Management Console snap-in does not support custom commands.

After you create an instance of ServiceController, you must set two properties on it to identify the service with which it interacts: the computer name and the name of the service you want to control.

NoteNote

By default, MachineName is set to the local computer, so you do not need to change it unless you want to set the instance to point to another computer.

Generally, the service author writes code that customizes the action associated with a specific command. For example, a service can contain code to respond to an ServiceBase.OnPause command. In that case, the custom processing for the Pause task runs before the system pauses the service.

The set of commands a service can process depends on its properties; for example, you can set the CanStop property for a service to false. This setting renders the Stop command unavailable on that particular service; it prevents you from stopping the service from the SCM by disabling the necessary button. If you try to stop the service from your code, the system raises an error and displays the error message "Failed to stop servicename."

Examples

The following example demonstrates the use of the ServiceController class to control the SimpleService service example. See the ServiceBase class for the example code for the SimpleService service.

using System;
using System.ServiceProcess;
using System.Diagnostics;
using System.Threading;

namespace ServiceControllerSample
{
class Program
{
public enum SimpleServiceCustomCommands
{ StopWorker = 128, RestartWorker, CheckWorker };
static void Main(string[] args)
{
ServiceController[] scServices;
scServices = ServiceController.GetServices();

foreach (ServiceController scTemp in scServices)
{

if (scTemp.ServiceName == "Simple Service")
{
// Display properties for the Simple Service sample
// from the ServiceBase example.
ServiceController sc = new ServiceController("Simple Service");
Console.WriteLine("Status = " + sc.Status);
Console.WriteLine("Can Pause and Continue = " + sc.CanPauseAndContinue);
Console.WriteLine("Can ShutDown = " + sc.CanShutdown);
Console.WriteLine("Can Stop = " + sc.CanStop);
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
while (sc.Status == ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}
}
// Issue custom commands to the service
// enum SimpleServiceCustomCommands
// { StopWorker = 128, RestartWorker, CheckWorker };
sc.ExecuteCommand((int)SimpleServiceCustomCommands.StopWorker);
sc.ExecuteCommand((int)SimpleServiceCustomCommands.RestartWorker);
sc.Pause();
while (sc.Status != ServiceControllerStatus.Paused)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
sc.Continue();
while (sc.Status == ServiceControllerStatus.Paused)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
sc.Stop();
while (sc.Status != ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
String[] argArray = new string[] { "ServiceController arg1", "ServiceController arg2" };
sc.Start(argArray);
while (sc.Status == ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
// Display the event log entries for the custom commands
// and the start arguments.
EventLog el = new EventLog("Application");
EventLogEntryCollection elec = el.Entries;
foreach (EventLogEntry ele in elec)
{
if (ele.Source.IndexOf("SimpleService.OnCustomCommand") >= 0 |
ele.Source.IndexOf("SimpleService.Arguments") >= 0)
Console.WriteLine(ele.Message);
}
}
}


}
}
}
// This sample displays the following output if the Simple Service
// sample is running:
//Status = Running
//Can Pause and Continue = True
//Can ShutDown = True
//Can Stop = True
//Status = Paused
//Status = Running
//Status = Stopped
//Status = Running
//4:14:49 PM - Custom command received: 128
//4:14:49 PM - Custom command received: 129
//ServiceController arg1
//ServiceController arg2


CRM work flow set property

1.If you want to send the property values in to custom workflow DLL’s syntax should be like
Field – Entity – Default value : {field (entity); default value}

2. If you just wanted to set the hard coded value
set the Default value {value}
CRM work flow set property

1. If you want to send the property values in to custom workflow DLL’s syntax should be like

Field – Entity – Default value : {field (entity); default value}

2. If you just wanted to set the value

Only you have to set the Default value {value}

Create Simple Windows Service - msdn

Link - http://msdn.microsoft.com/en-us/library/zt39148a.aspx


Walkthrough: Creating a Windows Service Application in the Component Designer
NoteNote

The Windows Service template and associated functionality is not available in the Standard Edition of Visual Studio.

The procedures in this topic demonstrate creating a simple Windows Service application that writes messages to an event log. The basic steps that you perform to create and use your service include the following:

  • Create a project by using the Windows Service application template. This template creates a class for you that inherits from ServiceBase and writes much of the basic service code, such as the code to start the service.

  • Write the code for the OnStart and OnStop procedures, and override any other methods that you want to redefine.

  • Add the necessary installers for your service application. By default, a class that contains two or more installers is added to your application when you click the Add Installer link: one to install the process, and one for each associated service that your project contains.

  • Build your project.

  • Create a setup project to install your service, and then install it.

  • Access the Windows 2000 Services Control Manager and start your service.

To begin, you create the project and set values that are required for the service to function correctly.

NoteNote

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Working with Settings.

Creating a Service

To create and configure your service

  1. On the File menu, click New Project.

    The New Project dialog box opens.

  2. Select Windows Service in the list of Visual Basic or Visual C# project templates, and name the project MyNewService. Click OK.

    NoteNote

    The project template automatically adds a component class named Service1 that inherits from System.ServiceProcess.ServiceBase.

  3. Click the designer to select Service1. Then, in the Properties window, set the ServiceName and the (Name) property for Service1 to MyNewService.

Adding Features to the Service

In the next section, you add a custom event log to the Windows service. Event logs are not associated in any way with Windows services. Here the EventLog component is used as an example of the type of component you could add to a Windows service.

To add custom event log functionality to your service

  1. In Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.

  2. From the Components tab of the Toolbox, drag an EventLog component to the designer.

  3. In Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.

  4. Add or edit the constructor to define a custom event log.

     public MyNewService()
    {
    InitializeComponent();
    if (!System.Diagnostics.EventLog.SourceExists("MySource"))
    {
    System.Diagnostics.EventLog.CreateEventSource(
    "MySource","MyNewLog");
    }
    eventLog1.Source = "MySource";
    eventLog1.Log = "MyNewLog";
    }


To define what occurs when the service starts

  • In the Code Editor, locate the OnStart method that was automatically overridden when you created the project, and write code to determine what occurs when the service starts running:

     protected override void OnStart(string[] args)
    {
    eventLog1.WriteEntry("In OnStart");
    }


    NoteNote

    A service application is designed to be long running. Therefore, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system after the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

To define what occurs when the service is stopped

  • In the Code Editor, select the OnStop procedure from the Method Name drop-down list, which was automatically overridden when you created the project. Write code to determine what occurs when the service is stopped:

     protected override void OnStop()
    {
    eventLog1.WriteEntry("In onStop.");
    }


You can also override the OnPause, OnContinue, and OnShutdown methods to define additional processing for your component.

To define other actions for the service

  • For the method that you want to handle, override the appropriate method and define what you want to occur.

    The following code shows what it looks like if you override the OnContinue method:

     protected override void OnContinue()
    {
    eventLog1.WriteEntry("In OnContinue.");
    }


Some custom actions have to occur when a Windows service is installed, which can be done by the Installer class. Visual Studio can create these installers specifically for a Windows service and add them to your project.

To create the installers for your service

  1. In Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.

  2. Click the background of the designer to select the service itself, instead of any of its contents.

  3. With the designer in focus, right-click, and then click Add Installer.

    By default, a component class that contains two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.

  4. In Design view for ProjectInstaller, click ServiceInstaller1 or serviceInstaller1.

  5. In the Properties window, make sure the ServiceName property is set to MyNewService.

  6. Set the StartType property to Automatic.

  7. In the designer, click ServiceProcessInstaller1 (for a Visual Basic project), or serviceProcessInstaller1 (for a Visual C# project). Set the Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.

    Security noteSecurity Note

    The LocalSystem account has broad permissions, including the ability to write to the event log. Use this account with caution, because it might increase your risk of attacks from malicious software. For other tasks, consider using the LocalService account, which acts as a non-privileged user on the local computer and presents anonymous credentials to any remote server.

To build your service project

  1. In Solution Explorer, right-click your project and then click Properties. The project's Property Designer appears.

  2. On the Application page, from the Startup object list, click MyNewService.

  3. Press CTRL+SHIFT+B to build the project.

Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers that are required to run the Windows service. To create a complete setup project you will have to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed. For more information about setup projects, see Setup and Deployment Projects. For more information about custom actions, see Walkthrough: Creating a Custom Action.

To create a setup project for your service

  1. In Solution Explorer, right-click your solution, point to Add, and then click New Project.

  2. Under Installed Templates, expand Other Project Types and then expand Setup and Deployment.

  3. Select Visual Studio Installer.

  4. In the Templates pane, select Setup Project. Name the project MyServiceSetup. Click OK.

    A setup project is added to the solution.

Next you will add the output from the Windows service project, MyNewService.exe, to the setup.

To add MyNewService.exe to the setup project

  1. In Solution Explorer, right-click MyServiceSetup, point to Add, and then click Project Output.

    The Add Project Output Group dialog box appears.

  2. MyNewService is selected in the Project box.

  3. From the list, select Primary Output, and click OK.

    A project item for the primary output of MyNewService is added to the setup project.

Now add a custom action to install the MyNewService.exe file.

To add a custom action to the setup project

  1. In Solution Explorer, right-click the setup project, point to View, and then click Custom Actions.

    The Custom Actions editor appears.

  2. In the Custom Actions editor, right-click the Custom Actions node and click Add Custom Action.

    The Select Item in Project dialog box appears.

  3. Double-click the Application Folder in the list to open it, select Primary Output from MyNewService (Active), and click OK.

    The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.

  4. In Solution Explorer, right-click the MyServiceSetup project and click Build.

To install the Windows Service

  1. To install MyNewService.exe, right-click the setup project in Solution Explorer and select Install.

  2. Follow the steps in the Setup Wizard. Build and save your solution.

To start and stop your service

  1. To open the Services Control Manager in Windows 7, Windows Vista, and Windows Server, right-click Computer on the Start menu, and then click Manage. In the Computer Management console, expand the Services and Applications node in the left pane. Click Services.

    You should now see MyNewService listed in the Services section of the window.

  2. Select your service in the list, right-click it, and then click Start.

  3. Right-click the service, and then click Stop.

To verify the event log output of your service

  1. Open Server Explorer and access the Event Logs node.

    NoteNote

    The Windows Service template and associated functionality is not available in the Standard Edition of Visual Studio.

  2. Locate the listing for MyNewLog and expand it. You should see entries for the actions your service has performed.

To uninstall your service

  • On the Start menu, open Control Panel and click Add or Remove Programs, and then locate your service and click Uninstall.

Next Steps

You might explore the use of a ServiceController component to enable you to send commands to the service you have installed.

You can use an installer to create an event log when the application is installed instead of creating the event log when the application runs. Additionally, the event log will be deleted by the installer when the application is uninstalled.


Windows Service Template

URL :