Munavvar Husein's Glory

Munavvar Husein's Glory This page is basically created for give the knowledge of C #.net and sql server.

31/01/2017

🕸🕸🕸🕸🕸🕸🕸
1. *PAN* - permanent account number.
2. *PDF* - portable document format.
3. *SIM* - Subscriber Identity Module.
4. *ATM* - Automated Teller machine.
5. *IFSC* - Indian Financial System Code.
6. *FSSAI(Fssai)* - Food Safety & Standards Authority of India.
7. *Wi-Fi* - Wireless fidelity.
8. *GOOGLE* - Global Organization Of Oriented Group Language Of Earth.
9. *YAHOO* - Yet Another Hierarchical Officious Oracle.
10. *WINDOW* - Wide Interactive Network Development for Office work Solution.
11. *COMPUTER* - Common Oriented Machine. Particularly United and used under Technical and Educational Research.
12. *VIRUS* - Vital Information Resources Under Siege.
13. *UMTS* - Universal Mobile Telecommunicati ons System.
14. *AMOLED* - Active-matrix organic light-emitting diode.
15. *OLED* - Organic light-emitting diode.
16. *IMEI* - International Mobile Equipment Identity.
17. *ESN* - Electronic Serial Number.
18. *UPS* - Uninterruptible power supply.
19. *HDMI* - High-Definition Multimedia Interface.
20. *VPN* - Virtual private network.
21. *APN* - Access Point Name.
22. *LED* - Light emitting diode.
23. *DLNA* - Digital Living Network Alliance.
24. *RAM* - Random access memory.
25. *ROM* - Read only memory.
26. *VGA* - Video Graphics Array.
27. *QVGA* - Quarter Video Graphics Array.
28. *WVGA* - Wide video graphics array.
29. *WXGA* - Widescreen Extended Graphics Array.
30. *USB* - Universal serial Bus.
31. *WLAN* - Wireless Local Area Network.
32. *PPI* - Pixels Per Inch.
33. *LCD* - Liquid Crystal Display.
34. *HSDPA* - High speed down-link packet access.
35. *HSUPA* - High-Speed Uplink Packet Access.
36. *HSPA* - High Speed Packet Access.
37. *GPRS* - General Packet Radio Service.
38. *EDGE* - Enhanced Data Rates for Globa Evolution.
39. *NFC* - Near field communication.
40. *OTG* - On-the-go.
41. *S-LCD* - Super Liquid Crystal Display.
42. *O.S* - Operating system.
43. *SNS* - Social network service.
44. *H.S* - HOTSPOT.
45. *P.O.I* - Point of interest.
46. *GPS* - Global Positioning System.
47. *DVD* - Digital Video Disk.
48. *DTP* - Desk top publishing.
49. *DNSE* - Digital natural sound engine.
50. *OVI* - Ohio Video Intranet.
51. *CDMA* - Code Division Multiple Access.
52. *WCDMA* - Wide-band Code Division Multiple Access.
53. *GSM* - Global System for Mobile Communications.
54. *DIVX* - Digital internet video access.
55. *APK* - Authenticated public key.
56. *J2ME* - Java 2 micro edition.
57. *SIS* - Installation source.
58. *DELL* - Digital electronic link library.
59. *ACER* - Acquisition Collaboration Experimentation Reflection.
60. *RSS* - Really simple syndication.
61. *TFT* - Thin film transistor.
62. *AMR*- Adaptive Multi-Rate.
63. *MPEG* - moving pictures experts group.
64. *IVRS* - Interactive Voice Response System.
65. *HP* - Hewlett Packard.

*Do we know actual full form of some words???*
66. *News paper =*
_North East West South past and present events report._
67. *Chess =*
_Chariot, Horse, Elephant, Soldiers._
68. *Cold =*
_Chronic Obstructive Lung Disease._
69. *Joke =*
_Joy of Kids Entertainment._
70. *Aim =*
_Ambition in Mind._
71. *Date =*
_Day and Time Evolution._
72. *Eat =*
_Energy and Taste._
73. *Tea =*
_Taste and Energy Admitted._
74. *Pen =*
_Power Enriched in Nib._
75. *Smile =*
_Sweet Memories in Lips Expression._
76. *etc. =*
_End of Thinking Capacity_
77. *OK =*
_Objection Killed_
78. *Or =*
_Orl Korec (Greek Word)_
79. *Bye =*♥
_Be with you Everytime._

