How to convert ORACLE XML String - CLOB as Valid XML and fetch values using XPATH

  -- Create the test table with a CLOB column
  CREATE a table with name - "SampleXmlCLOB" along with following columns
  ID INTEGER PRIMARY KEY,
  Subject VARCHAR(256),
  XML_CLOB_STRING CLOB

Table created.

How to read value using XPATH :
SELECT XmlType(SampleXmlCLOB .XML_CLOB_STRING).EXTRACT('//DATAMATRIX/FSDATAMATRIX[1]/FIELD1/text()').GETSTRINGVAL() FROM 
SampleXmlCLOB  WHERE SampleXmlCLOB .ID = 100

Internet Explorer - CSS CONDITIONAL Comments

Microsoft implemented conditional comments in their browser, which allow you to link a stylesheet that will be interpreted by a browser alone.



You can also target only a certain version of IE:
















While conditional comments are better, we can also target some versions of Internet Explorer using the following syntax:
.class {
  width:200px; /* All browsers */
  *width:250px; /* IE */
  _width:300px; /* IE6 */
  .width:200px; /* IE7 */
}
Since this technique is not W3C compliant,conditional comments is best option. For more details please refer Microsoft official documentation -
http://msdn.microsoft.com/en-us/library/ms537512%28VS.85%29.aspx

How to RESET Default CSS Styles set by browsers

Web browsers define different default styling for html elements, the first thing to do is to always include a CSS reset in your stylesheet. By using this code, you're already eliminating lots of future headaches.

html,body,div,ul,ol,li,dl,dt,dd,h1,h2,h3,h4,h5,h6,pre,form,p,blockquote,fieldset,input,hr {margin:0; padding:0;}
h1,h2,h3,h4,h5,h6,pre,code,address,caption,cite,code,em,strong,th {font-size:1em; font-weight:normal; font-style:normal;}
ul,ol {list-style:none;}
fieldset,img,hr {border:none;}
caption,th {text-align:left;}
table {border-collapse:collapse; border-spacing:0;}
td {vertical-align:top;}

ADD FILE HEADER OR CHANGE LOG TO FILES IN VISUAL STUDIO BY USING MACRO

