Wednesday, September 28, 2011

Dynamically Calculate Control Dimension at UI

Calculate the dimension of controls at UI in term of rows*columns. This accepts parent container width/height and number of controls to draw. You may also provide what ratio you need for controls.


/// Calculate control dimension as per parent size and required ratio
/// param name="ParentWidth">Parent control width
/// param name="ParentHeight">Parent control height
/// param name="TotalControls">Total control
/// param name="RatioX">X ratio of control to maintain
/// param name="RatioY">Y ratio of control to maintain
/// param name="TotalColumns">get columns
/// param name="TotalRows">get rows
public void CalculateDimensions(int ParentWidth, int ParentHeight, int TotalControls, int RatioX, int RatioY, out int TotalColumns, out int TotalRows)
{
TotalColumns = TotalRows = 1;

      double areaRatio = Math.Sqrt(((double)(ParentHeight * RatioX) / (double)(ParentWidth * RatioY)) / (double)TotalControls);
      double expectedWidth = areaRatio * ParentWidth;
      double expectedHeight = areaRatio * ParentHeight;

      if (ParentWidth > ParentHeight)
            TotalColumns = (int)Math.Ceiling((double)ParentWidth / (double)expectedWidth);
      else
            TotalRows = (int)Math.Ceiling((double)ParentHeight / (double)expectedHeight);

bool isOK = false;
      while (!isOK)
      {
            if (ParentWidth > ParentHeight)
            {
                  TotalRows = (int)(Math.Ceiling((double)TotalControls / (double)TotalColumns));
                  if (TotalColumns >= TotalRows) isOK = true; else TotalColumns++;
            }
            else
            {
                  TotalColumns = (int)(Math.Ceiling((double)TotalControls / (double)TotalRows));
                  if (TotalRows >= TotalColumns) isOK = true; else TotalRows++;
            }
       }
}

Thursday, June 30, 2011

C# Shortcuts (Automatic Properties)


C # 3.0 introduces automatic properties. A property is usually (but not have to) to a private variable that is exposed to the outside world through getters and setters. The following is a common example of this



public class Employee
{
 private string _fName;
 public string FName
 {
    get { return _fName; }
    set { _fName = value; }
 }
}
Now see the magic...
public class Employee
{
 public string FName { get; set; }
}
C # compiler automatically creates a variable background and the right to get and set properties. Why is it useful? After all, you could have just done a string variable instead of a public class.

When you define as a property allows you to add validation logic in the current class at a later stage. The signature in the memory of the class will not change which means that any external library compiled code need not be recompiled

C# Shortcuts (Nullable objects)

The variable must have a value, can not be empty. Sometimes it would be convenient, it was possible to give a "null" (for example, undefined) variable. . NET 2.0 Nullable general use, that makes this possible. The next two lines to produce exactly the same purpose:


Nullable myVar = null;
or use this...
int? myVar = null;
By one ? According to a definition of the variable, the compiler will wrap a Nullable  generic type.

C# Shortcuts (Alias ​​long namespaces and types)


The names of the identifiers of C # can be very long. For example if you are automating Microsoft Office in C #, you may want to do something as simple as MS Word to open and edit a document. You can use the "use" to create an alias for a class or namespace.


using ShortWord = Microsoft.Office.Interop.Word;
Now in code simply use ShortWord where ever you want...
ShortWord.Application = new ShortWord.Application() { Visible = True; }


C# Shortcuts (Using Statement)


Often, you will need to allocate a system resource or network resources, etc. Each time you need such a resource, there are three crucial steps to go through:

You will have the resource you use, and then get rid of it. If you forget to properly dispose of it, you create a memory or resource leaks. This is best illustrated through the following models


// Step-A. Allocation of desired object here
Font myFont = new Font("Arial", 12.0f);
try
{
     // Step-B. use the resource (myFont) here
}
finally
{
     // Step-C. Dispose your object here
     if (myFont != null)
        ((IDisposable)myFont).Dispose();
}
Using allows us to use to compress this to:
//Allocate the desired resource here
using (Font myFont = new Font("Arial", 12.0f))
{
    // Use the resource here
}
// The best part is that Disposal is automatic.


