Monday, October 2, 2017

Create a copy of database and renaming it using mdf & ldf files

If You want to use the same directory for your mdf\ldf files You will have to (physically) rename them.
1. Detach files from local PC
2. Rename mdf and ldf files
3. Copy\Move the files to the server directory where the original Database is stored.
(In My example I used D:\Data for mdf and E:\Logs for ldf, change the path before running the script)
4. Use this code:

USE [master]
GO
CREATE DATABASE [myNewSite_db] ON 
( FILENAME = N'D:\Data\myNewSite_db.mdf' ),
( FILENAME = N'E:\Logs\myNewSite_db_log.ldf' )
FOR ATTACH
GO

Sunday, October 1, 2017

Difference Between String and StringBuilder


String are Immutable (Not Modifiable). If you try to modify the string it actually creates a new string and the old string will be then ready for garbage collection.StringBuilder when instantiated, creates a new string with predefined capacity and upto that capacity it can accodomate string without needing to create a new memory location for the string....i mean it is modifiable and can also grow as and when needed.

When the string needs to be modified frequently, preferably use StringBuilder as its optimized for such situations.

Tuesday, September 22, 2015

Stored procedure slow when called from web, fast from Management Studio

Some time this problem occurs due to compiled query plan became corrupt, or invalid.

Stored procedure slow when called from web, fast from Management Studio becuase Basically connections through Sql Server Management Studio (SSMS) by default have SET ARITHABORT ON. ADO.NET connections do not.

The main difference when running with or without this setting, a different query plan is created for the both stored procedure calls. In case of ARITHABORT was OFF, the SSMS command would use the pre-compiled cached query plan that the ADO.NET connection was using (compiled query plan became corrupt, or invalid.), and therefore timeout.

Use following Command to refresh the query Plans.

DBCC DROPCLEANBUFFERS

DBCC FREEPROCCACHE

Query parameterization promotes the reuse of cached execution plans, thereby avoiding unnecessary compilations, and reducing the number of ad-hoc queries in the plan cache. This is called Parameter Snifting.

Sql-server using Parameter Snifting (Default Enabled).

You can change the Behaviour of Parameter snifting, is you have knowledge of Parameter snifting.

Monday, July 13, 2015

C#, Read a file

C#, Code to read a file 

String strHtmlMessage = String.Empty;
String strFilePath = HttpContext.Current.Server.MapPath("~/Mails/Confirmationmaill.htm");
  using (StreamReader sr = new StreamReader(strFilePath))
  {
    strHtmlMessage = sr.ReadToEnd();
 }

Wednesday, June 17, 2015

Time on my EC2 windows instance changed automatically

Configure Windows time sync:

First ensure that you can get time from a NTP server, otherwise the instructions below are not going to work.
To test, get the current variance from an NTP server using the following Windows Time service command
w32tm /stripchart /samples:5 /computer:pool.ntp.org /dataonly

In a VPC we had to open UDP port 123 for inbound connections in the NAT security group.

To configure NTP time sync in Windows

1. Registry edit - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\W32Time\TimeProviders\NtpClient
Set SpecialPollInterval to polling interval in seconds (we set ours to 60).
2. Registry edit - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\W32Time\Parameters
Set Type to NTP
3. Run the following commands to configure the time servers (can use other servers, we're using 4 time servers - 0.pool.ntp.org, time.nist.gov, 1.pool.ntp.org, and 2.pool.ntp.org)

net stop w32time

w32tm /config /syncfromflags:manual /manualpeerlist:"0.pool.ntp.org,0x1 time.nist.gov,0x1 1.pool.ntp.org,0x1 2.pool.ntp.org,0x1"

net start w32time

To review the config
w32tm /query /configuration

To check the sync against a time server
w32tm /stripchart /samples:5 /computer:pool.ntp.org /dataonly

Saturday, November 29, 2014

How to increase Session Timeout?


We can set our custom session timeout in our applications by following Methods


1.    In Web.config file we can set session timeout like as shown below 

<configuration>
<system.web>
 <sessionState mode="InProc" timeout="120">
 </sessionState>
 </system.web>
</configuration>

Note that if you are using Forms authentication, the Forms timeout setting will log the user out after the set timeout period so you will also have to adjust this attribute:
<authentication mode="Forms" >
 <forms  timeout="120">
 </authentication>

2.    In  Global.asax file we can set session timeout in Session_Start event like this

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session.Timeout = 120;
}