Adding the Macro:
1. Click “Tools” menu
2. Click “Macros” menu item
3. Click “Macros IDE…” menu choice
4. Right click on “My Macros”
5. Click “Add” menu item
6. Choose “Add Module…” (a module is a VB term for a static C# class with all static members)
7. Enter the name of “FileHeader” (or whatever you want to name your module)
8. Paste the code below and update any variables to match your organization or name

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module FileHeader

    Sub FileHeader()
        Dim doc As Document
        Dim docName As String
        Dim companyName As String = "My Company"
        Dim authorName As String = "Benedict Alphonse"
        Dim copyrightText As String = "© 2009 My Company. All rights reserved"
        Dim Email As String = "benedictkmu@gmail.com"
        Dim Summary As String

        ' Get the name of this object from the file name
        doc = DTE.ActiveDocument

        ' Get the name of the current document
        docName = doc.Name

        ' Set selection to top of document
        DTE.ActiveDocument.Selection.StartOfDocument()
        DTE.ActiveDocument.Selection.NewLine()

        ' Write first line
        DTE.ActiveDocument.Selection.LineUp()
        DTE.ActiveDocument.Selection.Text = "#region File Header"
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "// ******************************************************************************************************************"
        DTE.ActiveDocument.Selection.NewLine()

        ' Write copyright tag
        DTE.ActiveDocument.Selection.Text = "// "
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "//     " + copyrightText
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "// "

        ' Write author name tag (optional)
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "// " + authorName + ""
        DTE.ActiveDocument.Selection.NewLine()

        ' Write email  tag (optional)
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "// " + Email + ""
        DTE.ActiveDocument.Selection.NewLine()

        ' Write email  tag (optional)
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "// " + docName + ""
        DTE.ActiveDocument.Selection.NewLine()

        ' Write email  tag (optional)
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "//------------------------------Revision History---------------------------------------------------------------------"
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "// Date             Author                  Change Log Comments"
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "//" + DateTime.Now.ToString("MMM/dd/yyyy") + "        " + authorName + "               " + "Newly Created" + "                  "
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "//                                                             "
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "//                                                             "
        DTE.ActiveDocument.Selection.NewLine()
        ' Write last line
        DTE.ActiveDocument.Selection.Text = "// ******************************************************************************************************************"
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "#endregion"
    End Sub

End Module

Macro Results This creates the following text inserted into the top of the source code document:
#region File Header
// ******************************************************************************************************************
// 
//     © 2009 My Company. All rights reserved
// 
// Benedict Alphonse

// benedictkmu@gmail.com

// ReportUtils.cs

//------------------------------Revision History---------------------------------------------------------------------
// Date             Author                  Change Log Comments
//Dec/01/2009        Benedict Alphonse               Newly Created                  
//                                                             
//                                                             
// ******************************************************************************************************************
#endregion
Adding Macro to Toolbar: To add this to a toolbar in your IDE:
1. Click “Tools” menu
2. Click “Customize…” menu choice
3. Activate “Commands” tab
4. Choose “Macros” category
5. Select “MyMacros.FileHeader.FileHeader” (or whatever you named it)
6. Drag command to your toolbar.
7. You can customize the icon, text, visibility of text/icon, etc. by right clicking on the toolbar button
8. Close customization dialog

Render Crystal Report in different file formats without CrystalReportViewer

public static void RenderCrystalReport(DataSet ResultSet, String ReportLocation, String RenderType,HttpResponse Response)
        {
            MemoryStream oStream = new MemoryStream();
            ReportDocument crystalReport = new ReportDocument();
            crystalReport.Load(HttpContext.Current.Server.MapPath(ReportLocation));
            crystalReport.SetDataSource(ResultSet);

            switch (RenderType)
            {
                case "PDF":
                    oStream = crystalReport.ExportToStream(ExportFormatType.PortableDocFormat) as MemoryStream;
                    Response.Clear();
                    Response.Buffer = true;
                    Response.ContentType = "application/pdf";
                    break;

                case "DOC":
                    oStream = crystalReport.ExportToStream(ExportFormatType.WordForWindows) as MemoryStream;
                    Response.Clear();
                    Response.Buffer = true;
                    Response.ContentType = "application/doc";
                    break;

                case "XLS":
                    oStream = crystalReport.ExportToStream(ExportFormatType.Excel) as MemoryStream;
                    Response.Clear();
                    Response.Buffer = true;
                    Response.ContentType = "application/vnd.ms-excel";
                    break;

            }


            Response.BinaryWrite(oStream.ToArray());
            Response.End();
        }

ORACLE CUSTOM FUNCTION - SPLIT DELIMITER STRING

-- User Defined Types to Hold string as table Starts --
CREATE OR REPLACE TYPE SPLITTED_TEXT AS OBJECT(SPLITTED_VALUE VARCHAR2(50));
CREATE OR REPLACE TYPE SPLITTED_TEXT_TABLE AS TABLE OF SPLITTED_TEXT;
-- User Defined Types to Hold string as table Ends--

-- Function to split delimiter string Starts --

CREATE OR REPLACE
FUNCTION OBF_SPLIT_DELIMITER_STRING_FN(p_string IN VARCHAR2, p_delimiter IN VARCHAR2)
RETURN SPLITTED_TEXT_TABLE PIPELINED
AS
    v_length   NUMBER := LENGTH(p_string);
    v_start    NUMBER := 1;
    v_index    NUMBER;
    --v_tempstring SPLITTED_TEXT_TABLE.SPLITTED_VALUE%type;
BEGIN
    WHILE(v_start <= v_length)
    LOOP
        v_index    := INSTR(p_string, p_delimiter, v_start);

        IF v_index = 0
        THEN    
           -- v_tempstring := SUBSTR(p_string,v_start);
            PIPE ROW(new SPLITTED_TEXT(SUBSTR(p_string,v_start)));
            v_start    := v_length + 1;
        ELSE
            --v_tempstring := SUBSTR(p_string, v_start, v_index - v_start);
            PIPE ROW(new SPLITTED_TEXT(SUBSTR(p_string, v_start, v_index - v_start)));
            v_start    := v_index + 1;
        END IF;
    END LOOP;

    RETURN;
END OBF_SPLIT_DELIMITER_STRING_FN;

-- Function to split delimiter string Ends--

-- Usage of Function Starts --

select * from table(OBF_SPLIT_DELIMITER_STRING_FN('one#two#three#four','#'))

-- Usage of Function Ends--

ORACLE CUSTOM FUNCTION - DELETE DB OBJECTS BY TYPE AND NAME

This function used to delete oracle DB objects such as Table,View And Index Etc.

--------- Function Body Starts ---------------

FUNCTION FIND_AND_DELETE_OBJECT_FN(STR_OBJECT_TYPE IN VARCHAR2,STR_OBJECT_NAME IN VARCHAR2)
RETURN VARCHAR2
IS
v_exist  INTEGER;
v_output VARCHAR2(10) := 'FAIL';
BEGIN
 select count(*) into v_exist from all_objects where OBJECT_NAME = STR_OBJECT_NAME AND OBJECT_TYPE = STR_OBJECT_TYPE;
 if v_exist = 1 then
  EXECUTE IMMEDIATE 'TRUNCATE TABLE '||STR_OBJECT_NAME;
  EXECUTE IMMEDIATE 'DROP TABLE '||STR_OBJECT_NAME;
  v_output := 'SUCCESS';
 end if;
RETURN v_output;
exception when others then
 raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END OBF_FIND_AND_DELETE_OBJECT_FN;

--------- Function Body Ends ---------------

-------- Function Usage Starts --------------

DECLARE
  STR_OBJECT_TYPE VARCHAR2(200);
  STR_OBJECT_NAME VARCHAR2(200);
  v_Return VARCHAR2(200);
BEGIN
  STR_OBJECT_TYPE := 'TABLE';
  STR_OBJECT_NAME := 'FSSPECANDTECH';
  v_Return := OBF_FIND_AND_DELETE_OBJECT_FN(
    STR_OBJECT_TYPE => STR_OBJECT_TYPE,
    STR_OBJECT_NAME => STR_OBJECT_NAME
  );
  DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

-------- Function Usage Ends--------------

Ultimate Developer and Power Users Tool List for Windows

I got to know that Scott Hanselman's 2009 Ultimate Developer and Power Users Tool List for Windows. This is very handy list. you can get more info of these lists from http://www.hanselman.com/blog/ScottHanselmans2009UltimateDeveloperAndPowerUsersToolListForWindows.aspx

Javascript - Multiple Email Addresses Validation

Function :



Cheatsheets - Every WebDeveloper Mush Have

JavaScript

JavaScript Cheat Sheet

Addison-Wesley’s JavaScript Reference Card

JavaScript Quick Reference

JavaScript and Browser Objects Quick Reference

JavaScript in 10 Minutes

CSS

CSS Help Sheet

CSS Shorthand Guide

CSS Cheat Sheet

Cascading Style Cheat Sheet

CSS Cheat Sheet

CSS Quick Reference

Leslie Franke CSS Cheat Sheet

Design 215 CSS Quick Reference

CSS Level 1 Quick Reference

CSS Level 2 Quick Reference

CSS Property Index

HTML/XHTML

HTML Help Sheet

XHTML Cheat Sheet

HTML Cheat Sheet

HTML Character Entities Cheat Sheet

PDF HTML Cheat Sheet

Character Entity References in HTML 4 and XHTML 1.0

HTML & XHTML Cheat Sheet

HTML Tags

HTML Quick Reference Guide

A Simple Guide to HTML

Reference HTML Cheat Sheet

HTML Tags Cheat Sheet

AJAX

What’s Ajax? Cheat Sheet

Prototype Cheat Sheet

Scriptaculous Combination Effects Cheat Sheet

Scriptaculous Cheat Sheet

AJAX for ASP.net Cheat Sheet

ASP.net AJAX Client Life-Cycle Events

MooTools Cheat Sheet

Colors

RGB Hex Color Chart

Interactive Color Picker

HTML Color Codes

Color Reference Guide

Microformats

Microformats Helper Cheat Sheet

Microformats Cheat Sheet

Jack Daniel’s Microformats Cheat Sheet

Browser Compatibility

W3C DOM Compatibility Tables

Browser Compatibility Interactive Table

XML

Fusebox 4.1 XML Cheat Sheet

VoiceXML Reference

MathML Reference

XML Schema 2001 Reference

XML Schema 2000/10

XSLT Quick References

XML TopicMaps 1.0 - Quick Reference Card

XML Quick References

XML Schema - Structures Quick Reference

XML Schema - Data Types Quick Reference

XSL FO Reference

XSLT Quick Reference Card

XSLT Reference

PHP

Jack Daniel’s PHP Cheat Sheet (HTML)

Interactive PHP Cheat Sheet (HTML)

Blue Shoes Developer - PHP Cheat Sheet (HTML)

PHP Cheat Sheet (HTML)

PHP Cheat Sheet (HTML)

Regular Expressions Reference Sheet (HTML)

Tiger PHP Cheat Sheet (PDF)

PHP 4 Reference Card (PDF)

PHP Templates Cheat Sheet (PDF)

Ruby

Ruby Cheat Sheet (PDF)

Jack Daniel’s Ruby on Rails Cheat Sheet (HTML)

Textmate Rails Cheat Sheet (PDF)

Zen Spider Ruby Quick Reference (HTML)

Rails Reference 1.1 (PDF)

Rails Active Resource Cheat Sheet (PDF)

ActiveRecord Relationships (PDF)

Rails Strings Cheat Sheet (PDF)

What Goes Where Cheat Sheet (PDF)

Ruby on Rails Cheat Sheet (PDF)

Ruby on Rails Form Helpers (PDF)

Perl

Perl Quick Reference (PDF)

Perl Cheat Sheet (HTML)

Perl 5 Cheat Sheet (HTML)

Perl Testing Reference Card (PDF)

Perl Quick Reference Card (PDF)

ASP.net

ASP.net Page Lifecycle Diagram (PNG)

.NET Format String Quick Reference (PDF)

ASP.NET 2.0 Page Life Cycle & Common Events (PDF)

Visual Studio 2005 Built-in Code Snippets (C#) (PDF)

Visual Studio 2005 Default Keybindings C# (PDF)

Visual Studio 2005 Default Keybindings VB.net (PDF)

ASP.NET AJAX Client Life Cycle & Events (PDF)

VB.net and C# Comparison (PDF) (Word)

Casting in VB.net and C# (HTML)

ASP.net Basics (PDF)

Python

Python 2.4 Cheat Sheet (HTML)

Python 2.2 Quick Reference (HTML)

Python Cheat Sheet (HTML)

Python 101 Cheat Sheet (HTML)

Python PHP Cheat Sheet (PDF)

Python Quick Reference (PDF)

ColdFusion

ColdFusion Reference Sheet (PDF)

ColdFusion Cheat Sheet (HTML)

ColdFusion Quick Reference (HTML)

Java / JavaServer Pages

JavaServer Pages Syntax (PDF)

JSP 2.0 XML Cheat Sheet (HTML)

Java Cheat Sheet : Java Glossary (HTML)

Java Reference Sheet (PDF)

MySQL

Jack Daniel’s MySQL Cheat Sheet (PDF) (PNG)

MySQL Reference Card (PDF)

Neal Parikh MySQL Cheat Sheet (HTML)

MySQL Reference Sheet (PDF)

Handy Cheat-Sheet of MySQL Commands (HTML)

MySQL Commands (HTML)

SQL Injection Cheat Sheet (HTML)

SQL Server

Jack Daniel’s SQL Server Cheat Sheet (PDF) (PNG)

A to Z SQL Server 2005 (HTML)

SQL Injection Cheat Sheet (HTML)

Mistakes what we are doing frequently in Software Development

1. Not understanding the user’s needs. Lack of user input, or not even asking. 2. Underestimating the size of the project. 3. Rushing through the planning stage, or avoiding the planning all together. Code first, plan later! BAD! 4. Not testing early enough, often, or at all! Make it a habit! 5. Choosing the “Cool” methodology at the time, vs. one that has worked in the past. Which leads into my next point… 6. Not using a methodology. 7. Letting a software developer run the software development project. 8. Bored, unmotivated team! You have to motivate your developers! If you can’t motivate, don’t bother trying to lead. Your team will fall asleep, literally. 9. Planning on catching up later. You won’t… don’t even think it! 10. Non Source Control! Ouch.. not good people… and no, just installing a software package is not it… 11. Deciding to switch your development tools when you’re already into the project. 12. Allowing feature creep. Just say NO! Everyone will be happier in the end. 13. Omitting necessary tasks to shorten the project plan. Really, what’s the point of doing this? 14. Insufficient management controls in the development project. 15. Lack of high level business sponsorship. 16. Adding people at the end of the project to “speed things up”. You will only slow things down… 17. No unit testing. Heck if you can do it, use Visual Studio Team Foundation Server and set up some automated testing nightly. 18. Stressed out software developers. If you have managed to perform even one or two of these software development mistakes, you will have a stressed out bunch of programmers to deal with! 19. Lack of error handling. 20. “Off by one” errors. These happen a lot during the software development process.. *sigh*. 21. Typos… Just use option strict and explicit please.. during one software development project, which I was on as a consultant, they were getting ridiculous amounts of errors everywhere… turned out the developer couldn’t spell and would declare variables with incorrect spelling.. no big deal, until you use the correct spelling when you’re assigning a value to it… and you had option explicit off. Ouch to them… 22. No understand the deployment or hardware the software is to be installed on. Ohhhh it’s for a Macintosh… lol. Well hopefully not that bad, but you get the point. 23. No naming style or code conventions. Honestly it doesn’t matter what you use… as long as you are consistent with the rest of the team, and hopefully at least yourself. 24. Using global variables everywhere. These are NOT your friend and hog memory like nothing you have ever seen before! 25. Not asking for help at all during the software development process. If you’re stuck, don’t fight with it for hours on end! Ask for help! 26. Not commenting your code. 27. Hogging all information to yourself. You think you’re more valuable this way? You’re actually not and there is a plan brewing to get you kicked off the development project, and possibly out of the company. You might want to brush up your sign “Will code for pizza!”. 28. Performing database operations at the application layer instead of the database layer. Not only is this putting the processing juice on your application instead of your server, but you have put your database at risk of data integrity issues, and getting bad data! Some of my hipster cool friends are always saying “It’s alllll good”, well, if your database can be caught saying this… and If everything looks good to your database, then you should be worried. It is NOT all good! 29. Not validating your data! Yikes… Yes.. let’s just assume all the data is perfect! NOT! 30. No load testing. What.. This is supposed to run on 1,000 user’s machines through Citrix? Interesting… Shouldn’t be an issue! lol… NOT. Credit goes to Original Author : http://www.realsoftwaredevelopment.com/

Software Developer - Must Know

1. Time spent writing great code It’s not about the quantity it’s the quality! However a twist to this is: It is about the quantity, and the quality. Far too many times you will get one of two scenarios. In scenario A, you have a developer that pumps out code like mad, things seem to be working… then bugs start happening, you don’t know why, seems to take forever to fix! Or they fix 10 and cause 5 more! But you get a lot of code… In scenario B, you have a developer that seems so smart! You interview him and he knows everything about everything, can speak the theory up and down! Yet for some reason, you have assigned him three features, and three weeks later, he is still working on something that should have been done in 3 days! You are so confused! He is so smart! He knows everything about generics, multi-threading, and can explain pointers to your grandmother and make her excited to want to code! Why is nothing getting done?! In your dream scenario, you get great code! Great code is done by a great developer that is super smart, knows what quality code is, and writes code like Tony Hawk rides his skateboard. It looks so natural! He or she is almost entertaining to watch! They also get it done at blinding speeds! They know how long each problem should take, and do not get caught up in finding the world’s best solution, that has multiple threads and layers, to write a game of pong. Bugs are nonexistent because they write unit tests for themselves, and just plain can code in their sleep! These guys are worth their weight in GOLD! 2. Interpretation of the problem So there is a problem out there, with millions of ways to solve it. Some people are just natural quick thinkers and can come up with multiple solutions instantly. However, what a great developer would do is totally define the problem before doing anything! A great developer will create a document or whiteboard the problem out. They will email their managers and say things like “Can we meet so I can explain to you how I understand the problem?” Next they will start giving you various solutions, etc. See, a great developer knows that the way they see the problem and interpret the problem, is probably not the way that the problem creator intended it to be understood. This is a key point, commit this to memory! A great developer will want to understand it fully, before attempting to approach a solution. Do you understand the problem 100%, no? 99%? Go ask more questions and be sure you are 100% clear! 3. How the problem is approached So once you have clearly defined the problem, you start coding right? Wrong! A great developer will look at the layout, and start thinking of various options, and based on the problem, will start thinking about the best approach to solve the problem. I view this like a game of chess. You can know how all the pieces move, know all the rules of the game, but do you just start moving? No! You analyze the board, come up with a game plan, look at your opponent, and look at what he or she usually do. It’s the same case when you approach a problem. Look at the problem, figure out what the outcome needs to be, what kind of time you have, the quality being expected, the tools you have to work with, etc. Then, start solving the problem. 4. Confidence in code As a manager, how confident can you be in their code. Some developers you can say “I need this completed by Friday” come Friday, you get an email saying “I have checked the code into the branch, it is ready for testing” and you just know that there will be very little, if any, bugs found by the quality assurance team. On the flip side, there are some developers that will email you instead and say “I am still not done, and it will be done on Monday morning first thing.” And you are nearly 95% sure that it will be there, however it will be ridden with bugs, and basically unusable for days, if not weeks, until bugs are completely ironed out of the code. Bottom line: The higher the confidence you can have in a developer, the closer they get to being great developers! Imagine being your manager, and the weight you lift off their shoulders if he doesn’t have to worry about your code! 5. Confidence in the solution It’s one thing to be confident in the code. If you have a great developer on your hands, you are confident in the solution. These great developers will be great architects. They are able to dissect the whole problem, and figure out how the problem needs to be solved. See it’s not just about coding with great code, it’s also largely about how you architect the solution! This is a key point, and really what separates the good, from the great in the software world. 6. Meets user requirements At the end of the day, you can have the best code, and the best solution possible, with all the best architecture, but does it meet the user’s requirement? It’s possible not! And you have completely failed. Now there are various degrees of missing the mark, but a great developer will hit the bull’s-eye consistently! They find out exactly what the user wants, come up with a great approach, show the user what they will get every step of the way with weekly builds that have no bugs, and continue to build upon the last version. Requirements are bang on, and the users do the jig! 7. Staying up to date Great developers are constantly updating their skills independently and proactively! They thirst for new knowledge and perfection like a cat with milk. They don’t wait for their managers to come to them and set goals, ask them to take courses, or are given books to get up to speed on. They go and get these things on their own! They find the conferences they want to go to, and send emails like “I would really love to go to Tech-Ed This Year! I will learn , and I will be able to contribute to . I foresee this saving us . If it’s at all possible, can the company help me pay for this trip?” If someone sent me this, I would not only help pay, I would pay the entire trip! Great developers are always attending all the user groups, like a .net user group for example, or a Java user group. They go to the “free local” meetings, and do whatever it takes to feed their brains! Do you read all the latest blogs and magazines? List your top 5 favorite development blogs right now! Can you do it? You should be able to drop them like you can do the actions to the YMCA! Stay up to date, it will stretch your mind! You will have the next big idea! You will be rewarded! 8. Contributes to team You can be one of the best, if not the best coder, architect, most brilliant guy on the team, but as far as I am concerned, if you are not able to share and contribute to your team, you are losing about half your value, if not more! A great developer makes others great around them! See, a good developer keeps getting better and better, but doesn’t share the knowledge they obtain, or how they obtain it. They learn new things, find out about new technologies, but don’t let anyone know about them! A good developer finishes their projects on time, but when push comes to shove, is not there for the rest of the team. A great developer is in touch with all the projects that are going on within the team, and is ready to lend a helping hand when needed! They will say things like “I noticed team A is working on , and I think I can help out, do you mind?” 9. Makes great meeting minutes This is incredibly important! There is nothing worse than calling a meeting, taking the time to explain new concepts, new ideas, brainstorm, come up with great designs, and not have anyone taking meeting minutes! Even if you have a designated meeting taker, I want to see everyone showing up with a pen, and paper (developer notebook is preferred). A great developer takes great notes! They write out all meeting minutes, and at the end of the meetings can be heard saying “So just to confirm, my action items are: . Did I get everything?” Next, a great developer will send their meeting minutes to the manger, listing the date of the meeting, the topic, and attendees. Following this, you will have the action items at the top, with who is the champion of the item. Below that, you have the detailed meeting minutes. A good developer, takes no meeting minutes, says yes every time you add something to his list… and hopes that his memory will serve him well. He then later emails you to check out his changes, and you cringe as you see he forgot a few things, but got 90% if it correct. This is a HUGE WASTE of time! For no reason at all! Take Great Meeting Minutes! 10. Teachable and takes criticism well If you have read this far, then hopefully you are taking all this in and will be trying to implement some of my suggestions in your day to day development efforts. See, another key area is the developers’ ability to learn from others, and take criticism well! By making yourself a teachable person, you turn into a sponge, and absorb enormous amounts of knowledge faster! Your seniors are there for a reason! Sure, they might be rusty at day to day coding, but they have gone through the trenches, and been through hundreds of battles, and have the wounds and scares! They have the “Blink” instinct to make great decisions, and make you great! They are in the position they are in because they LOVE to see you succeed, and want to make you grow! Of course, this is the ideal work environment, but that’s where you want to be anyway if you are a great developer! I absolutely guarantee you, and promise you, that the better you can improve this skill, make yourself extremely teachable, make notes on suggestions and criticism, and make a point of improving them, the better chance you have at becoming greater than you have ever imagined possible! If you on the other hand, choose to think of yourself as “elite”, and have nothing more to learn, you will always be stuck where you are. If you are not growing, you are not even staying at status quo, you are dying! Grow! 11. Always available when needed This is a give and take. If you are working for a great company, they will be flexible with you. They should never question doctor’s appointments that you couldn’t schedule after work, start times, end times, or lunch breaks. They should encourage you to go to the gym at lunch, pay for lunches when you go out with the team, etc. They should give you a few days off after some crunch time work. This list goes on and on. However, with all those perks, comes responsibility, no question! If it’s crunch time, a great developer will suggest to you that he will come in on the weekend if needed. They will stay as late as possible and as late as is needed to ensure the job gets done! See, great developers take responsibility for their creations! Now, this is not a necessity of course, but it is the mark of a great developer. Some people just want the 8-4:30, and will be good developers, but they will never be great. Great developers are team players to the end, and view their work like art, and view their team, like a family. 12. Dress’s professionally every day You never know when a client will come by on a tour. You never know when you will be called into a meeting, not everything is planned. And when that time comes, you have to be ready to dance! A good developer wears normal clothes Monday to Friday, even stretches it with black jeans, and runners that look like dress shoes. On casual Fridays, they wear shorts, runners, and a T-shirt. When the tour comes by on Friday with a new huge account, you can’t call on him to join you for lunch because he is not dressed appropriately. A great developer dresses in great business clothes Monday to Friday. They dress for success! See, by looking the part, you become the part! Of course, if you have no skills, you will not be promoted to a manager or team leader just because you dress sharp. But if you have great skills, and dress in a suit and tie, you have just catapulted yourself up in rank, no question. The 400 dollars you will spend on a decent suit and tie will pay you back within the year. I promise you! 13. Communication Ability This is another critical category! There are so many good developers out there, but there are not a lot of great developers. Why? Because a lot of the good developers, are terrible communicators. There are many levels of communication, ranging from email, to small SCRUM meetings, all the way up to large executive meetings and your ability to contribute at the executive level. Then you get to “The Show” where you are presenting for hundreds of people, showing off software. While you don’t need to get to the final stages, you need to be able to at least communicate your ideas clearly and effectively in meetings. The better your communication, the farther you will go. Bottom line: If you want to be an executive, you have to be a 9 or 10 at communication. Even when you take meeting minutes, or send out status reports, you need to communicate extremely well! Don’t just say “I fixed bug 1371″ on your daily report! Show off; explain how hard it was to solve the problem, how long, or how quick you solved it! Explain the technology you used! And explain how you will ensure the problem doesn’t happen again. Your status reports should not be a bad thing you don’t like to do! They should be an exciting part of your week where you get to show off to your manager! 14. Goal Setting Skill Good developers can get things done, and go throughout their day to day by doing what you tell them to do. They don’t really think far ahead and think of what they want to be doing in a year, five years, or even 10 years. Some good developers know what they want… but have no real plan to get there! A great developer has the goals for the year, the next five years, and knows roughly where he will be in 10 years. Great developers also take it to the next level by not only thinking about their goals, but also visualize it! They can see exactly what they will be doing in five years, to the level of where they will be doing it. Even more, a great developer will create a detailed plan for his next year, complete with courses he will take, projects he will complete, and relationships he will build. 15. Organizational Skill The final key component that really brings everything together is organization. You may be the best developer in the world, but if you are not organized, you will fall apart and become bogged down! Eventually you will be overwhelmed and start losing your edge. Great developers keep an extremely clean desk, they keep all their notebooks, and write very clearly. They print out their daily outlook calendar of meetings and tasks. They have an inbox process to deal with emails, meetings, and new assignments. They keep file folders and can instantly pull up projects, meeting minutes, and other details when asked to produce them. Bonus Tip: Passion! One of my team members read my post and reminded me of something that every single person on my team has in buckets! Passion! Without passion in what you do day to day, you will not be a great developer, or great at anything for that matter. Lack of passion is the number one reason so many developers never become great! It is also the number one reason people do not succeed! A passionate developer will outperform even the best technical developers if they are not passionate about their job, their role, and their project. Think about it, if you have read this far, are you going to make an effort to make all the changes I listed? They seem simple, but without the passion to do these things, are you really going to commit today and be successful? So there you have it! These are some of the key principles I am using in rating my development team during the review process. Mind you, I provide my team members with the best environment I possibly can, and in return I want great developers! And they want to all be great developers! You can use these rules to rate your developers, or if you are a developer yourself, please use this list to make changes if needed, and catapult your career past your peers! Credit goes to original author : http://www.realsoftwaredevelopment.com/

Javascript Custom Functions Part 2

addSpace

Add space to the beginning of an argument.

Syntax

addSpace(stringValue, [numlength])

stringValue is the string which you want to add the space to. numlenght is the length of the return string, i.e. add space/s to the string to make it "numlength" long. Default "numlength" is 10.

Description

When you want to align the value of the form text box, you can use this function.

Examples

The following returns "    123.45".
addSpace("123.45", 10);
addSpace("123.45");

Code

function addSpace(argvalue, numlength) { if (! numlength > 0) numlength = 10; if (argvalue.length < numlength) { for(var i = argvalue.length; i < numlength; i++) argvalue = " " + argvalue; } return argvalue; }

customSplit

Split the argument string into an array of strings.

Syntax

customSplit(strValue, separator, strArrayName)

strValue is the string to be splited with separator as the delimeter. After spliting, array of strings are stored in new "Array" object, strArrayName.

Description

Since some of the browsers does not support latest version of javascript, which has split() function. "customSplit" function can be used then.

This function will return the length of the array created.

Examples

var strvalue = "abc##123##zzz##$$$";
var returnArraySize = customSplit(strvalue, "##", "NewArray");
The above will create the following:
NewArray[0] has value "abc"
NewArray[1] has value "123"
NewArray[2] has value "zzz"
NewArray[3] has value "$$$"
returnArraySize      has value "4"

Code

function customSplit(strvalue, separator, arrayName) { var n = 0; if (separator.length != 0) { while (strvalue.indexOf(separator) != -1) { eval("arr"+n+" = strvalue.substring(0, strvalue.indexOf(separator));"); strvalue = strvalue.substring(strvalue.indexOf(separator)+separator.length, strvalue.length+1); n++; } eval("arr" + n + " = strvalue;"); arraySize = n+1; } else { for (var x = 0; x < strvalue.length; x++) { eval("arr"+n+" = \"" + strvalue.substring(x, x+1) + "\";"); n++; } arraySize = n; } eval(arrayName + " = new makeArray(arraySize);"); for (var i = 0; i < arraySize; i++) eval(arrayName + "[" + i + "] = arr" + i + ";"); return arraySize; }

DeleteCookie function

Delete the cookie.

Syntax

DeleteCookie(cookieName)

cookieName is the cookie that you want to delete.

Description

Examples

Code

function DeleteCookie(cookiename) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cookieVal = getCookie(cookiename); if (cookieVal != null) document.cookie = name + "=" + cookieVal + "; expires=" + exp.toGMTString(); return; }

See also

getCookie functions.

formatDecimal function

Print the floating point number with certain decimal point.

Syntax

formatDecimal(number, boolean, decimal)

number is the floating point number which will be formatted.

boolean is used to decide whether add "0" at the end of the floating point number or not.

decimal is how many decimal point you wnat. (Default is 2)

Description

This function will print the floating point number passed in with the decimal point that users need.

Examples

formatDecimal("123.2333", true, 2); will return "123.23".
formatDecimal("123", true, 2);  will return "123.00".
formatDecimal("123", false, 2);  will return "123".
formatDecimal("123.2", true, 2); will return "123.20".
formatDecimal("123.2", false, 2); will return "123.2".
formatDecimal("123.456", true, 2); will return "123.46".
formatDecimal(".235", true, 2);  will return "0.24".
formatDecimal("0.9999", true, 2); will return "1.00".
formatDecimal("0.9999", false, 2); will return "1".


Code

function formatDecimal(argvalue, addzero, decimaln) { var numOfDecimal = (decimaln == null) ? 2 : decimaln; var number = 1; number = Math.pow(10, numOfDecimal); argvalue = Math.round(parseFloat(argvalue) * number) / number; // If you're using IE3.x, you will get error with the following line. // argvalue = argvalue.toString(); // It works fine in IE4. argvalue = "" + argvalue; if (argvalue.indexOf(".") == 0) argvalue = "0" + argvalue; if (addzero == true) { if (argvalue.indexOf(".") == -1) argvalue = argvalue + "."; while ((argvalue.indexOf(".") + 1) > (argvalue.length - numOfDecimal)) argvalue = argvalue + "0"; } return argvalue; }

See also

formatCurrency function.

formatValue function

Print a number according to the format specified. Used for currency format.

Syntax

formatValue(argvalue, format)

argvalue is the number which will be formatted.

format is the format of the result.

Description

The number passed in will be formatted according to the format specified by the user. This function is written for formatting a currency number.

And formatDecimal function is needed.

Examples

formatValue(1223.434, "$##,###.##")  will return "$1,223.43"
formatValue(1223.43, "$##,###.##")  will return "$1,223.43"
formatValue(1223., "$##,###.##")  will return "$1,223.00"
formatValue(1223, "$##,###.##")  will return "$1,223.00"
formatValue(23., "$##,###.##")   will return "$23.00"
formatValue(23.3, "$##,###.##")  will return "$23.30"
formatValue(124343423.3, "$###,###,###.##") will return "$124,343,423.30"

Code

function formatValue(argvalue, format) { var numOfDecimal = 0; if (format.indexOf(".") != -1) { numOfDecimal = format.substring(format.indexOf(".") + 1, format.length).length; } argvalue = formatDecimal(argvalue, true, numOfDecimal); argvalueBeforeDot = argvalue.substring(0, argvalue.indexOf(".")); retValue = argvalue.substring(argvalue.indexOf("."), argvalue.length); strBeforeDot = format.substring(0, format.indexOf(".")); for (var n = strBeforeDot.length - 1; n >= 0; n--) { oneformatchar = strBeforeDot.substring(n, n + 1); if (oneformatchar == "#") { if (argvalueBeforeDot.length > 0) { argvalueonechar = argvalueBeforeDot.substring(argvalueBeforeDot.length - 1, argvalueBeforeDot.length); retValue = argvalueonechar + retValue; argvalueBeforeDot = argvalueBeforeDot.substring(0, argvalueBeforeDot.length - 1); } } else { if (argvalueBeforeDot.length > 0 || n == 0) retValue = oneformatchar + retValue; } } return retValue; }

See also

formatDecimal function.

GetCookie function

Get the value of a cookie.

Syntax

GetCookie(CookieName)

CookieName is the cookie whose value that you want to get.

Description

If the cookie specified doesn't exist, "null" will be returned.

Examples

If the document.cookie contains:
USER_ID=abc
USER_GP=

// variable "userid" has value "abc".
var userid = GetCookie("USER_ID");
// variable "usergp" has value "".
var usergp = GetCookie("USER_GP");
// variable "userpw" has null value.
var userpw = GetCookie("USER_PW");

Code

function GetCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return GetCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } function GetCookieVal(offset) { var endstr = document.cookie.indexOf(";", offset); if (("" + endstr) == "" || endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); }

isEmail function

Determine an argument if it is an email address format.

Syntax

isEmail(testValue)

testValue is the value that you want to check.

Description

This function only check if the argument has email address's format, i.e. id@some.host, it will not connect to some.host to check if it is valid. There is not any method to validate an email address except you ask the user to key in their correct email address.

It is better you use trim to remove both the leading and the trailing space/s before you pass the value to this function.

Examples

The following return "true".
isEmail("abc@some.host");

The followings return "false".
isEmail("abc");
isEmail("abc@somehost");
isEmail("abc@.some.host");
isEmail("abc@some.host.");

Code

function isEmail(argvalue) { if (argvalue.indexOf(" ") != -1) return false; else if (argvalue.indexOf("@") == -1) return false; else if (argvalue.indexOf("@") == 0) return false; else if (argvalue.indexOf("@") == (argvalue.length-1)) return false; // arrayString = argvalue.split("@"); (works only in netscape3 and above.) var retSize = customSplit(argvalue, "@", "arrayString"); if (arrayString[1].indexOf(".") == -1) return false; else if (arrayString[1].indexOf(".") == 0) return false; else if (arrayString[1].charAt(arrayString[1].length-1) == ".") { return false; } return true; }

isURL function

Determine an argument if it is a URL.

Syntax

isURL(testValue)

testValue is the value that you want to check.

Description

Examples

The followings will return "true".
isURL("http://some.host");
isURL("http://some.host/");
isURL("http://some.host/dir");
isURL("http://some.host/dir/");
isURL("http://some.host/dir/htmlfile");
isURL("http://some.host:123");
isURL("http://some.host:123/");

The followings will return "false".
isURL("http://.some.host/");
isURL("http://some.host./");
isURL("http://some.host:/");
isURL("http://some.host:.123/");
isURL("http://some.host:123./");
isURL("http://some.host:123./dir";
isURL("http://");
isURL("htp://");

Code

function isURL(argvalue) { if (argvalue.indexOf(" ") != -1) return false; else if (argvalue.indexOf("http://") == -1) return false; else if (argvalue == "http://") return false; else if (argvalue.indexOf("http://") > 0) return false; argvalue = argvalue.substring(7, argvalue.length); if (argvalue.indexOf(".") == -1) return false; else if (argvalue.indexOf(".") == 0) return false; else if (argvalue.charAt(argvalue.length - 1) == ".") return false; if (argvalue.indexOf("/") != -1) { argvalue = argvalue.substring(0, argvalue.indexOf("/")); if (argvalue.charAt(argvalue.length - 1) == ".") return false; } if (argvalue.indexOf(":") != -1) { if (argvalue.indexOf(":") == (argvalue.length - 1)) return false; else if (argvalue.charAt(argvalue.indexOf(":") + 1) == ".") return false; argvalue = argvalue.substring(0, argvalue.indexOf(":")); if (argvalue.charAt(argvalue.length - 1) == ".") return false; } return true; }

isW function

Determine an argument if it only contains "word" characters.

Syntax

isW(testValue)

testValue is the value that you want to check.

Description

"Word" characters are alphanumeric plus "_".

Example

The followings will return "true".
isW("abc123")
isW("ABC123")
isW("aBc_123")

The followings will return "false".
isW("abc 123")
isW("@#+=")
isW("! Abc")

Code

function isW(argvalue) { var onechar = ""; for (var n = 0; n < argvalue.length; n++) { onechar = argvalue.substring(n, n+1); if ((onechar < "0" || onechar > "9") && (onechar < "A" || onechar > "Z") && (onechar < "a" || onechar > "z") && (onechar != "_")) { return false; } } return true; }

ltrim function

Remove the leading space/s of an argument.

Syntax

ltrim(stringValue)

stringValue is the string which the leading space/s will be removed.

Description

Examples

The following will return "abc ".
ltrim("  abc ")
The following will return "a b c  ".
ltrim("  a b c  ")

Code

function ltrim(argvalue) { while (1) { if (argvalue.substring(0, 1) != " ") break; argvalue = argvalue.substring(1, argvalue.length); } return argvalue; }

makeArray function

Create an array object.

Syntax

makeArray(intArraySize)

intArraySize is the length of the array created.

Description

Some browser does not support latest javascript which has Array object. This function can be used in those browser.

Examples

The following will create an array with 3 in length.
newArray = new makeArray(3);

Code

function makeArray(IntarrSize) { for (var n = 0; n < IntarrSize; n++) this[n] = ""; return this; }

numCheck function

Determine an argument if it only contains number.

Syntax

numCheck(testValue)

testValue is the value that you want to check.

Description

numCheck function will return true if the argument only contains "0-9".

Examples

The followings will return "true".
numCheck("1234")
numCheck("0123")

The followings will return "false".
numCheck("abcd")
numCheck("a123")
numCheck("123a")
numCheck("12.3")

Code

function numCheck(argvalue) { if (argvalue.length == 0) return false; for (var n = 0; n < argvalue.length; n++) if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9") return false; return true; }

ParseCookies function

Parse the cookies data and assign these data to "document.Cookie_cookie_name".

Syntax

ParseCookies()

Description

The value of cookie, cookieName, is stored in "document.Cookie_cookieName.value".

There are few ways to save the cookie data, but I found that this is the way which works in both Netscape3.0 and Internet Explorer3.0.

Examples

If the server returns the following cookie:
 Set-Cookie: Cookie1=Value1; Cookie2=Value2
After you call the ParseCookies().
parseCookies();
"document.Cookie_Cookie1.value" will contains value "Value1";
"document.Cookie_Cookie1.name" will contains value "Cookie1";
"document.Cookie_Cookie2.value" will contains value "Value2";
"document.Cookie_Cookie2.name" will contains value "Cookie2";

Code

function ParseCookies() { var cookie_string; var cookie_name; var cookie_value; var tmpcookie = document.cookie; var cookie_count = 0; while (tmpcookie.indexOf("; ") != -1) { cookie_string = tmpcookie.substring(0, tmpcookie.indexOf("; ")); cookie_name = cookie_string.substring(0, cookie_string.indexOf("=")); cookie_value = cookie_string.substring(cookie_string.indexOf("=") + "=".length, cookie_string.length); eval("document.Cookie_" + cookie_name + " = new Cookies(cookie_name, cookie_value);"); tmpcookie = tmpcookie.substring(tmpcookie.indexOf("; ") + "; ".length, tmpcookie.length); cookie_count++; } cookie_name = tmpcookie.substring(0, tmpcookie.indexOf("=")); cookie_value = tmpcookie.substring(tmpcookie.indexOf("=") + "=".length, tmpcookie.length); eval("document.Cookie_" + cookie_name + " = new Cookies(cookie_name, cookie_value);"); cookie_count++; return cookie_count; } function Cookies(argname, argvalue) { this.name = argname; this.value = unescape(argvalue); return this; }

replace function

Substitute a string X to a string Y in an argument.

Syntax

replace(stringValue, X, Y)

stringValue is the string which has all X will be substituted by Y.

Description

This function will replace all the string X to string Y in the argument, it can not change the string X in certain place.

Examples

The following will return "abcABCdefgh".
replace("abc123defgh", "123", "ABC");

Code

function replace(argvalue, x, y) { if ((x == y) || (parseInt(y.indexOf(x)) > -1)) { errmessage = "replace function error: \n"; errmessage += "Second argument and third argument could be the same "; errmessage += "or third argument contains second argument.\n"; errmessage += "This will create an infinite loop as it's replaced globally."; alert(errmessage); return false; } while (argvalue.indexOf(x) != -1) { var leading = argvalue.substring(0, argvalue.indexOf(x)); var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, argvalue.length); argvalue = leading + y + trailing; } return argvalue; }

rtrim function

Remove the trailing space/s of an argument.

Syntax

rtrim(stringValue)

stringValue is the string that you want to remove its trailing space/s.

Description

Examples

The following will return "abc".
rtrim("abc   ")
The following will return "a b c".
rtrim("a b c   ")
The following will return "  abc".
rtrim("  abc  ")

Code

function rtrim(argvalue) { while (1) { if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ") break; argvalue = argvalue.substring(0, argvalue.length - 1); } return argvalue; }

SetCookie function

Setting new cookie value.

Syntax

SetCookie(cookiename, cookievalue, expires, path, domain, secure)

Description

To retrieve the cookie's value, try parseCookie function.

For more information about cookie, see Netscape's Cookie Specification at http://home.netscape.com/newsref/std/cookie_spec.html.

Examples

SetCookie("Cookie1", "Value1", null, "/");
SetCookie("Cookie2", "Value2", new Date(), "/");
document.cookie will have value "Cookie1=Value1; Cookie2=Value2".

Code

function SetCookie(cookiename, cookievalue) { var argv = SetCookie.arguments; var argc = SetCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = cookiename + "=" + escape(cookievalue) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path )) + ((domain == null) ? "" : ("; domain=" + domain )) + ((secure == true) ? "; secure" : ""); return; }

trim function

Remove both the leading and the trailing space/s of an argument.

Syntax

trim(stringValue)

stringValue is the string which the leading and the trailing space/s will be removed.

Description

When you use this function, make sure ltrim and rtrim are inside the same html file too.

Examples

The following will return "abc".
trim("  abc  ")
The following will return "a b c".
trim("  a b c  ")

Code

function trim(argvalue) { var tmpstr = ltrim(argvalue); return rtrim(tmpstr); }

Microsoft's New Decision (Search) Engine - Bing

Microsoft Corp. unveiled Bing, a new Decision Engine and consumer brand, providing customers with a first step in moving beyond search to help make faster, more informed decisions. Bing is specifically designed to build on the benefits of today’s search engines but begins to move beyond this experience with a new approach to user experience and intuitive tools to help customers make better decisions, focusing initially on four key vertical areas: making a purchase decision, planning a trip, researching a health condition or finding a local business.

The result of this new approach is an important beginning for a new and more powerful kind of search service, which Microsoft is calling a Decision Engine, designed to empower people to gain insight and knowledge from the Web, moving more quickly to important decisions. The new service, located at http://www.Bing.com, will begin to roll out over the coming days and will be fully deployed worldwide on Wednesday, June 3.

The explosive growth of online content has continued unabated, and Bing was developed as a tool to help people more easily navigate through the information overload that has come to characterize many of today’s search experiences. Results from a custom comScore Inc. study across core search engines show that as many as 30 percent of searches are abandoned without a satisfactory result. The data also showed that approximately two-thirds of the remaining searches required a refinement or requery on the search results page.

“Today, search engines do a decent job of helping people navigate the Web and find information, but they don’t do a very good job of enabling people to use the information they find,” said Steve Ballmer, Microsoft CEO. “When we set out to build Bing, we grounded ourselves in a deep understanding of how people really want to use the Web. Bing is an important first step forward in our long-term effort to deliver innovations in search that enable people to find information quickly and use the information they’ve found to accomplish tasks and make smart decisions.”

More Details : http://www.microsoft.com/presspass/press/2009/may09/05-28NewSearchPR.mspx

Setting Cursor Position in TextBox with Javascript

function setCaretPosition(elemId, caretPos) {
  var elem = document.getElementById(elemId);

  if(elem != null) {
      if(elem.createTextRange) {
          var range = elem.createTextRange();
          range.move('character', caretPos);
          range.select();
      }
      else {
          if(elem.selectionStart) {
              elem.focus();
              elem.setSelectionRange(caretPos, caretPos);
          }
          else
              elem.focus();
      }
  }
}
The first expected parameter is the ID of the element you wish to insert the cursor on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the cursor at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the cursor at the end.

ASP.NET WebForms FAQ

1. JavaScript

1.1 How to get client date and time

You can use java script function to show the date and time.

<script type="text/javascript">
   function displayTime()
   {
       var localTime = new Date();
       var year= localTime.getYear();
       var month= localTime.getMonth() +1;
       var date = localTime.getDate();
       var hours = localTime .getHours();
       var minutes = localTime .getMinutes();
       var seconds = localTime .getSeconds();   
       var div=document.getElementById("div1");
       div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
   }
script>

Then you can call it at web page.

<body onload="displayTime();">
   <form id="form2" runat="server">
   <div id="div1">div>
   form>
body>

Related posts:

http://forums.asp.net/p/1247758/2303034.aspx

1.2 How to access a control by using JavaScript

Reference the ClientID property (or UniqueID) of the control in the JavaScript.

protected void Page_Load(object sender, EventArgs e)
{
   Button btn= new Button();
   btn.ID = "btn5";
   btn.Attributes.Add("runat", "server");
   btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
   btn.Text = "Test";
   this.form1.Controls.Add(btn);
}

function pop(InputBoxID)
{
   var InputControl = document.getElementById(InputBoxID);
   alert(InputControl.value);
}

Or you can use the following method:

btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
   alert(InputBox.value);
}

Related posts:

http://forums.asp.net/p/1239593/2260331.aspx#2260331

1.3 How to invoke a server-side function with JavaScript

Firstly, you can drag a server button and put the server function into the button Click even,

protected void Button1_Click(object sender, EventArgs e)
{
  FunctionName();
}

Secondly, you can call the server function at JavaScript by using the following code,

document.getElementById("Button1").click();

Related posts:

http://forums.asp.net/p/1242420/2274228.aspx

1.4 How to retrieve server side variables using JavaScript code

<asp:HiddenField ID="HiddenField1" runat="server" />    
public partial class LoginDemo : System.Web.UI.Page
{  
   private string str="hello";
   protected void Page_Load(object sender, EventArgs e)
   {
       HiddenField1.Value=str;
   }
}

Then you can access the control HiddenField1 using javascipt:

<script type="text/JavaScript">
Var tt=document.getElementByID(“HiddenField1”);
alert(tt.value);
script>

Related posts:

http://forums.asp.net/p/1000655/1319119.aspx

1.5 How to assign a value to a hidden field using JavaScript in ASP.NET

We can use JavaScript to set the value of a hidden control and get its value at the server after a post back.

<input id="Hidden1" type="hidden" />
<script type="text/JavaScript">
var str=”hello”
document.getElementByID(“Hidden1”).value=str
script>
protected void Page_Load(object sender, EventArgs e)
{
   string str=request["Hidden1"].ToString();
}

Related posts:

http://forums.asp.net/p/1262153/2362090.aspx

1.6 How to register the JavaScript function at Code-Behind

Use ResterStartupScript

this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","");

Use Literal control,

private void Button2_Click(object sender, System.EventArgs e)
{
   string str;
   str="");
           }
           else
           {
               if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")
               {
                   string ImagePath = "images/";
                   string sPath = Server.MapPath(ImagePath) + dataName + fileName;
                   string imgPath = ImagePath + dataName + fileName;
                   this.FileUpload1.PostedFile.SaveAs(sPath);
                   this.ClientScript.RegisterStartupScript(this.GetType(),
                         "Startup", "");
                   this.Image1.ImageUrl = imgPath;
                   this.btnSubmit.Enabled = false;
                   this.btnSubmit.Text = "Success!";
                   this.btnSubmit.Enabled = true;

               }
               else
               {
                   this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
                         "");
               }
           }
       }
       else
       {
           this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
                  "");
       }
   }
}

