Pages

Jul 12, 2010

How to show date alone in GridView BoundField when using DateTime as DataType in DataBase.


DateTime Formatting in GridView:
Usually we create a field with DataType DateTime in Database 
say for eg. MSAccess database.
Now when you show this in the GridView it shows Date along with 
time like 7/6/2010 8:10:12 PM
But you may be in situation to show only the Date alone.
like 7/6/2010
To do so, simple specify the format in the GridView BoundField like

<Columns>
    <asp:BoundField 
              DataField="Date1" 
              HeaderText="Date" 
              DataFormatString="{0:d}" />
</Columns>

Refer the below link for different other formats
http://msdn.microsoft.com/en-us/library/
system.web.ui.webcontrols.boundfield.dataformatstring.aspx

Jul 10, 2010

How to show a alert message or confirmation when deleting row from GridView without postback + Asp.Net

This is a basic logic needed in Grid-view while deleting a data. By mistake people may click
on the delete button and if there is no alert or confirmation, some valuable data may be lost.
Let's go for implementation, below is the grid-view


<asp:GridView ID="GridView2" runat="server"  AutoGenerateSelectButton="true"
            DataKeyNames="ID"  AutoGenerateDeleteButton="true"
            onrowdatabound="GridView2_RowDataBound" >
      <Columns>
                <asp:BoundField DataField="ID" HeaderText="SL.No" Visible="false"/>
                <asp:BoundField DataField="Project" HeaderText="Project" Visible="false"/>
      </Columns>
</asp:GridView>

In the above grid the two properties namely AutoGenerateSelectButton,
and AutoGenerateDeleteButton let you show the Select and
Delete button on the GridView.
Now on onrowdatabound event of the GridView we implement the logic like


  protected void GridView2_RowDataBound(object sender,
                                                            GridViewRowEventArgs e)
    {
        // Gets the Delete command column, which is the first column
        foreach (Control control in e.Row.Cells[0].Controls)
        {
            // Gets the Delete link button
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
               DeleteButton.OnClientClick =
               "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }
The above code will show you an alert message before deleting a row.

How to access ServerSide method from GridView's ItemTemplate

Calling a CodeBehind Method From GridView's ItemTemplate:


While working with GridView, there may be a case where 
we actually need to do some operations in serverside for 
which we may be in a need to call a server side
method from ItemTemplate of a GridView.


Say for example, 
I had a situation where i need to call a server side 
method (which return a string value) from ItemTemplate.
So i used a label in the ItemTemplate like 



<asp:TemplateField HeaderText="Testing">
<ItemTemplate>
<asp:Label ID="lblCustomerAge" Text='<%# GetCategory() %>' runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>


Here GetCategory is the server side method.Code-behind is given below

  protected string GetCategory()
    {
       // Do whatever you want here
        return "TestCategory"; // For eg. passing a string
    }

Jul 6, 2010

How to split a sentence into word using C# + Regular Expressions


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string[] w = SplitWords("This is a Sample, Test");
        foreach (string s in w)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }

    /// <summary>
    /// Get all the words in the input string and separate them.
    /// </summary>
    static string[] SplitWords(string s)
    {
        //
        // Split on all non-word characters.
        // ... Returns an array of all the words.
        //
        return Regex.Split(s, @"\W+");
        // @      special verbatim string syntax
        // \W+    one or more non-word characters together
    }
}
Output:
This
is
a
Sample
Test

Jul 3, 2010

How to find the System Name in C#

Lets make use of the Namespace 
using System.Security.Principal; to find the System name.


Below is the code:
lblSysNo.Text = WindowsIdentity.GetCurrent().Name.ToString();

Jul 1, 2010

How to pass double couted paramaters to Command line utilities programatically + c#

Invoking a Command Line Utility From C#:


For eg. let's consider FWTools which has a command line utility named 
ogr2ogr for converting tab to kml
Below is the code to invoke the command line utility ogr2ogr

Invoking Command Line without parameters:

