Pages

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, February 27, 2012

ToolkitScriptManager On MasterPage To Use AjaxControlToolkit Controls


Add ToolkitScriptManager On MasterPage In Asp.Net
How To Add ToolkitScriptManager On MasterPage To Use AjaxControlToolkit Controls On Content Pages In Asp.Net 

When we use AjaxControlToolkit controls on content pages of site with master page, we get some errors becuase ScriptManager or ToolkitScriptManager not placed properly on master page.

One of such error is

"AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll."

This error occurs if you are using .NET framework 3.5 or avobe and have placed ScriptManager on the masterPage.

To fix this error remove ScriptManager and place ToolkitScriptManager on Master Page.


If you receive

"'ToolkitScriptManager' must be placed inside a form tag with runat=server" error

Or

The control with ID 'yourAjaxcontrolID' requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it error.

Then either you have placed ToolkitScriptManager in head section of MasterPage or in ContentPlaceHolder.

ToolkitScriptManager must be placed within the form tag of MasterPage.
If you place ToolkitScriptManager on master page as mentioned above, YOu don't need to put any scriptmanagerproxy or ToolkitScriptManager on content pages.

HTML SOURCE OF MASTER PAGE WITH ToolkitScriptManager SHOULD LOOK LIKE SHOWN BELOW
   1:  <%@ Master Language="C#" AutoEventWireup="true" 
   2:  CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
   3:   
   4:  <%@ Register assembly="AjaxControlToolkit" 
   5:  namespace="AjaxControlToolkit" tagprefix="asp" %>
   6:   
   7:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   8:  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   9:   
  10:  <html xmlns="http://www.w3.org/1999/xhtml">
  11:  <head runat="server">
  12:  <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
  13:  <title>Using AjaxControlToolkit With MasterPage</title>
  14:  <asp:ContentPlaceHolder id="head" runat="server"/>
  15:  </head>
  16:   
  17:  <body>
  18:  <form id="form1" runat="server">
  19:  <div>
  20:  <asp:ToolkitScriptManager ID="ToolkitScriptManager1" 
  21:                            runat="server">
  22:  </asp:ToolkitScriptManager>    
  23:   
  24:  <asp:ContentPlaceHolder id="ContentPlaceHolder1" 
  25:                          runat="server">
  26:  </asp:ContentPlaceHolder>
  27:  </div>
  28:  <p style="text-align: center">master page</p>
  29:  Place your master page contents here 
  30:  </form>
  31:  </body>
  32:  </html>

HTML SOURCE OF CONTENT PAGES WITH AJAX CONTROLS SHOULD LOOK LIKE MENTIONED BELOW
   1:  <%@ Page Title="" Language="C#" 
   2:  MasterPageFile="~/MasterPage.master" 
   3:  AutoEventWireup="true" CodeFile="Default2.aspx.cs" 
   4:  Inherits="Default2" %>
   5:   
   6:  <%@ Register Assembly="AjaxControlToolkit" 
   7:  Namespace="AjaxControlToolkit" TagPrefix="asp" %>
   8:   
   9:  <asp:Content ID="Content1" ContentPlaceHolderID="head" 
  10:               Runat="Server">
  11:  </asp:Content>
  12:   
  13:  <asp:Content ID="Content2" 
  14:               ContentPlaceHolderID="ContentPlaceHolder1" 
  15:               Runat="Server">
  16:   
  17:  <asp:TextBox ID="TextBox1" runat="server"/>
  18:  <asp:PasswordStrength ID="PasswordStrength1" 
  19:                        runat="server" 
  20:                        TargetControlID="TextBox1" 
  21:                        DisplayPosition="RightSide"
  22:                        StrengthIndicatorType="BarIndicator" 
  23:                        BarBorderCssClass="BarBorder"
  24:                        StrengthStyles="BarIndicatorweak;
  25:                        BarIndicatoraverage;BarIndicatorgood;">
  26:  </asp:PasswordStrength>
  27:   
  28:  </asp:Content>

Wednesday, February 22, 2012

How to check htaccess and mod_rewrite is enabled ?


1. Open a blank notepad document

2. Copy and paste the following code into the blank notepad

YOU ARE NOT USING MOD_REWRITE - TRY LINK2';} ELSEIF($_GET['LINK']==2){ECHO'CONGRATULATIONS!! YOU ARE USING APACHE MOD_REWRITE';} ELSE{ECHO 'LINUX APACHE MOD_REWRTE TUTORIAL';} ?>


