Round up a number to highest 10s place

0

Download Source Code

Recently we faced a problem that we need to round-up a number to greatest 10s place.
For ex: we needed to round-up a number as follows
1023 -> 2000
37911 -> 40000
912345 –> 1000000

First we checked Math.Round(). But it didn’t solve our problem.  Math.Round() supports only rounds a value to the nearest integer or to the specified number of fractional digits. Further checking we come up a solution by using Math.Ceiling() method.

Math.Ceiling()returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.
For ex:
Math.Ceiling(7.3)     -> 8
Math.Ceiling(7.64)     -> 8
Math.Ceiling(0.12)     -> 1

Below is the solution we came up

decimal[] values = { 1023, 37911, 23000, 1234, 912345 };
foreach (var value in values) {
//// get the lenght of the 10s places;
var length = (int)Math.Log10((double)value);
//// using Math.Pow() calculate the power of 10s
var power = Math.Pow(10, length);
//// var roundadValue = Math.Ceiling(1023 / 1000) * 1000;
var roundadValue = Math.Ceiling(value / (decimal)power) * (decimal)power;

Console.WriteLine("Value:{0} Rounded Value:{1}", value, roundadValue); 

}

Math.Ceiling() Results

The Logic


Math.Ceiling(value / (decimal)power) * (decimal)power;
var roundadValue = Math.Ceiling(1023 / 1000) * 1000;

so, for any number, fist compute power of 10s and then it use for above calculation to get the results.

Generate insert statements from the specific table data using SQL Server

0

When you are deploying your application, sometimes you may want to generate SQL script with the insert statement of the specific database table. In this article I will show you two easiest ways to do this with SQL Server and SQL Server tools.

1. Using Database Publishing Wizard (“SqlPubWiz.exe”)

If you install Visual studio 2008 / Visual Studio 2008 Express full version, it will automatically install the Microsoft SQL Server Data Publishing Wizard on the following location.
[SQL Server Installation Location]\90\Tools\Publishing\[version]\ SqlPubWiz.exe

If it is not there you can download it from the following URL
http://go.microsoft.com/fwlink/?LinkId=119368

SQLPubWiz location

SQLPubWiz location

When you run the “SqlPubWiz.exe”, it will open the database publishing wizard

Database Publishing Wizard

Database Publishing Wizard

Click next and enter the database server connection information accordingly.

Database Publishing Wizard - Database Server Connection

Database Publishing Wizard – Database Server Connection

Click next, and it will ask you to select the database, which you want to generate the data from

Database Publishing Wizard - Select Database

Database Publishing Wizard – Select Database

Next screen will ask to select the Object type. You can use this database publishing wizard to generate data and schema both. In here I consider only for the data generation part. Now choose “Tables” as an option and click next. (Make sure to uncheck “Script all objects in the selected database”)

Database Publishing Wizard - Choose Object Type

Database Publishing Wizard – Choose Object Type

Then, the next ask to select the table which you want to generate the data from. Select whatever the table you want and click next.

Database Publishing Wizard - Choose Tables

Database Publishing Wizard – Choose Tables

Next step ask to specify the output location. You can enter the file name and the location there.

Database Publishing Wizard - Select an Output Location

Database Publishing Wizard – Select an Output Location

By clicking Next, It shows to select the publishing options. There are three publishing types, Schema only, Data only, or Schema and data. Here you have to select “Data only”.

Database Publishing Wizard - Select Publishing Option

Database Publishing Wizard – Select Publishing Option

Click next and it will generate the insert data script for you.

Database Publishing Wizard - Publishing Progress

Database Publishing Wizard – Publishing Progress

Database Publishing Wizard - Generated Script

Database Publishing Wizard – Generated Script

2. Using SQL Server Generate Script wizard

SQL Server Generate Script

SQL Server Generate Script

When you select “Generate Script” menu item, it will open the Generate SQL Server Scripts Wizard dialog.

SQL Server Generate Script - Wizard Dialog

