Wednesday, March 10, 2010

Real nice menu code

Making a note of this site for future...

Pretty cool menu effects.. Might use it in the new IAI design..

Sexy Drop Down menu with jQuery

A back button for asp.net pages


For my app I needed a back button. Internet explorer and other browsers have back buttons, most mice have them as well but I needed my own small link to drop on my forms. Implementing it was no big deal, given you consider one essential quirk. After browsing around on the web I consider it worthwhile to share my findings.

The essential thing is what back really stands for. When an user is working with an aspx page she will regularly post back to the page leading to many renderings of the same url. By default back is back to the previous request. An application like Community Server (which is an asp.net app) works this way. Write you comment and click submit. When you click the back button of your mouse after that you'll be back editing the comment. When you click submit again it might look like you 're posting an updated comment. In reality CS does receive a new comment. (Don't try this at home, to prevent comment spamming CS blocks posting comments in that pace). To give the user a better user experience thesmartNavigation property of an asp.net webform comes to the help. Setting it to true will redirect the user to the previous page when the back button is clicked. It does this by some script magic. Alas smartNavigation can play some nasty tricks on you when you try to redirect from a page which has it enabled.

In code you can see from which url the user came in the UrlReferrer property of the Request.. This always show the url of the last roundtrip, whether smartNavigation is switched on or off. So it will be the url of the page itself on a postback. On the first rendering of the page it will contain the intended page the user came from. So checking postback in combination with the referrer should do to find the desired url. The url has to be stored over roundtrips. On the best example I found on the web, by master of mysteryJuval Löwy, it is stored in the session. This is a full demo ((free) registration required) where clicking a linkbutton performs a redirect to an URL. But besides problems with smartnavigation I think the viewstate would be a better place to store the url than the session.

I use a plain HyperLink. The essence of my back link boils down to

private void Page_Load(object sender, System.EventArgs e)
{
if (! IsPostBack)
HyperLink1.NavigateUrl = Request.UrlReferrer.AbsoluteUri;
}

The NavigateUrl is set on the first request and will be saved over roundtrips in the viewstate.

As I am a bad and a lazy typist I don't want to code these lines again and again. Let's make it a custom control. Take these steps:

  • Add a new project, a Web ControlLibrary
  • Delete the webusercontrol1
  • Add a new item to the library, a Web Custom Control. Give it a real name
  • Delete all generated implementation code
  • Copy in this code
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace ButonBacklLibrary
{
///
/// Summary description for MyBackButton.
///

[ToolboxData("<{0}:MyBackButton runat=server>")]
public class MyBackButton : System.Web.UI.WebControls.HyperLink
{
protected override void OnLoad(EventArgs e)
{
if (! Page.IsPostBack)
base.NavigateUrl = Page.Request.UrlReferrer.AbsoluteUri;
base.OnLoad (e);
}

[Browsable(false)]
public new string NavigateUrl
{
get
{
return base.NavigateUrl;
}
}
}
}

The MyBackButton inherits from the HyperLink control. In the overriden OnLoad method the code to get the referral url is executed and stored in the NavigateURL property of the base, HyperLink, class. It no longer makes sense to manipulate the NavigateURL property of the back control in the designer or from code. I cannot override the property as it is not virtual. Using the new keyword the original property is shadowed. In code and in the designer my version of the property named NavigateURL is used. The implementation of the property can still get to the inherited property. The property getter just reads the base property, but the setter property has gone. I can no longer change the URL from code. By setting the [Browsable(false)] attribute on the property it will also be gone from the property window in the designer.

To get this button into the VS toolbox:

  • Right click the toolbox
  • Choose Add/Remove items
  • In the dialog click the browse button
  • Select the library we just built It's the dll in the bin\debug or bin\release directory
  • The control will show up in the toolbox.

You can start using the control in you project. Debugging works well, breakpoints set in the control's source will be hit.

Now you have a back button which is independent of the smartNavigation and session settings. But it does need the viewstate. Fiddling with that is another story.

Friday, February 5, 2010

C# questions

HOLY MOTHER OF GOD

Saw these questions on http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx

And didnt know any of these....

My goal is to answer 5 questions out of these each day...

What Great .NET Developers Ought To Know

Everyone who writes code

  • Describe the difference between a Thread and a Process?
  • What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
  • What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
  • What is the difference between an EXE and a DLL?
  • What is strong-typing versus weak-typing? Which is preferred? Why?
  • Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.
  • What is a PID? How is it useful when troubleshooting a system?
  • How many processes can listen on a single TCP/IP port?
  • What is the GAC? What problem does it solve?

Mid-Level .NET Developer

  • Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.
  • Describe what an Interface is and how it’s different from a Class.
  • What is Reflection?
  • What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
  • Are the type system represented by XmlSchema and the CLS isomorphic?
  • Conceptually, what is the difference between early-binding and late-binding?
  • Is using Assembly.Load a static reference or dynamic reference?
  • When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
  • What is an Asssembly Qualified Name? Is it a filename? How is it different?
  • Is this valid? Assembly.Load("foo.dll");
  • How is a strongly-named assembly different from one that isn’t strongly-named?
  • Can DateTimes be null?
  • What is the JIT? What is NGEN? What are limitations and benefits of each?
  • How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
  • What is the difference between Finalize() and Dispose()?
  • How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
  • What does this useful command line do? tasklist /m "mscor*"
  • What is the difference between in-proc and out-of-proc?
  • What technology enables out-of-proc communication in .NET?
  • When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

Senior Developers/Architects

  • What’s wrong with a line like this? DateTime.Parse(myString);
  • What are PDBs? Where must they be located for debugging to work?
  • What is cyclomatic complexity and why is it important?
  • Write a standard lock() plus “double check” to create a critical section around a variable access.
  • What is FullTrust? Do GAC’ed assemblies have FullTrust?
  • What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
  • What does this do? gacutil /l | find /i "Corillian"
  • What does this do? sn -t foo.dll
  • What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
  • Contrast OOP and SOA. What are tenets of each?
  • How does the XmlSerializer work? What ACL permissions does a process using it require?
  • Why is catch(Exception) almost always a bad idea?
  • What is the difference between Debug.Write and Trace.Write? When should each be used?
  • What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
  • Does JITting occur per-assembly or per-method? How does this affect the working set?
  • Contrast the use of an abstract base class against an interface?
  • What is the difference between a.Equals(b) and a == b?
  • In the context of a comparison, what is object identity versus object equivalence?
  • How would one do a deep copy in .NET?
  • Explain current thinking around IClonable.
  • What is boxing?
  • Is string a value type or a reference type?
  • What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?
  • Why are out parameters a bad idea in .NET? Are they?
  • Can attributes be placed on specific parameters to a method? Why is this useful?

C# Component Developers

  • Juxtapose the use of override with new. What is shadowing?
  • Explain the use of virtual, sealed, override, and abstract.
  • Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
  • Explain the differences between public, protected, private and internal.
  • What benefit do you get from using a Primary Interop Assembly (PIA)?
  • By what mechanism does NUnit know what methods to test?
  • What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
  • What is the difference between typeof(foo) and myFoo.GetType()?
  • Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
  • What is this? Can this be used within a static method?

ASP.NET (UI) Developers

  • Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.
  • What is a PostBack?
  • What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
  • What is the element and what two ASP.NET technologies is it used for?
  • What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?
  • What is Web Gardening? How would using it affect a design?
  • Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?
  • Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?
  • Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?
  • Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.
  • What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?
  • Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.
  • Explain how cookies work. Give an example of Cookie abuse.
  • Explain the importance of HttpRequest.ValidateInput()?
  • What kind of data is passed via HTTP Headers?
  • Juxtapose the HTTP verbs GET and POST. What is HEAD?
  • Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.
  • How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?
    Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.
  • How does VaryByCustom work?
  • How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 (as in http://localhost/page.aspx?q=5)?

Developers using XML

  • What is the purpose of XML Namespaces?
  • When is the DOM appropriate for use? When is it not? Are there size limitations?
  • What is the WS-I Basic Profile and why is it important?
  • Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace.
  • What is the one fundamental difference between Elements and Attributes?
  • What is the difference between Well-Formed XML and Valid XML?
  • How would you validate XML using .NET?
  • Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes("//mynode");
  • Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)
  • What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.
  • What is the difference between an XML "Fragment" and an XML "Document."
  • What does it meant to say “the canonical” form of XML?
  • Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?
  • Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
  • Does System.Xml support DTDs? How?
  • Can any XML Schema be represented as an object graph? Vice versa?

Tuesday, January 19, 2010

Tip! Use the Document Map

Once you have applied your Heading styles, choose View > Document Map. You can now see roughly what will be included in your Table of Contents.
Right-click in the Document Map to choose which levels of heading to view.

Problem: Length of text, ntext, or image data (x) to be replicated exceeds configured maximum 65536.

Problem: Length of text, ntext, or image data (x) to be replicated exceeds configured maximum 65536.

This message occurs when you attempt to insert into a text, ntext, or image column that is published in a replication article.

Solution: Use sp_configure to increase 'max text repl size'

The default value for the maximum configuration size is only 65536. Once it's increased, the insert can proceed. To increate the size execue sp_configure on 'max text repl size'. This stored procedure does the job:

CREATE PROC usp_CONFIGURE_ReplicationSizeForBlobs

@NewSize int = 100000000

/*
* Sets the 'max text repl size' instance wide configuration setting
* that governs the maximum size of an image, text, or ntext column
* in a replicated table.
*
* Example:
exec usp_CONFIGURE_ReplicationSizeForBlobs default
**********************************************************************/
AS

print 'Old size'
exec sp_configure 'max text repl size'

print ' Setting new size'
exec sp_configure 'max text repl size', @NewSize

print 'Reconfiguring'
RECONFIGURE WITH OVERRIDE

print 'New size'
exec sp_configure 'max text repl size'

& is bad bad bad

When transmitting XML through asp.net web service, it doesnt like "&"

So make sure and replace it with AND !!!

Tuesday, November 24, 2009

GridView with CSS

<asp:GridView ID="gvShowCourses" runat="server" AutoGenerateColumns="false" CssClass="Grid" AlternatingRowStyle-CssClass="AlternatingItem"></asp:GridView>
and in the css file add the following style :

.Grid{ border:none; color:#333333; width:100%; }
.Grid tr{ vertical-align:top;}
.Grid th {background-color:#990000;font-weight:bold;color:White;padding:5px;}
.Grid td {background-color:#eeeeee;font-weight:normal;color:#333333;padding:5px;}
.AlternatingItem td{background-color:#FFFFFF;font-weight:normal;color:#333333;padding:5px;}

Difference between textarea and all other controls

When disabling the controls on the form.. remember:

All the other controls like text and button and dropdrownlist, you set Enabled= false.

But with textarea, you set Disabled = true;

Do not know why that is different.

Clear dropdown index...

Finally found the solution to the following error :

Server Error in '/' Application.
Cannot have multiple items selected in a DropDownList.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Cannot have multiple items selected in a DropDownList.

Solution:
You just set the dropdownlist.SelectedIndex = -1;

Thats all folks !!!


Friday, August 28, 2009

using COALEASE in t-sql

So, you have text you want to select for all the rows of a table, almost similar to AVG function for numbers

Here is the solution I found, thanks Viper

DECLARE @AllNotes varchar(4000)

SELECT @AllNotes = COALESCE(@AllNotes + ', ', '') + (Notes + ' (added by ' + addedby + ')')
FROM   Ranking
WHERE  scholarshipID=52

PRINT @AllNotes

Monday, July 6, 2009

ASP.net 2.0 memberships issue

I was trying to install and run the memberships and roles DB from asp.net 2.0 and had the following error show up repeatedly

An error was encountered. Please return to the previous page and try again.

The following message may help in diagnosing the problem: An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 5110 and the SqlException message is: The file "S:\APP_DATA\ASPNETDB_TMP.MDF" is on a network path that is not supported for database files. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. Creating the ASPNETDB_1735c56c9fbe43928ee626f81923d937 database... at System.Web.Administration.WebAdminPage.CallWebAdminHelperMethod(Boolean isMembership, String methodName, Object[] parameters, Type[] paramTypes) at ASP.security_users_adduser_aspx.PopulateCheckboxes() in c:\Windows\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles\Security\Users\addUser.aspx:line 28 at ASP.security_users_adduser_aspx.Page_Load() in c:\Windows\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles\Security\Users\addUser.aspx:line 22 at System.Web.Util.CalliHelper.ArglessFunctionCaller(IntPtr fp, Object o) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

So, after hours of research and tonnes of googling, here is what resolved my issues

My web.config has following setup now


If you do this the SqlRoleProvider will be lost and cannot connect to the database. If you did this you have to supply a cutom role provider thru your web.config like this one,
< enabled="true" defaultprovider="CustomizedRoleProvider">
<>
< add name="CustomizedRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="AnotherLocalServer" / >
< /providers >
< /roleManager >







Friday, April 24, 2009

dekh lo Khvaab magar Khvaab kaa charchaa na karo

dekh lo Khvaab magar Khvaab kaa charchaa na karo
log jal jaayenge suuraj kii tamannaa na karo

vaqt kaa kyaa hai kisii pal bhii badal sakataa hai
ho sake tum se to tum mujh pe bharosaa na karo

kirchiyaan TuuTe hue aks kii chubh jaayengii
aur kuchh roz abhii aaiinaa dekhaa na karo

[aks = reflection]

ajnabii lagne lage Khud tumhen apnaa hii vajuud
apne din raat ko itnaa bhii akelaa na karo

Khvaab bachchon ke khilaunon kii tarah hote hain
Khvaab dekhaa na karo Khvaab dikhaayaa na karo

be-Khayaalii men kabhii uNgaliyaa.N jal jaayengii
raakh guzare hue lamhon kii kuredaa na karo

mom ke rishte hain garmii se pighal jaayenge
dhuup ke shahar men "Aazer ye tamaashaa na karo

Wednesday, January 14, 2009

इक इंतज़ार सा था अब नज़र में वो भी नहीं

इक इंतज़ार सा था अब नज़र में वो भी नहीं
सफर में मरने की फुर्सत थी घर में वो भी नहीं

ज़रा मलाल की ज़ुल्मत को टालने के लिए
कई ख़याल थे अब तो असर में वो भी नहीं

[malaal = sorrow/anguish; zulmat = darkness; asar = effect]

जो संग -ओ -खार थे मेरी ही गर्दिशों तक थे
मैं रह -गुज़र में नहीं रह -गुज़र में वो भी नहीं
[sang = stone; Khaar = thorn]

थे चश्म -ऐ -बाम नगर में अजब तुलू के रंग
वो इक निशात -ऐ -सहर था सहर में वो भी नहीं
[tuluu = dawn; nishaat-e-subah = happiness of dawn]

रहे न कुछ भी मगर ये कैफ क्या कम है
जिस आगही की कमी थी हुनर men वो भी नहीं
[kaif = intoxication; aagahii = forewarning; hunar = skill]

Wednesday, December 3, 2008

Apne man mein hi achanak yun safal ho jayenge

Apne man mein hi achanak yun safal ho jayenge
Kya khabar thi aapse milkar hum gazal ho jayenge
Yeh kise maloom tha woh waqt bhi aa jaayega
Ki aap meri zindagi ke rashifal ho jayenge
bhor ki pahli kiran ki tarah ek baar hum ko dekh lo
hum bhi khil kar muskura kar ek kamal ho jayenge

Monday, November 10, 2008

shayari

http://www.funonthenet.in/component/option,com_smf/Itemid,36/action,profile/u,29683/sa,showTopics/start,40

Thursday, November 6, 2008

Office is fun sometimes !!

I now know why people hate me...

Jason: I am going to Vaccuum my cubicle
Me: I will too

Abhi's Messanger Status - My cubicle is clean
Jason's Messanger Status - My cubicle is cleaner
Abhi's Messanger Status - Jason is a show-off
Jason's Messanger Status - Abhi's just jealous
Abhi's Messanger Status - its not jealousy its the fact
Jason's Messanger Status - Abhi's new name is stretch

So, thats when I walked to his cubicle and sprayed him with sarah jessica parker brand perfume....

Now..
Abhi's Messanger Status - Jason smells really nice
Jason's Messanger Status - Please join "I hate Abhi" club

diiwaanaa banaanaa hai to diiwaanaa banaa de

diiwaanaa banaanaa hai to diiwaanaa banaa de
warnaa kahii.n taqdiir tamaashaa na banaa de

aye dekhanewaalo.n mujhe ha.Ns ha.Ns ke na dekho
tum ko bhii mohabbat kahii.n mujh saa na banaa de

mai.n Dhuu.NDh rahaa huu.N merii wo shammaa kahaa.N hai
jo bazm kii har chiiz ko parwaanaa banaa de

aakhir koii suurat bhii to ho Khaanaa-e-dil kii
Kaabaa nahii.n banataa hai to but_Khaanaa banaa de

"Behzad" har ek jaam pe ek sajdaa-e-mastii
har zarre ko sang-e-dar-e-jaanaa.N naa banaa de

dukh fasaanaa nahii.n ke tujh se kahe.n

dukh fasaanaa nahii.n ke tujh se kahe.n
dil bhii maanaa nahii.n ke tujh se kahe.n

aaj tak apanii bekalii kaa sabab
Khud bhii jaanaa nahii.n ke tujh se kahe.n

ek tuu harf_aashnaa thaa magar
ab zamaanaa nahii.n ke tujh se kahe.n

be-tarah dil hai aur tujh se
dostaanaa nahii.n ke tujh se kahe.n

ai Khudaa dard-e-dil hai baKhshish-e-dost
aab-o-daanaa nahii.n ke tujh se kahe.n

tumhaarii anjuman se uTh ke diivaane kahaa.N jaate

tumhaarii anjuman se uTh ke diivaane kahaa.N jaate
jo vaabastaa hue tum se vo afasaane kahaa.N jaate

[anjuman = gathering; vaabastaa = related; afasaane = tales]

nikal kar dair-o-kaabaa se agar milataa na maiKhaanaa
to Thukaraaye hue insaa.N Khudaa jaane kahaa.N jaate

[dair = temple]

tumhaarii beruKhii ne laaj rakh lii baadaaKhaane kii
tum aa.Nkho.n se pilaa dete to paimaane kahaa.N jaate

[baadaaKhaanaa = tavern/pub]

chalo achchhaa huaa kaam aa ga_ii diivaanagii apanii
vagarnaa ham zamaane bhar ko samajhaane kahaa.N jaate

'Qateel' apanaa muqaddar Gam se begaanaa agar hotaa
phir to apane-paraaye ham se pahachaane kahaa.N jaate

Wednesday, November 5, 2008

patthar ke jigar vaalo.n Gam me.n vo ravaanii hai

patthar ke jigar vaalo.n Gam me.n vo ravaanii hai
Khud raah banaa legaa bahataa huaa paanii hai
phuulo.n me.n Gazal rakhanaa ye raat kii raanii hai
is me.n terii zulfo.n kii be-rabt kahaanii hai

[berabt=incongruous/not connected]

ek zahan-e-parenshaa.N me.n vo phuul saa cheharaa hai
patthar kii hifaazat me.n shiishe kii javaanii hai

[zahan=mind; pareshaa.N=troubled; hifaazat=protection]

kyo.n chaa.Ndanii raato.n me.n dariyaa pe nahaate ho
soye hue paanii me.n kyaa aag lagaanii hai
is hausalaa-e-dil par ham ne bhii kafan pahanaa
ha.Ns kar koii puuchhegaa kyaa jaan gavaanii hai

[hausalaa=courage; kafan=shroud; gavaanaa=to lose]

rone kaa asar dil par rah rah ke badalataa hai
aa.Nsuu kabhii shiishaa hai aa.Nsuu kabhii paanii hai
ye shabanamii lahajaa hai aahistaa Gazal pa.Dhanaa
titalii kii kahaanii hai phuulo.n kii zabaanii hai

[lahajaa=style; titalii=butterfly]