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

Month: September 2008 Page 1 of 3

Check Existence of temp table in memory

How to check whether the temp table is exists on the memory or not?The reason why you need this is because your stored procedure can throw the error when you try to drop a temp table which is not exists anymore on the memory. The best practice to drop a temp table is normally to check the existence of the table on the memory then we drop the table if it is exists

--Drop the table after usage
IF object_id('tempdb..#tmpStandardCostRate') IS NOT NULL
BEGIN
   DROP TABLE #tmpStandardCostRate
END

Find Index in all the tables SQL Server

This is a query to find all the indexes in your table including when it was last updated

Find all indexes on all tables

SELECT
	OBJECT_NAME(OBJECT_ID) AS 'Table Name',
	[name] as 'Statistic',
	STATS_DATE(object_id, index_id) AS 'Last Updated Statistics Date'
FROM
	sys.indexes
ORDER BY
	 STATS_DATE(object_id, index_id)
DESC

Find all indexes on a particular table

SELECT
	OBJECT_NAME(OBJECT_ID) AS 'Table Name',
	[name] as 'Statistic',
	STATS_DATE(object_id, index_id) AS 'Last Updated Statistics Date'
FROM
	sys.indexes
WHERE
        OBJECT_NAME(OBJECT_ID)  = 'YourTableName'

This SQL query returning the information about number of rows in the table as well as number of update/insert/delete after the last index has been rebuilt

SELECT
	'TABLE ' = substring(sysobjects.name,1,30) , ' INDEX ' = substring(sysindexes.name,1,30)
	,sysIndexes.rowcnt, sysindexes.rowmodctr
	,[last updated]=STATS_DATE(sysobjects.id, sysindexes.indid)
        ,user_seeks,user_scans,user_lookups,user_updates
FROM	sysobjects
INNER JOIN sysindexes ON sysobjects.id = sysindexes.id  AND sysindexes.indid > 0
INNER JOIN sys.dm_db_index_usage_stats iusage ON iusage.object_id = sysobjects.id  AND iusage.index_id = sysindexes.indid
WHERE
	sysobjects.xtype = 'U'
AND
	iusage.database_id = (SELECT dbid FROM master.dbo.sysdatabases WHERE [name] = db_name())
ORDER BY sysobjects.name

Convert DataTable to CSV Function

This is the class that you can use to create a CSV file from DataTable. Basically what it does is to iterate each column and row in datatable and separate them with comma.

Class/Function:

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;

namespace BusinessLayer
{
    public class CSVBuilder
    {
        public static string BuildCSVDocument(DataTable table)
        {
            StringBuilder   builder = new StringBuilder();
            DataColumn      col;

            // append header
            for (int index = 0; index < table.Columns.Count; index++)
            {
                col = table.Columns[index];
                builder.AppendFormat("{0},", col.ColumnName);
            }

            builder.AppendLine();

            // append rows
            foreach (DataRow row in table.Rows)
            {
                object[] values = row.ItemArray;

                for (int index = 0; index < values.Length; index++)
                {
                    object value = row[index];
                    string valueString;

                    if (value is DateTime)
                    {
                        valueString = Convert.ToDateTime(value).ToString("dd/MM/yyyy hh:mm");
                    }
                    else if (value is string)
                    {
                        valueString = value.ToString().Replace("'", "`").Replace(",", "");
                    }
                    else
                    {
                        valueString = value.ToString();
                    }

                    builder.AppendFormat("{0},", valueString);
                }

                builder.AppendLine();
            }

            return builder.ToString();
        }

        public static void StreamCSV(DataTable table, HttpResponse response, string fileName)
        {
            // convert the extract to CSV
            string csv = BuildCSVDocument(table);

            // Send it to browser
            response.ClearContent();
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.ContentType = "text/csv";

            // Write to the stream
            StreamWriter sw = new StreamWriter(response.OutputStream);
            sw.Write(csv);
            sw.Close();

            response.Flush();
            response.Close();
        }
    }
}