// Create an instance for System.Diagnostic.Process
Process proc = new Process();
// Provide the utility name with location
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
// Start the process
proc.Start();

Invoking Command Line with normal parameters:
Note: -f, KML, sourcepath, destpath are arguments separted by space
Process proc = new Process(); 
string driver = @"-f KML C:\FWTools2.4.7\bin\zeeee.kml 
C:\FWTools2.4.7\bin\Morocco.tab"
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.Arguments = driver; 
proc.Start();
proc.WaitForExit(); // use if you want your  program to wait for the process to complete.
proc.Close();

Invoking Command Line with Double couted parameters:

Usually space in the arguments list denote that each are separate
argument separated by space.

In the above code KML is the name of the driver used to convert 
Tab to KML.

And to convert ESRI's shape file to MapInfo's Tab file the driver 
used is "MapInfo File", which itself has a space

so by default command line arguments will consider it as a
two parameter one is "MapInfo" and other is "File"
so the program goes wrong.

Below is the solution, how to pass the double couted paremeter

string driver = "-f " + @"""" + "MapInfo File" + @"""" +
 @" C:\FWTools2.4.7\bin\test.tab C:\FWTools2.4.7\bin\test.shp";

By using this methodology, we can pass "MapInfo File" as a 
single argument to a command line utility.

Jun 30, 2010

How to find the GridView RowID on SelectedIndexChanged Event of DropDownList inside ItemTemplate of GridView

Once there is a case where i need to bind a dropdownlist depending 
on the selection of other dropdownlist.
The above case is a usual one which we can do in a selectedIndexChanged Event. 
But here the twist is, 
I have both the dropdownlist inside a GridView as ItemTemplate.
So when i write a selectedIndexChanged how do i identify the actual row id of the GridView where the current DropDownList is present.
Here we go for the solution..
Write the below code to the selectedIndexChanged Event of the DropDownList



