Sponsored Ad

Wednesday, April 28, 2010

Operator Overloading in C# | Operator Overloading Example

 

This sample post will help you to get hands on experience with operator overloading in C#.

Operator overloading give a different meaning to existing operator and enhance the functionality to work with other rich objects etc.

like in this given example we have used plus(+) operator to work with object of the class and it gives the result after adding the variable of the class.

Operator Overloading in C# | Operator Overloading Example

 

using System;
using System.Collections.Generic;
using System.Text;

namespace Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            OpOverloading a = new OpOverloading(20);
            OpOverloading b = new OpOverloading(25);
            OpOverloading c;
            c = a + b;
            System.Console.WriteLine(c.i);
            Console.ReadLine();
        }
    }
    public class OpOverloading
    {
        public int i;
        public OpOverloading(int j)
        {
            i = j;
        }
        public static OpOverloading operator +(OpOverloading x, OpOverloading y)
        {
            System.Console.WriteLine("operator + " + x.i + " " + y.i);
            OpOverloading z = new OpOverloading(x.i + y.i);
            return z;
        }
    }

}

Friday, April 23, 2010

How to Display Message in Status Bar - JavaScript

 

This Sample JavaScript Code illustrate you that how to display message in browser window status bar. As you can check – message “This is CSharpHub.com Official Post” is displaying in given figure.

How to Display Message in Status Bar - JavaScript

The window.status property is used to assign the given message and it will display in browser.

window represent the whole browser window and status is its one property.

<html>
<head>
<script type="text/javascript">
function load()
{ window.status = "This is CSharpHub.com Official Post" }
</script>
</head>
<body onload="load()">
<p>Check the Message in Internet Explorer Satus Bar.</p>
</body>
</html>

Thursday, April 22, 2010

How to Find Control by Given Type in C#

 

This small utility will help you to find a control by given type from a ControlCollection. This utility will loop through all the controls in collection recursively and return the control if find any otherwise it will return null value.

using System.Web.UI;

private static Control FindControlByType(ControlCollection C, Type mytype)
      {
          Control gr = null;
          for (int i = 0; i < C.Count; i++)
          {
              System.Type t = C[i].GetType();

              if (t == mytype || t.IsSubclassOf(mytype)) gr = C[i];
              else
                  if (C[i].HasControls()) gr = FindControlByType(C[i].Controls, mytype);
              if (gr != null) break;
          }
          return gr;
      }

How to Add Effect in Image and Text using CSS

 

We can add effects in our html images and text using css – cascading style sheet.

Lets start with a image as given below in code add style property in image tag and inside Blur “Add” , “Direction” and “Strength” is playing important roll to give a special effect.

style="Filter: Blur(Add = 0, Direction = 225, Strength = 5)"

Same thing is applicable for text also. you can change the values of these 3 parameters and get different effects.

<html>
<head>
<style type="text/css">
img.x { position:absolute; left:0px; top:0px; z-index:-1 }
</style>
</head>
<body>

<img src="Sunset.jpg" style="Filter: Blur(Add = 0, Direction = 225, Strength = 5)">
<br>
<br>

<span style="width: 600; height: 50; font-size: 36pt; font-family: Arial Black; color: blue; Filter: Blur(Add
= 1, Direction = 50, Strength = 7)">Text blur effect</span>

</body>
</html>

Tuesday, April 20, 2010

How to Control Display Order of Controls Through CSS | z-index

 

This is a post to discuss the display order of controls using css setting. z-index is a property by which display order can be controlled.

Lets have a example of image and a heading. image added with img tag of html and a h1 heading is added as well.

for the image tag we given z-index:-1 property. while for h1 tag nothing is specified. by default z-index contains 0 value.

z-index property can be applied on every control which support CSS settings. while some of the control do not support z-index property at all. in place of z-index there can be any other property.

 

<html>
<head>
<style type="text/css">
img.x { position:absolute; left:0px; top:0px; z-index:-1 }
</style>
</head>
<body>
<h1>This is a Heading</h1>
<img class="x" src="Venue Map.gif" width="100" height="180">
<p>image tag have z-index –1 so h1 will come top of image.</p>
</body>
</html>

Monday, April 19, 2010

How to Use Visibility Through CSS

 

This simple HTML code will help you to apply visibility through CSS. This example contains example of both options

1. visible

2. hidden

When you run this code. It will display tag only containing visible. by default all tags are visible.

 

<html>
<head>
<style type="text/css">
h1.visible {visibility:visible}
h1.invisible {visibility:hidden}
</style>
</head>
<body>
<h1 class="visible">This will display because of visible option</h1>
<h1 class="invisible">This will not display because of  hidden option</h1>
</body>
</html>

