Tuesday, June 2, 2015

Finding which event fired(button clicked) in Page_Load or Page_Init/Page_PreInit

I was working on an app and I wanted to turn off Event Validations when a certain action was performed to Render the HTML. Keeping them on won't let me render my UserControl to an HTML file. So I wanted to capture the Event right in Page_PreInit so that I can disable Event Validation of Page. Note that this can only be done either programmatically before Page is Initialized, or as a Page directive in aspx file.

Request.Form["__EVENTTARGET"] is the variable that will capture the information for the button clicked.

One additional aspect to note is to have UseSubmitBehavior="false" for the Button Web Control to generate the value for "__EVENTTARGET".

So in your html:

<asp:Button runat="server" ID="btnDownload" UseSubmitBehavior="false" ClientIDMode="Static" Text="Download" style="display:none;" OnClick="btnDownload_Click" />

In code behind, this is what you would have:


protected void Page_PreInit(object sender, EventArgs e) 
 { 
if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"].Contains("btnDownload"))
Page.EnableEventValidation = false;//(NO INTELLISENSE!)disable event validation when the button is clicked for downloading file
}

Friday, May 15, 2015

Filtering/Grouping by multiple columns in sql subquery

I have been struggling for a while to have multiple columns in subquery and then filtering out the result.

Often with composite keys in the staging table, you want to check if there are any duplicates.

Taking an example of a fictitious "sales" table:

select * from sales where order_number in
(select order_number from sales
group by order_number, customer_id
having count(*)>1)

Above query might not give the desired results if I am looking for particular results with filters. The reason being I did not apply all the fields in the select query for the ones used in group by.

An extensible solution below takes care of that:

--Use CTE to store result for further filtering
with cte as (select s1.field1, s1.field2, s1.field3 from sales as s1
where exists
--Have a subquery for multiple column grouping. Compare it with the fields of the parent query, which would yield 1 corresponding record
(select s2.field1, s2.field2, sd.field3  from sales as s2
where s2.field1=sd1.field1 and s2.field2=s1.field2 and sd.field3=s1.field3
group by field1,field2,field3
) --Have your extra condition here for filtering
)
select * from cte where reached_target='Y'  -- Get all those qualified records needed

In this case, Common Table Expression (CTE) does come in very handy to filter out the final resultset.

Tuesday, April 21, 2015

Defining and using Server variables in the html head section of page

My browser was caching the javasscripts and css and it gets annoying when you are multiple design changes to code. So I decided to do cache busting. I defined a Random number variable in code behind and wanted to use it in html <head> so that every time a request is made, the browser takes it as a new request to the server with a fresh copy of styles and javascript files. The solution is a little quirky, but works:

     <link href="mystyle.css?rn=<%="" +Rand %>" type="text/css" rel="stylesheet"/>

where:
rn : is variable for Random Number
Rand : is server side generated Random number

Considering the Random number generated as 1234, the output would be like below:

     <link href="mystyle.css?rn=1234" type="text/css" rel="stylesheet"/>


Note: Use this for development only. Caching is always good to have in production to speed up loading times. With any new build of css/javascript, a version number can be assigned to get a fresh copy.

Wednesday, October 23, 2013

Doing a LoC count in Visual Studio

I just wanted to know how many lines of Code do I have in my Solution. Here's a nice trick posted by a fellow blogger that uses Regular Expressions. Way to go! Quick and Easy!

http://blog.schuager.com/2009/01/line-count-in-visual-studio.html

Basically, search for the Following Regex in the solution:

