Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Month: August 2008 Page 1 of 5

Optimizing Nested Query in SQL Server

My friend has been asked to optimize the SQL query for a forum application. Basically the Query is used to list the thread as well as the last person who posted on the forum. He and me tried to optimize that and we can fasten up the query up to only 13 secs which is not really well 🙁 . then the sql guru is coming to help him and show him the better way in writing the query and it performs only 1 sec. I thought it’s gonna be a good lesson to be shared it on my blog. There you go:

--Non Optimized Version
SELECT
	ForumTopic.ForumTopicID, ForumTopic.Title, Members.Username AS MemberName,
	ForumTopic.Views, ForumTopic.Replies,
	(
		SELECT TOP 1
			ForumPost.EnteredDate
		FROM
			ForumPost
		WHERE
			ForumPost.ForumTopicID = ForumTopic.ForumTopicID
		ORDER BY
			ForumPost.ForumPostID DESC
	) AS LastPostEnteredDate,
	(
		SELECT TOP 1
			Members.Username
		FROM
			ForumPost
		INNER JOIN
			Members
		ON
			ForumPost.EnteredBy = Members.MemberID
		WHERE
			ForumPost.ForumTopicID = ForumTopic.ForumTopicID
		ORDER BY
			ForumPost.ForumPostID DESC
	) AS LastPostMemberName
FROM
	ForumTopic
INNER JOIN
	Members
ON
	ForumTopic.EnteredBy = Members.MemberID
WHERE
	ForumID = @ForumID
AND
	ForumTopic.Valid = 1
ORDER BY
	LastPostEnteredDate DESC
--optimized version
SELECT
	ForumTopic.ForumTopicID,
	ForumTopic.Title,
	Members.UserName as MemberName,
	ForumTopic.Views,
	ForumTopic.Replies,
	ForumPost.EnteredDate as LastPostEnteredDate,
	Members1.Username as LastPostMemberName
FROM
	(
		SELECT
			ForumTopicID, MAX(ForumPostID) AS ForumPostID
		FROM
			ForumPost
		WHERE
			ForumTopicID IN (
				SELECT
					ForumTopicID
				FROM
					ForumTopic
				WHERE
					ForumTopic.ForumID = @ForumID
				AND
					ForumTopic.Valid = 1)
		GROUP BY
			ForumTopicID
	) RecentPost
INNER JOIN
	ForumPost
ON
	ForumPost.ForumPostID = RecentPost.ForumPostID
INNER JOIN
	ForumTopic
ON
	ForumTopic.ForumTopicID = RecentPost.ForumTopicID
INNER JOIN
	Members
ON
	ForumTopic.EnteredBy = Members.MemberID
INNER JOIN
	Members Members1
ON
	ForumPost.EnteredBy = Members1.MemberID
ORDER BY
	ForumPost.EnteredDate DESC

Recursive SQL using CTE in SQL Server 2005

How to do a recursive query in SQL Server 2005, Recursive in the terms of you got a table where it has foreign key to the other record on the same table. Assume a table employee where a record on that table can be an employee or a manager which is an employee as well, or let’s call it when you have nested structure within one table, call it as a tree structure. I’ve googled and found the way in doing it so I believe it’s worthy for me to share with everyone

Table Schema

How to get the whole structure by using one SQL query, we can utilize CTE(Common table expression) and using UNION ALL to do the recursive and do the INNER JOIN with the CTE it self

--get all contentPageID for the page and its children
WITH dynamicPages(contentPage_id, parentContent_id, contentPageName) AS
	(
		SELECT
			c.contentPage_id, c.parentContent_id, c.ContentPageName
		FROM
			tblContentPage c
		WHERE
			c.contentPage_id = @contentPage_id
		UNION ALL
		SELECT
			c.contentPage_id, c.parentContent_id, c.contentPageName
		FROM
			tblContentPage c
		INNER JOIN
			dynamicPages b
		ON
			c.parentContent_id = b.contentPage_id
	)
SELECT * FROM dynamicPages

Paging in Order BY using LINQ

This is a simple way of doing the paging in LINQ. If I do the paging before the ORDER BY then it will give me different result set. The paging is should be after the ORDER BY Statement. So you sort first then you paging it.

        /// 
        /// to get all the have your say using paging based on optional parameter
        /// of isapproved and sorted descending based on the posted date
        /// 
        /// 
        /// 
        /// 
        /// 
        public IQueryable HaveYourSaySelectApproved(bool? IsApproved, int startPage, int pageSize)
        {
            var haveyoursay = from h in HaveYourSayContext.HaveYourSays
                                      orderby h.DatePosted descending
			select h;

            if (IsApproved.HasValue)
            {
                haveyoursay = from h in HaveYourSayContext.HaveYourSays
                              where (h.IsApproved == IsApproved.Value)
                              orderby h.DatePosted descending
                              select h;
            }

	return haveyoursay.Skip(startPage * pageSize).Take(pageSize);
        }