SQL Server Generate Script – Wizard Dialog

By clicking next, it asks to select the database which you want to generate the script.

SQL Server Generate Script Wizard - Select Database

SQL Server Generate Script Wizard – Select Database

By clicking Next, It shows to select the script options dialog box. In here, you change the “Script Data” as “True” and click the next button

SQL Server Generate Script Wizard - Choose Script Option

SQL Server Generate Script Wizard – Choose Script Option

Next screen will ask to select the Object type. Now choose “Tables” as an option and click next.

SQL Server Generate Script Wizard - Choose Object Type

SQL Server Generate Script Wizard – Choose Object Type

Next screen ask you to select the tables which you want to generate the data from. Select whatever the tables and click next

SQL Server Generate Script Wizard - Choose Tables

SQL Server Generate Script Wizard – Choose Tables

Next step ask to specify the output options. If you select “Script to file” as an option, then you can enter the file name and the location there.

SQL Server Generate Script Wizard - Output Option

SQL Server Generate Script Wizard – Output Option

Next two steps are very strait forward. It shows the script generation summary, and by clicking next it will generate the script with insert statements for the selected tables.

SQL Server Generate Script Wizard - Script Summary

SQL Server Generate Script Wizard – Script Summary

SQL Server Generate Script Wizard - Script Progress

SQL Server Generate Script Wizard – Script Progress

SQL Server Generate Script Wizard - Generated Script

SQL Server Generate Script Wizard – Generated Script

How to Fix Orphaned SQL Users

13

Recently I had to involve in a database migration task. I backed up the database and restored successfully in the new server. However when I access the database through the web site, database login didn’t work. The problem was even though the database user is included in the restored database; the login information was not there. So I re-created the login in the server, but it also didn’t work.

This phenomenon is called “orphaned users“.

Database with orphaned users

Details of the Problem:

User logon information is stored in the syslogins table in the master database. By changing servers, or by altering this information by rebuilding or restoring an old version of the master database, the information may be different from when the user database dump was created. If logons do not exist for the users, they will receive an error indicating “Login failed” while attempting to log on to the server. If the user logons do exist, but the SID (secure identifier) in master..syslogins and the sysusers table in the user database differ, the users may have different permissions than expected in the user database. (Microsoft et.al)

User login information in syslogins table in the master database

User login information in syslogins table in the master database

User information in the sysusers table in the user database

User information in the sysusers table in the user database

See above example, both tables contain the different SID for the username “eyepax”

How to fix:

1. The easiest way to fix this is delete the user from the restored database and then create and setup the user & corresponding permission to the database.

2. If the user owns a schema in the database, you won’t be able to delete the user. Then you can use the special stored procedure “sp_change_users_login”.

Syntax

sp_change_users_login [ @Action = ] action
[ , [ @UserNamePattern = ] user]
[ , [ @LoginName = ] login]
[ , [ @Password = ] password]

Arguments

[@Action =] action

Following are the list of actions can be performed by the procedure.

Value Description
Auto_Fix Links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins. You should check the result from theAuto_Fix statement to confirm that the correct link is in fact made. Avoid using Auto_Fix in security-sensitive situations.
When using Auto_Fix, you must specify user and password; login must be NULL. user must be a valid user in the current database.
Report Lists the users and corresponding security identifiers (SID) in the current database that are not linked to any login.
user, login, and password must be NULL or not specified.
Update_One Links the specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specified.

To perform the operations, first you have to select the database which contained the issues. Here are some of the operations you can perform.

  • Lists the orphaned users
EXEC sp_change_users_login 'Report'
Lists the orphaned users

Lists the orphaned users

  • If you already create a SQL server with same login information and if you want to map that with the database user
EXEC sp_change_users_login 'Auto_Fix', 'user'
Auto fix orphaned user

Auto fix orphaned user

3. MSDN says, maps an existing database user to a SQL Server login. sp_change_users_login feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use ALTER USER instead.

Syntax