Related posts:

http://forums.asp.net/p/1051895/2171502.aspx

3.5 How to get a File Upload control work with an UpdatePanel

The FileUpload control does not work with asynchronous post backs and therefore does not work from within an AJAX UpdatePanel.

The trick to make the FileUpload to work within an Ajax UpdatePanel is to setup a PostBackTrigger in the UpdatePanel control.

Demo code:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers >
<asp:PostBackTrigger ControlID ="Button1" />
Triggers>
<ContentTemplate >
<asp:FileUpload ID ="fileupload1" runat ="server" /><br />    
<asp:Button ID ="Button1" runat ="server" Text ="Upload" OnClick="Button1_Click" /><br />
<asp:Label ID ="Lable1" runat ="server"  Text ="">asp:Label>
<asp:LinkButton ID ="LinkButton1" runat="server" Text ="Click Here" OnClick="LinkButton1_Click">asp:LinkButton>
ContentTemplate>
asp:UpdatePanel>

Related posts:

http://forums.asp.net/p/1105208/1689084.aspx

4. Calendar

4.1 How to change the culture settings for a Calendar

In calendar.aspx.cs:

private void Page_Load(object sender, System.EventArgs e)
{
   System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("ens");
   System.Threading.Thread.CurrentThread.CurrentCulture = culture;
   System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}