^~(:Wh@//.+)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@/#).+

Wednesday, October 2, 2013

Using Razor syntax with Javascript

Following approach was done to have the razor syntax in Javascript. Wrapping the javascript <text> with does the job!

@if(Model!=null){
<text>"<span style="color: #76768d; font-size: 14px; font-weight: bold;">@Model.title</span>" +</text>
}


Although the code above looks like Razor syntax placed in HTML, this has been used in Javascript and works perfect!

Friday, September 20, 2013

Using CKEditor in your MVC project

CKEditor is an Amazing Rich Text Editor to be used in your MVC Applications. I had implemented that one of my forms and was bent over to implement it throughout the project, replacing the existing editor which was little buggy.

Implementation has been made very easy with the release of the newer version of CKEditor 4

First you need to use the HTMLHelpers to create a Text Area:

@Html.TextArea("controlid", "controlvalue")   


Then place your CKEditor javascript script below the control. This will replace the TextArea with the Editor

CKEDITOR.replace('controlid', {
                uiColor: '#808080',
                height: '120px',
                toolbar: [
           ['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'Image', 'Table'],
           ['FontSize', 'TextColor', 'BGColor', 'Source'],
                //                                ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
          ]
            });


Form submission is magically taken care of by MVC Approach on postback

But all that was not plain and simple on Ajax based submissions. I had some trouble implementing it on one of the Ajax based forms. This is what I did based upon the CKEditor API
the click of the submit button.

$(document).ready(function() {

    $("#btnSubmit").click(function(){

        $("#controlid").val(CKEDITOR.instances["controlid"].getData());

    });

});


And I had Success at last!

Wednesday, August 7, 2013

Using Jquery and JQuery UI inside AJAX UpdatePanel

I wanted to call a JQuery "alert" on the Click event of a button, which was also a Trigger to an Update Panel. My condition for the alert was in code behind. For those who experienced this, JQuery/javascript doesn't work nicely with UpdatePanel

Searching on Google led me to the solution below and it works as expected!

protected void btnPrevious_Click(object sender, ImageClickEventArgs e){ 
     int curpageindex=-1;
     if ((int)ViewState["Pageindex"] > 0)
     { 
         //Your code
         BindData();
     }
     else if ((int)ViewState["Pageindex"] == 0) 
         ScriptManager.RegisterStartupScript([updatePanelId], this.GetType(), "click", "firstrecord();", true);                       }
 
Please bear in mind that ScriptManager is the Ajax ScriptManager that has different overloading Parameters, one of them being a reference to the UpdatePanel.

Here's a nice explaination of how this works.

Monday, June 3, 2013

Using Mercurial as a preferred Source Control

I needed a Source Control to track changes in my projects, I have been hearing good things about Mercurial and its integration into Visual Studio 2010 with the tools like TortoiseHg and VisualHg. Not to mention that Mercurial is an Open Source software and available for free download. Mercurial is a Distributed Version Source Control (DVCS) where each client has entire copy of the repository.

Got a jump start on Installing and integrating Mercurial with a great video here, which shows all the installing as well as configuration process.

Mercurial can be downloaded here.

Its fun to work with Mercurial using the Command line too, though the GUI does take care of your needs. Here's a neat list of commands to execute your changes:

http://searchco.de/lists/list-of-mercurial-commands

One of the important commands that I would like to remember is in below example, which fetches me the changeset along with the filename. I can also specify the range of the changeset. In the example shown, the command will fetch the changes between the changesets 1 and 10.

hg log --stat -r 1:10


I also would like to include the .hgignore file which is quite handy for committing the changes to the repository.

# use glob syntax
syntax: glob

*.obj
*.pdb
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.scc
*.DotSettings
[Bb]in
[Dd]ebug*/**
obj/
[Rr]elease*/**
_ReSharper*/**
NDependOut/**
packages/**
[Tt]humbs.db
[Tt]est[Rr]esult*
[Bb]uild[Ll]og.*
*.[Pp]ublish.xml
*.resharper
*.ncrunch*
*.ndproj


Enjoy!

Wednesday, May 8, 2013

Passing down a string with an apostrophe to javascript function

Its like back to  Javascript 101, but sometimes its forgotton and takes up some time to identify whats wrong with the script. Thats what happened to me. I wasn't sure how would I parse my string. Finally got an answer.

 Edit Content

The escape character takes care of the apostrophe, and the HtmlDecode takes care of any browser based compatibility issues

Tuesday, April 16, 2013

Connecting to a Remote SQL Server and Import Data from your local SQL Server (2008 Express)

I have a remote database sitting on VPS and I need to transfer the data to the remote server. All I do is first register/connect the remote Sql server in my Management Studio. For this, enter the provided server name using the registered domain name (or IP Address)  along with the provided port number. Append the Sql server name (I appended \SQLExpress).

Doing this will enable you to connect the remote server in your local management studio (assuming you enter the correct authentication details for username/password !).

Before you go ahead with the next step of doing data migration, make sure first you run the database scripts so that your indexes/foreign keys are intact. Once this is done, you can use the import/export wizard to export data from your local machine to the remote server. A tiny trick is to use the import wizard from the destination database rather than using the export wizard from the source database. This will ensure your configuration for destination database is aptly configured.

Sorry this is very bland write-up without any screenshots or proper explanation, but hopefully I'll provide them when I have more time.



Thursday, April 4, 2013

Profiler for SQL Express

I have SQL Express currently installed on my machine. Since I am working on the "free" version, the package doesn't include SQL Profiler. I highly depend on SQL Profiler to trace down queries. What to do now? Well, Google is my friend! I found this utility, available on Codeplex. Download and use it!

Tuesday, April 2, 2013

Links to Bookmark and Follow up

Some Notes on Semantic Versioning. Follow up on this, Usman! 

http://semver.org/

The World of Entity Framework :

http://msdn.microsoft.com/en-US/data/ee712907

Entity Framework Version History :

http://msdn.microsoft.com/en-us/data/jj574253









Wednesday, March 6, 2013

AJAX Caching issue in Internet Explorer (IE) 9 (way back upto IE 6)

I had been pulling my hair apart for resolving the browser compatibility issue. My MVC App has been working well in other browsers, but while doing testing, I found a notorious issue in IE. I had been hung on this issue for several hours. Tried clearing history/cache.. No luck. Tried using the cache trough developer tools (F12)... No luck.. Tried resetting the Browser to its default installation, thinking I might have accidently clicked on a setting for the browser to malfunction... No luck! restarted the machine a couple of times.... But I guess I was looking at the wrong place. Doing a google search for the correct keywords might have helped in the first place! Further research led me to find that IE caches the AJAX requests while others don't. Thats actually BAD news for me, because that gives me inconsistency in data.


Fellow internet geeks had posted a few solutions to overcome this issue:

http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9-ajax-response-caching-asp-net-mvc-3-jquery/

http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/

http://ivida.co.uk/2011/09/29/ie-9-ajax-request-caching-mvc/




This worked for me! Yay!

$(document).ready(function() {
$.ajaxSetup({ cache: false });
});

Friday, March 1, 2013

Access the Log for the scheduled processes

The log for the scheduled processes (to trace the failures) is available at:

\\WINDIR\Tasks\SchedLgU.txt

Other resources that I found on the web regarding this can be looked here:

 http://blogs.technet.com/b/rspitz/archive/2010/11/07/scheduled-tasks-appear-hung-in-the-running-state-on-windows-server-2003-based-systems.aspx

Check the following link to increase the size of the file:
http://support.microsoft.com/kb/169443

Thursday, January 17, 2013

Using Heidi as MySql Client to connect to remote server

I had to make some db modifications for one of my clients to the mysql database on the remote server. I hardly have any experience working on the php/mysql arena. Call it my lack of knowledge or understanding, but I had a hard time connecting to the remote server. I tried mysql workbench, but that would crash right when I went ahead to access the database. I was frustrated since I had to make one small change and it was sucking up my time. Then someone over the internet suggested HeidiSql.

Apart from being able to "connect successfully", HeidiSql is really fast and provides and great clean UI to manage your data. Point to be noted for future refs!!

Monday, November 26, 2012

Resolving the Validation of viewstate MAC failed error

I have been receiving the following error on the page when I clicked on the link (in the Gridview) before the Page had fully loaded. My Page has a Gridview which uses DataKeyNames. Additionally it had a lot of Javascript ads which slowed down loading of the Page.

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.





On doing some research, I found out that the due to the use of GridView and the DataKeyNames, the Framework implements a ViewState Encryption Technique for keeping the data secure. Hence, when a link is clicked on a partial page load, the encryption tag might not have been rendered on the page, causing the page to crash.  

I read this excellent post which aptly details the issue and its resolution.

Basically, it appears to be some sort of bug in the existing Framework and the blog posts a workaround.

I used Solution 3 since it still was keeping the Security aspects in place which executing the page elegantly. Basically what it did was to remove the Validation script right before the end of the form tag and place it after the beginning of the Tag. 
protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        System.IO.StringWriter stringWriter =
            new System.IO.StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlWriter);
        string html = stringWriter.ToString();
        string[] aspnet_formelems = new string[5];
        aspnet_formelems[0] = "__EVENTTARGET";
        aspnet_formelems[1] = "__EVENTARGUMENT";
        aspnet_formelems[2] = "__VIEWSTATE";
        aspnet_formelems[3] = "__EVENTVALIDATION";
        aspnet_formelems[4] = "__VIEWSTATEENCRYPTED";
        foreach (string elem in aspnet_formelems)
        {
            //Response.Write("input type=""hidden"" name=""" & abc.ToString & """")
            int StartPoint = html.IndexOf("= 0)
            {
                //does __VIEWSTATE exist?
                int EndPoint = html.IndexOf("/>", StartPoint) + 2;
                string ViewStateInput = html.Substring(StartPoint,
                  EndPoint - StartPoint);
                html = html.Remove(StartPoint, EndPoint - StartPoint);
                int FormStart = html.IndexOf("", FormStart) + 1;
                if (EndForm >= 0)
                    html = html.Insert(EndForm, ViewStateInput);
            }
        }

        writer.Write(html);
    }

Friday, October 12, 2012

Hiding Tabs(MenuItem) in asp:Menu

I was working on the asp:Menu where I have to hide a certain Tab if there is no content for it. This is what I did. I knew the index of the Tab that Had to be removed:

//tabs_Menu is the id for asp:Menu
MenuItemCollection menuitems=tabs_Menu.Items; 
menuitems.Remove(tabs_Menu.Items[1]);

Monday, July 16, 2012

Finding Duplicates and copying Excel formula to the end of data

I have an excel file that has about 100,000 records. I wanted to find out the duplicates in a particular column before removing them. So I had to mark the rows with something as an identifier. Below is what I found for the formula. So essentially if the duplicates are in Column A, this formula should be placed in an empty column(or a new column):

=IF(COUNTIF(A:A, A1)>1, "Duplicate !","")

I had to apply this formula to all the 100,000 records, and someone over the internet posted a nice example of doing this:

http://www.handyexceltips.com/2008/01/16/dragging-a-formula-down/

Very useful in those time crunches !

Thursday, June 7, 2012

Batch Update using SQL

Though this is a fairly easy process, its worth mentioning here since it is something which cannot be thought about. Using top x in your query, you could basically choose how many records need to be updated. This is helpful for processing the records as required
UPDATE top (100)  TableName 
SET
    column1 = getdate(),
    remarks = 'batch for API Upload'
 where column2 is not null and column1 > '2012-1-1'

Monday, June 4, 2012

Extract Date from DateTime Field in SQL

I was working on SQL to create a view to get the reports for our subscribers and group them by day. This is fairly easy to implement in .NET, but I have been licking SQL candies for a while and so wanted to try it out. This is how I did:
 SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
I could have used varchar converstion and "trimmed" the time value, but I had to further sort the resultset based upon the date obtained, so it was important for me to have it as a date type.