Wednesday, February 29, 2012

New keyword and polymorphism

The new keyword will block inherited methods referring to normally overridden methods.
In this case the base method will be called

public class Parent
    {
        public void msgShow2()
        {
            MessageBox.Show(this.show2()); 
        }
       
       
        public virtual string show2()
        {
            return "parent" + this.GetType().ToString();
        }
       
        public virtual string  show()
        {
            return  "parent" + this.GetType().ToString();   
        }
    }


public class Child1 : Parent
    {
        public override string show2()
        {
            return "Child1:override" + this.GetType().ToString();
        }
       
        public override string show()
        {
            return "Child1" + this.GetType().ToString();
        }
        public void message()
        {
            MessageBox.Show("Child1"); 
        }

    }

public class Child2 : Parent
    {
        public new string show2()
        {
            return "Child1:new" + this.GetType().ToString();
        }
        public override string show()
        {
            return "Child2" + this.GetType().ToString();
        }
        public void message()
        {
            MessageBox.Show("Child2");
        }

    }

            Running the following

            Child1 c1 = new Child1();
            Child2 c2 = new Child2();


            List<Parent> l = new List<Parent>();
            l.Add(c1);
            l.Add(c2);

            foreach (Parent p in l)
            {
                p.msgShow2();
              //c1 will be derived
              //c2 will call the base

            }

what causes a InvalidCastException?

when a parent reference refers to a child - then casting to the child works fine

Parent pt ;
pt = c1;
((Child1)pt).message();

When a parent object is instantiated, likewise this will work

Parent pt = new Parent() ;
pt = c1;
((Child1)pt).message();

However a child object set to a parent will not compile
Parent pt = new Parent();
c1 = pt;

and an explicit cast will cause a runtime error  InvalidCastException

Parent pt =
new Parent();

c1 = (Child1)pt;//invalidcast


if however the parent is referencing a child then of course there is no runtime error

Parent
pt = new Parent();

pt = c1;
c1 = (Child1)pt;

why is there explicit casting in c#

there are 2 basic places where this is needed - when the precision is being truncated in numeric value types
and to access the members of actual type ;for example, if a child object is referenced by a parent then to get to the childs method you would need
   
   ((Child1)parent1).message()

I believe that with a number (1).ToString() works because it is implicitly being casted to object

Cool things cross apply does


select * from
(
select 1 as customer_id, 'herby' as name
union select 2 as customer_id, 'george' as name
union select 3 as customer_id, 'ben' as name
) a

cross apply
(

select customer_id, sale,date,
sum(sale) over(partition by customer_id,month(date)) total_of_cust_month,
sum(sale) over(partition by month(date)) total_of_month
from
(
select 1 as customer_id, 34.67 as sale, '1/1/2011' as date
union select 1 as customer_id, 3464.67 as sale, '2/1/2011' as date
union select 1 as customer_id, 364.67 as sale, '2/5/2011' as date
union select 1 as customer_id, 3374.67 as sale, '3/1/2011' as date
union select 2 as customer_id, 3448.67 as sale, '1/1/2011' as date
union select 2 as customer_id, 3324.67 as sale, '2/1/2011' as date
union select 2 as customer_id, 4.67 as sale, '2/4/2011' as date
union select 2 as customer_id, 3443.67 as sale, '3/1/2011' as date
union select 3 as customer_id, 3344.67 as sale, '1/1/2011' as date
union select 3 as customer_id, 3544.67 as sale, '2/1/2011' as date
union select 3 as customer_id, 3.67 as sale, '2/3/2011' as date
union select 3 as customer_id, 6334.67 as sale, '3/1/2011' as date) as main
where main.customer_id = a.customer_id
) b

cool things
  1. we can get multiple rows - subqueries cant
  2. we can get multiple columns - subqueries cant

Tuesday, February 28, 2012

example of cross join


select * from 
(select 1 id , 'ball' item
 union select 2 id , 'bat' item
 union select 3 id , 'glove' item
) as a
cross join
(select 'New York' location
 union select 'Philadelphia' location
 union select 'Miami' location )
as b



google maps api key change

I used the windows 7 search for where the maps api was being called in a certain website - the search did not look into .master pages - pain in the neck.

I set it at the map call level and that helped on my local development environment but not on the website

I eventually found it in the master page and all is well

BTW visual studio didnt search the master pages either -

TABLESAMPLE example

SELECT
FROM
id, name dbo.customers TABLESAMPLE SYSTEM(20 PERCENT)