Related posts:

http://forums.asp.net/t/1133896.aspx

4.2 How to select multiple non-sequential dates at Code-Behind

Invoke the member function ‘Add’ of the control's SelectedDates collection. You can add dates in any sequence, because the collection will automatically arrange them in order for you.

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
   Calendar1.SelectedDates.Clear();
   Calendar1.SelectedDates.Add(new DateTime(2008, 8, 1));
   Calendar1.SelectedDates.Add(new DateTime(2008, 8, 7));
   Calendar1.SelectedDates.Add(new DateTime(2008, 8, 15));   
}

Related posts:

http://forums.asp.net/t/1260917.aspx

4.3 How to disable some dates in Calendar control

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
   string date="02/01/2008";
   DateTime dt = DateTime.Parse(date);
   if (e.Day.Date == dt)
       e.Day.IsSelectable = false;
}

Related posts:

http://forums.asp.net/t/1230073.aspx

How to: Customize Individual Days in a Calendar Web Server Control

4.4 How to extend Calendar control for Server-Side validation

Refer to:

http://support.microsoft.com/default.aspx?scid=kb;en-us;310145

4.5 How to set ToolTips and links in Calendar control’s DayRender event

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
   e.Cell.Controls.Clear();
   HyperLink link = new HyperLink();
   link.Text = e.Day.Date.Day;
   link.ToolTip = "anything you want here!";
   link.NavigateUrl = url;
   e.Cell.Controls.Add(link);
}