*share these meanings as majority of us don't know*👌👌👌👌👌👌👌👌

27/10/2013

Full form of computer terms:
* HTTP - Hyper Text Transfer Protocol.
* HTTPS - Hyper Text Transfer Protocol
Secure.
* IP - Internet Protocol.
* URL - Uniform Resource Locator.
* USB - Universal Serial Bus.
* VIRUS - Vital Information Resource
Under Seized.
* 3G - 3rd Generation.
* GSM - Global System for Mobile
Communication.
* CDMA - Code Divison Multiple Access.
* UMTS - Universal Mobile
Telecommunication
System.
* SIM - Subscriber Identity Module.
* AVI = Audio Video Interleave
* RTS = Real Time Streaming
* SIS = Symbian OS Installer File
* AMR = Adaptive Multi-Rate Codec
* JAD = Java Application Descriptor
* JAR = Java Archive
* JAD = Java Application Descriptor
* 3GPP = 3rd Generation Partnership
Project
* 3GP = 3rd Generation Project
* MP3 = MPEG player lll
* MP4 = MPEG-4 video file
* AAC = Advanced Audio Coding
* GIF = Graphic InterchangeableFormat
* JPEG = Joint Photographic
ExpertGroup
* BMP = Bitmap
* SWF = Shock Wave Flash
* WMV = Windows Media Video
* WMA = Windows Media Audio
* WAV = Waveform Audio
* PNG = Portable Network Graphics
* DOC = Document (Microsoft
Corporation)
* PDF = Portable Document Format
* M3G = Mobile 3D Graphics
* M4A = MPEG-4 Audio File
* NTH = Nokia Theme (series 40)
* THM = Themes (Sony Ericsson)
* MMF = Synthetic Music Mobile
Application File
* NRT = Nokia Ringtone
* XMF = Extensible Music File
* WBMP = Wireless Bitmap Image
* DVX = DivX Video
* HTML = Hyper Text Markup Language
* WML = Wireless Markup Language
* CD - Compact Disk.
* DVD - Digital Versatile Disk.
* CRT - Cathode Ray Tube.
* DAT - Digital Audio Tape.
* DOS - Disk Operating System.
* GUI - Graphical User Interface.
* HTTP - Hyper Text Transfer Protocol.
* IP - Internet Protocol.
* ISP - Internet Service Provider.
* TCP - Transmission Control Protocol.
* UPS - UninterruptiblePower Supply.
* HSDPA - High Speed Downlink Packet
Access.
* EDGE - Enhanced Data Rate for GSM
[Global System for Mobile
Communication] Evolution.
* VHF - Very High Frequency.
* UHF - Ultra High Frequency.
* GPRS - General Packet Radio Service.
* WAP - Wireless Application Protocol.
* TCP - Transmission Control Protocol .
* ARPANET - Advanced Research
Project Agency Network.
* IBM - International Business
Machines.
* HP - Hewlett Packard.
* AM/FM - Amplitude/ Frequency
Modulation.
* WLAN - Wireless Local Area Network.

08/06/2012

//-------------------------------------------------------------------
//How to sync the system date time with internet date time
//-------------------------------------------------------------------
//Just copy and paste belowe code in any C # (.cs) file and just call the method named as "Synchronize()". Your code is working

using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;