3.    In IIS setting you can also set default session timeout.

1.    Open IIS start-->run type-->inetmgr and press enter.
2.    Click on "Web Site" and click “Session State in right Pane.


3.    Once open Session State set timeout in under cookie settings section like as shown below


Set idle timeout:
1.    Open IIS start-->run type-->inetmgr and press enter.
2.    Click on "Application Pool" and select “Advance Settings”
3.    Increase the idle timeout according to screenshot.

Saturday, May 24, 2014

Get size of all tables in database

Determining space used for each table in a SQL Server

SELECT t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB,
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN  sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN  sys.schemas s ON t.schema_id = s.schema_id
WHERE t.NAME NOT LIKE 'dt%' AND t.is_ms_shipped = 0 AND i.OBJECT_ID > 255
GROUP BY t.Name, s.Name, p.Rows
ORDER BY t.Name

Friday, May 23, 2014

AWS Multi-Factor Authentication (MFA):

MFA adds extra security by requiring users to enter a unique authentication code from their authentication device when accessing AWS websites or services.

For MFA to work, you must assign an MFA device (hardware or virtual) to the IAM user or root account. The MFA device must be unique for each user; a user cannot enter a code from another user's device to authenticate.

Virtual MFA device: A virtual MFA device uses a software application that generates six-digit authentication codes that are compatible with the Time-Based One-Time Password (TOTP) standard, as described in RFC 6238. The software application can run on mobile hardware devices, including Smartphone. Most virtual MFA applications allow you to host more than one virtual MFA device, which makes them more convenient than hardware MFA devices. However, you should be aware that because a virtual MFA might be run on a less secure device such as a Smartphone, a virtual MFA might not provide the same level of security as a hardware MFA device.

Use the MFA device when logging on or accessing AWS resources. For access to an AWS website, you need a user name, password, and MFA code (an OTP). For access to MFA-protected APIs, you need access keys, the device serial number (hardware) or ARN (virtual device), and an MFA code.


Virtual MFA Applications Applications for your smartphone can be installed only from the application store that is specific for your phone type. In the list below are names of some applications for different smartphone types.
AndroidAWS Virtual MFA; Google Authenticator
iPhoneGoogle Authenticator
Windows PhoneAuthenticator
BlackberryGoogle Authenticator


To configure and enable a virtual MFA device for use with your root account
  • Use your root credentials to sign in to the AWS Management Console, and then go to the IAM console.
  • On the IAM Dashboard, click Manage MFA Device. This starts the Manage MFA Device wizard.

  • In the wizard, select A virtual MFA device and then click Continue.
  • Confirm that a virtual MFA application is installed on the device, then click Continue. IAM generates and displays configuration information for the virtual MFA device, including a QR code similar to the following graphic.
  • With the Manage MFA Device wizard still open, open the virtual MFA application on the device. The easiest way to configure the application is to use the application to scan the QR code. If you cannot scan the code, you can enter the configuration information manually.
    • To use the QR code to configure the virtual MFA device, follow the app instructions for scanning the code. For example, you might need to tap the camera icon or tap a command like Scan account barcode, and then use the device's camera to scan the code.
    • If you cannot scan the code, enter the configuration information manually by typing the Secret Configuration Key value into the application. For example, to do this in the AWS Virtual MFA application, tap Manually add account, and then type the secret configuration key and click Create.
    Important:Make a secure backup of the QR code or secret configuration key, or make sure that you enable multiple virtual MFA devices for your account. If the virtual MFA device is unavailable (for example, if you lose the smartphone where the virtual MFA app is configured), you will not be able to sign in to your account and you will have to contact customer service to remove MFA protection for the account.

    Note:The QR code and secret configuration key are unique and cannot be reused.
    When you are finished configuring the device, the device starts generating six-digit numbers.
  • Type the six-digit number that's currently displayed by the MFA device. Wait 30 seconds for the device to generate a new number, and then type the new six-digit number into the Authentication Code 2 box.
  • Click Continue.