Saturday, April 17, 2010

How to Log Message in Event Log Using C#

 

How to Log Message in Event Log Using C#

This simple method will help to log your own events into service log viewer. Just call the given method with specific service message and it will add message in Event viewer. This is very helpful in complicated and multithreaded applications to know execution sequence and errors etc.

Call of the method:

ServiceLogMessage("abc");

 

public static void ServiceLogMessage(string strMessage)
    {
        EventLog MyLog = new EventLog();
        // create a new event log
        // Check if the the Event Log Exists
        if (!EventLog.SourceExists("MYServiceLog"))
        {
            EventLog.CreateEventSource("MYServiceLog", "MYServiceLog" + " Log"); // Create Log
        }
        MyLog.Source = "MYServiceLog";
        //' Write to the Log
        EventLog.WriteEntry("MYServiceLog" + " Log", DateTime.Now.ToString() + " " + strMessage, EventLogEntryType.Information);
        MyLog = null;
    }

Friday, April 16, 2010

How to Print a Page in JavaScript

 

While website development, there is always need of client side rich functionalities. JavaScript is very powerful client side language, which supports number of good functionalities.  Lets discuss print functionality in JavaScript.

window.print() function is used to print the current page.  you need to call it at any particular event. The sample code is given below. Please let me know if you face any problem while implementing.

<html>
<head>
<script type="text/javascript">
function printpage()
{ window.print() }
</script>
</head>
<body>
<form>
<input type="button" value="Print this page" onclick="printpage()">
</form>
</body>
</html>

Thursday, April 15, 2010

How to use Confirm Button in JavaScript

 

Sometimes we need to take confirmation before processing certain task. This can be implemented using JavaScript, there is a confirm function in JavaScript which takes message as input and if user accept the confirmation it return true otherwise false. Here is small demonstration of this function. Please let me know incase of any questions.


<html>
<body>
<script type="text/javascript">
var name = confirm("Press a button")
if (name == true)
{ document.write("You pressed OK") }
else
{ document.write("You pressed Cancel") }
</script>
</body>
</html>

Tuesday, April 13, 2010

How To Refresh Webpage Using JavaScript

 

This Sample code illustrate you that how to refresh web page using JavaScript code.  the function refresh() refresh the page every time its called. You can call it whenever page refresh is needed.

Here its called at body load. Whenever user will click on refresh button the body will load and function get called.

<html>
<head>
<script type="text/javascript">
function load()
{
setTimeout("refresh()", 3000)
}
function refresh(){
window.location.reload()
load()
}
</script>
</head>
<body onload="load()">
<form>
<input type="button" value="Click here to Refresh Page">
</form>
</body>
</html>

Monday, April 12, 2010

Uppercase and Lowercase in JavaScript

 

This post illustrate you JavaScript Uppercase and Lowercase inbuilt methods. here the str variable contains some string and uppercase and lowercase method is applied on both. you can check output once you run the given program.

<html>
<body>
<script type="text/javascript">
var str=("This is Example of JavaScript UpperCase and LowerCase.")
document.write("<br>")
document.write(str.toLowerCase())
document.write("<br>")
document.write(str.toUpperCase())
document.write("<br>")
</script>
</body>
</html>

<html>
<body>
<script type="text/javascript">
var famname = new Array(4)
famname[0] = "CSharpHub.com"
famname[1] = "SharePointBank.com"
famname[2] = "BharatClick.com"
famname[3] = "SoftwareTestingNet.com"
for (i=0; i<4; i++){
document.write(famname[i] + "<br>")
}
</script>
</body>
</html>

Sunday, April 11, 2010

Convert Degree to Radians and Radians to Degree in C#

 

This small utility will help you to convert degree to radians and radians to degree for mathematical operations. there is two separate functions for each. use as per your requirement.

 

public static float ToDegrees(float radians)
      {
          // This method uses double precission internally,
          // though it returns single float
          // Factor = 180 / pi
          return (float) (radians * 57.295779513082320876798154814105);
      }

      public static float ToRadians(float degrees)
      {
          // This method uses double precission internally,
          // though it returns single float
          // Factor = pi / 180
          return (float) (degrees * 0.017453292519943295769236907684886);
      }

Friday, April 9, 2010

How to Copy One Stream To Another in C#

 