BTW - This is better than the classic method of getting sample data
       select top 5 * from stats order by  newid()    
because in large amounts time will be spent creating the GUID

comma delimited lists in sql server

once upon a time I did this with cursors (cursors, cursors I say!)

  this is easier:
ALTER PROCEDURE [dbo].[getCommaDelim]
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
    declare  @list varchar(1000)
set @list = ''
   
      SELECT @list =@list + name + ',' from customers
select @list
END

if the @list is not set thusly:
set @list = ''
then the result will be null

intersect example

SELECT numFROM(SELECT 0 AS numUNION ALL
SELECT 0 AS Expr1UNION ALL
SELECT 5 AS Expr1UNION ALLSELECT - 55 AS Expr1) AS aINTERSECT
SELECT
numFROM(SELECT 0 AS numUNION ALL
SELECT 0 AS Expr1UNION ALL


results : 0,5

Unions vs Union All

Unions return unique values - even from seperate selects

SELECT     num
FROM         (SELECT     0 AS num
                       UNION ALL
                       SELECT     0 AS Num
                       UNION ALL
                       SELECT     5 AS Num) AS a
UNION
SELECT     num
FROM         (SELECT     0 AS num
                       UNION ALL
                       SELECT     0 AS Num
                       UNION ALL
                       SELECT     5 AS Num) AS b

 returns 0,5
union all doesn't remove doubles in seperate selects  and returns
0
0
5
0
0
5

Join imitating not exists

select *  from
(
select 1 id,'herby' name
union select 2 id,'john' name
) a
left join
(select 1 id ,23.56 amount) b
on a.id = b.id
where b.id is null

Monday, February 27, 2012

except acting like a not in or not exists

with test (id,name)
as
(
select 1 id,'herby' name
union select 2 id,'john' name
)
select * from test
where id in
(
select id from test
except
 select 1 id
)

interesting sql tidbit

this:
(
select 3 as herby
union select 1
)
order  by herby

works

with group by - it doesnt

you need:



select * from
(
select 3 as herby
union select 1
) as main
group by main.herby

why do you need exists - why isnt an inner join enough?

inner join returns multiple rows

theoretically the database could quit looking for a specific row after its true


perhaps another reason why there is exists so there could be not exists

Sunday, February 19, 2012

why are there events?

when you can handle events with a public intance of a delegate?

1)to disallow = operator , events allow only +=
2)to disallow delegate being directly called - with events it only works with an event handler

Friday, February 17, 2012

Proof that windowing comes last before order by

select id ,item, count(*) over()-- ,
-- sum(price) over(partition by id  )
/* running totals dont work yet */
from
(
select 1 id , 'beans' item, 1.66 price
union
select 2 id , 'tomatoes' item, 3.66 price
union
select 3 id , 'potatoes' item, 6.66 price
union
select 4 id , 'chips' item, 1.36 price
) main
where main.id <4

Giving CLR functions rights to writes

I created a CLR function to write to a file. This of course raised a permissions error to files
The following is what I had to do to get it to work

1)Check who is the owner of the database – make sure it’s the same as master
SELECT name, SUSER_SNAME(owner_sid)
FROM   sys.databases

2)If different
ALTER AUTHORIZATION ON database::xversions TO sa;
(or EXEC sp_changedbowner 'sa')
GO

3)Create the assembly with EXTERNAL_ACCESS
create assembly TSQLFunctions
from
'c:\program files\assemblies\TSQLFunctions.dll'
WITH PERMISSION_SET=EXTERNAL_ACCESS
go

how to script all stored procedures etc in a sql database

how to find who is locking a document

view state gaffe

a common error in  O'Reilly's programming c# 3.0 - that viewstate is needed for retaing choices in drop downs- the following disproves that: 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="test_view_state._Default"  %>

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:Label ID="Label1" runat="server"
            Text="Label"></asp:Label>
        <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
       
        <br />
        <asp:ListBox ID="ListBox1" runat="server">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
        </asp:ListBox>
       
    </div>
    <uc1:property ID="property1" runat="server"  Text ="hhhhh"  />
    </form>
    </body>
</html>

namespace test_view_state
{
    [Author("george", version = 1.1)]
    public partial class _Default : System.Web.UI.Page
    {

        [Conditional("DEBUG")]
        private void callout()
        {
            this.EnableViewState = false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

    }

    [System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct)]
    public class Author : System.Attribute
    {
        private string name;
        public double version;

        public Author(string name)
        {
            this.name = name;
            version = 1.0;
        }
    }

}