// First Identify the row in which the dropdown value has been changed
        GridViewRow gr = (GridViewRow)
            ((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
 //find the control in the current row
        // selected dropdownlist
        DropDownList Projectddl = (DropDownList)gr.FindControl("ddlTest");
        // Dropdownlist to bind
        DropDownList Datumddl = 
               (DropDownList)(gr.FindControl("ddlSamp"));
        if (Projectddl.SelectedItem.Value == "SomeSelectedValue")
        {            
           // bind the second dropdownlist here
          Datumddl .DataSource = dTable;

          Datumddl .DataTextField  = member;
          Datumddl .DataValueField = member;
          Datumddl .DataBind();
        }

Jun 26, 2010

How to find expandedPaneId of Rad Sliding Pane and collapse + Client side

While using more sliding panes in my project , there was a need to expand and collapse panes manually and programatically. 


When doing so, i noticed a problem with Sliding Pane that when we try to expand a pane when already other pane is expanded , there was a mesh. 


Both the panes are expanded but the Close[x] button is not working in the panes.
i.e we are unable to close the pane using the Close[x] button on the pane.


so here we go how to solve this problem?
The solution is " Lets find the expanded pane id for the SlidingZone and collapse it first before opening a new pane. Below is the code.


// finds the Rad sliding zone first in which the pane resides
var slidingZone = $find("SlidingZone1");
(or)
 var slidingZone = $find("<%= SlidingZone1.ClientID %>"); // for Master Page Scenerio


// find the expanded pane id of the zone and collapse it
var expandedPaneId = slidingZone.get_expandedPaneId();


 // To collapse the pane 
      slidingZone.collapsePane(expandedPaneId );



After this, one can perform expand collapse pane operations as shown in my previous post without mesh.

May 17, 2010

How to Add a Water mark text to an image using C#.

 Below is the method which will add a text as a water marked text to an image.


 public Bitmap WaterMarkToImage(string ImagePath, string watermark)
            {
                Bitmap bmp;
                bmp = new Bitmap(ImagePath);
                Graphics graphicsObject;
                int x, y;
                try
                {
                    //create graphics object from bitmap
                    graphicsObject = Graphics.FromImage(bmp);
                }
                catch (Exception e)
                {
                    Bitmap bmpNew = new Bitmap(bmp.Width, bmp.Height);
                    graphicsObject = Graphics.FromImage(bmpNew);


                    graphicsObject.DrawImage(bmp, new Rectangle(0, 0, 
                    bmpNew.Width, bmpNew.Height), 0, 0, bmp.Width, 
                    bmp.Height, GraphicsUnit.Pixel);
                    bmp = bmpNew;
                }


                int startsize = (bmp.Width / watermark.Length);
               //get the font size with respect to length of the string


                //x and y cordinates to draw a string
                x = 0;
                y = bmp.Height / 2;                    


               System.Drawing.StringFormat drawFormat = 
               new System.Drawing.StringFormat(StringFormatFlags.NoWrap);
                //drawing string on Image
                graphicsObject.DrawString(watermark, new Font("Verdana", 
                startsize, FontStyle.Bold), 
                new SolidBrush(Color.FromArgb(100, 255, 255, 255)), x, y, drawFormat);


                //return a water marked image
                return (bmp);
            }


Method Call:

         System.Drawing.Bitmap bmp = 
         WaterMarkToImage(@"D:\images\IMG_2933.jpg", "Intraspatial Softech");
         bmp.Save(@"D:\images\c1.jpg");


May 14, 2010

Problem calling Java-script method from codebehind with master-page and update panel

we normally use
Page.ClientScript.RegisterStartupScript(this.GetType(), "key", "Sys.Application.add_load(method_Name);", true);
to call a javascript on runtime form code behind.
Placing the above code on page load or a button click makes the script to fire on the start up of subsequent postback.


But this make not work in the case where we give a
ajax post back intead of normal postback.


so to call a javascript method on ajax postback , here we go


ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Key", "ServiceDownAlert();", true);


Javascript Method:

function ServiceDownAlert() {
        alert("Image Not Available ! Please Try Later !");
    }

Apr 19, 2010

How to set a Navigation tool as active tool on page load in MaxExtrem 6.8.0

Set Zoom-In Tool as Active Tool on Page Load:
Usually the sample applications that map extreme provide have no tools set as a default active tool.
We need to select the tool(say ZoomIn tool or Zoom out etc as per our requirements). But while developing applications for customer requirement we may need to set some tool as active tool so as to simply the customer process.


Below is the method used to set the Zoom-In tool as the Active tool on page load.
private void SetActiveTool(string toolName)
    {
        string activateCode = String.Format("{0}Tool.Activate();", "ctl00$ContentPlaceHolder1$" + toolName);
        string activateScript = String.Format("<script type='text/javascript'>AppendScriptToForm('{0}');</script>", activateCode);
        Page.RegisterStartupScript("Key1", activateScript);
    } 


The above code applies for the Master Pages. You can directly provide the tool name in normal page scenario.

How to Expand and Collapse a rad Sliding pane from client side while using Master Pages.

Below is the code used to Expand the Rad Sliding Pane:


       // finds the Rad sliding zone first in which the pane resides
        var slidingZone = $find("<%= SlidingZone1.ClientID %>");
       // finds the Rad sliding pane need to be expanded.
        var pane = $find("<%= SlidingPane1.ClientID %>");
       // Expands the pane
        slidingZone.expandPane(pane.get_id());


      // To collapse the pane 
      slidingZone.collapsePane(pane.get_id());

Apr 5, 2010

How to stretch the contents of the web page to its full extent without margin?

This is because the default margin has some values set when we create a web page. so set the margin to 0 to 
stretch your page content to the full extent of the web page using the CSS.


<style type="text/css">
body {
 margin-top: 0px;
 margin-right: 0px;
 margin-bottom: 0px;
 margin-left: 0px
}
</style>


Or even simplied as


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

Mar 2, 2010

how to make the server side button click event firing depend on javascript return?

Using OnClick and OnClientClick:
Usually we have situations where we have to check for something in the client side and decide whether to fire the server side event or not.
Say for eg.
some client side validations. Lets see how to do this
Now in the sever side OnClick event i have certain operation to be performed, 
before that i need to make some client side validations. 
Say for eg. To check for GridView's count and decide whether to allow or stop the servide side event firing.

<asp:Button ID="btnSubmit" runat="server" 

OnClientClick="javascript:return CheckGridCount();" OnClick="btnSubmit_Click" />
Above is the way we call the javascript method CheckGridCount() to perform the check.



function CheckGridCount()
{
    var gv = document.getElementById('gridView1');
    var count = gv.rows.length;
    if(count >0)
  {
     return true;
  }
  else
  {
   alert("Please select Atleast one item");
    return false;
  }
}

If the above method return true then the server side event fires and postback occurs
else an alert is shown and nothing happens thus avoiding an unnecessary postback.

Feb 15, 2010

Unit Testing - An Overview

UNIT TESTING:
 As soon as we think of testing , as a developer the first thing comes to mind is the Developer level Unit Testing.   Now lets see some definitions and examples of the Developer level Testing.

UNIT TEST – THE CLASSIC DEFINITION :

A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions afterward. If the assumptions turn out to be wrong, the unit test has failed. A “unit” is a method or function.

Black Box vs. White Box Test

Black box testing is different from white box testing.  The kind of testing that you can perform on the code determines, among other things, the complexity of the unit test.

Black Box Testing

A black box test (also known as a "functional test") is one in which you feed it inputs and verify the outputs without being able to inspect the internal workings.  Furthermore, one doesn't usually have information regarding:
  • how the box handles errors
  • whether your inputs are executing all code pathways
  • how to modify your inputs so that all code pathways are executed
  • dependencies on other resources
Black box testing limits your ability to thoroughly test the code, primarily because the you don't know if you're testing all the code pathways.  Typically, a black box test only verifies that good inputs result in good outputs (hence the term "functional test").
Classes are often implemented as black boxes, giving the "user" of the class access only to the public methods and properties that the implementer selected.

White Box Testing

A white box provides the information necessary to test all the possible pathways.  This includes not only correct inputs, but incorrect inputs, so that error handlers can be verified as well.  This provides several advantages:
  • you know how the box handles errors
  • you can usually write tests that verify all code pathways
  • the unit test, being more complete, is a kind of documentation guideline that the implementer can use when actually writing the code in the box
  • resource dependencies are known
  • internal workings can be inspected
In the "write the test first" scenario, the ability to write complete tests is vital information to the person that ultimately implements the code, therefore a good white box unit test must ensure that, at least conceptually, all the different pathways are exercised.
Another benefit of white box testing is the ability for the unit test to inspect the internal state of the box after the test has been run.  This can be useful to ensure that internal information is in the correct state, regardless of whether the output was correct.  Even though classes are often implemented with many private methods and accessors.  with C# and reflection, unit tests can be written which provide you the ability to invoke private methods and set/inspect private properties.




1.5 A simple unit test example
Assume we have a SimpleParser class in our project that we’d like to test as shown in listing 1.1. It takes in a string of 0 or more numbers with a comma between them. If there are no numbers it returns zero. For a single number it returns that number as an int. For multiple numbers it sums them all up and returns the sum (right now it can only handle zero or one number though):
Listing 1.1: A simple parser class we’d like to test
public class SimpleParser
{
public int ParseAndSum(string numbers)
{
if(numbers.Length==0)
{
return 0;
}
if(!numbers.Contains(","))
{
return int.Parse(numbers);
}
else
{
throw new InvalidOperationException("I can only handle 0 or 1 numbers for
now!");
}
}
}
We can add a simple console application project that has a reference to the assembly containing this class, and
write a method like this in a class called SimpleParserTests, as shown in listing 1.2.
The test is simply a method, which invokes the production class (production: the actual product you’re building
and would like to test) and then checks the returned value. If it’s not what is expected to be, it writes to the
console. It also catches any exception and writes it to the console. 
Listing 1.2:A simple coded method that tests our SimpleParser class.
class SimpleParserTests
{
public static void TestReturnsZeroWhenEmptyString()
{
try
{
SimpleParser p = new SimpleParser();
int result = p.ParseAndSum(string.Empty);
if(result!=0)
{
Console.WriteLine(@"***
SimpleParserTests.TestReturnsZeroWhenEmptyString:
-------
Parse and sum should have returned 0 on an empty string");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}

Next, we can simply invoke the tests we’ve written using a simple Main method run inside a console
application in this project, as seen in listing 1.3. The main method is used here as a simple test runner, which
invokes the tests one by one, letting them write out to the console for any problem. Since it’s an executable, this
can be run without human intervention (assuming no test pops up any interactive user dialogs).
Listing 1.3: Running our coded tests via a simple console application
public static void Main(string[] args)
{
try
{
SimpleParserTests.TestReturnsZeroWhenEmptyString();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
The test also catches any exception that might occur and writes it to the console output.



INTEGRATION TESTING:

Testing two or more dependent software modules as a group.

An integration test would exercise many units of code that work together to evaluate one or more results, while a unit test would usually exercise and test only a single unit in isolation.

What Is NUnit?

NUnit is an application designed to facilitate unit testing.  It consists of both a command line and Window's interface, allowing it to be used both interactively and in automated test batches or integrated with the build process.  The following sections discuss NUnit as it applies to C# programming.

How Does NUnit Work?

NUnit utilizes attributes to designate the different aspects of a unit test class.

TestFixture

The TestFixture attribute designates that a class is a test fixture.  Classes thus designated contain setup, teardown, and unit tests.

SetUp

The SetUp attribute is associated with a specific method inside the test fixture class.  It instructs the unit test engine that this method should be called prior to invoking each unit test.  A test fixture can only have one SetUp method.

TearDown

The TearDown attribute is associated with a specific method inside the test fixture class.  It instructs the unit test engine that this method should be called after invoking each unit test.  A test fixture can only have one TearDownmethod.

Test

The Test attribute indicates that a method in the test fixture is a unit test.  The unit test engine invokes all the methods indicated with this attribute once per test fixture, invoking the set up method prior to the test method and the tear down method after the test method, if they have been defined.
The test method signature must be specific: public void xxx(), where "xxx" is a descriptive name of the test.  In other words, a public method taking no parameters and returning no parameters.
Upon return from the method being tested, the unit test typically performs an assertion to ensure that the method worked correctly.

ExpectedException

The ExpectedException attribute is an optional attribute that can be added to a unit test method (designated using the Test attribute).  As unit testing should in part verify that the method under test throws the appropriate exceptions, this attribute causes the unit test engine to catch the exception and pass the test if the correct exception is thrown.
Methods that instead return an error status need to be tested using the Assertion class provided with NUnit.

Ignore

The Ignore attribute is an optional attribute that can be added to a unit test method.  This attribute instructs the unit test engine to ignore the associated method.  A requires string indicating the reason for ignoring the test must be provided.

Suite

The Suite attribute is being deprecated.  The original intent was to specify test subsets.

An Example

 [TestFixture]
public class ATestFixtureClass
{
    private ClassBeingTested cbt;
 
    [SetUp]
    public void Initialize()
    {
        cbt=new ClassBeingTested();
    }
 
    [TearDown]
    public void Terminate()
    {
        cbt.Dispose();
    }
 
    [Test]
    public void DoATest()
    {
        cbt.LoadImage("fish.jpg");
    }
 
    [Test, Ignore("Test to be implemented")]
    public void IgnoreThisTest()
    {
    }
 
    [Test, ExpectedException(typeof(ArithmeticException))]
    public void ThrowAnException()
    {
        throw new ArithmeticException("an exception");
    }
}