Inserted Table and Deleted Table On SQL Server

this is only a simple trigger and table to monitor the activity on an update activity to “members” table. it tracks the date when the update query is being executed and who execute it, it will be quite useful for a database that has many applications accessing it with different SQL User

Holding table :

CREATE TABLE [dbo].[MemberUpdateTracking](
	[MemberTrackingID] [int] IDENTITY(1,1) NOT NULL,
	[MemberID] [int] NULL,
	[BeforeMemberCode] [varchar](50) NULL,
	[BeforeFirstName] [varchar](255) NULL,
	[BeforeSurname] [varchar](255) NULL,
	[BeforeUserName] [varchar](255) NULL,
	[BeforePassword] [varchar](255) NULL,
	[BeforeEmailAddress] [varchar](255) NULL,
	[AfterMemberCode] [varchar](50) NULL,
	[AfterFirstName] [varchar](255) NULL,
	[AfterSurname] [varchar](255) NULL,
	[AfterUserName] [varchar](255) NULL,
	[AfterPassword] [varchar](255) NULL,
	[AfterEmailAddress] [varchar](255) NULL,
	[ModifiedDate] [datetime] NOT NULL,
	[SQLUser] [varchar](255) NOT NULL,
 CONSTRAINT [PK_MemberUpdateTracking] PRIMARY KEY CLUSTERED
(
	[MemberTrackingID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

Triggers:

CREATE TRIGGER [dbo].[tr_Member_UPDATE]
	ON [dbo].[Members]
	FOR UPDATE
AS
BEGIN
	SET	NOCOUNT ON

	DECLARE @MemberID			int
	DECLARE @AfterFirstName		varchar(255)
	DECLARE @AfterSurname		varchar(255)
	DECLARE @AfterMemberCode	varchar(50)
	DECLARE @AfterUserName		varchar(255)
	DECLARE @AfterPassword		varchar(255)
	DECLARE @AfterEmailAddress	varchar(255)

	DECLARE @BeforeFirstName	varchar(255)
	DECLARE @BeforeSurname		varchar(255)
	DECLARE @BeforeMemberCode	varchar(50)
	DECLARE @BeforeUserName		varchar(255)
	DECLARE @BeforePassword		varchar(255)
	DECLARE @BeforeEmailAddress	varchar(255)


	--get information what will been inserted
	SELECT @MemberID = MemberID,
		   @AfterFirstName = FirstName,
		   @AfterSurname = Surname,
		   @AfterUserName = Username,
		   @AfterPassword = [Password],
		   @AfterMemberCode = MemberCode,
		   @AfterEmailAddress = EmailAddress
	FROM
		Inserted

	--only need for strange behaviour issue that we had before otherwise not necessary
	IF (@AfterFirstName = '' OR @AfterSurname = '' OR @AfterFirstName IS NULL OR @AfterSurname IS NULL)
	BEGIN
		--get the original information
		SELECT  @BeforeFirstName = FirstName,
				@BeforeSurname = Surname,
				@BeforeUserName = Username,
				@BeforePassword = [Password],
				@BeforeMemberCode = MemberCode,
				@BeforeEmailAddress = EmailAddress
		FROM
			Deleted

		--track the changes
		INSERT INTO MemberUpdateTracking(MemberID, BeforeMemberCode, BeforeFirstName,
					BeforeSurname, BeforeUserName, BeforePassword, BeforeEmailAddress,
					AfterMemberCode, AfterFirstName, AfterSurname, AfterUserName, AfterPassword,
					AfterEmailAddress, ModifiedDate, SQLUser)
		VALUES
			(@MemberID, @BeforeMemberCode, @BeforeFirstName, @BeforeSurname,
					@BeforeUserName, @BeforePassword, @BeforeEmailAddress, @AfterMemberCode,
					@AfterFirstName, @AfterSurname,
					@AfterUserName, @AfterPassword, @AfterEmailAddress,
					GETDATE(), SYSTEM_USER)
	END
END

Undo compressing old files by windows

My computer was losing its graphic card driver and somehow losing sound as well and I realised that i’ve been compressing the old files via disk clean up.

I thought i want to do reformat my PC, I tried to google to undo the compressing old files by windows and I’ve found that you need to run this from the command prompt. It will uncompress all the old files that has been compressed through windows disk clean up.I wonder why they don’t create a functionality to undo this.

C:\>compact /u /s /a /q /i *.*

Find a control in ContentPlaceHolder

I have a user control and I would like to hide a control on the page container that host this user control. I try to use

Page.FindControl("litContent")

But It throws an error of object not found. The solution is you need to find the contentplaceholder first on the master page then you find the control that you want from that placeholder. It’s a bit tricky since i thought once you get a Page instance then you can get all control hosted on the Page instance itself.

1. Place this tag on your asp.net page where it hosts your control


2. go to the page behind of the user control/page where you want to place your logic to hide/show it

'hide the dynamic page from the parent page
Dim mainContent As ContentPlaceHolder = CType(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)

If Not (mainContent Is Nothing) Then
   Dim contentPlaceHolder As Literal = CType(mainContent.FindControl("litContent"),Literal)
   If Not (contentPlaceHolder Is Nothing) Then
       contentPlaceHolder.Visible = False
   End If
End If

AJAX Update Panel Timeout Issue

I have an asp.net page where the page will query the report from the database. To query the report itself might cause timeout exception on the page itself before the report result is being returned from database.

You need to do it in two steps, first you need to override the script timeout only for the pageitself. put this code in your code behind

    Dim pageTimeOut As Integer
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        pageTimeOut = Server.ScriptTimeout

        'this is in seconds
        Server.ScriptTimeout = 2500
End Sub

Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

Server.ScriptTimeout = pageTimeOut

End Sub

The next step is required only if you use AJAX Update panel. Put this script on the aspx page


   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
        function (sender, args)
        {
             if (args.get_error() && args.get_error().name == 'Sys.WebForms.PageRequestManagerTimeoutException')
            {
                  // remember to set errorHandled = true to keep from getting a popup from the AJAX library itself
                 args.set_errorHandled(true);
             }
        });

Simple LINQ Tutorial

I’ve started learning about LINQ because I need to keep up to date with the latest technology out there. I’ve created a simple Business Layer which interact directly with Linq to SQL(DBML). It includes Insert, Update, Delete, Select and paging with LINQ.

Hopefully this tutorial will be useful enough for someone who is going to learn about LINQ. With LINQ we can really simplify/integrate the stored procedure into our Code base but it doesn’t mean LINQ does not support Stored Procedure.

It supports Stored Procedure as well since we might use Stored Procedure for complex calculation. You don’t need to create a table adapter anymore since LINQ does everything the same as table adapter.

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

namespace LinqCore.Factories
{
    public class GroupFactory
    {

        /// 
        /// this is used to get all the groups
        /// 
        /// 
        public IQueryable GetAllGroups()
        {
            GroupsDataContext db = new GroupsDataContext();
            var groups = from g in db.Groups
                         select g;

            return groups;
        }

        /// 
        /// this is used to get the group based on the group id
        /// 
        /// 
        /// 
        public Group GetGroup(int groupid)
        {
            GroupsDataContext db = new GroupsDataContext();

            var groups = from g in db.Groups
                         where (g.GroupID == groupid)
                         select g;

            return groups.SingleOrDefault();
        }

        /// 
        /// this is used to insert Or Update which determined by the nullable
        /// integer value of the groupID
        /// 
        /// 
        /// 
        /// 
        public void GroupUpdate(int? groupID, string groupName, bool valid)
        {
            GroupsDataContext db = new GroupsDataContext();
            Group group = new Group();

            if (groupID.HasValue)
            {
               group = db.Groups.Single(p => p.GroupID == groupID.Value);
            }

            group.GroupName = groupName;
            group.valid = valid;

            if (!groupID.HasValue)
            {
                db.Groups.InsertOnSubmit(group);
            }
            db.SubmitChanges();
        }

        /// 
        /// this is used to delete a group based on its ID
        /// 
        /// 
        public void GroupDelete(int groupID)
        {
            GroupsDataContext db = new GroupsDataContext();

            Group group = db.Groups.Single(p => p.GroupID == groupID);
            db.Groups.DeleteOnSubmit(group);
            db.SubmitChanges();
        }

        /// 
        /// this is used to do paging for the returned result
        /// 
        /// 
        /// 
        /// 
        public IQueryable GetAllGroups(int startIndex, int pageSize)
        {
            GroupsDataContext db = new GroupsDataContext();
            var groups = from g in db.Groups
                         select g;

            return groups.Skip(startIndex).Take(pageSize);
        }
    }
}

Using temp table and SQL stored procedure in Table Adapter

I was having a problem when adding a stored procedure into table adapter. The error was “Invalid object” of my temporary table name inside stored procedure.

It’s a bit strange since what i thought the table adapter only care about the results being returned but what it is actually checking up the existence of the table it self. FMTONLY is used to “Returns only metadata to the client. Can be used to test the format of the response without actually running the query”.

--uncomment this to regenerate it in table adapter
--comment it once you are done with generating the table adapter
SET FMTONLY OFF

File Stream/Stream response in AJAX Update Panel

Last few months, I got a problem to place a button to generate a CSV file in the update panel. I was having a problem related with response error. So what i did was to place the button outside the Update Panel. Today, I found a simple solution to place this button inside the AJAX Update panel

1. You need to set the page mode on the page load event

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.Form.Enctype = "multipart/form-data";
}

2. set the update Panel Children as trigger to true


3. set the trigger to your button


   

Page 1 of 5

Powered by WordPress & Theme by Anders Norén