Related posts:

http://forums.asp.net/p/1036174/1800067.aspx

4.6 How to give some dates different appearances

We can do this with the following code:

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
   if (e.Day.Date.Month == 2 && e.Day.Date.Day == 25)
   {
       e.Cell.BackColor = System.Drawing.Color.Yellow;
   }
   if (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday)
   {

       e.Cell.Controls.Clear();
       e.Cell.Text = "today isweekend";
   }
}

Related posts:

http://forums.asp.net/p/1036174/1800067.aspx

How to: Customize Individual Days in a Calendar Web Server Control

How to: Format Calendar Web Server Control Elements Using Styles

5. List controls

5.1 How to enable ASP.NET DropDownList with OptionGroup support

We can override the function of DropDownList, and add the additional property for it.

Here are some good articles about it.

Refer to:

http://www.codeproject.com/KB/custom-controls/xlist.aspx

http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx

5.2 How to disable an item in DropDownList

<asp:DropDownList ID="DropDownList1" runat ="server" Width="235px" AutoPostBack="False">
   <asp:ListItem>1asp:ListItem>
   <asp:ListItem>2asp:ListItem>
   <asp:ListItem>3asp:ListItem>
   <asp:ListItem>4asp:ListItem>
asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
   DropDownList1.Attributes.Add("onchange", "change();");
}
<script type ="text/javascript" >
     function change()
     {
        var dd=document.getElementById ('<%=DropDownList1.ClientID %>');
        var value=dd.options[dd.selectedIndex].value;
        if(value!="2") //supose you want to disable the item numbered 2
        {
           setTimeout("__doPostBack('DropDownList1','')", 0);
        }
      }