namespace Automic_Clock_Sync
{
///
///
///
public class SyncTime : IDisposable
{
Data Members

private byte[] buffer = null;
private IPAddress timeServerIpAddress;
private bool printDiagnosticMessages;
private static char[] SeparatorArray = null;
private Thread clockThread = null;
private static CultureInfo englishUSACulture = null;



Constructor

///
///
///
public SyncTime()
: this(IPAddress.Parse("132.163.4.101"))
{
buffer = new byte[256];
printDiagnosticMessages = false;
SeparatorArray = new char[] { ' ' };
clockThread = new Thread(Synchronize);
englishUSACulture = new CultureInfo("en-US");
}

///
///
///
///
public SyncTime(IPAddress timeServerIpAddress)
{
this.timeServerIpAddress = timeServerIpAddress;
}



Public Strcuture
///
///
///
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
///
///
///
public short wYear;

///
///
///
public short wMonth;

///
///
///
public short wDayOfWeek;

///
///
///
public short wDay;

///
///
///
public short wHour;

///
///
///
public short wMinute;

///
///
///
public short wSecond;

///
///
///
public short wMilliseconds;
}


Public Methods

SetSystemTime
///
///
///
///
///
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime([In] ref SYSTEMTIME st); // http://msdn.microsoft.com/en-us/library/ms724942(VS.85).aspx


Synchronize
///
///
///
public void Synchronize()
{
try
{
clockThread.Start();

TimeSpan error = SynchronizeLocalClock();
}
catch (Exception ex)
{
throw ex;
}
}


Dispose
///
///
///
public void Dispose()
{
try
{
buffer = null;
clockThread = null;
}
catch (Exception ex)
{
throw ex;
}
}




Private Methods

QueryDaytimeString
///
///
///
///
///
private string QueryDaytimeString(out TimeSpan roundTripTime)
{
try
{
// Use RFC-867 protocol to query time from NIST time server...
int count = 0;
Stopwatch stopWatch = new Stopwatch();

while (true)
{
++count;

using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IPEndPoint hostEndPoint = new IPEndPoint(timeServerIpAddress, 13);

stopWatch.Reset();
stopWatch.Start();
socket.Connect(hostEndPoint);
int numberOfBytes = socket.Receive(buffer);
stopWatch.Stop();

if (numberOfBytes == 51)
{
roundTripTime = stopWatch.Elapsed;
string daytimeString = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, numberOfBytes).Trim();
return daytimeString;
}
else
{
if (printDiagnosticMessages)
{
Console.WriteLine("Attempt #{0}: byte count received = {1}", count, numberOfBytes);
}
}
}

Thread.Sleep(100);
}
}
catch (Exception ex)
{
throw ex;
}
}


ParseDaytimeProtocol
///
///
///
///
///
private static DateTime ParseDaytimeProtocol(string daytimeString)
{
DateTime now = DateTime.Now;

try
{
// 54708 08-08-30 18:53:02 50 0 0 770.8 UTC(NIST) *
// 0 1 2 3 4 5 6 7 8
// http://tf.nist.gov/service/its.htm
// See "Daytime Protocol (RFC-867)"

string[] resultTokens = daytimeString.Split(SeparatorArray, StringSplitOptions.RemoveEmptyEntries);
if (resultTokens[7] != "UTC(NIST)" || resultTokens[8] != "*")
{
throw new ApplicationException(string.Format("Invalid RFC-867 daytime protocol string: '{0}'", daytimeString));
}

int mjd = int.Parse(resultTokens[0]); // "JJJJ is the Modified Julian Date (MJD). The MJD has a starting point of midnight on November 17, 1858."
now = new DateTime(1858, 11, 17);
now = now.AddDays(mjd);

string[] timeTokens = resultTokens[2].Split(':');
int hours = int.Parse(timeTokens[0]);
int minutes = int.Parse(timeTokens[1]);
int seconds = int.Parse(timeTokens[2]);
double millis = double.Parse(resultTokens[6], englishUSACulture); // this is speculative: official documentation seems out of date!

now = now.AddHours(hours);
now = now.AddMinutes(minutes);
now = now.AddSeconds(seconds);
now = now.AddMilliseconds(-millis);
}
catch (Exception ex)
{
throw ex;
}

return now;
}