C# Shortcuts (Object Initializers)


When you create a new object, it is often necessary to assign one or more of its properties. The introduction of C # 3.0 you can now use object initializers, and to improve the readability of this, and reduce your code


Employee emp = new Employee();
emp.Name = "Mr Smith";
emp.Designation = "Driver";

Now make it short like this...
Employee emp = new Employee {emp.Name = "Mr Smith", emp.Designation = "Driver"};

C# Shortcuts (?? Null Coalesce Operator)

How often to check for null values ​​in the code?
Then the null-coalesce operator (??) is convenient. To see how this works, consider the following sample code.


object c = null;
object a = new object();
object b;

if (c != null)
    b = c;
else
   b = a;
Now using the "?" conditional statement you may write it as...
object c = null;
object a = new object();
object b = (c != null) ? c : a;
Now make it even shorter using ?? null-coalesce operator...
object c = null;
object a = new object();
object b = c ?? a;

C# Shortcuts (? Conditional Operator)


"?" operator is convenient. It allows you to pack a common "if then else" statement model in a single activity

Normally we use the following.


int x = 70;
int y = 95;
int min;

if (x < y)
  min = x;
else
  min = y;
But this can be written as...
int x = 70;
int y = 95;
int min = (x > y) ? x : y;

Tuesday, June 28, 2011

CSS Positioning - Elements Center Alignment


CSS is a mighty beast, and an integral part of any self-respecting web site. After all, this power comes a lot of different tricks you can use to accomplish the mission. Some of the tricks associated with the placement of content, and today we are going to do with it. This tutorial we are going to reveal some of the best ways to center the content when the content may be.

There are many ways the center of your content using CSS. Some are a little further forward than the other channel, but fortunately they are all relatively simple to implement. At the end of this tutorial, you should be able to do something like this:

I'm focused!

Center Horizontally

One of the easiest ways you can use elements of the center is the text-align: center on the package contents. For example:





I am Centered...




As you can see we use the property text-align both the content and packaging. It is because we center the text on the parent div that will be inherent inner div. So we must adapt our text inside div to the left. It is easy to implement, but not perfect.

We can indeed use the margins to the horizontal center of things as well. But when you use the margins, we generally have a content container that has a defined size. Sometimes you even have to give your wrapper contained an exact size, as well. For the first example, we started with the worst:





Again Centered...




As you can see that we have to give us both the packaging and the width of our container. Because we all know the numbers, we can do some 'math to reach our goal. We are half the width of the pack, which is 200 pixels, subtract half the width of the content. This gives us a margin of 150 pixels, which is the central fact in full. Although this is strictly forward and ensures that the content is at the center no matter what the width of our wrapper, it is an easier way.

This method consists in the margins of automobiles, which means that the CSS margins are calculated for us. In this case, we still have to give our content contains a wide range of ... but our package. This means that our budget can be any size you want. In addition, we can shorten the margin up / down left / right as well.





Atlast I Am focused...




This is usually the preferred method to center the content, but there is a problem. If you are looking for a good match, you must go to the text with the alignment method, such as automatic margins are not supported by all browsers. All modern browsers support auto margins, but not only in older browsers.

If you feel adventurous, try our latest example of the horizontal center. It is "relatively" the positioning of the contents of our container, and then move a little. This is what it would look like:







I'm focused!





Here we take the content and the relative position of it. This allows us to use the property left to move the content around us, which we used for the left: 50%. This will move the content, but not centralized, as the top left hand pointing to the center of the contents of the container, moves to the right. To satisfy this, as the first example, the margin is calculated half-width of our content, but this time we are reducing the current drive. The end result is a central content.

So those are the main ways to get in half horizontally and CSS. There are other tricks you can do things, but these methods are the most common, and in the case of the first two, the most dynamic. However, there is a trick to get things centered vertically.

Center Vertically

This is where the trick There are two ways to focus your content vertically on the page. But before you dig I want to emphasize that both methods require your content for a specified height. There are several ways to focus on content without having to adjust the height, but they showed a lack of compatibility between browsers. These two routes are your best paris.