Usage

 private void GenerateMyCsv()
    {
        lblErrorOrderID.Visible = false;

        try
        {
            tdsReports.MissingBatchNumberSelectDataTable dtBatch =
                ReportFactory.GetMissingBatch(txtOrderID.Text);

            //display no results returned message
            if (dtBatch.Rows.Count != 0)
            {
               CSVBuilder.StreamCSV(dtBatch , Response, "MyCSV.csv");
            }

        }
        catch (ApplicationException ex)
        {
            lblErrorOrderID.Text = ex.Message;
            lblErrorOrderID.Visible = true;
        }
        catch (Exception ex)
        {
            lblErrorOrderID.Text = ex.Message;
            lblErrorOrderID.Visible = true;
        }
    }

Generic Logging Class in .NET

This is a snippet code which is useful in creating your own logging class. You can compile this as a library and use it accross the projects.

using System;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;

namespace MyLogging
{
    /// 
    /// provides event logging capabilities
    ///
    /// requires a LogSource setting in app/web.config, which must match the name of the event log
    /// 
    public class Logger
    {
        #region constants

        static readonly string ERROR_NOSOURCE = "MyLogging - cannot write to event log - please specify a LogSource in app/web.config";

        #endregion

        #region static ctor

        static Logger()
        {
            if (ConfigurationManager.AppSettings["LogSource"] == null)
            {
                throw new ApplicationException(ERROR_NOSOURCE);
            }
            else
            {
                _source = ConfigurationManager.AppSettings["LogSource"].ToString();

                if (!EventLog.SourceExists(_source))
                {
                    EventLog.CreateEventSource(_source, "Application");
                    EventLog.WriteEntry(_source, "log source created");
                }
            }
        }

        #endregion

        #region properties - LogSource

        private static string _source = null;

        public static string LogSource
        {
            get { return _source; }
            set { _source = value; }
        }

        #endregion

        #region public logging methods

        /// 
        /// logs an exception, using reflection to determine calling method and module
        /// 
        /// 
        public static void LogException(Exception ex)
        {
            MethodBase  method = ex.TargetSite;
            Module      module = method.Module;

            string      msg = module.Name + "." + method.Name
                            + " - " + ex.Message
                            + Environment.NewLine
                            + "Stack Trace - " + ex.StackTrace;

            LogMessage(msg, EventLogEntryType.Error);
        }

        /// 
        /// logs a (non-error) message
        /// 
        /// 
        public static void LogMessage(string message)
        {
            LogMessage(message, EventLogEntryType.Information);
        }

        /// 
        /// logs a message, with specified EventLogEntryType
        /// 
        /// 
        /// 
        private static void LogMessage(string message, EventLogEntryType type)
        {
            message = Assembly.GetExecutingAssembly().FullName + " - " + message;

            //if (_source == null)
            //{
            //    throw new ApplicationException(ERROR_NOSOURCE);
            //}

            EventLog.WriteEntry(_source, message, type);
        }

        #endregion
    }
}

overriding maximum file upload size in ASP.NET

To override maximum file size that can be uploaded in you website, you need to put this in your web.config

      
        
      

Another Entry to My Blog

I’ve decided to buy a domain which basically link to the same server. My new domain is http://www.fransiscus.com.au and at the same time I’ll migrate my content from Joomla to WordPress .I will try to blog more and writing a better blog to share more .NET knowledge with everyone. I feel so excited to move to my new workplace on the 8th september 2008 🙂 and I hope new place = new project = new knowledge to be shared with everyone

CSV parsing in SQL server

I’ve got this SQL Function to parse comma separated value into a table. We need this function when our application commit separated comma value in a text. We normally do this when we want to send an array of value to the SQL server

CREATE FUNCTION [dbo].[SplitCSV](@CSV text)
-- Returns a table with txtValue column
RETURNS @OutTable table(txtValue text)
AS
BEGIN

declare @currentposition int
declare @nextposition    int
declare @lengthOfString  int