MeasureSystemClockError
///
///
///
///
private TimeSpan MeasureSystemClockError()
{
try
{
TimeSpan roundTrip;
string daytimeString = QueryDaytimeString(out roundTrip);
double halfTripMilliseconds = roundTrip.TotalMilliseconds / 2.0;
TimeSpan halfTrip = new TimeSpan(0, 0, 0, 0, (int)halfTripMilliseconds);

DateTime nist = ParseDaytimeProtocol(daytimeString) + halfTrip;
DateTime here = DateTime.Now.ToUniversalTime();
TimeSpan diff = (nist - here);

return diff;
}
catch (Exception ex)
{
throw ex;
}
}


SynchronizeLocalClock
///
///
///
///
private TimeSpan SynchronizeLocalClock()
{
try
{
TimeSpan diff = MeasureSystemClockError();
DateTime corrected = DateTime.Now + diff;
SetTimeLocal(corrected);
return diff;
}
catch (Exception ex)
{
throw ex;
}
}


SetTimeLocal
///
///
///
///
private static void SetTimeLocal(DateTime local)
{
try
{
SetTimeUtc(local.ToUniversalTime());
}
catch (Exception ex)
{
throw ex;
}
}


SetTimeUtc
///
///
///
///
private static void SetTimeUtc(DateTime utc)
{
try
{
SYSTEMTIME st = new SYSTEMTIME(); // http://msdn.microsoft.com/en-us/library/ms724950(VS.85).aspx
st.wYear = (short)utc.Year;
st.wMonth = (short)utc.Month;
st.wDayOfWeek = 0; // Microsoft documentation (see URL above) says: "The wDayOfWeek member of the SYSTEMTIME structure is ignored."
st.wDay = (short)utc.Day;
st.wHour = (short)utc.Hour;
st.wMinute = (short)utc.Minute;
st.wSecond = (short)utc.Second;
st.wMilliseconds = (short)utc.Millisecond;

//if (!SetSystemTime(ref st))
//{
// throw new ApplicationException("Error setting time.");
//}
}
catch (Exception ex)
{
throw ex;
}
}



}
}

19/05/2012

SQL Server # TSQL to Rename Database Name along with its Logical and Physical Name

There are many ways to rename the SQL server Database name. Today, I will explain how to rename a Database in SQL Server using T-SQL along with its Logical and Physical Name.

The very easiest and most popular way of renaming is – Suppose, you have a database named as “TestDB”. Now you want to rename it with “NewTestDB”.

--Rename the data base "TestDB to New_TestDB".
EXEC sp_renameDB 'TestDB','New_TestDB'
GO

Above given example just renames the Database title (name); However if you want to rename the physical file, just Detach the database, Go to the file path which is currently located, rename both the LDF and MDF file, and now here Attach the database.

Below steps are given for renaming the database by using the TSQL statement – Just open SSMS Copy the below scripts and press F5.

USE TestDB
GO

è First of all set the database for a single user, it will disconnect all the currently connected users.
ALTER DATABASE TestDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

è Now rename the Database title (Name).
EXEC master..sp_renamedb 'TestDB','NewTestDB'
GO

è Now the change the Logical file name, because above statement just change the name of the Database.
ALTER DATABASE NewTestDB MODIFY FILE (NAME=N'TestDB', NEWNAME=N'NewTestDB')
GO

ALTER DATABASE NewTestDB MODIFY FILE (NAME=N'TestDB_log', NEWNAME=N'NewTestDB_log')
GO

è Now Detach the Database for change the Physical file name, as we can't do anything with the physical file when the database is in active mode.
EXEC master.dbo.sp_detach_db = N'NewTestDB'
GO

è Now Change the SSMS settings if you haven’t set it.
è This is necessary because the below provided command will not run without set this.
sp_configure 'show advanced options'
GO

/* 0 = Disabled , 1 = Enabled */
sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE WITH OVERRIDE
GO

è Now rename your physical files with the use of command.
EXEC xp_cmdshell 'RENAME "F:\CD\Temporary Work\TestDB.mdf", "NewTestDB.mdf"'
GO

