Search This Blog

Friday, August 31, 2012

Height div to window height with scroll

Java > Height div to window height with scroll

<script type="text/javascript" language="javascript">

    window.onload = function () { SizeDiv(); }

    function getDocHeight() {

        var D = document;

        return Math.max(

        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),

        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),

        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );

    }

    function SizeDiv() {
        
        document.getElementById('leftCol').style.height = getDocHeight()-175 + "px";
     
    }

</script>







Wednesday, August 22, 2012

SqlCommand, SqlParameter c#

C# > Data SqlCommand SqlParameter 


SqlCommand
Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database.

SqlParameter 
Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns

Example:

SqlCommand myCommand = new SqlCommand("dbo.[sp_copy]", connString);
myCommand.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter("@ret_id", SqlDbType.Int);
param.Direction = ParameterDirection.ReturnValue;
myCommand.Parameters.Add(param);

param = new SqlParameter("@Source", SqlDbType.Int);
param.Direction = ParameterDirection.Input;
param.Value = asset_id;
myCommand.Parameters.Add(param);

myCommand.ExecuteNonQuery();

id = Convert.ToInt32(myCommand.Parameters[0].Value);







Generate Method Stub

Visual Studio

Generate Method Stub is an IntelliSense Automatic Code Generation feature that provides an easy way to have Visual Studio create a new method declaration at the time you are writing a method call. Visual Studio infers the declaration from the call.








Saturday, August 18, 2012

SET NOCOUNT SQL Server

SQL Server > Transact-SQL > SET NOCOUNT           

Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results.
SET NOCOUNT { ON | OFF }
Remarks

  • ON the count is not returned
  • OFF the count is returned





Trunc Date Only No Time SQL Server

SQL Server > Built-in Functions CAST > Trunc

Trunc date in SQL Server


SELECT Cast(GetDate() AS date)

Results:2012-08-18







Convert .NET DateTime.Ticks to SQL datetime

SQL Server > Convert .NET DateTime.Ticks to SQL datetime

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.





C#

var t = DateTime.Now.ToUniversalTime().Ticks; // ToUniversalTime : Converts the value of the current DateTime object to Coordinated Universal Time (UTC).

SQL Server Function to convert


create function TicksToDateTime
(@Ticks bigint)
RETURNS datetime AS
BEGIN
        -- First, we will convert the ticks into a datetime value with UTC time
         DECLARE @BaseDate datetime;
         SET @BaseDate = '01/01/1900';
         DECLARE @NetFxTicksFromBaseDate bigint;
         SET @NetFxTicksFromBaseDate = @Ticks - 599266080000000000;
-- The numeric constant is the number of .Net Ticks between the System.DateTime.MinValue (01/01/0001) and the SQL Server datetime base date (01/01/1900)
         DECLARE @DaysFromBaseDate int;
         SET @DaysFromBaseDate = @NetFxTicksFromBaseDate / 864000000000; -- The numeric constant is the number of .Net Ticks in a single day.
         DECLARE @TimeOfDayInTicks bigint;
         SET @TimeOfDayInTicks = @NetFxTicksFromBaseDate - @DaysFromBaseDate * 864000000000;
        DECLARE @TimeOfDayInMilliseconds int;
        SET @TimeOfDayInMilliseconds = @TimeOfDayInTicks / 10000; -- A Tick equals to 100 nanoseconds which is 0.0001 milliseconds
        DECLARE @UtcDate datetime;
        SET @UtcDate = DATEADD(ms, @TimeOfDayInMilliseconds, DATEADD(d,@DaysFromBaseDate, @BaseDate)); -- The @UtcDate is already useful. If you need the time in UTC, just return this value.
      -- Now, some magic to get the local time
         RETURN @UtcDate + GETDATE() - GETUTCDATE();
END
GO
select dbo.TicksToDateTime(634808765429446556)

result:

2012-08-18 11:49:02.947




msdb.dbo.sp_send_dbmail SQL Server sp_send_dbmail

SQL Server > System Stored Procedures > sp_send_dbmail

Using sp_send_dbmail you can send an e-mail message to the specified recipients.
This stored procedure is in placed the msdb database.

Syntax and parameters:

sp_send_dbmail @profile_name , @recipients , @copy_recipients, @blind_copy_recipients ,  @from_address, @reply_to, @subject, @body, @body_format, @importance, @file_attachments
 
Example send email with file attached:
 
declare @_recipients nvarchar(max)=''
declare @_ord_id nvarchar(255)
declare @_subject nvarchar(max)
declare @_body nvarchar(max)

set @_subject = 'Order with id=11 was delivered.'; set @_body = 'Order with id=11 was delivered.' + CHAR(13) +CHAR(13) + 'PLEASE DON''T REPLY TO THIS EMAIL!';
set @_recipients = 'to@domain.com'

exec msdb.dbo.sp_send_dbmail @profile_name = 'smtp profile name',
@recipients = @_recipients, @from_address = 'order@domain.com', @subject = @_subject, @body = @_body, @body_format = 'TEXT', @file_attachments ='C:\File.txt';




Where to find the definition?
 
USE msdb;
GO sp_helptext 'dbo.sp_send_dbmail';
SELECT
   definition FROM    sys.sql_modules WHERE    object_id = OBJECT_ID('dbo.sp_send_dbmail');

Database Mail Configuration Wizard

To start the Database Mail Configuration Wizard, in Object Explorer, expand Management, right-click Database Mail, and then click Configure Database Mail.





Monday, August 13, 2012

Error message after you install the .NET Framework 4.0: "Could not load type 'System.ServiceModel.Activation.HttpModule'"

ASP.NET > HttpModule

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.



