Thứ Bảy, 12 tháng 12, 2009

A C# Visual Studio.Net, Excel, and InterDev tab control.

Sample Image - cwTab.jpg

Introduction

cwTab is a control written in C# that gives you the ability to add Visual Studio.Net, Excel, and InterDev tabs to any application. The control is fully customizable.

The class is written in C# and uses a double-buffering class provided by Microsoft. The code demonstrates using GDI+ for drawing, event handling, enumerations in C#, overrides, attributes, properties and double buffering. Please see thecontrol.cs file for full details.

If you have any questions or comments please email me at Italo@WeissInc.com. Please let me know what you think.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

source : codeproject

Data Base Independent Data Access Layer

Data Base Independent Data Access Layer
By Nazish Ali Rizvi

Introduction

In this Article I want to describe you how we can approach a data base free data layer.

It doesn't mean that we will not use any database, but we will try to incorporate any data source with our data layer. This kind of problem happen when we are not sure about either data source/Database will be Oracle, SQLServer, Access, etc.

An advantage having with this approach is when data source changes there is no single line change in our database layer.

Scope

C#, VB.NET, Visual Basic, Java (Both Desktop and web)

Implementation of Data Access Layer

Let me describe whatever approaches I have tried to solve this problem. First I thought I have to use Interface level communication rather than implementation as we were doing in past.

Rather than using Sqlconnection, Oledbconnection, SqlCommand, OledbCommand etc.

For connection
- DbConnection.
For Command
- IDbCommand.

One problem solves of specific connection and command objects. Another problem is how I should tell my data access layer to retrieve parameter for stored procedure. Because if I write in the code then our problem is remain we have to modify the data access layer after any data source changes.

Then I have to introduce a file which can be modified on runtime and then ready to another data source.

I introduced an Xml file for this.

                   
Class Diagram

Class Code

For Generic connection and command I use factory method to get the generic connection irrespective of any data source.

private static IDbConnection GetConnectionFromFactory(string strDBProvider, string strDBConnectionString, IDbConnection objIdbConnection)         {             switch (strDBProvider)             {                 case _SQLSERVER:                     {                         objIdbConnection = new SqlConnection(strDBConnectionString);                         break;                     }                 case _ORACLE:                     {                         objIdbConnection = new OleDbConnection(strDBConnectionString);                         break;                     }                 case _OTHER:                     {                         objIdbConnection = new OleDbConnection(strDBConnectionString);                         break;                     }             }             return objIdbConnection;         } 
Similarly for I have to apply this generic theme to all of my ADO.net objects.
public static IDataParameter[] GetParameter(int parmaterCount)         {             IDataParameter[] idbParamters = null;             if (parmaterCount > 0)             {                   switch (/*ConfigurationSettings.AppSettings["providerName"]*/"sqlserver")                 {                     case _SQLSERVER:                         {                             idbParamters = new SqlParameter[parmaterCount];                             break;                         }                     case _ORACLE:                         {                             idbParamters = new OleDbParameter[parmaterCount];                             break;                         }                       case _OTHER:                         {                             idbParamters = new OleDbParameter[parmaterCount];                             break;                         }                 }             }             return idbParamters;         } 
And same operation with DataCommand Objects. There are some comments on ConfigurationSettings.AppSettings.Because I was using this in dll and I cann.t access the ConfigurationSettings.AppSettings object. But we can use any way around on it. Anyhow this is not our point of discussion here.
        public static IDbCommand GetIDBCommand()         {             IDbCommand objIdbComand = null;                switch (/*ConfigurationSettings.AppSettings["providerName"]*/"sqlserver")             {                 case _SQLSERVER:                     {                         objIdbComand = new SqlCommand();                         break;                     }                 case _ORACLE:                     {                         objIdbComand = new OleDbCommand();                         break;                     }                   case _OTHER:                     {                         objIdbComand = new OleDbCommand();                         break;                     }             }               return objIdbComand;         } 
We can pass our stored procedure code and object value array. We have a utility method through which we can access the stored procedure name and it.s collection of parameters.

There is one thing very strictly follow that you have to pass object value array in same sequence of the parameter as you have defined in the stored procedure in the database. This stored procedure parameters sequence is also reflecting in the configXml file.

Retrieving stored procedure information form Configuration file