LINK 1 = LINK 1 Does NOT use Mod Rewrite. LINK 1 uses standard URL:rewrite.php?link=1
LINK 2 = LINK 2 - Yes, Uses Apache's Mod Rewrite using this URL:: link2.html


How this works: both links are for this same page, except they both are different. link one is without the mod_rewrite and link2 is using mod_rewrite. Link1 show the php file, with with mod_rewrite we are mascaraing the php file into a html file. you can use whatever type of extension you want, you can change it to .htm or .shtml etc... all you have to do is to make sure you also chang it in the .htaccess file
NOTE: when you click on LINK2, you should see a message that says: Congratulations!! You are using Apache mod_rewrite
500 ERROR: If you get a 500 Error, this means you made a typo or mistake creating the files OR you are not allowed to use .htaccess
404 ERROR: if you get a 404 error, then this means you do not have Mod_Rewrite on this server.


3. Now Save the file as "rewrite.php"

4. Now create a file called .htaccess - to make this type of file, open another blank notepad document

5. Copy and paste the following code into the .htaccess file:
RewriteEngine On
RewriteRule ^link([^/]*).html$ rewrite.php?link=$1 [L]


6. Save as ".htaccess" (if you are using notepad as I am, make sure to put quotes in between .htaccess example: ".htaccess" otherwise, notepad will create a file called .htacces.txt and we don't need the .txt at the end only .htaccess)

7. Now upload these two file into a new directory in your site. for example: test/

8. Open the rewrite.php file with your browser to the location you just uploaded. for example:
http://www.your_website.com/test/rewrite.php

9. you should see two links, LINK1 and LINK2 Click on LINK1 and the same page will display.

10. Now click on LINK2 and the same page will display with the a mod_rewrite message. If it doesnt you either did something wrong. Check your steps. If you checked your steps, refresh your browser, and if refreshing doesnt work, then you dont have mod_rewrite enabled or you dont have permission to run .htaccess files on your website. talk to your web hosting company to make sure they allow apache .htaccess - Some hosting companies do not allow .htaccess because some people take advantage of this feature, so many web hosting companies block their users from using. so check with them


If you get a 500 Error, then you do not have mod_rewrite enabled in your server.

Tuesday, February 7, 2012

Visual Studio Keyboard Shortcuts

Visual studio keyboard shortcuts.

Below is the list of Commonly used visual studio keyboard shortcuts.

Navigation



Ctrl + ]
Moves the cursor to the matching Closing or Opening brace
Ctrl + hyphen
Moves cursor to its previous position
Shift + F7
Switch between the Design View and Source View
Ctrl + Tab
Displays the all open files in VS
Ctrl + Shift + F
Find 
F3
Search Again or continue search 


Editing


Ctrl + k + c
Comment a selected line or all selected lines of code 
Ctrl + k + u
Uncomment a selected line or all selected lines of code
Ctrl + x, Ctrl + c, Ctrl + v
Cut, Copy, Paste


Code Related


Ctrl +SpaceBar
Complete word if exist
Tab (Twice)
Inserts Code snippet, eg type while and press Tab twice, or type prop and press Tab twice
Ctrl + Period (.)
Shows SmartTag menu 
F5
Start or run the application 
F6 or Ctrl + Shift + B
Build the solution 
F9
Insert or remove breakpoint
Ctrl + S
Save 
Ctrl + Alt + L
Open Solution Explorer

Sunday, October 23, 2011

How MySQL Transaction works ?


A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.

Practically you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.
You can not use transactions directly, you can but they would not be save and guaranteed. If you plan to use transactions in your MySQL programming then you need to create your tables in a special way. There are many type of tables which support transactions but most popular one isInnoDB.
You can execute these SQL commands in PHP by using mysql_query() function.

  1. Begin transaction by issuing SQL command BEGIN WORK
  2. Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE
  3. Check if there is no error and everything is according to your requirement.
  4. If there is any error then issue ROLLBACK command otherwise issue a COMMIT command.
Those who have no idea about the MySQL Transactions can take a look at the below code.
It will help you to get an overall idea about how a transaction works in MySQL.
 
mysql_query("START TRANSACTION");

$a = mysql_query("INSERT INTO table_name (amount) VALUES('100')");
$b = mysql_query("INSERT INTO table_name (amount) VALUES('200')");
if ($a and $b) {
    mysql_query("COMMIT");
} else {        
    mysql_query("ROLLBACK");
}

reffered frm aravindisonline

How MySQL Transaction works ?


A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.