-- Assign the starting position of the string
SET @currentposition = 0
 -- The reason for this is to force entrance into the while loop below.
SET @nextposition = 1

WHILE @nextposition > 0
BEGIN
-- Assign the next position to be the current index of ',' + 1
SELECT @nextposition = charindex(',', @CSV, @currentposition + 1)

-- In here we need to find 2 things. The position of the ','
-- and the length of the string segment in between.
SELECT @lengthOfString = CASE WHEN @nextposition > 0
       THEN @nextposition
       ELSE DATALENGTH(@CSV) + 1
       END - @currentposition - 1

--After the length and position is found all we need to do
--is take the substring of the string passed in.
INSERT @OutTable (txtValue)
       VALUES (substring(@CSV, @currentposition + 1, @lengthOfString))

--Set the current position to the next position
SELECT @currentposition = @nextposition
END
RETURN
END

Usage in SQL Query

SELECT
	VenueID
FROM
	Venues
WHERE
	PostCode
IN
	(SELECT CAST(txtValue as VarChar) FROM dbo.splitcsv(@PostCode))

Project item ‘4294967294’ does not represent a file

Project item ‘4294967294’ does not represent a file, this error comes out when I try to open a solution which results in some of the projects can not be loaded (the source file is on the right location and path). I’ve spent two hours to three hours to resolve this issue.
This problem can be resolved by checking out all the files under that solution (from tfs explorer, before you open the solution on your visual studio) and it will resolve the problem for sure. but it’s not practical if you keep doing this and it’s not good to check out all the files if you are not using it.

The root of this problem is caused by Reporting Project. in detail,I’ve checked in reportname.rdl.data for every single report and reportsprojectname.rptproj.user file. Those files must not be checked in at all, remove it from your TFS or VSS and it will work.

Dynamic Order By in ROW_NUMBER()

How to do order by in your paging using ROW_NUMBER() feature on SQL Server 2005

SELECT a.CurrentPrice, a.LotQuantity, a.IsAuction,
	a.AuctionID, a.AuctionName, a.DateStart, a.DateFinish,
	a.StartingPrice, a.ReservePrice, a.FixedPrice, a.BidIncrement,
	p.ProductID, p.CategoryID, p.BrandID, p.ProductName, p.ContentID, p.ThumbImageID,
	Row_Number() OVER
	(
		ORDER BY
		CASE
			WHEN @OrderBy = 'Price_ASC'	THEN CurrentPrice
			WHEN @OrderBy = 'ClosingSoon_ASC'	THEN ISNULL(DateFinish, DATEADD(DAY, 100, GETDATE()))
		END ASC,
		CASE
			WHEN @OrderBy = 'Price_DESC'		THEN CurrentPrice
			WHEN @OrderBy = 'ClosingSoon_DESC'	THEN ISNULL(DateFinish, DATEADD(DAY, 100, GETDATE()))
		END DESC,
		CASE
		       WHEN @OrderBy = 'Name_ASC'			THEN AuctionName
		END ASC,
		CASE
		       WHEN @OrderBy = 'Name_DESC'			THEN AuctionName
		END DESC
		) AS RowNum
FROM Auction a
	INNER JOIN Products p ON a.ProductID = p.ProductID
	INNER JOIN [Content] c ON p.ContentID = c.ContentID

webform_dopostbackwithoptions is undefined

A few days back I’ve got the error message “webform_dopostbackwithoptions is undefined” on the project that i’m working on.
The strange thing it happened only when I activated the securepagemodule, when i deactivated the module it works perfectly. I tried to debug it with HTTP debugger (fiddler tool) and i found that on that particular page, there is a request from webresources.axd but the request is not into https but into http and what i believe since the page is on secure mode therefore it discards the “webresources.axd” since it’s not secure. The workaround for this issue is by adding entry of “webresources.axd” under securepage and the problem is solved.

This is the sample of web.config for it

 
        
         
   </secureWebPages

NOTE:This is resolved in the new version of securepage module

Page 1 of 3

Powered by WordPress & Theme by Anders Norén