XmlNodeList xnlstParamtercollection = xnode.SelectNodes("parameterMappings/parameter");               if (xnlstParamtercollection != null && xnlstParamtercollection.Count > 0)             {                 IDBParameter = DataProvider.GetParameter(parameterValues.Length);                 int paramcounter = 0;                 foreach (XmlNode name in xnlstParamtercollection)                 {                     IDBParameter[paramcounter] = DataProvider.GetParameterInstance();                     IDBParameter[paramcounter].ParameterName = name.SelectNodes("@name").Item(0).InnerXml;                     IDBParameter[paramcounter].Value = parameterValues[paramcounter];                       if (name.SelectNodes("@direction").Item(0).InnerXml == DEFAULT_PARATMER_DIRECTION)                         IDBParameter[paramcounter].Direction = ParameterDirection.Input;                      else                         IDBParameter[paramcounter].Direction = ParameterDirection.Output;                     objIdbCommand.Parameters.Add(IDBParameter[paramcounter]);                       paramcounter++;                 }             } 
There is also possibility that you can retrieve the parameter collection from the SQLServer directly .But anyway this is working fine. Because here is our main intention is database free DAL.

Specialized parameter retrieving mechanism for SQLServer

But now consider the scenario when we have specially data source SQLServer. Then we have to use this function which is not including in my code but you can consider it.

private static SqlParameter[]   DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)             {                   if( connection == null ) throw new ArgumentNullException( "connection" );                   if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );                     SqlCommand cmd = new SqlCommand(spName, connection);                   cmd.CommandType = CommandType.StoredProcedure;                     connection.Open();                   SqlCommandBuilder.DeriveParameters(cmd);                   connection.Close();                     if (!includeReturnValueParameter)                    {                         cmd.Parameters.RemoveAt(0);                   }                                    SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];                     cmd.Parameters.CopyTo(discoveredParameters, 0);                     // Init the parameters with a DBNull value                   foreach (SqlParameter discoveredParameter in discoveredParameters)                   {                         discoveredParameter.Value = DBNull.Value;                   }                   return discoveredParameters;             } 
I will try my best to improve this article in next version because truly speaking this is an idea how we can implement this Database frees DataAccessLayer. But I am sure when you people read it then you can also incorporate your ideas in it or you can give me suggestion which is very helpful for me.

Future Development

This bit is pretty much up to you guys, if anyone makes any valid suggestions I'd be more than happy to implement them.

History

Version 1.0

source : http://www.csharphelp.com/archives4/archive706.html

C#

This section provides a quick tour of the C# language.

C# Language Specifications

C# Language References

  • C# Keywords
    Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.
  • C# Operators
    C# provides a large set of operators, which are symbols that specify which operations to perform in an expression. C# predefines the usual arithmetic and logical operators, as well as a variety of others. In addition, many operators can be overloaded by the user, thus changing their meaning when applied to a user-defined type.
  • C# Preprocessor Directives
    Learn about C#'s conditional compilation directives.
  • C# Language Features
    Learn about arrays, Main method, properties, indexers, passing parameters, and other language features
  • C# Language Tutorials

    The C# tutorials provide an overview of the basics of the language and identify important language features. Each tutorial includes one or more sample programs. The tutorials discuss the sample code plus provide additional background information. They also link to the corresponding sample abstract topics, where you can download and run the sample programs.

How to use Ajax with CakePHP using jQuery ..

With this post, I am going to explain how to make AJAX calls using jQuery in cake php. Effective posting related to this topic is very rare. Cake php is a PHP framework designed using MVC pattern. You have model, controller and view. In the cake php layout page, normally you add the fallowing code somewhere in the page.

After executing the controller funcitons, the relavent view *.ctp file will be rendered where you have placed above code inside the layout page. If you consider blog example, after executing PostsController is view() action, view.ctp file will be rendered. This is the default behaviour of cake php. But, you may need more control when rendering view files in cake php than the above default behaviour. Sometime, you may need to load the relavent view file is contents into a spacific DIV tag in currently rendered page without refreshing the page. In this case, you may need AJAX support with cake php. I will explain how to do this with cake php. And also, I am going to explain how to get JSON response from cake php is controller function and update some contents of the page with javascript function. I am going to use jQuery support for this functionality. To have jQuery support for my cake php project, I include the fallowing in my laytout page.(This layout may be default.ctp or your own another layout page).

link(jquery-1.3.2);?>