EXEC xp_cmdshell 'RENAME "F:\CD\Temporary Work\TestDB_log.ldf", "NewTestDB_log.ldf"'
GO

è Now just attach the database. (Currently detached by us).
CREATE DATABASE NewTestDB ON
( FILENAME = N'F:\CD\Temporary Work\NewTestDB.mdf' ),
( FILENAME = N'F:\CD\Temporary Work\NewTestDB_log.ldf' )
FOR ATTACH
GO

è Now set the database as multi users can work on this.
ALTER DATABASE NewTestDB SET MULTI_USER
GO

è Finally you can see that, the physical files are renamed.
SELECT
name AS [Logical Name],
physical_name AS [DB File Path],
type_desc AS [File Type],
state_desc AS [State]
FROM
sys.master_files
WHERE
database_id = DB_ID(N'NewTestDB')
GO

Conclusion
Hence, we have learnt how we can rename the SQL Server Database along with its Logical & Physical using some simple TSQL statements.

25/03/2012

Accessibility in C #
-----------------------------------------------
Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the following table.

Accessibility - Meaning
public - Access not limited
protected - Access limited to this class or classes derived from this class
internal - Access limited to this program
protected internal - Access limited to this program or classes derived from this class
private - Access limited to this class

23/12/2011

Clipboard Ring and Toolbox Snippets

Introduction

Today I show you my favorite feature in visual studio which is Clipboard Ring and Toolbox Snippets.

Implementation

1. Clipboard Ring

Many times I wish I could go back to something I copied & pasted just a few minutes ago, then to have to go and copy the same text all over again.Turns out that Visual Studio already has this “hidden”feature. It’s called the Clipboard Ring.

If you copy a number of items to the clipboard, pressing [Ctrl] + [Shift] + [V] will paste the last text that was copied, but it will also highlight the pasted phrase.

Continue holding down [Ctrl] + [Shift] and press [V] again. This will cause that highlighted section to cycle through the other items on the clipboard. This is extremely useful when you have to copy multiple lines of separate text to a new document.

You can also use [Ctrl] + [Shift] + [Insert]keys instead of [Ctrl] + [Shift] + [V]

2. Toolbox Snippets

Now, you might be saying, “Great, but what if I want to save a piece of code that I use frequently in multiple places? It means samepiecesof code change in multiple files. I don’t want to have to cycle through the clipboard ring every time.” Well, there’s also a feature for that!

If you highlight a section of code (or text) and drag it to the Toolbox, VS will create a "snippet” (not to be confused with code snippets). When u want back that code then youdragged into the VS editor or double click on that snippet it will paste in VS editor.

And last but not leastthese snippets also available in next day.

23/12/2011

SHRINKFILE and TRUNCATE Log File in SQL Server 2008

Introduction

You know there is always an issue - the log file growing very fast and big. If you have plenty of storage, then this might not be a problem for you. Anyway, this is no exception in the latest version of SQL, we still have to do something to truncate and shrink these files.

Implementation

1) Let’s first check the log file size.

SELECT
--DB_NAME(database_id) AS DatabaseName,
--Physical_Name,
Name AS Logical_Name,
(size*8)/1024 SizeMB
FROM
sys.master_files
WHERE
DB_NAME(database_id) = 'tempdb'
GO

Output

Logical_Name SizeMB
tempdb 60
tempdb_log 313


2) Now truncate the log file.

USE tempdb;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE tempdb
SET RECOVERY SIMPLE WITH NO_WAIT;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE(tempdb_log, 1); --file_name is the logical name of the file to be shrink
GO
-- Reset the database recovery model.
ALTER DATABASE tempdb
SET RECOVERY FULL WITH NO_WAIT;
GO

3) Let’s check the log file size.

SELECT
--DB_NAME(database_id) AS DatabaseName,
--Physical_Name,
Name AS Logical_Name,
(size*8)/1024 SizeMB
FROM
sys.master_files
WHERE
DB_NAME(database_id) = 'tempdb'
GO