ALTER USER userName
WITH <set_item> [ ,...n ]

<set_item> ::=
NAME = newUserName
| DEFAULT_SCHEMA = schemaName
| LOGIN = loginName

Argument

userName -Specifies the name by which the user is identified inside this database.
LOGIN =loginName, Re-maps a user to another login by changing the user’s Security Identifier (SID) to match the login’s SID.
NAME =newUserName, Specifies the new name for this user. newUserName must not already occur in the current database.
DEFAULT_SCHEMA =schemaName, Specifies the first schema that will be searched by the server when it resolves the names of objects for this user.

ALTER USER UserName WITH LOGIN = UserName
Alter user

Alter user

For more information

sp_change_users_login
http://msdn.microsoft.com/en-us/library/ms174378(v=sql.110).aspx

ALTER USER
http://msdn.microsoft.com/en-us/library/ms176060.aspx

Troubleshoot Orphaned Users (SQL Server)
http://msdn.microsoft.com/en-us/library/ms175475.aspx

SMTP, POP3 and IMAP

7

SMTP, POP3 and IMAP are TCP/IP protocols used for mail delivery. Email clients use POP3 and IMAP protocol to retrieve email from the server (incoming mail) over TCP/IP connection. Outgoing mail for both POP and IMAP clients uses the SMTP. Main difference between POP3 and IMAP is,

  • POP3 – Downloads email locally
  • IMAP – Mail is stored on the mail server

SMTP

Simple Mail Transfer Protocol (SMTP) servers handle the sending of your e mail messages to the Internet. The SMTP server handles outgoing e mail, and is used in conjunction with a POP3 or IMAP incoming e mail server.

POP3

Post Office Protocol 3 (POP3) servers hold incoming e mail messages until you check your e mail, at which point they’re transferred to your computer. POP3 is the most common account type for personal e mail. Messages are typically deleted from the server when you check your e mail.

IMAP

Internet Message Access Protocol (IMAP) servers let you work with e mail messages without downloading them to your computer first. You can preview, delete, and organize messages directly on the e mail server, and copies are stored on the server until you choose to delete them. IMAP is commonly used for business e mail accounts.

Default Ports

  • SMTP AUTH: Port 25 or 587 (some ISPs are blocking port 25)
  • SMTP StartTLS Port 587
  • SMTP SSL Port 465
  • POP Port 110
  • POP SSL Port 995
  • IMAP Port 143
  • IMAP SSL Port 993
  • IMAP StartTLS Port 143

The following list of SMTP, POP3, and IMAP server should help you if you don’t know what mail server you should use for your mail account.

  SMTP POP3 IMAP
Gmail smtp.gmail.com pop.gmail.com imap.gmail.com
  SSL Port 465 SSL Port 995 SSL Port 993
  StartTLS Port 587
TLS/SSL encryption required: yes
Please make sure, that POP3 access is enabled in the account settings. Login to your account and enable POP3. Please make sure, that IMAP access is enabled in the account settings. Login to your account and enable IMAP.
Outlook.com smtp.live.com pop3.live.com imap.mail.yahoo.com
  StartTLS Port 587 SSL Port 995 SSL Port 993
  TLS/SSL encryption required: yes TLS/SSL encryption required: yes  
Yahoo Mail smtp.mail.yahoo.com pop.mail.yahoo.com  
  SSL Port 465 SSL Port 995  
Yahoo Mail Plus plus.smtp.mail.yahoo.com plus.pop.mail.yahoo.com plus.imap.mail.yahoo.com
  SSL Port 465 SSL Port 995 SSL Port 993
Yahoo UK smtp.mail.yahoo.co.uk pop.mail.yahoo.co.uk imap.mail.yahoo.co.uk
  SSL Port 465 SSL Port 995 SSL Port 993
Yahoo Deutschland smtp.mail.yahoo.de pop.mail.yahoo.de imap.mail.yahoo.de
  SSL Port 465 SSL Port 995 SSL Port 993
