On this page

Working with the sql server 2000 sequences in c#
Sequence implementation in SQL server 2000
Why did SQL Server 2000 stopped connecting remotely ?
Lectures for the semester finnals
Microsoft "surface" - science fiction came to life ?
Why did Shimon stoped posting ?
Finding the true enjoyment of a process
Lost in Polymorphism world
Wrapping Unhandled exceptions from a WinForm application
Static objects in aspx page - Bad idea

Ads

Navigation

Search

Categories

Clouds

Sql Server (5) .Net (16) .Net 2.0 (2) C# (3) @ff Topic (5) Architectural solutions (9) ASP (1) BDD (5) Blog related (8) database (2) Development process (8) Facebook (1) job interviews (1) Lessons (5) Life (12) Microsoft (5) IIS 6 (2) SPS (sharepoint server) (3) Drivers (1) Internet Explorer (2) Windows 2003 server (1) NightDuck (2) Performance (5) Security (9) Sql Server 2000 (4) Study (2) TDD (1) Threading (3) Under the hood (1) Web (1) Web services (1) XSS (6)

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 33

Sign In
Pick a theme:

 Thursday, July 19, 2007
Thursday, July 19, 2007 8:12:19 PM (GMT Standard Time, UTC+00:00) ( Sql Server  | C# | Sql Server 2000 )

For those who didn't read the previews post about Sequence Implementation In SQL Server 2000 , please read it before continuing.

basically the idea is quite simple but i tough to add this post to complete the sequence framework.
adding some handling functions to your DAL object :

        /// <summary>
        /// this procedure retrieves from the database the value of the desired sequence.
        /// this is a generic function that gets the stored procedure to get the data from and the sequence name itself
        /// </summary>
        /// <param name="seqName">the name of the desired sequence</param>
        /// <param name="storedProcedure">the stored prosedure to call</param>
        /// <param name="connection">the connection to the database</param>
        /// <returns>an integer that represent the value of the sequence</returns>
        internal virtual int GetSequenceID(string seqName,string storedProcedure, SqlConnection connection)
        {
            int ret = int.MinValue;
            
            // Create a command
            SqlCommand command = new SqlCommand(storedProcedure, connection);    
            command.CommandType = CommandType.StoredProcedure;

            // pass the parameter of the sequence name for the series sequence
            SqlParameter p1 = new SqlParameter("@seqName",SqlDbType.VarChar);
            p1.Value = seqName;
            p1.Direction = ParameterDirection.Input;
            command.Parameters.Add(p1);        

            // open connection or using it if already opened
            bool OpenedConnection = false;
            try
            {
                if(connection.State!=System.Data.ConnectionState.Open)
                {
                    OpenedConnection = true;
                    connection.Open();
                }            
                
                // Execute the command
                ret = Convert.ToInt32(command.ExecuteScalar());
            }
            finally
            {
                if ((OpenedConnection) && (connection.State != System.Data.ConnectionState.Closed))
                    connection.Close();
            }
            
            return ret;
        }


        /// <summary>
        /// this is an internal function that retrieves the sequence value
        /// generally, it wraps the other internal method that does the actual work
        /// </summary>
        /// <param name="seqName">the name of the sequence that we want</param>
        /// <param name="storedProcedure">the stored procedure that we address for</param>
        /// <returns>the value of the sequence</returns>
        internal int GetSequenceID(string seqName,string storedProcedure)
        {
            int ret = int.MinValue;

            // Use the connection
            using(SqlConnection connection = DalServices.Connection())
            {
                try
                {
                    // Open the connection
                    connection.Open();
                    
                    // Get the object throught the internal method
                    ret = GetSequenceID(seqName,storedProcedure,connection);
                }
                
                finally
                {
                    // Close the connection
                    if (connection.State != System.Data.ConnectionState.Closed) connection.Close();
                }
            }
            
            return ret;
        }


and add some wrapping functions to extern the methods:

        /// <summary>
        /// The Next value of the series sequence
        /// </summary>
        /// <returns>the value of the sequence</returns>
        public int GetNextSeries()
        {
            // Calling the internall function to get the value
            return GetSequenceID("sq_series","sp_SequenceNextVal");
        }

        /// <summary>
        /// The current value of the series sequence
        /// </summary>
        /// <returns>the value of the sequence</returns>
        public int GetCurrentSeries()
        {
            // Calling the internall function to get the value
            return GetSequenceID("sq_series","sp_SequenceCurrVal");
        }

once again i'm a happy kamper.
Comments [0] | | # 
 Wednesday, July 18, 2007
Wednesday, July 18, 2007 7:06:10 PM (GMT Standard Time, UTC+00:00) ( Sql Server  | Architectural solutions | Sql Server 2000 )

for those folks who worked with oracle, know that sequence is an internal database object which has it's own methods and properties.
hey, why shouldn't i use this wonderful auto number feature that sql server has ?
well, auto number will give you a good solution to most of your needs that a sequence provided in oracle.
but, here is some conditions where auto number just won't suffice :

  • Managing more than one "auto number" in one table - auto number can be defined only at one field.
  • Managing the same auto number across multiple tables - the auto number can be asigned only to a specified table.

the solution is simple:
we will create some framework that will allow us to manage sequences and work with them.

first we will create one table to contain the sequences.

CREATE TABLE [dbo].[sysSequences] (
    [SequenceName] [char] (30) COLLATE Hebrew_CI_AS NOT NULL ,
    [Incrasement] [int] NOT NULL ,
    [StartValue] [int] NOT NULL ,
    [CurrentValue] [int] NOT NULL
) ON [PRIMARY]
GO

next thing we need to do is create some stored procedures that will handle these sequences.

the create sequence procedure :

CREATE procedure dbo.sp_Create_Sequence
(
    @seqName     varchar(30),
    @Increasement     int,
    @startValue    int
)
as
begin

declare @r int
begin transaction

    -- Check if the sequence exists
    set @r =(    select count(*)
    from sysSequences where SequenceName = @SeqName)
    
    if @r <> 0 --if error is raised
    begin
        goto LogError
    end

insert into sysSequences (SequenceName,Incrasement,StartValue,CurrentValue)
values (@seqName,@Increasement,@startValue,@startValue)    

commit transaction
goto ProcEnd

LogError:
rollback transaction
RAISERROR ('Can not create sequence with name %s, sequence exists already.',16,1,@seqName)

ProcEnd:
end

once we created the "object" (not really an object, more as a row in the sequence table), lets get his current value

create procedure dbo.sp_SequenceCurrVal
(
    @seqName     varchar(30)

)
as
begin

declare @rows int

begin transaction
    -- Check if the sequence exists
    set @rows =(    select count(*)
    from sysSequences where SequenceName = @SeqName)
    
    -- if no such row
    if @rows = 0
    begin
        goto LogError
    end

    -- Get the new value
    select CurrentValue from sysSequences
    where SequenceName = @SeqName
    
commit transaction
goto ProcEnd

LogError:
rollback transaction
RAISERROR ('sequence named %s, does not exists.',16,1,@seqName)

ProcEnd:
end

and the "get next value" method (very similar to the get current procedure.)

create procedure dbo.sp_SequenceNextVal
(
    @seqName     varchar(30)

)
as
begin

declare @rows int

begin transaction
    -- Check if the sequence exists
    set @rows =(    select count(*)
    from sysSequences where SequenceName = @SeqName)
    
    -- if no such row
    if @rows = 0
    begin
        goto LogError
    end


    -- Update the sequence increasement
    update sysSequences
    SET CurrentValue = CurrentValue + Incrasement
    where SequenceName = @SeqName

    -- Get the new value
    select CurrentValue from sysSequences
    where SequenceName = @SeqName
    
commit transaction
goto ProcEnd

LogError:
rollback transaction
RAISERROR ('sequence named %s, does not exists.',16,1,@seqName)

ProcEnd:
end


thats it, done.
now we have some sql server sequences

 

Comments [0] | | # 
 Saturday, July 14, 2007
Saturday, July 14, 2007 7:59:46 AM (GMT Standard Time, UTC+00:00) ( Windows 2003 server | NightDuck | Sql Server 2000 )

or, What have the latest windows 2003 service pack 2 has done to my sql server ?


Today i scheduled for my self some working time on the NightDuck project (Coming Soon),
but suddenly something went wrong, the sql server, which installed on a physically different machine than the development rig, gave me the following message:

"Sql server does not exist or access denied ConnectionOpen(Connect())"

what could have go wrong ?

the interesting part is when i tried to connect to the server remotely (remote desktop) and connecting to the Sql server from the localhost, it had no problems what so ever.
Since the sql server machine is not a dependency of a production application or something like that, i went wild on the experiments to try and fix the problem

  • Lets restart the sql server service - no good.
  • Router configurations and port forwarding - nothing has changed since the last time i worked on the project, thats not the problem either
  • SQL SERVER user - defining a new user did not solved the problem either

so i started googling on the subject, and found a few things, like this one for example at the Microsoft site :
Potential causes of the "SQL Server does not exist or access denied" error message

this article has a list of things that may cause this problem (hard to guess by it's name).
checking the relevant ones, i came across this article about ports needed by the sql server.
i made a little test to check if the ports are ok, i tried to telnet the machine from the dev PC on the 1433 port, but with no luck,
in an effort to isolate the problem i tried that from the localhost of the server, telneting to the localhost on port 1433, which gave me an error "could not connect...".
this is what i was looking for !
At this point the problem is completely isolated, why ?

  • the router configuration is not an issue (request does not go out from the machine)
  • the development rig is not part of the equation anymore
  • firewall is not the problem

based on these symptoms, I've searched once more, and stumbled upon a forum thread about a very similar issue, when installing service pack 2 on windows XP causes the same effect.
Apparently, if you have an out of date version of the file DBNETLIB.dll ,the Service Pack 2 disables TCP/IP access to MS SQL Server.
This is a defense against the Slammer worm. (some ugly work around by Microsoft a have to say...)

the solution is installing the SQL Server 200 security tools , which sets things back to normal.

since the windows 2003 service pack 2 is quite new, i guess this thread will be useful


update :
Just wondering how many others encountered this specific problem,
if you find this info useful, please leave a comment.

Comments [1] | | # 
 Saturday, June 30, 2007
Saturday, June 30, 2007 4:56:27 PM (GMT Standard Time, UTC+00:00) ( Study )

for the next exams i'll post some recorded lectures that may help (thanks maor).

i'll update this post (for the next topics..)

Algorithems 2 - Boyer Moore

Update:
Algorithems 2 - Last lecture by kfir - Reductions - part1
Algorithems 2 - Last lecture by kfir - Reductions - part2

Update : 06.07.07

Infi2 Notes of the last lectures :
rafi1.rar (1.55 MB)
rafi2.rar (2.94 MB)
rafi3.rar (2.44 MB)
Infi2Jane.rar (2.01 MB)

Some tests :
infiTests.rar (758.66 KB) - pack of tests from early years
2006itzik.mdi (646.73 KB) - test from the last year

Comments [0] | | # 
 Wednesday, June 20, 2007
Wednesday, June 20, 2007 1:12:58 PM (GMT Standard Time, UTC+00:00) ( Life )
WOW !!!
this has my first reaction to this concept of surface computing, it is really amazing .

object recognition, 30'' Table screen, touch activated, complete integration with other consumer devices (phones, digital cameras, PDA's,mp3 players and so...)
i got to say that this interface can really change the way we interact with computers (not to mention how cool it looks..)




check this video :


here is some links on this subject :
http://arstechnica.com/news.ars/post/20070530-what-lurks-below-microsofts-surface-a-qa-with-microsoft.html
http://www.microsoft.com/surface/


Comments [0] | | # 
 Saturday, June 09, 2007
Saturday, June 09, 2007 9:51:44 PM (GMT Standard Time, UTC+00:00) ( .Net 2.0 | Architectural solutions | Life | NightDuck )

No, I'm no retiring from the coding field...
actually I'm in the opposite direction.
the last few months I've been working on a new system thats about to go online in the next few months.
busy as hell in architecture issues, coding issues and more...
i decided to take the opportunity of this project and Finlay get into the asp.net 2.0 .
so i tried to do some coding here

Convert.ToDotNet2(Shimon);

but that only returned an exception of InvalidCasting.
so, i sat on my bottom and started to learn all that is to know to introduce myself to the new features (yes, i know it's about time).

from what i can see, asp.net 2.0 will introduce to the world a lot of "drag&drop" programmers.
take for example the login controls that come built-in:

  • it's great for the beginner programmer.
  • this is one well of a !#@#!!# for an architect.

i mean, they coupled a GUI to a "generic" DB structure, Why ???
what if i want to manage my roles and permissions in other manner (say hierarchical roles...),
or just manage the user in my DB with all the other tables so i can do some easy data mining ?
to do that i need to write some providers to the controls that equals to implementing the business logic from scratch.
i will extent later on that matter (some other post...)

building this project as a one man show gave me an oppertunity of a vast view on a system besides playing with one module.
from now on, i'll continue update here the progress of the project.

 

Comments [0] | | # 
 Saturday, April 21, 2007
Saturday, April 21, 2007 8:00:50 PM (GMT Standard Time, UTC+00:00) ( Life )

just to be clear, I'm not talking about computer process .
I'm talking about the daily processes that we do every day.
have you ever stopped for a second to wonder, what are the things that you enjoy the most ?
i mean what are the daily processes do you enjoy the most, what defines them ?

think about that for a second, a person spends a great part of his time @ work (if not most of his time),
so it is imperative to do something that you enjoy from,
otherwise you'll suffer most of the month to accomplish things with your paycheck at the end of the month.
this kind of deal is not such a great bargain, not for me anyway.

so, i began thinking, what sort of things i like or dislike.
to be honest, i thought about this for a long time (couple of months to be exact), and came with some sort of list of things.

i want to share this list with you.

  • Playing on the guitar - OK, i know this is a vast subject, I'll try to be more specific...
    - i enjoy creating my own songs(although most of them not really worth hearing them).
    - i enjoy improvising as a lead guitar or just as a solo.
    - i really don't like playing other people songs (even if those songs are really good, scorpions for example).
  • Do some hacking (Ethical only), and finding solutions to various security problems.
  • Building computer systems (Hardware), i know this sounds a little bit stupid,
    but new hardware stuff and creating some systems with it to meet some user demands does the trick for me.
  • Designing software systems.
  • Finding solutions to problems that no one could solve ( not necessary software problems).
  • Creating a software infrastructure architecture.
    - knowing that your design/creation will be used by many of your colleagues.
    - knowing things will work efficiently,oriented by performance, flexibility and even security.
  • Giving lectures about subjects i like to do and have some expertise in it.
  • I hate doing repeatable work, I'll give some examples :
    - solving lots of math problems of the same kind.
    - writing software programs that require the same solutions over and over.
    - working at a factory like jobs
  • I like reading about new stuff on the web - i guess that updating yourself is a must for everyone.

here is some conclusions after looking over and over on this list :

  • i like to preform creative tasks that stimulate the brain
  • i like doing things that i can express my self.
  • i like receiving a positive feedback and a respect from the society ( who does not ?).

now, all i have to do is finding a job that suits the mentioned above :)

what do you think about the subject ?
how would you summerize does list of things ?

btw,
i've added a file of a record i've done with a friend just before i got drafted to the army.
anjoy


prototype1.mp3 (682.45 KB)
Comments [0] | | # 
 Monday, April 16, 2007
Monday, April 16, 2007 11:12:18 AM (GMT Standard Time, UTC+00:00) ( .Net | C# )

ok, this is the point where all the OOP guru's can contribute some of thier knowledge.
i'm facing some strange problem maybe someone can point the solution.

i'm having this code :

public class Father
{
}

public class Son:Father
{
}

public class Tester
{
    public void TestFunc(Father a)
    {
    }

    public void Test()
    {
        Son aSon = new Son();

        TestFunc(aSon);
    }    
}

this code will compile with no problems.

but if i want to pass the object by reference, it will cause a compilation error.

public class Father
{
}

public class Son:Father
{
}

public class Tester
{
    public void TestFunc(ref Father a)
    {
    }

    public void Test()
    {
        Son aSon = new Son();

        TestFunc(ref aSon);
    }    
}

the error i'm getting is something like : "can not convert 'ref son' to 'ref Father' "
does someone knows why ?
Comments [0] | | # 
 Sunday, March 04, 2007
Sunday, March 04, 2007 6:35:22 PM (GMT Standard Time, UTC+00:00) ( .Net | Architectural solutions | Threading )

couple weeks ago, my friend and co-worker, shani raba, presented me a problem.
they have some sealed application as an .exe file that throws some exceptions and crashes their application.

So, i Thought that is a good idea to wrap the targeted application with reflection, and catch the unhandled thrown exceptions.

to demonstrate this,
I've created an application with a button that throws an exception.

private void button1_Click(object sender, System.EventArgs e)
{
    throw new Exception("my Exception, need to be wrapped");
}

the next thing that we need to create is the wrapper.

so, creating a console application with this code should have solved the problem:

[STAThread]
static void Main(string[] args)
{

    Assembly assembly = Assembly.LoadFrom ("cashTester.exe");

    Type t = assembly.GetType("cashTester.Form1");
    object o = Activator.CreateInstance(t);
    try
    {
        Application.Run((Form)o);
    }
    catch(Exception ex)
    {
        Console.Write("exception was thrown : " + ex.Message);
    }
}

running this code in debug mode successfully catch the exception from the winform.
but, for some reason, in a normal run, this code won't catch the exception.

makes you wonder, huh ?

so i did some thinking, what on earth can make this phenomena ?
The answer is : Threads.
Yes, like it or not, but this is the subject that everyone tries to avoid it.
everyone knows it exists, and no one really likes it,
but we can't run from the problem, we need to confront it.

So, what can we do ?

since Application.Run launches a new thread, we can add to the Application.ThreadException event handler, an exception handling method.

like this class :

 

/// <summary>
/// The Wrapper class
/// </summary>
public class Wrapper
{

    /// <summary>
    /// Public cunstructor
    /// </summary>
    public Wrapper()
    {
    }

    /// <summary>
    /// This function will initialize the exception handling
    /// </summary>
    public void Init()
    {
        // define handlers for unhandled exceptions
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.exp);
        Application.ThreadException +=new System.Threading.ThreadExceptionEventHandler(this.ThreadExp);
    }

    /// <summary>
    /// This method is for the threads exceptions
    /// </summary>
    /// <param name="o">the object</param>
    /// <param name="args">Thread exception args</param>
    void ThreadExp(object o, System.Threading.ThreadExceptionEventArgs args)
    {
        // Write the message to the console
        Console.Write("Unhandled thread exception was thrown : " + args.Exception.Message);
    }

    /// <summary>
    /// This method is for the unhandled exceptions from the main thread
    /// </summary>
    /// <param name="o">the object</param>
    /// <param name="args">exception arguments</param>
    void exp(object o,System.UnhandledExceptionEventArgs args)
    {
        // Write the message to the console
        Console.Write("Unhandled exception was thrown : " + ((Exception)args.ExceptionObject).Message);
    }

    public void Run()
    {
        // Load the assembly
        Assembly assembly = Assembly.LoadFrom ("cashTester.exe");

        // get the type of the object
        Type t = assembly.GetType("cashTester.Form1");

        // invoke it
        object o = Activator.CreateInstance(t);

        // Run the application - note that this line starts an additional thread
        Application.Run((Form)o);
    }
}

 

now, all we need is to launch it :

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
    Wrapper w = new Wrapper();
    w.Init();
    w.Run();
}

 

now we got an exception wrapper for launching applications.

Shani, tell me if that helped ...

p.s.
There are more ways to do it, but this is the simplest one

Comments [2] | | # 
Sunday, March 04, 2007 12:17:48 PM (GMT Standard Time, UTC+00:00) ( .Net | Architectural solutions )

Yesterday, good friend of mine, Lev rosenblit, asked me a good question.
what are the life cycle of static objects in an aspx page.
so, at first without any hesitation, i answered that the object will die after the request event ends.
the dude insists that I'm wrong on that matter, so i decided to check it out .

here is some code snippet to check it out :

        private static int myStaticInt = 0;
        private void Page_Load(object sender, System.EventArgs e)
        {
            myStaticInt++;
            Response.Write(myStaticInt);
        }

by theory (which is objects in an aspx page die after the end of the request), this code should print the number "1" on each request.
but the result was different, on each request, the result increased.

digging a little on the web, i found that static objects live inside the App domain and not in the page context.
This interesting fact raised some interesting question, an architectural one:
what would happen if the code run in NLB configuration (Network Load Balancing)?

on that matter their is a session state issue which is solved by getting the session state from a shared database,
but what about the static objects that live inside the App domain ?
what can be done to share those object ?

from my point of view, this is a bad choice in architecture when you choosing to use static objects inside your page.
thus, it won't always work, and will be hardware Dependant system.

Comments [0] | | #