Output

Logical_Name SizeMB
tempdb 60
tempdb_log 313

Consider the following information when you plan to shrink a file:

Make a full backup of your database before shrink the database file.
From setting the database to simple recovery, shrinking the file and once again setting in full recovery, you are in fact losing your valuable log data and will be not able to restore point in time. Not only that, you will also not able to use subsequent log files.
A shrink operation is most effective after an operation that creates lots of unused space, such as a truncate table or a drop table operation.
Most databases require some free space to be available for regular day-to-day operations. If you shrink a database repeatedly and notice that the database size grows again, this indicates that the space that was shrunk is required for regular operations. In these cases, repeatedly shrinking the database is a wasted operation. In this case, you should consider increasing the Growth Rate of your Database to keep the performance under control.
A shrink operation does not preserve the fragmentation state of indexes in the database, and generally increases fragmentation to a degree. This is another reason not to repeatedly shrink the database.

23/12/2011

Get numeric value from string using TSQL
Introduction
Many times while working on applications, we often land into a situation where we want to get the only numeric values from alpha numeric string. There are some approaches given, like you may achieve it with making a loop and without loop.

Approaches
I have prescribed as a simple query, but you will achieve same by making a function.

1. Get the numbers through loop.
DECLARE VARCHAR(MAX) = 'ABC1DEF2GHI3'
DECLARE INT
SET = PATINDEX('%[^0-9]%', )
WHILE > 0
BEGIN
SET = STUFF(, , 1, '' )
SET = PATINDEX('%[^0-9]%', )
END
SELECT ISNULL(,0) 'Numeric Values'
OUTPUT

Numeric Values
123

2. Get the numbers without loop.

DECLARE VARCHAR(MAX) = 'ABC1DEF2GHI3'
DECLARE VARCHAR(MAX) = ''
SELECT
=
+
CASE WHEN NumericValue like '[0-9]' THEN NumericValue ELSE '' END FROM
(
SELECT
SUBSTRING(,NumericValue,1) NumericValue
FROM
(
SELECT
number NumericValue
FROM
master..spt_values
WHERE
TYPE = 'p'
AND number BETWEEN 1 AND LEN()
) T
) T
SELECT ISNULL(,0) 'Numeric Values'
OUTPUT

Numeric Values
123

Limitation
There is a limitation in 2nd approach, the table “master..spt_values” contains only 2048 rows value. So if you want to get the numbers from the very big text contains above 2048 characters, then this approach is not suitable.
To over come this limitation, you can use “Tally Table” instead of “master..spt_values”. Replace “master..spt_values” with “Tally Table”.
Want to get more information about Tally Table? Click here.

Conclusion
If you have the need of numeric values only from less characters of 2048, then no need to process for “Tally Table”. Just use the “master..spt_values”.

23/12/2011

New Date and Time Functions in SQL Server 2008

Introduction

SQL Server 2008 introduces five new date and time functions namely SYSDATETIME, SYSDATETIMEOFFSET, SYSUTCDATETIME, SWITCHOFFSET and TODATETIMEOFFSET.

In this article described new functions in detail.

1) SYSDATETIME

The SYSDATETIME function basically returns the current system timestamp without the time zone information.

SELECT SYSDATETIME()
GO

SYSDATETIME
------------------------
2011-06-27 16:06:15.9409129

2) SYSDATETIMEOFFSET

The SYSDATETIMEOFFSET function is much similar to SYSDATETIME function; however it will also get you the time zone information.

SELECT SYSDATETIMEOFFSET()
GO

SYSDATETIMEOFFSET
-------------------------------
2011-06-27 16:07:01.8205935 +05:30

3) SYSUTCDATETIME

The SYSUTCDATETIME function returns the Greenwich Mean Time (GMT) or the Coordinated Universal Time (UTC). This time is derived from the current local system time and the time zone settings of the server where SQL Server 2008 is running.

SELECT SYSUTCDATETIME()
GO