To resolve this issue, run the following command line:


aspnet_regiis.exe /iru

The Aspnet_regiis.exe file can be found in one of the following locations:

%windir%\Microsoft.NET\Framework\v4.0.30319

%windir%\Microsoft.NET\Framework64\v4.0.30319 (on a 64-bit computer)







Get Current Url ASP.NET (VB.NET)

ASP.NET > Get Current Url

The ServerVariables collection is used to retrieve the server variable values.

SERVER_NAME: Returns the server's host name, DNS alias, or IP address
SERVER_PORT: Returns the port number to which the request was sent
SCRIPT_NAME: Returns a virtual path to the script being executed

Example: Get Current Url with parameters

Public Shared Function GetCurrentUrl()
' currentUrl
 Dim currentUrl = "http://" &HttpContext.Current.Request.ServerVariables  ("SERVER_NAME").ToString()

 If HttpContext.Current.Request.ServerVariables("SERVER_PORT").ToString() <> "" Then
    currentUrl = currentUrl + ":" + HttpContext.Current.Request.ServerVariables("SERVER_PORT").ToString()
  End If
  currentUrl = currentUrl + HttpContext.Current.Request.ServerVariables ("SCRIPT_NAME").ToString()
 If HttpContext.Current.Request.QueryString.ToString() <> "" Then
   currentUrl += "?" + HttpContext.Current.Request.QueryString.ToString()
 End If
 Return currentUrl
End Function




Friday, August 10, 2012

SqlCommand CommandTimeout Property

C# > Data > SqlCommand > CommandTimeout

The time in seconds to wait (timeout) for the command to execute. The default is 30 seconds.

A value of 0 indicates no limit and will wait indefinitely until command is executed.

Example:

SqlConnection con = new SqlConnection("connString");
SqlCommand com = new SqlCommand("exec your_stored_procedure", con);
com.CommandTimeout = 60;






Thursday, August 9, 2012

Convert number to datetime SQL Server

SQL Server > Built-in Functions > CAST Numbers to Date

Sometimes we need to convert numbers (year, month, day) to date like DateSerial.

In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD format - this will work on any SQL Server system with any language and regional setting in effect.

Example:

declare @year int
declare @month int
declare @day int

set @year = 2012
set @month = 9
set @day = 30

SELECT
CAST(
CAST(@year AS VARCHAR(4)) +
RIGHT('0' + CAST(@month AS VARCHAR(2)), 2) +
RIGHT('0' + CAST(@day AS VARCHAR(2)), 2)
AS DATETIME)

Result:
2012-09-30 00:00:00.000





Tuesday, August 7, 2012

DBCC SHRINKDATABASE (Transact-SQL)


Shrinks the size of the data and log files in the specified database.


DBCC SHRINKDATABASE
( database_name | database_id | 0
[ , target_percent ]
[ , { NOTRUNCATE | TRUNCATEONLY } ]
)
[ WITH NO_INFOMSGS ]




Arguments

database_name | database_id | 0

Is the name or ID of the database to be shrunk. If 0 is specified, the current database is used.

target_percent

Is the percentage of free space that you want left in the database file after the database has been shrunk.

NOTRUNCATE

Compacts the data in data files by moving allocated pages from the end of a file to unallocated pages in the front of the file. target_percent is optional.

The free space at the end of the file is not returned to the operating system, and the physical size of the file does not change. Therefore, when NOTRUNCATE is specified, the database appears not to shrink.

NOTRUNCATE is applicable only to data files. The log files are not affected.

TRUNCATEONLY

Releases all free space at the end of the file to the operating system but does not perform any page movement inside the file. The data file is shrunk only to the last allocated extent. target_percent is ignored if specified with TRUNCATEONLY.

TRUNCATEONLY is applicable only to data files. The log files are not affected.

WITH NO_INFOMSGS
Suppresses all informational messages that have severity levels from 0 through 10.



Thursday, August 2, 2012

IIS Error: This configuration section cannot be used at this path.


IIS Error: This configuration section cannot be used at this path.
This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=”Deny”), or set explicitly by a location tag with overrideMode=”Deny” or the legacy allowOverride=”false”.
Note: When you meet this error you must consider where IIS locates your error. For example, in the image above the error relates to handlers tag. I have this error twice when publish WCF Services, one with handlers and one with modules.

Solution:
- Navigate to C:\Windows\System32\inetsrv\config
- Right click on file applicationHost.config and open it with Notepad
- Search and find the tag which IIS has error with it and edit overrideModeDefault = “Allow”. Remember to save file before close it

Wednesday, August 1, 2012

Mouse Cursor C#

C# > Cursors

Cursors provides a collection of Cursor objects for use by a Windows Forms application.
 
Example: 1. Wait cursor
public Form1()
{
    InitializeComponent();             

    this.Cursor = Cursors.WaitCursor; // Wait cursor, an hourglass shape.
     // do something
    this.Cursor = Cursors.Default; //default cursor, usually an arrow cursor.
}

 












While (c#)

C# > Statements > while

While statement executes a statement or a block of statements until a specified expression evaluates to false.
A while loop can be terminated with
  • break
  • goto
  • return
  • throw
Pass control to the next iteration with the continue statement.
   
Example:

int i = 0;
while (i < 10)
{
     if (i == 1)
   {
         i = 2;
     continue; // goto to next loop
   }
   if (i == 2)
     return; // exit while
   if (i==5)
     break; // exit while
  
   i= i + 1;
}

 







MS Excel: Concatenate strings

Excel > Operators> Concatenate

To concatenate multiple strings into a single string in Excel, you can use the "&" operator to separate the string values.
string_1 & string_2 & string_n