The above line links jquery-1.3.2.js file to my layout page.
Now, you we have jQuery support for our business. But not all. jQuery has sevaral UI supports. Next, we will start the real task. I am going to create the client side javascript function that makes AJAX request to cake php controller is action.

I am going to create Post data view function(Think about cake php blog example) with ajax support. Post title will be listed as links, and when user clicks on link, the relavent post information will display in a DIV tag somewhere in the same page.


)">



$posts is a variable defined in a controller before rendering this page.
The above code shows how to create list of links using cake php. When click on each link, viewPost() function will be called and relavent post id will be passed into that function. The viewPost() function will take the responsibilities to make the AJAX request to cake php action and subsequently update the page contents.

The javascript code for the viewPost() function as fallows.

function viewPost(postId){
var data = "id="+ postId;
$.ajax({
type: "post", // Request method: post, get
url: "/cake/index.php/posts/view/", // URL to request
data: data, // post data
success: function(response) {
document.getElementById("post-view").innerHTML = response;
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
}

$.ajax() is a jquery function that suports to make AJAX request to the server. You have to specify the path to your cake php action for url option. "success" and "error" are tow callback functions suporting by $.ajax() function. "success" callback function will be fired with the succesfull response from the server. If some error occured at the server "error" callback function will be fired. The code for updating client side with successfull response should take place inside the "success" callback function.

The "success" callback function will be passed the contents of the response page if the server response type is ext/html. In this case, response will be the contents of /app/views/posts/view.ctp file. In this case the server response type will be ext/html. "success" callback function will receive the reponse data and set as the inner html of the DIV tag with id "post-view". You can do what ever with the response data. Keep in mind, this response data is just text or html. Using data option, we can pass some data into the server as http post data.
Next, we will explore the server side code for the view action in cake php controller.

The code as fallows.

function view($id = null) {
Configure::write( wouldebug, 0);
if($id == null){
$id = $_POST["id"];
}
$this->pageTitle = View Post;
if($this->RequestHandler->isAjax()) {
$post = $this->Post->findById($id);
$this->set(post, $post);
$this->layout = ajax;
$this->render(view);
} else {
$post = $this->Post->findById($id);
$this->set(post, $post);
$this->layout = post_layout;
$this->render(view);
}
}

This function supports for both behaviours. The cake php default behaviours and also this function responses for AJAX request. Function checks the request type for ajax or normal request and then proceed based on that. Cake php is RequestHandler component helps to check the request type.If the request is AJAX request, the layout is being changed to ajax to support for a ajax response.
When the request is ajax, /app/views/posts/view.ctp file is content will be passed to the client as normal text/html. Then from the client side, "success" callback function will get this response and update the client page. If the request is normal request,/app/views/posts/view.ctp file will render in default cake php is behaviour, where you have placed .

Next we will consider,how to get the response as JSON object from cake php is controller action. Some time you may need to get JSON object as the response from the php controller is action. With slight changes to above code, we can have a JSON response. The javascript function making the AJAX request as fallows.

function viewPost(postId){
var data = "id="+ postId;
$.ajax({
type: "post", // Request method: post, get
url: "/cake/index.php/posts/view/", // URL to request
data: data, // Form variables
dataType: "json", // Expected response type
success: function(response) {
var sb = [];
sb[sb.length] = "Title :" + response.data.title + "";
sb[sb.length] = "Body :" + response.data.body;
document.getElementById("post-view").innerHTML = sb.join("");
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
}

Note that, I have specified the dataType option as "json". This is important, if we want to get JSON response from the server. JSON object from the server will automatically converted into a javascript object. Then we can traverse the object and update the page with some dynamic html.

Next we will see the server side code, which makes the json response.

function view($id = null) {
if($id == null){
$id = $_POST["id"];
}
$post = $this->Post->findById($id);
$this->set(post, $post);
$this->pageTitle = View Post;
if($this->RequestHandler->isAjax()) {
Configure::write( wouldebug, 0);
$post = $this->Post->findById($id);
$this->layout = ajax;
$this->autoLayout = false;
$this->autoRender = false;
$this->header(Content-Type: application/json);

$data = array();
$result = array();
$data = array( itle => $post[Post][ itle],
ody => $post[Post][ody]);
$result[ istatus] = "success";
$result[ wouldata] = $data;
echo json_encode($result);
return;

} else {
$this->layout = post_layout;
$this->render(view);
}
}


This function also supports for both the behaviours, ie: cake php is default behaviour which renders /app/views/posts/view.ctp file after executing the action method. If the request is ajax request, it creates a JSON object and send it back to the browser as the response. PHP json_encode() function makes PHP array into JSON object. Note that, I have set change the layout to ajax and autoRender to false. Content type should be set to application/json for JSON response. Like this you can response any of data as JSON objects back to the browser. In the client side, use some javascript to create the dynamic html from these data. You can do nice ajax with JSON. Personally, I like JSON. I hope you too.

Original Source:
http://siriwardana.blogspot.com/2009/11/ajax-calls-with-cake-php-using-jquery.html

CakePHP jQuery Ajax Helper (Easy Scriptaculous Replacement)

We created this cakephp ajax helper so we could easily replace Scriptaculous with jQuery without changing the code and still have built-in functionality like pagination working properly. The helper could still be improved, but we have decided to publicly release it so that CakePHP developers can utilize it for CakePHP Development.


Download It Here

To install it, all you need to do is to drop in the new ajax.php file into views/helpers/. This jQuery ajax library is using the same syntax as the original ajax lib(except for in-place editor). So, it makes replacing the Scriptaculous with jQuery a peace of cake.

The libraries needed are jquery.js, jquery.form.js(http://malsup.com/jquery/form/), and jquery.editable.js (http://www.appelsiini.net/projects/jeditable).

The only limitation the jQuery Ajax helper has compared to the original Ajax helper that it only supports updating a single div. So, you can’t update multiple divs with a single ajax call.

Here is the example usage:


echo $ajax->link('Ajax link', '/ajax_test/post_test', array(
'update' => 'ajax_reply'
));
?>


echo $ajax->form('test', 'post', array('model' => 'Test', 'url' => '/ajax_test/post_test', 'update' => 'ajax_reply'));
echo $form->input('Test.value', array('id' => 'test_observe'));
echo $form->end('Submit');
?>


Test text...

echo $ajax->editor('ajax_editor', '/ajax_test/editor_test', array(
'cancel' => 'Cancel',
'submit' => 'OK',
'onblur' => 'submit',
'tooltip' => 'Click to edit',
'callback' => "function(value, settings){ alert(value); }",
)); ?>



echo $ajax->observeField('test_observe', array(
'url' => '/ajax_test/post_test',
'update' => 'ajax_reply'
));
?>

source: blog.loadsys

When you are in an administration panel, sometimes you want a "quick save" feature that allows you to save without leaving the page. Here is how to accomplish this with CakePHP and jQuery.

To start, download jQuery and the jQuery Form Plugin JavaScript. Include them in your view with the JavaScript helper:Copy Codeblock to Clipboard

PHP:
  1. $javascript->link(array('jquery', 'form'), false);

Include the RequestHandler in your controller detect an Ajax save attempt. Also include the JavaScript helper if you haven't already.

Copy Codeblock to Clipboard

PHP:
  1. var $helpers = array('Javascript');
  2. var $components = array('RequestHandler');

Next we want to override our save function with the ajax quick save. Put this right before your $this->Model->save($this->data) in your save action.

Copy Codeblock to Clipboard

PHP:
  1. if ($this->RequestHandler->isAjax()) {
  2. if ($this->Article->save($this->data)) {
  3. echo 'success';
  4. }
  5. Configure::write('debug', 0);
  6. $this->autoRender = false;
  7. exit();
  8. }

This detects if the request is ajax, then saves the data. Then it sends back a simple, "success" message to let you know things went fine. It also writes debug to 0 and doesn't render anything, then exits.

Lastly, lets create and include a JavaScript file that performs the quick save.

Copy Codeblock to Clipboard

JavaScript:
  1. jQuery(function($){
  2. $('')
  3. .click(function(){
  4. $(this).parents("form:first").ajaxSubmit({
  5. success: function(responseText, responseCode) {
  6. $('#ajax-save-message').hide().html(responseText).fadeIn();
  7. setTimeout(function(){
  8. $('#ajax-save-message').fadeOut();
  9. }, 5000);
  10. }
  11. });
  12. return false;
  13. })
  14. .appendTo('form div.submit');
  15. });

This adds a button called, "Quick Save" to each form on the page where a div with class="submit"exists (you may want to switch this to the id of the form you want to add quick save to). Then It also attaches a click event to the button that submits the form via the jQuery Form Plugin.

In a few simple steps, we've created a quick save feature that saves your data whenever you want without leaving the page.