script>

Related posts:

http://forums.asp.net/p/1041568/1451492.aspx

5.3 How to hold the selected value for a DropDownList

You should place your data binding code for the dropdownlist in the !page.Ispostback block.

the !postback block will ensure it will only be filled once during post backs.

if(!Page.IsPostBack)
{
   //bind template drop down here 
}

Related posts:

http://forums.asp.net/p/1251081/2312321.aspx

6. User control

6.1 How to add a new property to UserControl

You can setup new properties inside the class definition of the user control at its .ascx.cs file.Example:

ascx file,

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
<asp:Calendar ID="Calendar1" runat="server">asp:Calendar>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>

ascx.cs file,

public partial class WebUserControl : System.Web.UI.UserControl
{
   String text2 = String.Empty;
   public String Text
   {
       get
       {

           return Label1 .Text ;
       }
       set
       {
           Label1 .Text  = value;
       }
   }
   public String Text2
   {
       get
       {
           return text2;
       }
       set
       {
           text2 = value;
       }
   }
   protected void Page_Load(object sender, EventArgs e)
   {
       TextBox1.Text = text2;
   }
}

aspx file

<%@ Register src="WebUserControl.ascx" mce_src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<uc1:WebUserControl id="WebUserControl1" runat="server" Text="Hello world" Text2="Hello world.">
uc1:WebUserControl>