The first way is exactly the same concept as our last example horizontally, except suitable for the vertical position. It looks like this:







I'm focused!





As you can see that the same basic concept. You respect the position of the content in the middle, then offset by half its height. It works in virtually any browser, you will meet, and is simple to implement. A good solution, but that's another way of doing things.

This solution is a bit strange at first, but it is the best way to center the content vertically. That said, it is a sensitive issue. Using a floating div to force the contents in the center of the page, and we all know that things float can be a pain at times. Fortunately, implementation is very simple:










The Centered!





So now we have this new arc, which can be called at the end float guide our container contents, a vertical center of the page. As long be remembered as the "clear" the entire contents of the container works as expected. To make things better, this method is said to be a very wise browser compatible, which means that it works with IE 5

While there are all sorts of crazy ways to center the content vertically, if you just want some centered text. Of course, you can use one of the solutions above, but this seems a little bit exaggerated. Well, it was our secret third option comes into play.







I'm focused!





This is one of the center line of the text, and I want to stress one. I'm sure you've noticed that the key to this method is the line height, which makes every line of text a certain height. This means that if the text is wrapped, the following line is 50 pixels high. This makes it a good solution if you need a quick solution for a line of text, but something else later.

So this is a set of techniques are the best solutions for centering content, then x and y planes They are simple to use, and get the job done. This concludes this tutorial, but just remember, when you need help coding have to do is connect the Code.

Being A Developer of Windows Mobile 7


I have a sad news :(  I have never built a Windows Mobile 7 applications.
As Guy Blend and WPF, which bubbled over in Silverlight, it may shock you, but time and effort (not enough of the former and too much of it) kept me do it Hello everyone. Of course, it does not allow Verizon Stinkin WP7 has not yet, but we hope that this issue will arrange soon.

Since I promised to write an annex to the mix in the action focuses on the mixture WP7, I think it's time we jumped on the bandwagon and made some WP7 development.

Where I am from

Since I have Visual Studio and Expression Blend installed everything I need to start developing was to download and install the developer tools Windows Phone. This includes the emulator and necessary WP7 types of projects. If you do not Blend or Visual Studio on your machine, free tools are a part of this installation.

Register App Hub

Since I intend to create and publish real applications I went ahead and created an account AppHub. There are some things you should know before you start. First, it costs $ 99 in advance, so be prepared to pay when creating your account. Second, you need a Live ID. Third, you can not create an account without a website URL. While this may seem trivial, it threw me because I did not create this site, I intend to use my phone still Apps. I went ahead and use this site with the hope that I can change it later.

The next thing I did not expect the requirement of a tag as a player. I'm not a gamer, I do not own an Xbox, and I'm not sure what player is a tag, so I obviously did not deliver. I was stuck on the screen gamer tag you want for a while until I found one I wanted, which was not taken (theblendguy).

The last thing that threw me for a circuit that was to fill in forms, all copies is strongly oriented to XBox Live. Once past the home screen, everything I've read the account was in XBox Hub of the application: there was no mention of Windows Mobile 7. I canceled to make sure I had made the right decision, but decided to go to my guns, especially when I saw the price was right. In fact, when all was said and done, I had the appropriate account.

I received an email confirmation, and graduated from the account. If I understand correctly, the next step is to contact me and GeoTrust to verify I am who I say I am. I like the fact that Microsoft is putting so much effort to examine the accounts and applications: in the long term should mean a stable quality of the applications, which is the beginning, if you want to succeed.

And here is the next step...

The next step is the development of applications. I have a couple in mind already. I'm going to write my experiences as I go forward, so keep watching this space.

The next day I created my account, I received an email from GeoTrust take me to another site where I had to verify my identity. From the start, be prepared for some questions seem intrusive. I had to give them my social security number and possibly my license and some less info such as date of birth and address. Also, if you have been at your current address for less than two years, you must provide the previous address.

This information is the first step. When you place this time, another page comes with a set of questions specific financial, which, theoretically, you should be able to respond. I received questions about my mortgage and car payment, including a couple of trick questions. The answers are multiple choice, so you do not give them special, and it does not matter, because it seems they know it all already anyway.

Of course this is all done in HTTPS, so I'm not concerned about the safety of me when I use a credit card online. I was quite surprised that although the BI is in place to develop a trick question that I mentioned. (And no, I'm not going to be more specific). Overall, the process was tedious, and I passed the test at this stage I'm just waiting for my developer ID AppHub. I will keep you all posted.