Yahoo AU/NZ smtp.mail.yahoo.com.au pop.mail.yahoo.com.au imap.mail.yahoo.com.au
  SSL Port 465 SSL Port 995 SSL Port 993
Windows Live (Hotmail) smtp.live.com pop3.live.com  
  StartTLS Port 587 SSL Port 995  

JavaScript Frameworks and Resources

1

Knockout.js

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.
http://knockoutjs.com/
Knockout.js

Angular.js

AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running what are known as single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. The library reads in HTML that contains additional custom tag attributes; it then obeys the directives in those custom attributes, and binds input or output parts of the page to a model represented by standard JavaScript variables. The values of those JavaScript variables can be manually set, or retrieved from static or dynamic JSON resources.
http://angularjs.org/
Angular.js

Backbone.js

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
http://backbonejs.org
Backbone.js

Node.js

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
http://nodejs.org/
Node.js

Modernizr

Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or not.
http://modernizr.com
Modernizr

Require.js

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
http://requirejs.org
Require.js

Less

LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.LESS runs on both the server-side (with Node.js and Rhino) or client-side (modern browsers only).
http://lesscss.org/
Less

Sass

Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
http://sass-lang.com
Saas

Online tools for troubleshooting web, SQL, XML and JSON

1

Have you ever wanted to troubleshoot someone else web page which contains the combination of JavaScript, CSS and HTML? Have you ever wanted to troubleshoot someone else SQL query without entering to the SQL server? Here are some useful online tool which make your life easier.

Following tools provide an online debugging environment for HTML, CSS and JavaScript.

1. jsFiddle

jsFiddle is the most popular JavaScript sandbox. It provides instantly ready coding environment for you to begin experimenting in as soon as the page loads.

http://jsfiddle.net/

JS Fiddle

2. JS Bin

JS Bin is another JavaScript sandbox. The design of this app is quite minimal and really allows you to focus on the code. By default, the page only shows the HTML and lives preview panes, but you can easily add JavaScript to that as well.

http://jsbin.com/

JS Bin

3. CSSDesk

CSSDesk is a CSS sandbox which allows you to put your HTML and CSS codes there and view the preview instantly. It is very useful for testing out codes before implementing them in your website permanently.

http://cssdesk.com/

CSS Desk

4. CodePen

CodePen is an app for sharing and playing around with front end code. It’s a site for building stuff from HTML, CSS and JavaScript.

http://codepen.io/pen/

Code Pen

Following tool can use for easy online testing and sharing of database problems and solutions.

1. SQL Fiddle

SQL Fiddle is a tool for easy online testing and sharing of database problems and their solutions. If you do not know SQL or basic database concepts, this site is not going to be very useful to you. However, if you are a database developer, there are a few different use-cases of SQL Fiddle intended for you:

  • You want help with a tricky query, and you’d like to post a question to a Q/A site
  • You want to compare and contrast SQL statements in different database back-ends
  • You do not have a particular database platform readily available, but you would like to see what a given query would look like in that environment

http://sqlfiddle.com/

SQL Fiddle

Following tools act as sandbox environment for JSON,  XML development, including (E)XSLT, XML validation (DTD, schema, RelaxNG) and XQuery.

1. XMLPlayground

XMLPlayground is a sandbox environment for XML development, including (E)XSLT, XML validation (DTD, schema, RelaxNG) and XQuery. It has five development panels into which you can either insert or upload code:

  • XML – your source XML. You can render it as a node tree via the ‘tree’ tab.
  • (E)XSLT – transform your XML with XSLT (1.0). EXSLT an XSL includes are supported.
  • Validation – validate your XML with Schema, DTD or RelaxNG.
  • CSS – style your output
  • XQuery – query or transform your XML with XQuery code (via XQIB)

http://xmlplayground.com/

XML Playground

2. JSON Fiddle

With JSON Fiddle, simulating and posting JSON in Fiddler is just as easy.

http://jsonfiddle.net

json fiddle