Practically you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.
You can not use transactions directly, you can but they would not be save and guaranteed. If you plan to use transactions in your MySQL programming then you need to create your tables in a special way. There are many type of tables which support transactions but most popular one isInnoDB.
You can execute these SQL commands in PHP by using mysql_query() function.

  1. Begin transaction by issuing SQL command BEGIN WORK
  2. Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE
  3. Check if there is no error and everything is according to your requirement.
  4. If there is any error then issue ROLLBACK command otherwise issue a COMMIT command.
Those who have no idea about the MySQL Transactions can take a look at the below code.
It will help you to get an overall idea about how a transaction works in MySQL.
 
mysql_query("START TRANSACTION");

$a = mysql_query("INSERT INTO table_name (amount) VALUES('100')");
$b = mysql_query("INSERT INTO table_name (amount) VALUES('200')");
if ($a and $b) {
    mysql_query("COMMIT");
} else {        
    mysql_query("ROLLBACK");
}

Monday, August 15, 2011

jQuery Validator Plugin - File upload validation issue : Solved


Hi folks, have you had an issue in validating file upload with jQuery Validatior Plugin.
Sample:
$("#check").validate({
        rules: {
            myfile: {required: true,
                        accept: "png|jpg|gif|jpeg"
                      },
            },
        messages: {myfile: "ERROR"    }
    });

here it checks for file having jpg,png,gif,jpeg extension and it works. But the problem is the if we make a file with name 'foo_bar.1jpg', the validator will take this as a valid file also. Here their plug-in fails....

So i have modified the plug-in code so that it will take only having valid image extension.

Just replace the accept function in the jquery.validate.js to the below code,


accept: function(value, element, param) {
            var truncate = value.split(".");
            value = truncate[1];
            param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
            return this.optional(element) || value.match(new RegExp("^(" + param + ")$", "i"));
        },



reffered by aravindisonline

Wednesday, May 18, 2011

Some PHP Snippets


HIGHLIGHT SPECIFIC WORDS IN A PHRASE

Sometimes, for example,
when displaying search results, it is a great idea to highlight
specific words. This is exactly what the following function can do:
1.function highlight($sString$aWords) {
2.    if (!is_array ($aWords) || empty ($aWords) || !is_string($sString)) {
3.        return false;
4.    }
5. 
6.    $sWords = implode ('|'$aWords);
7.    return preg_replace ('@\b('.$sWords.')\b@si''<strong style="background-color:yellow">$1</strong>'$sString);
8.}
Source: http://www.phpsnippets.info/highlights-words-in-a-phrase

GET YOUR AVERAGE FEEDBURNER SUBSCRIBERS

Recently,
Feedburner counts had lots of problems and it’s hard to say that the
provided info is still relevant. This code will grab your subscriber
count from the last 7 days and will return the average.
01.function get_average_readers($feed_id,$interval = 7){
02.    $today date('Y-m-d'strtotime("now"));
03.    $ago date('Y-m-d'strtotime("-".$interval." days"));
04.    $feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
05.    $ch = curl_init();
06.    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
07.    curl_setopt($ch, CURLOPT_URL, $feed_url);
08.    $data = curl_exec($ch);
09.    curl_close($ch);
10.    $xml new SimpleXMLElement($data);
11.    $fb $xml->feed->entry['circulation'];
12. 
13.    $nb = 0;
14.    foreach($xml->feed->children() as $circ){
15.        $nb += $circ['circulation'];
16.    }
17. 
18.    return round($nb/$interval);
19.}
Source: http://www.catswhoblog.com/how-to-get-a-more-relevant-feedburner-count

AUTOMATIC PASSWORD CREATION

