Showing posts with label Tips and Tricks. Show all posts
Showing posts with label Tips and Tricks. Show all posts

Friday, November 01, 2013

Delete all the rows from all the tables in SQL Server

If you are in situation where you just want empty database structure, without having data in it.

Run following select statement which will generate set of delete statement to delete all the records for all the tables in your database.

SELECT
'Delete from ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ';' 
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Type = 'BASE TABLE'
ORDER by TABLE_NAME


In case your database is large and you want to know status of which table is currently getting deleted you can use following:

SELECT
'Print(''Delete started for ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ''');' +
'Delete from ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ';' +
'Print(''Delete done for ' + Table_Catalog + '.' + Table_Schema + '.' + Table_Name + ''');'  +
'Print(''.............'');'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Type = 'BASE TABLE'
ORDER by TABLE_NAME

Sunday, August 25, 2013

SQL Server Performance Tuning and Query Optimization Videos

If you are like me, who don't get much chance to get your hands dirty in fine tuning sql server queries, then you must watch this videos.

I am really thankful to this guy, who has posted such a useful videos.

http://www.youtube.com/playlist?list=PL2900t3sPCl1MZi88lYsRLUcSled8wAMU

Frankly speaking their is lot of materials out their on this topic and I always avoid learning because of that.  This videos helped me to quickly get started to attack problem I was facing.

If you landed here searching how to improve performance of your website then along with database sql indexing you should also look for this checklist.
http://dotnetguts.blogspot.com/2012/09/all-about-aspnet-website-performance.html

Generate C# Class from JSON File or URL

I have came across a useful site which will be helpful in generating C# Class from JSON File or URL.

This will be very useful when you are using JsonConvert.DeserializeObject Method.

http://json2csharp.com/


Generate JSON File from database data using c#

Following code will help you to generate JSON file from database table.

//Get records from database
var products = db.Products.ToList();

//Generate JSON from database data
using (StringWriter writer = new StringWriter())
{
    // Json.Write sends a Json-encoded string to the writer.
    System.Web.Helpers.Json.Write(products, writer);
   
    // When ready, you can send the writer
    // output to the browser, a file, etc.
    //Response.Write(writer); 
    /*Uncomment above line to view JSON
       output in browser*/

    using (StreamWriter outfile =
               new StreamWriter(@"c:\Temp\Products.json"))
    {
        outfile.Write(writer.ToString());
    }
}

Please note: In order to have this code work, you will need to have "System.web.Helpers" dll added to your solution.

Saturday, August 17, 2013

Adding Column to SQL Server using Database Defensive Programming Technique

Recently I have learned good way to add column to sql server using database defensive programming technique from my co-worker.  All the credit for this blog post goes to him.  Thank you sir incase you are reading this blog post. (I have purposefully avoid mentioning name of co-worker due to privacy reason.)

Following example is very simple and self explanatory, Incase if you didn't get anything then pass your comment in comment section.


BEGIN TRANSACTION
IF EXISTS(SELECT 1 from information_schema.tables 
          where table_name = 'MyTableName')
  BEGIN
    Print('Table Exist');

    --Add Column MyColumn
    IF NOT EXISTS(SELECT 1 from information_schema.columns 
                  where table_name = 'MyTableName' 
                  and Column_Name='MyColumn')
     BEGIN
 ALTER TABLE MyTableName ADD MyColumn varchar(345) NULL;
 Print('MyColumn Column Added');
     END

    ELSE
     
     BEGIN
 Print('MyColumn Column Already Exist');
     END



  END

Else
    BEGIN
  Print('Table does not Exist');
    END


IF @@ERROR <> 0
    BEGIN
        PRINT('Problem in running script, Rolling back');
        ROLLBACK TRANSACTION;
    END
ELSE
 BEGIN
  PRINT('Script Run Successfully');
        COMMIT TRANSACTION;
 END

Sunday, March 11, 2012

How to be ProActive rather than ReActive in Software World

Many times people have habit of speaking be Proactive rather than Reactive and blah... blah...

I found a very good video giving an example on this, In a true sense.  This is what i say "Customer Care".

What i can say guy's be patient and listen to his keynotes till end.  This guy is true genius and thinking out of box.  I really enjoyed every bit of it.






Monday, January 23, 2012

How do I remove my personal details from Google search?

If you want to remove your personal details/data from google search results try use some of these tools:
1. Wizard Removing Content From Google
2. Keeping personal information out of Google.
3. User Webmaster Tools for remove data:

If you don’t already have one, then
1) Create a Google account (I am sure you might have one, if not create a gmail account)
2) Go to this URL: https://www.google.com/webmasters/tools/removals



3) Click on "Create a new removal request" button
4) Type in URL you would like to remove.
That's it you are done.

Wednesday, December 21, 2011

Copy of Session Object

Many times we try to make copy of session object, but in case when we are modifying copied object we might noticed that session object gets updated automatically, the reason is both copied object and session object are pointing to same location, even if you tried to use "new" operator while creating object.

Scenario
Let say you have Member Class as mentioned under
public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }
}


Problem:
Member objMember = new Member();
objMember.FirstName = "Sachin";
objMember.LastName = "Tendulkar";

Then try to save object in Session
Session["MemberObj"] = objMember;

This method will work good till we are just accessing object from session, but in case if we try to update object created from session it will update value of session also.

That is,
Member newMember = new Member(); //Even though object is created using "new" keyword.
newMember = (Member) Session["MemberObj"];
newMember.FirstName = "Kapil"; //This will update session FirstName also.


Solution:
To make copies of session you need to create a clone method in class.

In above class create a method clone, to support copy of session.


public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }


public Member clone()
{
   Member cloneMember = new Member();
       cloneMember.FirstName = this.FirstName;
   cloneMember.LastName = this.LastName;
}
}

Now, while accessing session object, you can call clone method to make copy of session.

Member newMember = new Member();
newMember = ((Member) Session["MemberObj"]).clone();

now if you try to modify object copied from session, will not update session object.
newMember.FirstName = "Kapil"; //Will not update session FirstName

Wednesday, August 05, 2009

Download File Comparison Tool Free

Download Free File comparison tool.


Many times we want to compare two files, and to perform that we used file comparison tools like Beyond compare. But Beyond compare is not free. So Alternate for Beyond compare, which can perform file comparision like beyond compare and its free, than dowload Turtoise SVN Subversion

Turtoise SVN is Free and it can provide file comparison facility same as popular beyond compare tool.

Turtoise SVN is popular file versioning tool, but it can also be used for file comparison and its Free.

For example purpose i have created two sample file to compare.


Step 2: Choose Files to be compare. For this example i have created two sample text file.
Note: You can compare any two file it can be .doc file, .xls file, .xml file, .cs file or any.

Step 3: Select two file and press cntrl key and press right mouse click and choose "Diff" for finding difference between two files.

Step 4: Following screenshot shows difference between two files.

Step 5: You can replace text block and manipulate file as per your wish. Right click the text from file you would like to use, and choose option "Use this text block" in order to use that text block for both the files.

Thursday, June 25, 2009

Create PDF Document on Fly in C# using iTextSharp

Create PDF Document on Fly in C# and VB.Net using iTextSharp

Step 1: Download iTextSharp DLL Files

Step 2: Follow instruction from article which explains step by step approach to create PDF Document on Fly in C#.

Tuesday, May 12, 2009

How to remove image from cache when Image is changed

How to remove image from cache when Image is changed.  If you are looking for How to Remove Cache Image from Client Browser than this post will be useful to you.


How Image Caching Starts
I was in search of Image Caching Technique which can load images which are comonly used in my application from cache, but should also support to display new image when it is replace.  
Example:  Images like Website Logo, Menu Images, and other commonly used images should be load from cache and so that user experience faster performance, but it should also be capable to display new image when changes is occur.  i.e. If user changes their user profile image, than it should display new image and invalidate old image on client browser.

To implement image caching in website which can perform above task i have implemented Image Caching Technique as mentioned in article

So after implementing it, i found that it will Cache the images and you have no control to invalidate cached image as it is stored on user browser, it can only be invalidated if user manually delete cache data, and it is certainly not in control of webmaster.

As first part works like charm (Caching commonly used images), so how should i remove cached image when user change his profile image or display most current image when cached image is changed.  Moreover my application has a dependency wherein name of image cannot be change on changing image.  i.e. User5.jpg is name of image, now whenever user changes his image, old image will be replaced with new image and will be stored with same name User5.jpg, but user browser has cached User5.jpg so how can i invalidate old image and instruct browser to display most current image.

This solution was provided by TechFriend on Asp.net Forum Thanks Mate!

Solution to remove or invalidate image from cache which is stored on user browser

Whenever you are trying to save image append querystring to it and save in database

Example:  if your image name is User5.jpg append querystring like
"~/Image/User5.jpg?" + DateTime.Now.ToString("ddyyhhmmss")

Now whenever User5.jpg image is retrieved from database it has unique querystring append which changes everytime you change image, so if user images changed, its associated name of image will also change and browser will display the latest image, rather than displaying old image as browser identifies it as unique image, which is never cache by browser.

Now whenever you display the image like
<img src="~/Image/User5.jpg?" + DateTime.Now.ToString("ddyyhhmmss")>

It will always display latest image, wherein image name is retrieved from database, and good thing is it will display that image from cache until that image is changed.

Supplement to solution in case Thumbnail Image is generated.
What if you are generating Thumbnail based on above image?  It can be problem as their is no image with name "~/Image/User5.jpg?" + DateTime.Now.ToString("ddyyhhmmss") stored physically on server.

Rest of logic for generating thumbnail image will work good, you just need to add few lines more to perform extra care in our case.  lines which needs to be added is marked in bold.

//Take Original Image Path and Returns Thumbnail Image Path
private string GetThumbnailView(string OriginalImagePath, int height, int width)
{
    string ImgLastVersionNumber = string.Empty;
    if (OriginalImagePath.IndexOf("?") != -1)
    {
        ImgLastVersionNumber = OriginalImagePath.Substring(OriginalImagePath.IndexOf("?"));
        OriginalImagePath = OriginalImagePath.Replace(ImgLastVersionNumber, string.Empty);
    }

    //Consider Image is stored at path like "UserImage\\user9.jpg"
    //Now we have created one another folder UserThumbnail to store thumbnail image of User Image.
    //So let name of image be same, just change the foldername while storing image.
    string thumbnailImagePath = OriginalImagePath.Replace("UserImages", "UserThumbnail");

    //If thumbnail image is not available, generate it.
    if (!System.IO.File.Exists(Server.MapPath(thumbnailImagePath)))
    {
        System.Drawing.Image imgThumbnailImage;

        System.Drawing.Image imgOriginalImage;
        if (!System.IO.File.Exists(Server.MapPath(OriginalImagePath)))
            imgOriginalImage = System.Drawing.Image.FromFile(Server.MapPath(clsGeneral.URLOfDefaultUserImage));
        else
            imgOriginalImage = System.Drawing.Image.FromFile(Server.MapPath(OriginalImagePath));

        imgThumbnailImage = imgOriginalImage.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
        imgThumbnailImage.Save(Server.MapPath(thumbnailImagePath), System.Drawing.Imaging.ImageFormat.Jpeg);

        if (!System.IO.File.Exists(Server.MapPath(OriginalImagePath)))
            imgThumbnailImage.Save(Server.MapPath(OriginalImagePath), System.Drawing.Imaging.ImageFormat.Jpeg);

        imgThumbnailImage.Dispose();
        imgOriginalImage.Dispose();
    }
    return thumbnailImagePath + ImgLastVersionNumber;
}

Thursday, April 30, 2009

event.keycode problem Firefox

Solution for event.keycode problem for Firefox and Chrome


I was trying to identify which key is pressed by user  so that I can perform operation accordingly.  keyup event works perfectly with IE, but it was not behaving as expected for Firefox and Chrome.

Following is solution i came across to solve event.keycode problem for firefox (Fix to identify which key is pressed by user on IE, Firefox and Chrome)

function WhichKeyPress(e) {
 if (!e) {
  //if the browser did not pass the event 
  //information to the function, 
  //we will have to obtain it from the 
  //event register
  if (window.event) {
       //Internet Explorer
        e = window.event;
     } else {
       //total failure, we have no 
      //way of referencing the event
       return;
     }
   }
   if (typeof (e.keyCode) == 'number') {
      //DOM
      e = e.keyCode;
    } else if (typeof (e.which) == 'number') {
      //NS 4 compatible
      e = e.which;
    } else if (typeof (e.charCode) == 'number') {
     //also NS 6+, Mozilla 0.9+
      e = e.charCode;
    } else {
      //total failure, we have no way of obtaining the key code
      return;
    }
}

I have called the above function in following manner.
<body onkeyup="WhichKeyPress();">

click Event Problem Firefox Solution

click Event in Firefox and Chrome doesn't work as expected, while it works perfectly with IE.


I have a following Javascript code which was not working
document.getElementById('hlHome').click()
Where "hlHome" is ID of Home Link

Example: I have defined link like following 
<a id="hlHome" runat="server"></a>

Following piece of code was working perfect with IE, but Firefox and Chrome didn't recognise this event.

Solution for Click Event Problem for Firefox, Chrome.
Wherever you are using click event as shown above replace that line with following.
window.location.href = document.getElementById('hlHome').href;

Sunday, December 14, 2008

Maintain Scroll Position Rating Control Ajax

Update to my previous post Rating Control Ajax - Display Message on Rating

Ajax Rating Control has bug, that is whenever user clicks the rating control, page causes jumps to top of the page. To avoid jump to top of page when user clicks Rating Control you need to add following line.

Add following line to maintain scroll position of page after user clicks rating control asp.net ajax.


protected void Page_Load(object sender, EventArgs e)
{
Rating1.Attributes.Add("onclick", "return false;");
}

For Detailed explanation about why Rating control jumps to top of page when user clicks on Rating control

Thursday, December 04, 2008

Rating Control Ajax - Display Message on Rating

One Famous Problem with Rating Control is How to Display Message after Rating is done, without making use of button click.

Following Images Explain How can we display label text on Rating Control Click, without explicitly clicking any button control.

Before Rating Control is Clicked


During Rating Control is Clicked


After Rating Control is Clicked


Now, lets understand how to display message on click of Star Image.

Step1: Declare CSS Styles in Style Sheet file Also Add Images to Image Folder


.ratingStar {
font-size: 0pt;
width: 31px;
height: 30px;
margin: 0px;
padding: 0px;
cursor: pointer;
display: block;
background-repeat: no-repeat;
}

.filledRatingStar {
background-image: url(Images/FilledStar.png);

}

.emptyRatingStar {
background-image: url(Images/EmptyStar.png);
}

.savedRatingStar {
background-image: url(Images/SavedStar.png);
}


Step2: Declare ScriptManager in .aspx file with EnablePartialRendering=true

<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server">
</asp:ScriptManager>

Step3: Declare UpdatePannel

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Declare Rating Control Here -->
</ContentTemplate>
</asp:UpdatePanel>

Step4: Add Rating Control and Label in UpdatePannel

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Rating Control -->
<cc1:Rating ID="Rating1" runat="server"
BehaviorID="RatingBhvrId1"
CurrentRating="3"
MaxRating="5"
StarCssClass="ratingStar"
WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar"
EmptyStarCssClass="emptyRatingStar"
OnChanged="Rating1_Changed"
ToolTip="Please Rate!"
style="float:left;">
</cc1:Rating>

<!-- Label to Display Message -->
<span id="lblResponse" class="heading"></span>
</ContentTemplate>
</asp:UpdatePanel>

Step5: Declare Necessary Javascript to show "Message" after user performs Rating with the help of e.CallbackResult

<script language="javascript" type="text/javascript">
Sys.Application.add_load(function()
{
$find("RatingBhvrId1").add_EndClientCallback(function(sender, e)
{
var lblCtrl = document.getElementById('lblResponse');
lblCtrl.innerHTML = e.get_CallbackResult();
});
});
</script>
Step6: Declaring Rating1_Changed Event
protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
System.Threading.Thread.Sleep(500);
int iRate = Convert.ToInt16(e.Value);
string strMessage = string.Empty;
switch (iRate)
{
case 1:
strMessage = "Not Useful";
break;
case 2:
strMessage = "Average";
break;
case 3:
strMessage = "Useful";
break;
case 4:
strMessage = "Informative";
break;
case 5:
strMessage = "Excellent";
break;
}
strMessage = "Thanks for Rating, You found this Question " + strMessage;
e.CallbackResult = strMessage;
}

Summary View of .aspx Page

<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server">
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:Rating ID="Rating1" runat="server"
BehaviorID="RatingBhvrId1"
CurrentRating="3"
MaxRating="5"
StarCssClass="ratingStar"
WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar"
EmptyStarCssClass="emptyRatingStar"
OnChanged="Rating1_Changed"
ToolTip="Please Rate!"
style="float:left;">
</cc1:Rating>
<br />
<span id="lblResponse" class="heading"></span>
<script language="javascript" type="text/javascript">
Sys.Application.add_load(function()
{
$find("RatingBhvrId1").add_EndClientCallback(function(sender, e)
{
var lblCtrl = document.getElementById('lblResponse');
lblCtrl.innerHTML = e.get_CallbackResult();
});
});
</script>
</ContentTemplate>
</asp:UpdatePanel>

Tuesday, July 22, 2008

Regular Expression Tester

Test your Regular Expression with Regular Expression Tester. Checking your .net regular expression would be easy with Regular Expression Tester.

Regular Expression Tester

Wednesday, June 18, 2008

Universal Time Zone Importance for Web Application

Universal Time Zone Importance

A Good Article explaining What is Universal Time Zone and Why you should make use of UTC, while storing information and how it can be benefited compare to storing Local Time Zone.

This article also explains which method to follow, SQL Server's built-in getdate() function or DateTime.Now property.

Scott Mitchell had ended the article very nicely by giving a good explanatory example.

Click here for UTC article with Asp.net and SQL Server

Sunday, June 15, 2008

DropShadowExtender AJAX Dynamic Length Problem and Solution

DropShadowExtender AJAX Dynamic Length Problem and Solution

When you are using AJAX Control Toolkit Control DropShadowExtender, you might run into problem when you are trying to increase length of pannel control dynamically.

A Real Time Scenario: I have assign DropDownExtender to my Login Control pannel, but when i tried to display ValidationSummary error, its run into problem.

Before Validation Fires everything runs smooth.


Problem starts when you try to display Validation Summary message in pannel.


So the solution is

Just add TrackPosition="true" in your DropDownExtender control definition.

so it should finally look something like below code.



<cc1:DropShadowExtender ID="DropShadowNewUser" runat="server"







TargetControlID="pnlNewUser" Opacity="75" Radius="6" Rounded="true"







TrackPosition="true">







</cc1:DropShadowExtender>

Wednesday, June 11, 2008

HTTP compression Improves performance

What is HTTP compression?
The overall goal of HTTP compression is to reduce the number of bytes that must be transmitted over the tubes between your server and the user's machine. Since transmission time is often the slowest bottleneck in loading a page, and since bandwidth directly relates to your costs as a site operator, reducing the bytes you transmit to the user can save you money and improve your site's performance.

HTTP Compression in asp.net

Read more in depth on


Few more good links on HTTP Compression with Asp.net, C#

Tuesday, June 03, 2008

Convert Word Document to HTML, PDF, and other formats

Convert Word Document to HTML, PDF, and other formats

You can convert word document to PDF, HTML and many other formats with google document it is simple and free service.

I have created a sample document for conversion


Convert Word Document in PDF Format







Word document in PDF format with all the formatting available.






Word Document converted in HTML Format

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape