Tuesday, July 31, 2012

How to get RowIndex on GridViewRowcommand Event

.aspx page
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'


.CS page (on row commond)
int iRowIndex = Convert.ToInt32(e.CommandArgument.ToString())
OR
Dim iRowIndex As Integer
iRowIndex = CType(CType(sender, Control).Parent.Parent, GridViewRow).RowIndex

Thursday, May 17, 2012

Get date diff in Year, Months, and Days in oracle

with t as (select to_date('30-JAN-1995') as date1
                     ,sysdate as date2 from dual)
                    
    select
      trunc((date2-date1)/365) as Years,
      trunc((trunc(date2-date1) - trunc((date2-date1)/365) * 365)/30) as Months,
      trunc((date2-date1) - ((trunc((trunc(date2-date1) - trunc((date2-date1)/365) * 365)/30) *30 ) + (trunc((date2-date1)/365) * 365))) days
   from t

Differences among Int32.Parse, Covert.ToInt32, and Int32.TryParse

Int32.Parse (string )

It converts the string representation of a number to its 32-bit signed integer equivalent.
When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

For example:

string n1 = "3233";
string n2 = "3233.33";
string n3 = null;
string n4 = "12340056789123456789123456789123456789123456789";

int result;
bool success;
result = Int32.Parse(n1); //-- 3233
result = Int32.Parse(n2); //-- FormatException
result = Int32.Parse(n3); //-- ArgumentNullException
result = Int32.Parse(n4); //-- OverflowException

Convert.ToInt32(string)
It converts the specified string representation of 32-bit signed integer equivalent.
This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException.
If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue,
it will throw OverflowException.

For example:

result = Convert.ToInt32(n1); //-- 3233
result = Convert.ToInt32(n2); //-- FormatException
result = Convert.ToInt32(n3); //-- 0
result = Convert.ToInt32(n4); //-- OverflowException

Int32.TryParse(string, out int)
It method converts the specified string representation of 32-bit signed integer equivalent to out variable,
and returns true if it is parsed successfully, false otherwise. This method is available in C# 2.0. When s is a null reference,
it will return 0 rather than throw ArgumentNullException. If s is other than an integer value, the out variable will have 0 rather
than FormatException. When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than
OverflowException.

For example:

 success = Int32.TryParse(s1, out result); //-- success => true; result => 3233
 success = Int32.TryParse(s2, out result); //-- success => false; result => 0
 success = Int32.TryParse(s3, out result); //-- success => false; result => 0
 success = Int32.TryParse(s4, out result); //-- success => false; result => 0

Int32.TryParse is better than that of Int32.Parse and Convert.ToInt32.
Convert.ToInt32 is better than Int32.Parse.

Saturday, January 21, 2012

Disabling the Back Button


When i was doing coding for sign in and sign out for my clients application, i found that after signing out from the application i transfered the control to login page e.g. login.aspx. At this point if i click the Back button of Browser it shows the content of previous page user was viewing.

As there was important data displayed on page it is security threat.

It is a threat for web applications displaying important information like credit card numbers  or bank account details.

I tried to find the solution on net but could not get satisfactory answer.

On searching i found following problem, and i think it is important to share this issue-

What happens when Back Button clicked

When we visit a page it is stored in a cache i.e. history on a local machine. Whenever user clicks the Back button, previous page is taken from this cache and displayed; request does not go to the server to check the login information as page is found on local cache. If we submit the page or refresh the page then only page is sent to the server side.

Caching-

Caching of Web Pages can happen in three separate entities in a Web environment.
When you think about caching, you usually think about the Web pages cached locally in your temporary Internet files of the profile that was used to log into local machine as a result of having visited the page. But caching can also occur within the Internet Information Server (IIS) Server, and If a proxy server is present, it can be configured to cache the pages.

Solution-

To avoid the displaying of page on click of back button we have to remove it from cache, or have to tell the server not to cache this page.

So if we do not cache the page then on click of back button request goes to server side and validation can be done whether session exist's or not.


This can be achieved by adding following code in the page load of the page for which we do not want to cache the page in history.

Response.Buffer=<SPAN style="COLOR: blue">true;<o:p></o:p>
Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
Response.Expires =-1500;
Response.CacheControl = "no-cache";
 if(Session["SessionId"] == null)
    {
    Response.Redirect ("Login.aspx");
    }
}

Code in Detail-  

Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);

In this instead of giving the current date we gave the date in the past so it confirms the expiration of page. So that allowing for time differences, rather than specify a static date. If your page is being viewed by a browser in a very different time-zone.


Response.Expires = -1500;    

Some IIS internals experts revealed this can be a very touchy parameter to rely upon and usually requires a rather"large" negative number or pedantically, that would be a very small number.

Response.CacheControl = "no-cache";

It tells the browser not to cache the page.

Things can work with only one line of code
i.e.     Response.CacheControl = "no-cache";

But it is good practice to delete the existing page from cache.


This code will tell the server not to cache this page, due to this when user clicks the Back button browser will not find the page in cache and then will go to server side to get the page.

Disabling cache can also be done by adding following line in Meta section of page


But when I tried this it does not worked for me.
Proxy Server Caching-

Response.CacheControl = "private";

It disables the proxy server caching and page is cached on local machine.

Response.CacheControl = "public";

Proxy server cache is enabled.

Users request pages from a local server instead of direct from the source.

So if the information displayed is critical information extra care should be taken to remove the page from cache on sign out.

Hence for such applications keeping pages non caching is good solution.

Monday, January 9, 2012

When you install the 32-bit version of Microsoft ASP.NET 2.0 on a 64-bit computer, the ASP.NET state service (Aspnet_state.exe) is not installed.

This problem may occur when one of the following conditions is true:
  • You install only the 32-bit version of ASP.NET 2.0 on a 64-bit computer where Microsoft Internet Information Services (IIS) is already configured to run in Microsoft Windows on Windows 64 (WOW64) mode.
  • You uninstall the 64-bit version of ASP.NET 2.0 before you install the 32-bit version of ASP.NET 2.0.
 
To resolve this problem, install the 64-bit version of ASP.NET 2.0 before you install the 32-bit version of ASP.NET 2.0.

Note The information in this article applies only to 64-bit computers that are running the 32-bit version of ASP.NET 2.0 and IIS in WOW64 mode. Additionally, the following steps configure the computer to run the 32-bit version of ASP.NET 2.0 and IIS in WOW64 mode.

To resolve this problem, follow these steps:
  1. If you already installed the 32-bit version of ASP.NET 2.0 on the computer, run the following command to uninstall the 32-bit version of ASP.NET 2.0:
    Framework\v2.0.50727\aspnet_regiis -u
  2. Run the following command to switch IIS to run in native mode:
    cscript DriveLetter:\inetpub\AdminScripts\adsutil.vbs set w3svc/AppPools/Enable32BitAppOnWin64 0
  3. Run the following command to install the 64-bit version of ASP.NET 2.0:
    Framework64\v2.0.50727\aspnet_regiis -i
  4. Run the following command to switch IIS to run in WOW64 mode:
    cscript DriveLetter:\inetpub\AdminScripts\adsutil.vbs set w3svc/AppPools/Enable32BitAppOnWin64 1
  5. Run the following command to install the 32-bit version of ASP.NET 2.0:
    Framework\v2.0.50727\aspnet_regiis -i

Wednesday, December 28, 2011

how to create a proxy from webservice?

There are two ways to create proxy from web Service:

1. Add web reference in your web application and use them.


2. Open the command prompt of visual studio and copy & paste bellow mentioned line:

For VB
=====
wsdl /language:VB /n:"<destination>" http://<source&lgt;?WSDL

For C# 
=====
wsdl /language:CS /n:"<destination>" http://
<source&lgt;?WSDL

Friday, December 2, 2011

how to download a file

        Response.ContentType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=aaa-13.pdf");
        Response.TransmitFile(Server.MapPath("~/Image/UserDetails-13.pdf"));
        Response.End();

Thursday, November 24, 2011

How to Store Viewstate to Persistence Medium



In this article we will discuss about How to store ViewState of a Page/Control on server or a custom data store like sql server or file.
As you all know ViewState is stored as part of html sent to your browser in form of hidden field. This is the default behavior of asp.net framework. Starting asp.net 2.0 you have more control over how & where view state should be stored? First of all let’s understand the reason behind not sending viewstate to client:-
1.)    ViewState can be tempered with on client side with tools like firebug, fiddler etc.
2.)    ViewState makes page bulky and page loading process becomes slow.

Asp.net 2.0 introduced two methods which help us out in this process:-
1.)    LoadPageStateFromPersistenceMedium
2.)    SavePageStateToPersistenceMedium
LoadPageStateFromPersistenceMedium loads viewstate data from your custom storage.
SavePageStateToPersistenceMedium saves viewstate data to persistence medium.
So let’s try to understand this with an example
1.   Create an empty website in visual studio
2.   Add a page say Default.aspx
3.   Write below code in aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
td>
tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
td>
tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
td>
tr>
table>
div>
form>
body>
html>

4. In code behind file write below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("1"));
items.Add(new ListItem("2"));
items.Add(new ListItem("3"));
DropDownList1.DataSource = items;
DropDownList1.DataBind();
}
}
protected override object LoadPageStateFromPersistenceMedium()
{
if (Session["DefaultPageViewState"] != null)
{
       string viewStateString = Session["DefaultPageViewState"] as string;
TextReader reader = new StringReader(viewStateString);
LosFormatter formatter = new LosFormatter();
object state = formatter.Deserialize(reader);
return state;
}
else
return base.LoadPageStateFromPersistenceMedium();
//return null;
}
protected override void SavePageStateToPersistenceMedium(object state)
{
LosFormatter formatter = new LosFormatter();
StringWriter writer = new StringWriter();
formatter.Serialize(writer, state);
Session["DefaultPageViewState"] = writer.ToString();
}
}
Open page in browser and page loads up with values in dropdown list.



Right click page and click View Source. See highlighted portion below..The viewstate field is empty.

Click the button to perform postback. You will see the dropdown still loads with data i.e. ViewState has been persisted and is working fine.
Just to cross check if our code is actually working. Comment out code in LoadPageStateFromPersistenceMedium method and return null instead. Again compile and run the code. Page will open fine first time but now click on postback , you will see dropdown losing data since it was stored in viewstate.

Sunday, October 30, 2011

how to get name of procedure where word like tablename, column name have been used in Oracle

SQL> select distinct name from user_source where upper(type)='PROCEDURE' and upp
er(text) like '%TABLENAME%';

NAME
------------------------------
SP_ABC
SP_BCD
SP_XYZ
SP_LMD
SP_WEEK_ABC
SP_WEEK_XYZ

Friday, October 28, 2011

How to count no of rows in a Textarea in javascript

function rowcount()

var area = document.getElementById("hist");
var text = area.value.replace(/\s+$/g, "");
var split = text.split("\n");
return split.length;
}

Thursday, August 18, 2011

How to get that particular table is being used in any procedure, trigger etc...?

select * from user_source where upper(text) like '%REVENUE_EMP_DTLS_WEEK_REPORT%'

Monday, June 27, 2011

What is the difference between hiding and overriding for casting related matters?

When you use virtual+new, the method definition of base class is hided by the definition provided in child class (called method hiding) . In this case, method of the class, whose object is created, will be called.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  //Will give output Base
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public new void foo()
        {
            Console.WriteLine("Child");
        }
    }


In second case, where you want to use virtual+override, Thats method overriding. In this case child class function will be called when you create object using casting.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  // output will be "Child"
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public override void foo()
        {
            Console.WriteLine("Child");
        }
    }


You can also combine both method overriding and hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }

Why does TextBox retains its value after multiple postbacks even if we set the EnableViewState property of the TextBox to False?

The reason being is ASP.NET uses this primitive to update the control's value. ASP.NET uses IPostBackDataHandler  for the controls that load the data from the form collection.
Actually all the controls which implement IPostbackdatahandler, implement the method LoadPostData and
RaisePostDataChangedEvent. But here the key method is LoadPostData, which returns true if the posted value is changed from earlier value and updates it with posted value, else it returns false.

As from the Page Life Cycle, we can see LoadPostData is called after the LoadViewState, whether viewstate is on or not,  it gets populated from the posted data. That's why the data get persisted even if viewstate is set to off for few controls. Following is the complete list of the controls, those implement IPostBackDataHandler.
  •  CheckBox
  •  CheckBoxList
  •  DropDownList
  •  HtmlInputCheckBox
  •  HtmlInputFile
  •  HtmlInputHidden
  •  HtmlInputImage
  •  HtmlInputRadioButton
  •  HtmlInputText
  •  HtmlSelect
  •  HtmlTextArea
  •  ImageButton
  •  ListBox
  •  RadioButtonList
  •  TextBox

Tuesday, June 21, 2011

Can we overload methods in WCF Service or Web Service?

Yes for a WCF Service use the Name property of OperationContractAttribute class
example:
[ServiceContract]
interface ddd
{
[OperationContract(Name = "one")]
int calc(int a,int b);

[OperationContract(Name = "two")]
double calc(double a,double b);
}

1)For a Web Service use the MessageName property of WebMethodAttribute class
2)Please comment the following line in the .cs file of the Web Service
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebMethod]
public string HelloWorld(string a) {
return "Hello"+" "+a;
}
[WebMethod(MessageName="second")]
public string HelloWorld()
{
return "Hello second";
}

What does a Windows Communication Foundation, or WCF, service application use to present exception information to clients by default?

However, the service cannot return a .NET exception to the client. The WCF service and the client communicate by passing SOAP messages. If an exception occurs, the WCF runtime serializes the exception into XML and passes that to the client.

What is the use of Is Required Property in Data Contracts?

Data Contracts, is used to define Required or NonRequired data members. It can be done with a property named IsRequired on DataMember attribute.


[DataContract]
public class test
{
      [DataMember(IsRequired=true)]
      public string NameIsMust;

      [DataMember(IsRequired=false)]
      public string Phone;          
}

Wednesday, June 15, 2011

Delete Duplicate Recods from a Table in SQL Server 2005

CREATE TABLE dbo.Dupes
(
    PK_Column INT IDENTITY(1,1),
    Dupe_String VARCHAR(32)
)



INSERT dbo.Dupes(Dupe_String)
    SELECT 'foo'
    UNION ALL SELECT 'foo'
    UNION ALL SELECT 'foo'
    UNION ALL SELECT 'bar'
    UNION ALL SELECT 'bar'
    UNION ALL SELECT 'splunge'
    UNION ALL SELECT 'splunge'
    UNION ALL SELECT 'mort'

SELECT * FROM dbo.Dupes


DELETE dbo.Dupes
    FROM dbo.Dupes d
    LEFT OUTER JOIN
    (
        SELECT Dupe_String, pk_column = MIN(PK_Column)
        FROM dbo.Dupes
        GROUP BY Dupe_String
    ) x
    ON d.pk_column = x.pk_column
    WHERE x.pk_column IS NULL

What is Event bubling?

The concept of calling parent event from child event.
For example, Let us take a GridView Control. GridView control consists of several events like row edit,update. We can edit a particular row of a gridview control by raising row edit event. The reslt of that row edit event effects to the gridview control data. Hence this concept is called Event Bubbling

Saturday, May 14, 2011

Difference between Oracle & Sql Server?

  • a better transaction system
  • packages
  • Cursor For Loops
  • anchored declarations (variables declared as table.column%type)
  • initial values for variable declarations
  • %rowtype variables
  • much lower overhead for cursors
  • BEFORE triggers
  • FOR EACH ROW triggers
  • While sequences require either discipline or before each row triggers, they are more flexible than SQL Server identity columns.
SQL Server Strengths:
  • Transact-SQL is just one language, so you don't have to worry about what's SQL, what's SQL*PLUS and what's PL/SQL.
  • Because T-SQL is just one language, the T-SQL collections actually work decently with SQL. You can join T-SQL table variables to real tables. This tends to mean, while PL/SQL is more powerful for procedural programming, you just don't need to do procedural programming in T-SQL.
  • If you perform a select query with no target, the results are automatically returned to the client. For production code, this means you don't need to declare and pass sys_refcursor. For ad-hoc research work, this means you can easily make scripts that perform lookups and display multiple recordsets.
  • SQL Server Management Studio is much better than SQL*Plus or SQL Developer. Because it just displays any returned recordsets, data retrieval procedures are very easy to test.
  • easier client connectivity setup (nothing as bad as tnsnames)
  • less confusion about what drivers to use, apart from JDBC
  • Declare a column "Int Identity Not Null Primary Key" and then you can forget about it.
  • Every variable name starts with an "@" sigil, which looks terrible, but prevents name collisions between variables and columns.
  • The case you declared a table or column with will be remembered, but it's not case sensitive, and you aren't limited to 30 characters.
  • Crystal Reports can call SQL Server stored procedures, where you tend to be forced into a view with Oracle.

Thursday, May 12, 2011

How to Show Flash movie

function createFlashMarkup(width,height,uri,replaceid){

 var embed = document.createElement('embed');
 embed.setAttribute('width',width);
 embed.setAttribute('height',height);
 embed.setAttribute('src',uri);

 var div = document.getElementById(replaceid);
 document.getElementsByTagName('body')[0].replaceChild(embed,div); 
}

window.onload = function(){
 createFlashMarkup('550','400','vuurwerk.swf','replaced-by-flash');
}