And wait for the message in your inbox.

Now that you're an official you can start to develop, and applications.

To Recompile All The Stored Procedures For Database


Recompiling an object is an advantage when the "indexes or other changes that affect statistics are made the database, compiled stored procedures and triggers may lose efficiency. Sp_recompile is a system stored procedure in SQL to rebuild an object, the next time it runs. Recompiling you can re-optimize queries.

Here is the query to recompile all the SPS in the database.

Declare @ name nvarchar (125), @ cmd nvarchar (300)

SPList declare the cursor / Cursor * It must be observed to go through all the SPS DB * /

Select the name of sys.objects

where type = 'P'

SPList open

FETCH NEXT from SPList / * get the record of the cursor * /

in the name @

While @ @ FETCH_STATUS = 0

start

Select @ cmd = 'EXEC sp_recompile [' + @ name + ']'

Exec @ cmd / * recompile the SP * /

FETCH NEXT SPList / * Get the name of SP after the cursor * /

@ In the name

Head

SPList close

Deallocate SPList

Remove The NOT NULL Column Constraint ALTER TABLE


Many times it may be necessary to remove the limitation Not Null applied to a column in a table. It is generally necessary to overcome the unexpected integrity constraints (which rarely happens, if well designed) against a table. We can remove the constaint Not Null using the ALTER TABLE .... ALTER COLUMN ... option.

A sample query is

Alter table dbo.Test

alter column test nvarchar (10) null;

You can also reuse the next.

Alter table dbo.Test

alter column test nvarchar (10) NOT NULL;

Find The Model For SQL Server Using PATINDEX () And CHARINDEX ()


Although these features are not commonly used, is very powerful in the search for a reason and return the location of the text / string / model. By understanding the functionality of the string functions, we will be able to understand the difference too.

PATINDEX ()

The search function of a pattern in a string / expression and returns the starting position of the first occurrence of the pattern. It works similarly to the operator, as in any application.

The general syntax is

PATINDEX ('% pattern%', expression)

You may have already noticed the '%' symbols used in the model. These are important, as I mentioned before, using the same syntax used for research by the LIKE operator.

Choose PATINDEX ('% System%', description) index location, description

From dbo.TestTable

CHARINDEX ()

CHARINDEX () function is similar to PATINDEX (). However, CHARINDEX search for the string expression specified in the start position (Start loction default is 1). If you have already noted above, we can begin to determine the position of PATINDEX ()

The general syntax is

CHARINDEX (expression1, expression2 [, start_location])

An example of the same data set used earlier would look like

Select CHARINDEX ("System", description) index position, description

from dbo.TestTable

We can also start position indlude. Below is a sample search function in the string from the position of three

Select charindex ("System", description, 3) indexlocation Description

from dbo.TestTable

Finally, the main difference between the PATINDEX () and CHARINDEX () is the ability to CHARINDEX To find a specific location.

Reindex The Database With A Large Gap With "DBCC DBREINDEX"


DBCC commands is one of the most commonly used are DBAs worldwide. Today I'm going to present a simple way to index the specific table or all indexes using DBCC.

The command used for this is

DBCC DBREINDEX

General Sytax

DBCC DBREINDEX

(

table_name

[, Index_name [, fillfactor]]

)

The best feature of this command is that we need not abandon such unique or primary key restrictions applied to the index to rebuild the index. This means that the index can be rebuilt without knowing the structure of a table or limitations.

It accepts three parameters. The table name, index name and the fill factor.

This is an example below

The command below will not be indexed and table "IDX_EMPL" "TBL_DIM_EMPL" with a fill factor of 80

DBCC DBREINDEX ("TBL_DIM_EMPL", "IDX_EMPL", 80)

The following command reindex all indexes on the table "TBL_DIM_EMPL"

DBCC DBREINDEX ("TBL_DIM_EMPL", "", 80)