SYSUTCDATETIME
------------------------
2011-06-27 10:38:25.6239407

4) SWITCHOFFSET

The SWITCHOFFSET function returns a DATETIMEOFFSET value that is changed from the stored time zone offset to a specified new time zone offset.

SELECT SYSDATETIMEOFFSET(),
SWITCHOFFSET (SYSDATETIMEOFFSET(), '+00:00')
GO

SYSDATETIMEOFFSET SWITCHOFFSET
------------------------------- -------------------------------------
2011-06-27 16:30:55.7127120 +05:30 2011-06-27 11:00:55.7127120 +00:00

5) TODATETIMEOFFSET

The TODATETIMEOFFSET function returns a DATETIMEOFFSET value that is translated from a DATETIME2 expression.

SELECT TODATETIMEOFFSET (GETDATE(),'+05:30')
GO

TODATETIMEOFFSET
---------------------------------
2011-06-27 16:26:56.340 +05:30

23/12/2011

Truncate decimals instead of Rounding from a double value In C #

Introduction
Many times while working on applications, we often land into a situation where we want to truncate the decimal places from a number instead of round like suppose we have 5.329 and I want to truncate the third digit then my required output will be 5.32. Here, I will walk through the different ways which I know in which we can achieve the same.

Approaches
I have created the approaches as making the C # method.

1. Truncate the decimals through the string operations.
Below method only usable if you want to truncate the decimal places to two.

Round
///
/// Truncate the last digit after two digit floating points.
///
/// A double-precision floating-point number to be rounded.
/// Double value contains two digit floating points.
public static double Round (double value)
{
double returnValue = 0;

try
{
//Convert the value into the string for round.
string input = Convert.ToString(value);

//Check if the input contains decimal places
if (input.Contains("."))
{
//Check if there are 3 or more digits after the decimal point.
if (input.Length - input.IndexOf(".", StringComparison.Ordinal) >= 4)
{
//Replace the input value with the required value.
//Added 3 to get only 2 digits after the decimal point.
input = input.Substring(0, input.IndexOf(".", StringComparison.Ordinal) + 3);
}
}
//Converts the string representation of a number to its System.Double equivalent.
returnValue = Convert.ToDouble(input);
}
catch { } //Suppress exception no need to handle.

return returnValue;
}


2. Truncate the decimals through the mathematical operations.
Through this method you can truncate any number of decimal places.

Round
///
/// Rounds a decimal value to a specified number of fractional digits.
///
/// A decimal number to be rounded.
/// The number of decimal places in the return value.
/// The number nearest to value that contains a number of fractional digits equal to decimals.
public static double Round(double value, byte decimals)
{
double returnValue = 0;

try
{
if (value != 0)
{
//Gets the power of 10 base on passed decimal parameter value (10^decimals).
double powValue = Math.Pow(10, decimals);

//Gets the truncated value.
returnValue = Math.Truncate(CDCommon.ToDouble(value * powValue)) / powValue;
}
}
catch
{ throw; }

return returnValue;
}


Conclusion
From both the ways, as per my opinion prefer the second approach in implementation because it’s very light compared to the first in terms of calculations.

23/12/2011

New DATETIME Data Types in SQL Server 2008
Introduction

From the beginning, Microsoft SQL Server DBAs have longed for two different data types, where you could store time and date separately. The long wait is over. In all of the older versions, we had only one data type that could store Datetime data type, and it stored both the value of the date and the value of the time.
Finally, in Microsoft SQL Server 2008, Microsoft is introducing a set of new data types for storing date, time and both date and time together. The new data types store more data as well, which means you can store dates anywhere from 01-01-01 to 9999-12-31 and also store time up to the fraction of 9999999.
There are four DATETIME data types newly introduced in SQL Server 2008. They are
DATE, TIME, DATETIMEOFFSET and DATETIME2.

1) DATE Data Type

The DATE data type stores only the date value.
The DATE data type returns data in the form of year, Month and Day. However, the format in which the date is returned is determined by the current language setting in SQL Server.
The range for the DATE data type is from 0001-01-01 through 9999-12-31.

