Wednesday 12 November 2014

Convert String To Color In SQLSERVER



CREATE FUNCTION dbo.fn_conversion_string_color
(
@in_string VARCHAR(200)
)
RETURNS NVARCHAR(500)
AS
BEGIN
DECLARE @fsetprefix BIT, -- append '0x' to the output
@pbinin VARBINARY(MAX), -- input binary stream
@startoffset INT, -- starting offset  
@cbytesin INT, -- length of input to consider, 0 means total length
@pstrout NVARCHAR(MAX),
@i INT,
@firstnibble INT ,
@secondnibble INT,
@tempint INT,
@hexstring CHAR(16)

SELECT @fsetprefix = 1,
@pbinin = SUBSTRING(HASHBYTES('SHA1', @in_string), 1, 3),
@startoffset = 1,
@cbytesin = 0

-- initialize and validate
IF (@pbinin IS NOT NULL)
BEGIN  
SELECT @i = 0,
@cbytesin = CASE  WHEN (@cbytesin > 0 AND @cbytesin <= DATALENGTH(@pbinin))
 THEN @cbytesin
 ELSE DATALENGTH(@pbinin)
 END,
@pstrout =  CASE  WHEN (@fsetprefix = 1)
 THEN N'0x'
 ELSE N''
 END,
@hexstring = '0123456789abcdef'
 
--the output limit for nvarchar(max) is 2147483648 (2^31) bytes, that is 1073741824 (2^30) unicode characters

IF (
((@cbytesin * 2) + 2 > 1073741824)
OR ((@cbytesin * 2) + 2 < 1)
OR (@cbytesin IS NULL )
)
RETURN NULL
 
IF (
( @startoffset > DATALENGTH(@pbinin) )
OR (@startoffset < 1 )
OR (@startoffset IS NULL )
)
RETURN NULL
 
-- adjust the length to process based on start offset and total length

IF ((DATALENGTH(@pbinin) - @startoffset + 1) < @cbytesin)
SELECT @cbytesin = DATALENGTH(@pbinin) - @startoffset + 1

-- do for each byte
WHILE (@i < @cbytesin)
BEGIN
-- Each byte has two nibbles  which we convert to character
SELECT @tempint = CAST(SUBSTRING(@pbinin, @i + @startoffset, 1) AS INT)
SELECT @firstnibble = @tempint / 16
SELECT @secondnibble = @tempint % 16
 
-- we need to do an explicit cast with substring for proper string conversion.  
SELECT @pstrout = @pstrout +
 CAST(SUBSTRING(@hexstring, (@firstnibble+1), 1) AS NVARCHAR) +
 CAST(SUBSTRING(@hexstring, (@secondnibble+1), 1) AS NVARCHAR)
SELECT @i = @i + 1
END
END
RETURN  '#' + UPPER(RIGHT(@pstrout, 6))
 END

Sunday 9 November 2014

Calculate Mean, Median, Mode Averages, StandardDeviation in C#

protected void Page_Load(object sender, EventArgs e)
{
List<double> doubleList = new List<double>();
doubleList.Add(10.00);
doubleList.Add(555.00);
double std = getStandardDeviation(doubleList);
double median = getMedian(doubleList);
double mean = getMean(doubleList);
IEnumerable<double> modes = getModes(doubleList);
}

private double getMedian(List<double> list)
{
List<double> orderedList = list
.OrderBy(numbers => numbers)
.ToList();

int listSize = orderedList.Count;
double result;

if (listSize % 2 == 0) // even
{
int midIndex = listSize / 2;
result = ((orderedList.ElementAt(midIndex - 1) +
  orderedList.ElementAt(midIndex)) / 2);
}
else // odd
{
double element = (double)listSize / 2;
element = Math.Round(element, MidpointRounding.AwayFromZero);

result = orderedList.ElementAt((int)(element - 1));
}

return result;
}
private double getMean(List<double> list)
{
return list.Average();
}
private IEnumerable<double> getModes(List<double> list)
{
var modesList = list
.GroupBy(values => values)
.Select(valueCluster =>
new
{
Value = valueCluster.Key,
Occurrence = valueCluster.Count(),
})
.ToList();

int maxOccurrence = modesList
.Max(g => g.Occurrence);

return modesList
.Where(x => x.Occurrence == maxOccurrence && maxOccurrence > 1)
.Select(x => x.Value);
}
private double getStandardDeviation(List<double> doubleList)
{
double M = 0.0;
double S = 0.0;
int k = 1;
foreach (double value in doubleList)
{
double tmpM = M;
M += (value - tmpM) / k;
S += (value - tmpM) * (value - M);
k++;
}
return Math.Sqrt(S / (k - 2));
}

Wednesday 12 February 2014

How to get each table space and row counts in SQL server

SELECT
SCHEMA_NAME(o.schema_id) + ',' + OBJECT_NAME(p.object_id) AS name,
reserved_page_count * 8 as space_used_kb,
row_count
FROM sys.dm_db_partition_stats AS p
JOIN sys.all_objects AS o ON p.object_id = o.object_id
WHERE o.is_ms_shipped = 0
ORDER BY SCHEMA_NAME(o.schema_id) + ',' + OBJECT_NAME(p.object_id) 

Monday 20 January 2014

Schedule a Job at specific Time using Global.asax

    void Application_Start(object sender, EventArgs e)
    {
        ScheduleTaskTrigger();
    }

    static void ScheduleTaskTrigger()
    {
        HttpRuntime.Cache.Add("ScheduledTaskTrigger",
                              string.Empty,
                              null,
                              Cache.NoAbsoluteExpiration,
                              TimeSpan.FromMinutes(60), // Every 1 hour
                              CacheItemPriority.NotRemovable,
                              new CacheItemRemovedCallback(PerformScheduledTasks));
    }
   
    static void PerformScheduledTasks(string key, Object value, CacheItemRemovedReason reason)
    {
        AutoMailService();
        ScheduleTaskTrigger();
    }
   
    static void AutoMailService()
    {
        //Your TODO
    }

Tuesday 7 January 2014

How to indentify request came from mobile device in ASP.NET

using System.Text.RegularExpressions;

  private bool isDevice()
    {
        string u = Request.ServerVariables["HTTP_USER_AGENT"];
        Regex b = new Regex(@"android.+mobile|android|mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);

        if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...