What NULLIF () Do? How It Differs From ISNULL ()?


NULLIF () returns zero if the two specified expressions are equal in function.

Syntax

NULLIF (expression1, expression2)

If expression1 = expression2, the function returns NULL.

ISNULL () function replaces an expression with no specified value.

The syntax used is

ISNULL (expression1, expression2)

If expr1 is NULL, then the function returns expression2 output.

ISNULL functionality can be written using if ... WHEN the

CASE WHEN expression1 THEN END ELSE NULL Expression2 expression1

An example of these two functions are shown below

Select ISNULL (NULL, 'hello') as IsNullOutPut1

, IsNull (1001, 1) as IsNullOutPut2

, NULLIF (100, 100) that NullIfOutPut1

, NULLIF (1, 100) that NullIfOutPut2

Changing The SQL Database In Single User Mode And Back To The Multi-User Mode


It is often necessary to modify the database in single user mode, especially if you are the DBA. A simple example would be to change the sorting options, or settings TE. A single user only allows a user (typically the DBA) to access the database. Therefore, it is easy to make changes without worrying about the blind alleys, and any claim, DB, and also without affecting users.

It is very easy to change the database in single user mode, in fact, it's just a script. Use the following script to change the mode.

ALTER DATABASE < > SET SINGLE_USER no_wait

NO_WAIT clause to set the single-user mode, when you run the query. Replacing this is to use the system stored sp_dboption

EXEC sp_dboption < > 'SINGLE USER', False

However, you must set the database in multiuser mode for other users to use. Without it, it will not be available to others.

Here is a script to set the basis for multi-mode.

ALTER DATABASE < > GAME MULTI_USER no_wait

Or alternative

EXEC sp_dboption < 'SINGLE USER'>, False

I advise you to maintain caution while changing database in single user mode, because it would link users already connected to the database.

The Benefits And The Differences Between CHAR And VARCHAR Data Types For SQL Server


All of you reading this have encountered these types of data, but have you ever thought about what the differences and advantages of the two?

The obvious difference that comes to mind in length. Yes! You are right. Varchar Char supports of various lengths and supports fixed length. This is the main advantage of the VARCHAR data type. For example, consider the varchar (10) and char (10). You can save the "GEEKEPISODE" Both types of data using the entire length of the target and save the "geek", char data type to use 10 characters in common, but only 4 VARCHAR

From the above examples, it seems better than CHAR VARCHAR all the time. But remember, CHAR was included as a separate type because it has certain advantages over VARCHAR.

VARCHAR use the extra space to store the length of the string stored in it, and mark the end of the string. Considering that the char data type does not use this extra space. This is certainly the advantage of data type CHAR.

Summary:

CHAR

It is used to store a fixed string / character data

It requires no additional space / bytes to capture the length and the end of the string.

Still, if the length of the string data / character is fixed. Example: SSN, systemId, EmpID.

It is faster than VARCHAR, when used in collections and queries.

VARCHAR

Used to store variable-length string.

Requires additional bytes / space to enter the time and the end of the chain.

use, if the length of the data string / character can not be determined at the design stage. Example: name, brief description

 Slower than the CHAR data type when used in collections and queries.

Here the above explanation also applies to data types nchar and nvarchar.

The Script In The Batch File Using Sqlcmd


I often create batch files to run SQL scripts (especially SPS), and then schedule jobs using SQL Agent / Task Scheduler. In this post, I will show you how to create a batch file with SQL commands.

First, the command used to execute SQL queries commnd SQLCMD system. The general syntax of this command is available on the link. I'm going with a single as follows

Server Name sqlcmd-Q-ES-o Query "Output Path"

here

E = secure connection (Windows Authentication)

-Server Name = S

-Q = CommandLineQuery

O = output file path

a simple command prompt can commnad

C: \ Users \ geekEpisodes> sqlcmd-IS "Local-SRV01"-Q "Select top 10 * from MyTestDatabase .. [ForecastHistory]"-o "C: \ New Folder \ output.txt"

All commands you execute the command can be run from batch control / files. to create a batch file with SQL commands to follow the steps below


1: Create a file with a bat or cmd (for example testfile.bat, test.cmd) ...