Although
I personally prefer leaving users to choose their password themselves,
a client recently asked me to generate passwords automatically when a
new account is created.
The following function is flexible: You can choose the desired length and strength for the password.
01.function generatePassword($length=9, $strength=0) {
02.    $vowels 'aeuy';
03.    $consonants 'bdghjmnpqrstvz';
04.    if ($strength >= 1) {
05.        $consonants .= 'BDGHJLMNPQRSTVWXZ';
06.    }
07.    if ($strength >= 2) {
08.        $vowels .= "AEUY";
09.    }
10.    if ($strength >= 4) {
11.        $consonants .= '23456789';
12.    }
13.    if ($strength >= 8 ) {
14.        $vowels .= '@#$%';
15.    }
16. 
17.    $password '';
18.    $alt = time() % 2;
19.    for ($i = 0; $i $length$i++) {
20.        if ($alt == 1) {
21.            $password .= $consonants[(rand() %strlen($consonants))];
22.            $alt = 0;
23.        else {
24.            $password .= $vowels[(rand() % strlen($vowels))];
25.            $alt = 1;
26.        }
27.    }
28.    return $password;
29.}
Source: http://www.phpsnippets.info/generate-a-password-in-php

COMPRESS MULTIPLE CSS FILES

If
you’re using different CSS files on your site, they might take quite
long to load. Using PHP, you can compress them into a single file with
no unnecessary white spaces or comments.
This snippet has been previously discussed on my “3 ways to compress CSS files using PHP” article.
01.header('Content-type: text/css');
02.ob_start("compress");
03.function compress($buffer) {
04.  /* remove comments */
05.  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!'''$buffer);
06.  /* remove tabs, spaces, newlines, etc. */
07.  $buffer str_replace(array("\r\n""\r""\n""\t"'  ''    ','    '), ''$buffer);
08.  return $buffer;
09.}
10. 
11./* your css files */
12.include('master.css');
13.include('typography.css');
14.include('grid.css');
15.include('print.css');
16.include('handheld.css');
17. 
18.ob_end_flush();
Source: http://www.phpsnippets.info/compress-css-files-using-php

GET SHORT URLS FOR TWITTER

Are you on Twitter? If yes, you probably use a url shortener such as bit.ly or TinyUrl to share your favorite blog posts and links on the network.
This snippet take a url as a parameter and will return a short url.
1.function getTinyUrl($url) {
2.    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
3.}
Source: http://www.phpsnippets.info/convert-url-to-tinyurl

CALCULATE AGE USING DATE OF BIRTH

Pass
a birth date to this function, and it will return the age of the
person; very useful when building communities or social media sites.
01.function age($date){
02.    $year_diff '';
03.    $time strtotime($date);
04.    if(FALSE === $time){
05.        return '';
06.    }
07. 
08.    $date date('Y-m-d'$time);
09.    list($year,$month,$day) = explode("-",$date);
10.    $year_diff date("Y") – $year;
11.    $month_diff date("m") – $month;
12.    $day_diff date("d") – $day;
13.    if ($day_diff < 0 || $month_diff < 0) $year_diff–;
14. 
15.    return $year_diff;
16.}
Source: John Karry on http://www.phpsnippets.info/calculate-age-of-a-person-using-date-of-birth

CALCULATE EXECUTION TIME

For
debugging purposes, it is a good thing to be able to calculate the
execution time of a script. This is exactly what this piece of code can
do.
01.//Create a variable for start time
02.$time_start = microtime(true);
03. 
04.// Place your PHP/HTML/JavaScript/CSS/Etc. Here
05. 
06.//Create a variable for end time
07.$time_end = microtime(true);
08.//Subtract the two times to get seconds
09.$time $time_end $time_start;
10. 
11.echo 'Script took '.$time.' seconds to execute';
Source: http://phpsnips.com/snippet.php?id=26

MAINTENANCE MODE WITH PHP

When
updating your site, it is generally a good thing to temporarily
redirect your users to a “Maintenance” page so they will not see any
critical info such as error messages.
This is generally done using an .htaccess file, but it can be done easily with PHP:
01.function maintenance($mode = FALSE){
02.    if($mode){
03.        if(basename($_SERVER['SCRIPT_FILENAME']) !='maintenance.php'){
04.            header("Location:http://example.com/maintenance.php");
05.            exit;
06.        }
07.    }else{
08.        if(basename($_SERVER['SCRIPT_FILENAME']) =='maintenance.php'){
09.            header("Location: http://example.com/");
10.            exit;
11.        }
12.    }
13.}
Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php

PREVENT JS AND CSS FILES FROM BEING CACHED

By
default, external files such as javascript and css are cached by the
browser. If you want to prevent this from caching, simply use this easy
tip:
1.<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet"type="text/css" /&glt;
The result will look like this:
1.<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css"/&glt;
Source: http://davidwalsh.name/prevent-cache

ADD (TH, ST, ND, RD, TH) TO THE END OF A NUMBER

Another useful snippet which will automatically add stndrd or th after a number.
01.function make_ranked($rank) {
02.    $last substr$rank, -1 );
03.    $seclast substr$rank, -2, -1 );
04.    if$last > 3 || $last == 0 ) $ext 'th';
05.    else if$last == 3 ) $ext 'rd';
06.    else if$last == 2 ) $ext 'nd';
07.    else $ext 'st';
08. 
09.    if$last == 1 && $seclast == 1) $ext 'th';
10.    if$last == 2 && $seclast == 1) $ext 'th';
11.    if$last == 3 && $seclast == 1) $ext 'th';
12. 
13.    return $rank.$ext;
14.}
Source: http://phpsnips.com/snippet.php?id=37