To configure and enable a virtual MFA device for a user
  • Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.
  • In the navigation pane, click User and then select the user you want to enable the virtual MFA for.
  • In the user details pane, select Security Credentials, and then click Manage MFA Device.
  • In the Manage MFA Device wizard, select A virtual MFA device and then click Continue.

  • Confirm that a virtual MFA application is installed on the user's mobile device and then click Continue. (For a list of apps that you can use as virtual MFA devices, see Multi-Factor Authentication.) IAM generates and displays configuration information for the virtual MFA device, including a QR code similar to the following graphic.

  • With the Manage MFA Device wizard still open, open the virtual MFA application on the device. If the device supports QR codes, the easiest way to configure the application is to use the application to scan the QR code. If you cannot scan the code, you can enter the secret configuration key manually.
    • To use the QR code to configure the virtual MFA device, follow the app instructions for scanning the code. For example, you might need to tap the camera icon or tap a command like Scan account barcode, and then use the device's camera to scan the code.
    • If you cannot scan the code, enter the configuration information manually by typing the Secret Configuration Key value into the application. For example, to do this in the AWS Virtual MFA application, tap Manually add account, and then type the secret configuration key and click Create.
    Note: The QR code and secret configuration key are unique and cannot be reused

    When you are finished configuring the device, the device starts generating six-digit numbers
  • In the IAM Manage MFA Device wizard, in the Authentication Code 1 box, type the six-digit number that's currently displayed by the MFA device. Wait 30 seconds for the device to generate a new number, and then type the new six-digit number into the Authentication Code 2 box.
  • Click Continue.

Thursday, May 22, 2014

Amazon - AWS CloudTrail

1. AWS CloudTrail captures AWS API calls made by or on behalf of an AWS account and delivers log files to an Amazon S3 bucket that you specify. Using CloudTrail's console in the AWS Management Console, the AWS CLI, or the CloudTrail API, you create a trail, which specifies the bucket for log file delivery and storage. By default, your log files are encrypted using Amazon S3 server-side encryption (SSE).

2. You can identify which users and accounts called AWS APIs for services that support CloudTrail, the source IP address the calls were made from, and when the calls occurred. You can integrate CloudTrail into applications using the API, automate trail creation for your organization, check the status of your trails, and control how administrators turn CloudTrail logging on and off.

3. CloudTrail typically delivers log files within 15 minutes of an API call. These log files contain API calls from all of the account's services that support CloudTrail.

4. (Optional) You create an Amazon SNS topic to which you subscribe for notifications that a new log file has arrived in your bucket. Amazon SNS can notify you in multiple ways, including programmatically using Amazon Simple Queue Service
You can aggregate log files from multiple AWS regions and multiple AWS accounts into a single Amazon S3 bucket

Price: There is no additional charge for CloudTrail, but standard rates for Amazon S3 and Amazon SNS apply.


Supported Services

Analytics

·         Amazon Elastic MapReduce
·         Amazon Kinesis

Application Services

·         Amazon Simple Workflow Service

Compute and Networking

·         AWS Direct Connect
·         Amazon Elastic Compute Cloud (EC2)
·         Elastic Load Balancing
·         Amazon Virtual Private Cloud

Database

·         Amazon Relational Database Service
·         Amazon Redshift

Deployment and Management

·         AWS CloudFormation
·         AWS CloudTrail
·         AWS Elastic Beanstalk
·         AWS Identity and Access Management
·         Amazon CloudWatch

Storage and Content Delivery

·         Amazon Elastic Block Store



Supported Regions
AWS CloudTrail supports the following endpoints:
Region Name
Region
Endpoint
Protocol
AWS Account ID
US East (Northern Virginia) Region
us-east-1
cloudtrail.us-east-1.amazonaws.com
HTTPS
086441151436
US West (Northern California) Region
us-west-1
cloudtrail.us-west-1.amazonaws.com
HTTPS
388731089494
US West (Oregon) Region
us-west-2
cloudtrail.us-west-2.amazonaws.com
HTTPS
113285607260
EU (Ireland) Region
eu-west-1
cloudtrail.eu-west-1.amazonaws.com
HTTPS
859597730677
Asia Pacific (Singapore) Region
ap-southeast-1
cloudtrail.ap-southeast-1.amazonaws.com
HTTPS
903692715234
Asia Pacific (Sydney) Region
ap-southeast-2
cloudtrail.ap-southeast-2.amazonaws.com
HTTPS
284668455005
Asia Pacific (Tokyo) Region
ap-northeast-1
cloudtrail.ap-northeast-1.amazonaws.com
HTTPS
216624486486
South America (Sao Paulo) Region
sa-east-1
cloudtrail.sa-east-1.amazonaws.com
HTTPS
814480443879