When you specify a datetime value, SQL Server automatically converts that value into the DATE data type, which means that only the date portion is stored.

Example:

DECLARE DATE
SET = '2011-05-17 05:29:15.1234567'

SELECT

Result:
2011-05-17

2) TIME Data type

The TIME data type stores only the time value.
The TIME data type returns data in the form of hour, minute, second and fractional second.

The fractional part of the seconds can support up to 7 decimal places.
The precision of the TIME data type supports a range of 00:00:00.0000000 through 23:59:59.9999999.

When you specify the TIME datatype in a Transact-SQL statement, you can specify the precision of the stored values by including the appropriate number within parentheses.

For example, to specify a precision of 7, you would specify TIME(7).
For a precision of 5, you would specify TIME(5), and so on.

If you do not specify the precision, 7 are assumed.

Example:

DECLARE TIME
SET = '2011-05-17 05:29:15.1234567'

SELECT

Result:
05:29:15.1234567

You can also specify a different precision when converting the data

DECLARE TIME
DECLARE TIME

SET = '2011-05-17 05:29:15.1234567'
SET = CAST( AS TIME(5))

SELECT

Result:
05:29:15.1234600

Notice that the fractional seconds have been rounded up.
The original fractional seconds were .1234567. However, if you specify a precision of 5, SQL Server will round up the "67" fractional part, returning .1234600 in the results, rather than .1234500.

When inserting data into a TIME column, you can specify a time value or a datetime value as shown in the following INSERT statements:

INSERT INTO TableName (ID, Time_DataType)
VALUES ('1004, 05:23:10.1234567'); --Only Time
INSERT INTO TableName (ID, Time_DataType)
VALUES (1005, '2011-05-17 05:23:10.1234567'); --Date & Time

In both cases, only the time is inserted into the Time_DataType column.

3) DATETIME2 Data Type

The DATETIME2 data type stores the both date and time value.
The data type DATETIME2 is the combination of the data type DATE and TIME.
DATETIME2 is used to store both a date value ranging from 01-01-01 to 9999-12-31 as well as a time value 00:00:00.0000000 to 23:59:59.9999999.

Example:

DECLARE DATETIME2
SET = CONVERT(DATETIME2,'01/01/0001 16:14:00.1234567')

SELECT

Result:
0001-01-01 16:14:00.1234567

We could limit the precision like (Precision value range 0-7),
DECLARE DATETIME2(4)
SET = CONVERT(DATETIME2,'01/01/0001 16:14:00.1234567')

SELECT

Result:
0001-01-01 16:14:00.1235

Notice that the fractional seconds have been rounded up.

4) DATETIMEOFFSET Data type

The DATETIMEOFFSET data type stores the date, time and time-zone offset value.
The DATETIMEOFFSET data type is nearly identical to the DATETIME2 data type, except that a DATETIMEOFFSET value includes one important addition that is a time-zone offset value.
The offset value represents the number of hours and minutes before or after Coordinated Universal Time (UTC).
A positive number indicates the amount of time to add to the UTC to determine the local time. (+05:30).
A negative number indicates the amount of time to subtract from the UTC to determine the local time. (-05:30)

The Date range is between 0001-01-01 and 9999-12-31.
The Time Range is between 00:00:00 and 23:59:59.9999999.
The Offset range is between -14:00 through +14:00.

Example:

DECLARE DATETIMEOFFSET
SET = CONVERT(DATETIMEOFFSET,'01/01/0001 16:14:00.1234567 +5:30')

SELECT

Result:
0001-01-01 16:14:00.1234567 +05:30

You can also set the precision of the data type, like

DECLARE DATETIMEOFFSET(4)
SET = CONVERT(DATETIMEOFFSET,'01/01/0001 16:14:00.1234567 +5:30')

SELECT

Result:
0001-01-01 16:14:00.1235 +05:30

Address

Surat

Alerts

Be the first to know and let us send you an email when Munavvar Husein's Glory posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Share