Related posts:

http://forums.asp.net/t/349580.aspx

6.2 How to access a dynamically created UserControl

You can use FindControl method to get a reference to the target child control of your user control and then use it just like any other controls.

Example:

UC.ascx,

<%@ Control Language="C#" ClassName="UC" %>
<script runat="server">
script>
<asp:TextBox ID="txtName" runat="server">asp:TextBox>

Page.aspx:

<%@ Page Language="C#" %>

<%@ Register src="UC.ascx" tagname="UC" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
   protected void btnLoad_Click(object sender, EventArgs e)
   {
       UC uc = new UC();
       uc.LoadControl("~/uc/UC.ascx");
       uc.ID = "MyUC";
       form1.Controls.Add(uc);
       (form1.FindControl("MyUC").FindControl("txtName") as TextBox).Text = "ASP.NET";
   }
script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>User Control Demotitle>
head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:Button ID="btnLoad" runat="server" Text="Loading user control ..."
            onclick="btnLoad_Click" />
   div>
   form>
body>
html>

6.3 How to access a control inside a UserControl

Assume there is a user control called UC and there is only a TextBox control inside it. Now drag this user control into a web page, you can use the following code to visit the TextBox control.

((TextBox)UC1.FindControl("TextBox1")).Text = "demo";

To known the basic principle, please refer to INamingContainer:

http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx

7. Dynamic controls

7.1 How to create a dynamic control

We can create the dynamic control in the Page_Init() event or Page_Load() event,