This C# method will help you to copy a given stream file to another stream file.  Just pass the source and destination streams and you will get stream copied into destination one.

       /// <summary>
       /// Copies the contents of one stream to another.
       /// </summary>
       /// <param name="source">The stream to copy from</param>
       /// <param name="dest">The destination stream</param>
       /// <remarks>Copying starts at the current stream positions</remarks>
       public static void CopyStreams(Stream source, Stream dest)
       {
           byte[] buffer = new byte[64 * 1024];

           int nRead = source.Read(buffer, 0, buffer.Length);
           while (nRead != 0)
           {
               dest.Write(buffer, 0, nRead );
               nRead = source.Read(buffer, 0, buffer.Length);
           }
       }

Thursday, April 8, 2010

How to Create List in HTML

 

List is very important for any webpage. To display well formatted and point wise data, we use list. List are different type and examples are given below.

List Example:

  • Item 1
  • Item 2
  • Item 3

Square List:

<body>
<h1 align="center">Example</h1>
<hr>
<ul type="square">
<li>Item 1
<li>Item 2
<li>Item 3
</ul>
</body>

 

Numeric Ordered List:

<body>
<h1 align="center" >Example</h1>
<hr>
<ol type="1">
<li>Item 1
<li>Item 2
<li>Item 3
</ol>
</body>

 

Alphabet Orders List

<ol type=”A” start=3>
<li>Item 1
<li>Item 2
<li>Item 3
</ol>

You can have type as: A or a or 1 or I or i
Start is a number.

 

Formatted List:

<body>
<h1 align="center">Example</h1>
<hr>
<dl>
<dt><b>Toyota</b>
<dd>Made in Japan
<dt><b>Ford</b>
<dd>Made in USA
<dt><b>Hyundai</b>
<dd>Made in Korea
</dl>
</body>

Wednesday, April 7, 2010

How to Encode Single Quotes and Double Quotes in C#

 

encodeSingleQuotes utility will help you to convert single quotes to double quotes in given string. This is very useful while working with JavaScript and database. Because single quotes is not supported sometimes or have different meaning.

        public static string encodeSingleQuotes(string pStrValue)
        {
            string returnString = pStrValue.Replace("\'", "\'\'");
            return returnString;
        }

encodeHtmlSingleDoubleQuotes utility will help you to convert single quote and double quote to Unicode characters or encode in html supported format. This useful while passing url as query string and for database operations.

        public static string encodeHtmlSingleDoubleQuotes(string pStrHtmlValue)
        {
            string returnHtmlString = pStrHtmlValue.Replace("'", "&#39;").Replace("\"", "&#34;");

            return returnHtmlString;
        }

Tuesday, April 6, 2010

How to Create Checkbox Field in C#

 

This post will illustrate you to create a Checkbox filed in C#. Just call this utility from your code and and pass the checkbox field properties as per requirement. you will get an checkbox filed as a results.

 

public static CheckBoxField GetCheckBoxField(string pDataTextField, string pHeaderText, bool pVisible, HorizontalAlign pHorizontalAlign, bool pWrapText, bool pSortable)
       {
           CheckBoxField chkField = new CheckBoxField();
           chkField.DataField = pDataTextField;
           chkField.SortExpression = (pSortable ? pDataTextField : "");
           chkField.HeaderText = pHeaderText;
           chkField.Visible = pVisible;
           chkField.ItemStyle.HorizontalAlign = pHorizontalAlign;
           chkField.ItemStyle.Wrap = pWrapText;
           chkField.ReadOnly = false;
           return chkField;

       }

Monday, April 5, 2010

How to Fill Dropdown with List of Months in C#

 

This utility will help you to fill dropdown with list of months. Developer need to pass the dropdown list in given month and dropdown will be filled with all twelve months.

You can customize this method and add only custom month just by modifying the month array list.

public static void GetMonth(ref DropDownList mDDMonth)
       {
           string[] MonthList = new string[12] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

           int MonthValue = 0;
           for (int i = 0; i < MonthList.Length; i++)
           {
               MonthValue = i + 1;
               mDDMonth.Items.Add(new ListItem(MonthList[i], MonthValue.ToString()));
           }
       }

How to Convert String to Char in C#

 

This C# Utility will guide you to Convert a string into character. Just pass a string value into this utility and and it will return a char string if conversion is successful other wise return a blank ‘ ’ char.

 

      /// <summary>
       /// PURPOSE: To convert a string to char. if error in conversion, it will bring back ' '.
       /// </summary>
       /// <param name="pStrValue"></param>
       /// <returns></returns>
       public static char getpropercharvalue(string pStrValue)
       {
           char returnValue = ' ';

           try
           {
               returnValue = char.Parse(pStrValue);
           }
           catch
           {
               returnValue = ' ';
           }

           return returnValue;
       }

Sponsored Ad

Development Updates