2: Add the file commands such as

sqlcmd-IS "Local-SRV01"-Q "Select top 10 * from MyTestDatabase .. [ForecastHistory]"-o "C: \ New Folder \ output.txt"

sqlcmd-IS "Local-SRV01"-Q "select count (1) of MyTestDatabase .. [ForecastHistory]"-o "C: \ New Folder \ Output2.txt"

sqlcmd-ES "SRV01 local"-Q "Exec MyTestDatabase .. [spPopulateData]"

3: Now save it.

4: Double-click the file and query the file exeuted. This file can be used in the Task Scheduler and other applications.


String Soundex() And Its Purpose In The SQL


Soundex code was developed to help defeat the effects of all spelling variations, which can occur in similar-sounding name (Smith, Smithe, Smythe, etc.). This allows users to index is based on the Soundex code is based on votes and "no", as it is written.

The Soundex system is not foolproof - after Gough sounding names and Goff (Goff), but a different code is generated for these two names. Soundex can however be more widely used to obtain a desired result (closer to a desired result atleast) This is an algorithm commonly used by many researchers.

Depending on SQL string is available for this and usually come handy. SOUNDEX () function.

It accepts a string (name) as a parameter and returns a 4 character. This code is known as code name soundex / string is sent as a parameter.

For example:

Choose Soundex ('Smith') O / P: S580

Select SOUNDEX ('Smith') O / P: S580

SELECT SOUNDEX ('green') O / P: G652

Another use for this is contrary to a user enters a field where you need to search for specific words, but words can be wrong (even if it can not produce 100% conversion).

Sequence Number As Per Each Group

Use the following to display the sequence numbers as per each group


select
         myGroupID, 
         myGROUPCOUNTER = ROW_NUMBER() OVER (PARTITION BY [myGroupIDORDER BY [myGroupID])
from
         myGroupTable



Database Files Location in SQL

Use the following to find the location of all database files (.mdf and .ldf) present in SQL server

SELECT physical_name as Path_Name FROM master.sys.master_files


Identity Column in SQL

Use following to make an identity column in a table of SQL database.

CREATE TABLE dbo.TableName(
ID INT IDENTITY(1,1) ,
LittleDescription varchar(50) ,
DetailedDescription varchar(1000)
);

Monday, June 27, 2011

SQL Server Database - Recover From Suspect mode


Sometimes you find your SQL database in suspect mode. This normally happens when your PC abnormally shutdowns or any other major hardware failure. Here i will explain how to recover your precious data from this.
In many cases there will be no change in the size of MDF and LDF files, but more likely LDF is corrupted.
So here is the solution of your problem.
  • First make sure that database is in suspect mode
    • Create a new empty database at some safe location
    • Now stop the SQL Server service
    • Replace the old MDF file over newly created
    • Start SQL service and database will try to recover it. (During this database will go to suspect mode)
  • Now we will put the database to emergency mode (This can be done by using ALTER DATABASE or following commands)
Sp_configure 'allow updates', 1
GO
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = ''
GO
sp_dboption '', 'single_user', 'true'
GO

Sp_configure 'allow updates', 0
GO
Reconfigure with override
GO
  • Try to use DBCC CHECKDB ('', REPAIR_ALLOW_DATA_LOSS) This will rebuild log file and run full repair of the MDF file)
DBCC CHECKDB('', REPAIR_ALLOW_DATA_LOSS)
Go
(*If it gives error use next step)
  • Then use DBCC REBUILD_LOG ('','new LDF path') to rebuild the LDF file
DBCC REBUILD_LOG('', 'new LDF path')
Go
  • Almost done. Now we will push database to normal mode (Again use either ALTER DATABASE or following commands)
Sp_configure 'allow updates', 1
GO
Reconfigure with override
GO
Update sysdatabases set status = 16 where name = ''
G
O
Sp_configure 'allow updates', 0
GO
Reconfigure with override
GO
  • Restart the engine of Microsoft SQL Server (I have successfully checked on Microsoft SQL 2000)
  • Verify your database by checking its tables and data.
* Don't forget to make a daily backup schedule next time :)