protected void Page_Load(object sender, EventArgs e)
{
   TextBox dynamicTextBox = new TextBox();
   dynamicTextBox.ID = "DynamicTextBox";
   dynamicTextBox.AutoPostBack = true;
   dynamicTextBox.Text = "InitData";
   dynamicTextBox.TextChanged += new EventHandler(dynamicTextBox_TextChanged);
   this.Form.Controls.Add(dynamicTextBox);
}
void dynamicTextBox_TextChanged(object sender, EventArgs e)
{
   Response.Write("hello");
}

Related posts:

http://forums.asp.net/t/1152363.aspx

7.2 How to access a user entered value in a dynamic created TextBox control

a. Get the value from the form's POST data. Here is the code:

if(Request.Form["dynamicTextBox"] != null)
   selectedValue = Request.Form["dynamicTextBox"].ToString();

b. Get the value by finding the control at the webpage.

TextBox txt=this.form1.FindControl("dynamicTextBox") as TextBox;

See the whole demo code,

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
   public string Res = string.Empty;
   protected void Page_Load(object sender, EventArgs e)
   {
       TextBox dynamicTextBox = new TextBox();
       dynamicTextBox.ID = "dynamicTextBox";
       form1.Controls.Add(dynamicTextBox);
   }
   protected void btnForm_Click(object sender, EventArgs e)
   {
       lblMsg.Text += "<br /> Form way:";
       if (Request.Form["dynamicTextBox"] != null)
           Res = Request.Form["dynamicTextBox"].ToString();
       lblMsg.Text += Res;
   }
   protected void btnFindControl_Click(object sender, EventArgs e)
   {
       lblMsg.Text += "<br /> FindControl way: ";
       TextBox dynamicTextBox = this.form1.FindControl("dynamicTextBox") as TextBox;
       Res = dynamicTextBox.Text;
       lblMsg.Text += Res;
   }
script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Demotitle>
head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:Label ID="lblMsg" runat="server" Text="">asp:Label>
       <asp:Button ID="btnForm" runat="server" Text="Form Way" OnClick="btnForm_Click" />
       <asp:Button ID="btnFindControl" runat="server" Text="FindControl Way" OnClick="btnFindControl_Click" />
   div>
   form>
body>
html>

Related posts:

http://forums.asp.net/p/1119972/1745762.aspx

7.3 Dynamic controls accessed by JavaScript

Reference the ClientID property (or UniqueID) of the control in the Javascript.

protected void Page_Load(object sender, EventArgs e)
{
   Button btn= new Button();
   btn.ID = "btn5";
   btn.Attributes.Add("runat", "server");
   btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
   btn.Text = "Test";
   this.form1.Controls.Add(btn);
}
function pop(InputBoxID)
{
  var InputControl = document.getElementById(InputBoxID);
  alert(InputControl.value);
}

Or,

Use the following method.
btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
  alert(InputBox.value);
}

Related posts:

http://forums.asp.net/p/1239593/2260331.aspx#2260331

7.4 How to retain all added server controls dynamically after post back

You should recreate these dynamic control at Page_load or Page_init() function everytime.

protected void Page_Load(object sender, EventArgs e)
{
   //recreate these dynamic control.
}

Related posts:

http://forums.asp.net/p/1242809/2280514.aspx

7.5 Why dynamically created controls disappear after a post back

The dynamic button must be re-created on each post back, so remove the if(!Page.IsPostBack). It's probably better if you create the controls at the Page_Init event.

Related posts:

http://forums.asp.net/p/1080863/1598618.aspx

8. Style

8.1 How to use with Code-Behind

Label1.Attributes.Add("style", "background-color:Red");

8.2 How to use with JavaScript

document.getElementById("Label1").style.backgroundColor = "Red";

8.3 How to remove a space

Add the following code inside of the “head” tag,

<style type="text/css">
body
{
   padding: 0px;
   margin: 0px;
}
style>

8.4 How to use with html

<link href="<%= CSS %>" rel="stylesheet" type="text/css" />

Note: CSS is valuable

Linked style sheet usually lives in tag, but there is no need to worry if it is put inside tag. As well, tag must have a runat=”server” attribute.

Related posts:

http://forums.asp.net/p/1197909/2076464.aspx

8.5 How to set an image as Button’s background

<input name="Submit" type="button" value="" style="border-style: none; background-color: Transparent; background-image: url('bg.png'); width: 68px; height: 20px; vertical-align: middle;" /> 

Related posts:

http://forums.asp.net/t/299555.aspx

8.6 How to color items in ListBox

Demo code:

<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;}
style>
protected void Page_PreRender(object sender, EventArgs e)
{
   bool flag=false;
   foreach (ListItem li in ListBox1.Items)
   {
       if (flag)
       {
           li.Attributes.Add("class", "optred");
           flag = false;
       }
       else
       {
           li.Attributes.Add("class", "optblue");
           flag = true;
       }
   }
}

Please refer to:

http://www.codeproject.com/KB/webforms/ColorListBox.aspx

9. Print

9.1 How to print a part of a web page with CSS

CSS CODE:

<style media="print">
       .Noprint
       {
           display: none;
       }
       .Print
       {
           page-break-after: always;
       }
style>

HTML CODE:

<div class="Noprint">
    I am not print;
div>
<div class="Print">
    I will print;
div>

Related posts:

http://forums.asp.net/t/981539.aspx

9.2 How to print a part of a web page with JavaScript (1)

JavaScript CODE:

<script language="JavaScript" type="text/JavaScript">
       function doPrint() {
       bdhtml=window.document.body.innerHTML;
       sprnstr="";
       eprnstr="";
       prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
       prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
       window.document.body.innerHTML=prnhtml;
       window.print();
       }
script>

HTML CODE:


This area will print!

<br />
I will not print?
<input id="btnPrint" type="button" value="Print" onclick="doPrint()" />

Related posts:

http://forums.asp.net/p/1234564/2256428.aspx

9.3 How to print a part of a web page with JavaScript (2)

JavaScript CODE:

<script language="javascript" type="text/javascript">
   function printdiv(divID)
   {
     var headstr = "<html><head><title>title>head><body>";
     var footstr = "body>";
     var newstr = document.all.item(divID).innerHTML;
     var oldstr = document.body.innerHTML;
     document.body.innerHTML = headstr+newstr+footstr;
     window.print();
     document.body.innerHTML = oldstr;
     return false;
   }
script>

HTML CODE:

<input name="b_print" type="button" onclick="printdiv('divID');" value=" Print " />
<div id="divID">
<h1 style="color:green">
The Div content which you want to printh1>
div>

Related posts:

http://forums.asp.net/t/1263912.aspx

10. Mail

10.1 What classes are needed to send e-mails in ASP.NET

Class MailMessage and SmtpMail are used to send emails from an ASP.NET application. MailMessage and SmtpMail are from System.Web.Mail namespace of .NET Framework 1.1 Class Library. Also, you can use System.Net.Mail instead of System.Web.Mail if you have .NET Framework version 2.0 installed.

10.2 How to send emails by using System.Net.Mail [top]

CODE-BEHIND:

MailMessage message = new MailMessage();
message.From = new MailAddress("fromusername@DomainName");
message.To.Add(new MailAddress("tousername@DomainName"));
message.CC.Add(new MailAddress("ccusername@DomainName"));
message.Subject = "Subject";
message.Body = "Content";
SmtpClient client = new SmtpClient();
client.Send(message);

web.config:

<system.net>
   <mailSettings>
       <smtp from="username@DomainName">
           <network host="SMTPServerName" port="25" userName="username" password="secret" defaultCredentials="true" />
       smtp>
   mailSettings>
system.net>

Related posts:

http://forums.asp.net/t/971802.aspx

10.3 How to configure a SMTP Server

Taking the IIS as an example, please review the following links:

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56c94d38-b10f-4a1b-a1cd-3714387a042a.mspx?mfr=true

http://www.codeproject.com/KB/winsdk/ConfigServerSmtp.aspx

10.4 How to send an email with Gmail server

Please read FAQ “How to send email by using System.Net.Mail?” first. Please note that you need to be aware of the following points while configuring the following settings:

· SMTP server name

· Port number

· SSL authentication

Gmail SMTP server name is “smpt.gmail.com”;

Gmail port is 465, not the default port 25;

The SSL authentication should be set to true;

So the secret of sending mails successfully with Gmail is: port 465, server name “smtp.gmail.com” and SSL = true.

Related posts:

http://forums.asp.net/p/1167140/1944223.aspx

http://forums.asp.net/p/1234241/2235990.aspx