A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for June, 2009

Dynamically Loading Controls in a WebPartZone

Posted by kiranpatils on June 29, 2009

Challenge:

I have configured my page to use WebPart — [Added WebpartManager,WebpartZone - Left,Center,Right]. Now, i show some list of items like Cricket Score, Current Weather….user can select one of them and when he/she says “OK”..I want to add my controls in WebpartZone..

Okay, leave this much complex i have one button on Webpart page on click of it i want to add one Calendar control to Webpartzone..How can i do this??

Solution:

you can do easily using following piece of code:

Calendar calendar = new Calendar();
GenericWebPart gwp = wpm.CreateWebPart(calendar); //wpm = Webpartmanager
//OR to get current webpartmanger use :
WebPartManager.GetCurrentWebPartManager(Page) method
//Add Webpart
wpm.AddWebPart(gwp,wpzb,i); //webPart,WebpartZone,ZoneIndex

HTH :)

Links:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.webpartmanager.addwebpart.aspx

Happy Programming!!:)

Calendar calendar = new Calendar();
GenericWebPart gwp = wpm.CreateWebPart(calendar); //wpm = Webpartmanager
//OR to get current webpartmanger use :
WebPartManager.GetCurrentWebPartManager(Page) method
//Add Webpart
wpm.AddWebPart(gwp,wpzb,i); //webPart,WebpartZone,ZoneIndex

Posted in WebParts | Leave a Comment »

Tableless WebParts and WebPartZones

Posted by kiranpatils on June 29, 2009

Challenge:

Before couple of days, I was working on WebParts and Webpartzones..Obviously for creating personalized portal for users. I finished it and now it is going for getting some cosmetic touch[CSS :) ]..But we found that WebPart is rendered as TABLE.. But we wanted to render it as <DIV>…I tried the whole web. i found so many ways like

1.control adapters — Not a 100% Solution :(

2. http://eksith.wordpress.com/2008/06/26/tableless-webparts/ — I was unable to implement it for me :( — But thanks from his comment part – i found the solution from there only.

Before looking at solution let us dig more how webaprts works;

When I add a WebPartZone on my page, this control will rendered using <table>
like this :

<table cellspacing="0" cellpadding="0" border="0" id="WebPartZone1">
<tr>
<td style="height: 100%;">
<table cellspacing="0" cellpadding="2" border="0" style="width:
 100%; height: 100%;">
<tr>
<td style="height: 100%;"></td>
</tr>
</table>
</td>
</tr>
</table>

and then I add a label as a webpart we will see the source code like this

<table cellspacing="0" cellpadding="0" border="0" id="WebPartZone1">
<tr>
<td style="height: 100%;">
<table cellspacing="0" cellpadding="2" border="0" style="width:
 100%; height: 100%;">
<tr>
<td>
<table cellspacing="0"
 cellpadding="2" border="0" id="WebPart_gwpLabel1"
 style="width: 100%;">
<tr>
<td>
<table cellspacing="0" cellpadding="0"
 border="0" style="width: 100%;">
<tr>
<td id="WebPartTitle_gwpLabel1"
 style="width: 100%; white-space: nowrap;">
 <span
 title="Untitled">Untitled</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding: 5px;">
 <span
 id="WebPartManager1_gwpLabel1_Label1">Hello World</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding: 0; height: 100%;"></td>
</tr>
</table>
</td>
</tr>
</table>

As you can see that Webpart — Label is placed under <td>

I am looking for something like this:

</div>
<div>
<div id="WebPartZone1">
<div id="WebPart_gwpstuff1">
<div id="WebPart_gwpstuff1">
<div>
 <span>Untitled</span></div>
<div>
<div>
<span id="WebPartManager1_gwpLabel1_Label1">Hello World</span></div>
</div>
</div>
</div>
</div>
</div>
<div>

Solution:

After investing so much of my time..i found something which works 100% for me...I hope it will work for you also..

It is here :

http://www.coderesearchcenter.com/post/TFRPortal-CSS-friendly-web-parts.aspx

Thanks/hats off to Jeff for such a nice piece of work..

Above one will not work with FireFox but it has steps how you can use the control within your application..And for firefox he only fixed the problem --

http://www.coderesearchcenter.com/post/TFRPortal-is-now-FireFox-friendly.aspx

So just grab it with source code and enjoy!! -- Pls don't forget to say thanks to Jeff for such a brilliant work!!

I have modified Jeff's code for CustomVerbs -- other than that it works like a charm!!

Hope this helps....

Links :

http://www.coderesearchcenter.com/post/TFRPortal-is-now-FireFox-friendly.aspx

http://forums.asp.net/t/987744.aspx?PageIndex=1

http://eksith.wordpress.com/2008/06/26/tableless-webparts/

Posted in WebParts | 2 Comments »

New Milestone : MCTS Web(70-528)

Posted by kiranpatils on June 27, 2009

Hi there, Whomsoever who keeps visiting my blog regularly i have a great news to share with you all…I have cleared MCTS – WEB 70-528 last week[Monday 22-June-2009] with 965/1000. Certificate is hanged on here:MCTS-Web

It has been really a great journey to achieve this. I purchased self placed training kit book while i was @ Baroda then i have been moved to Bangalore for work assignment and there i didn’t got time to clear it as busy schedule :) . Now i am back to Baroda and i firmly decided to give in June[I decided on 15th June but because of deadline @ work it got delayed on 22nd].

Thanks a lot for all of them who wished me and boosted me up :) Cheers!

If you are not clear about Microsoft certification and have some FAQ’s that how it will benefited to you and stuff like that then please go and visit :

http://www.microsoft.com/learning/en/us/certification/cert-default.aspx

See this document it covers certification benefits for employee and employer:

http://download.microsoft.com/download/F/7/3/F7395EE6-5642-4AB9-A881-786D0350E88D/Skills_Development_White_Paper_2009.doc

See how many peoples are certified. I guess you must like to be counted in them :)

http://www.microsoft.com/learning/en/us/certification/cert-overview.aspx#tab5

Here is the snap which shows path for MCPD on MS VS 2005 Path :

MCPD 2005 Path

I would love to see if some one come up with the similar path image for MCPD on Microsoft Visual Studio 2008…Would you like to do it for me? yes you..

So the picture given above might clear your picture regarding certification :) [I had penned down it on my own so correct me if i missed something]

So choose any certification exam[I suggest to start you can start with 70-536 – I call it “Entrance exam” as it opens so many doors if you give just one exam – And it is valid/required for MS VS 2008 exam also :) purchase a book for the same/download the PDF from Web and start reading it..

Read the book twice and register your self at your nearest prometric center to give an exam..

Basic exam rules:

Total Questions : 45

Total time : 150 Minutes

Minimum Passing Score : 700

What Certificate i get if i give any exam? What does it stands for?

MCP = Microsoft Certified Professional

MCTS = Microsoft Certified Technology Specialist

MCPD = Microsoft Certified Professional Developer

MCP = 70-536/Any first exam you give

MCTS = 70-536 + 70-526/70-528/70-529

MCPD = MCTS + 70-548/70-547/70-549

Certification I hold currently

MCP(rgb) MCTS(rgb)_513

MCTS_WINDOWS 

If you have any query please feel free to post me comment here. I would be happy to reply them.

Happy Programming!

Imagination is everything. It is the preview of life’s coming attractions.–Albert Einstein

Posted in Milestones | 31 Comments »

How to Break Recursive function?

Posted by kiranpatils on June 26, 2009

Challenge:

I have one Recursive function which  should check for some condition if it matches then return true. But after match what it does it calls itself from last call stack. Means

Call 1

Recursive Call1 — -Here condition matches and i say retrun true; //expected result is it should stop executing the function. But it calls last Call 1 from Call stack — This is what i understood from the Web resources…some one can correct me if i am wrong :)

Solution:

Problem is fine but what’s the solution????..Here is the way i did it[Just for demonstration purpose]:


/// <summary>
 /// Counter Variable
 /// </summary>
 static int counter = 1;

 /// <summary>
 /// IsValid or not flag
 /// -- Keep it static else it won't work
 /// </summary>
 static bool isValid = false;

 private static void MyRecusiveFunction(int p)
 {
 //RESET STATIC VARIABLE TO FALSE
 isValid = false;

 //if condition matches
 if (counter == 2)
 {                
 //return true;
 //COMMENTED as it was not effective for returning
 //Earlier method return type was BOOL now it has
 //been replace with void as we can access static
 //variable from anywhere
 isValid = true;                
 }

 //if condition not achieved
 if (counter < p)
 {
 counter++;
 MyRecusiveFunction(p++);
 }

 }

Basic idea is using static variable and setting it when match found :)

Links :

http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=37288


Posted in .NET | Leave a Comment »

Can I have a Switch Statement with more than one Case Criteria?

Posted by kiranpatils on June 23, 2009

Challenge:

How can i put more than one criteria for switch case??…I would like to achieve the below things:

if((condition1 == true) || (condition2 == true))
 {

 //I am inside..

}

How to do this with switch? Here is the way…

Solution:

//For C# Champs
switch (Nationality)
{
case "Indian":
case "Ind":
//Hey i am Indian
break;
}
‘For VB Champs
Select Case temp
 Case "Indian", "Ind"
 'Hey i am Indian
 Exit Select
End Select

Posted in .NET | Leave a Comment »

New Password should not be same as old password with ChangePassword Control

Posted by kiranpatils on June 9, 2009

Challenge:

You have dropped ChangePassword Control which allows user to change password. User will provide Current Password, New Password. But you want that New Password can’t be same as Old password..for security reason…how can you do this?

Solution:

1. Hook onchangingpassword-[Occurs before the password for a user account is changed by the membership provider]. event of ChangePassword Control:

<asp:ChangePassword ID="ChangePassword1" runat="server"
onchangingpassword="ChangePassword1_ChangingPassword">
</asp:ChangePassword>

2. In Handler compare password:

protected void ChangePassword1_ChangingPassword(object sender, LoginCancelEventArgs e)
{
if (<span style="color:#000000;">ChangePassword1.CurrentPassword == ChangePassword1.NewPassword)</span>
{
//TODO Show Message
//Cancel the event

e.Cancel = true;//set it to true else it will show the msg as well as change the password also
}
}

Happy Programming!!:)

Posted in ASP.NET, ASP.NET Controls | 5 Comments »

Logout problem or Back Button Problem after signout

Posted by kiranpatils on June 8, 2009

Challenge:

1. You are using ASP.NET’s Form Authentication

2. All your pages[Except Login :) page] should be accessible only to authenticated users?

3. You have signout/Logout button where you are doing like this:

4. Now user is logged out and viewing the Login page and if he/she tries to go Back using Back Button of Browser…they can access it [Hoohh..its loophole] Or if some expert user is using your application directly plays with address bar and say /MyAccountSummary.aspx[Nooooooo] and he/she can access the page..

Now you must be wondering that i have logged out the user using standard ASP.NET Methods then also how can user access the secure items?? Don’t get excited and say it is “BUG IN ASP.NET”…[Pls note my words there are so so so less chance you will find a bug in Microsoft's Framework]..So before pointing them out we should have our fundas clear :)

Solution:

Okay, let me tell you why the strange behavior is..It is because of Client Side Browser caching…Browser Guys to improve the performance they cache the pages at client machine..So, user is accessing whatever secured item after Logout it is coming from cache….server is not aware about it[else he is smart enough to stop this:)] …So, Let’s stop this Client Side Browser Caching by following Code:

you can try this to put in your pages: Page_Load – which you don’t want to be cached by client side:

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

That’s it :)

Before going for celebration Please see some of my best practices

As per the OOPs Guy i suggest that create a page/Class[NoCachePage.CS] known as “NoCachePage” which derives directly from System.Web.UI.Page looks like as following:

/// <summary>
/// Author : Kiran Patil
/// Date   : 08-June-2009
/// Description: This Page will be used to act
///              as a base page for all the pages
///              which should not get cached at client
///              side
/// </summary>
public partial class NoCachePage : System.Web.UI.Page
{
    /// <summary>
    /// This function will be used to load
    /// initial data for a page
    /// </summary>
    ///
<param name="sender">Page</param>
    ///
<param name="e">EventArguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore(); 

    }
}

Now all your applications page which should not get cached at Client Side derive it from NoCachePage. Looks like following:

/// <summary>
/// Author : Kiran Patil
/// Date   : 08-June-2009
/// Description: This Page will be used to load
///              Account summary of an user
/// </summary>
public partial class AccountSummaryPage : NoCachePage
{
    /// <summary>
    /// This function will be used to load
    /// initial data for a page
    /// </summary>
    ///
<param name="sender">Page</param>
    ///
<param name="e">EventArguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //secure code goes here..I can give you
        //guarantee that it is secure now..
    }
}

HTH

Please don’t forget to have a look at this link:
http://forums.asp.net/t/1432437.aspx

public partial class NoCachePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
}

Posted in ASP.NET | Leave a Comment »

Stop Wrapping using NOWRAP

Posted by kiranpatils on June 6, 2009

Challenge:

I am using repeater in that i have one column named as “EmployeeName” in which i have one record “Bill Gates” but when i view the page it shows in two lines..

Bill

Gates

I would like to see “Bill Gates” in one line..How can i do this?

Solution:

<TD NOWRAP>Bill Gates</TD>

That’s it for whatever row you want to stop wrapping add attribute NOWRAP.

Webliography:

http://www.htmlcodetutorial.com/tables/_TD_NOWRAP.html

Programming with Fun! :)

Posted in ASP.NET | Leave a Comment »

How to Access MailSettings Configuration Settings Programmatically

Posted by kiranpatils on June 5, 2009

Challenge:

I have my mail settings in web.config file in mailSettings section..like as shown below:

<system.net>
 <mailSettings>
 <smtp from=myEmail@mySite.com>
 <network defaultCredentials="true" host="mail.myhost.com" password="xxx" userName="xxx"/>
 </smtp>
 </mailSettings>
</system.net>

i like to access it in my code. How can i do that?

Solution:

In .NET World nothing is impossible[As per my thinking in real world too :) ].

 //get current application's configuration file
 Configuration configurationFile =     WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
//access mailsetting section and cast it to MailSettingsSectionGroup Class
MailSettingsSectionGroup     
mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

 if (mailSettings != null)
 {
 string form = mailSettings.Smtp.From;
 int port = mailSettings.Smtp.Network.Port;
 string host = mailSettings.Smtp.Network.Host;
 string password = mailSettings.Smtp.Network.Password;
 string username = mailSettings.Smtp.Network.UserName;
 }

Hope this helps

Happy programming!!

Posted in ASP.NET | Leave a Comment »

How to get only DATE portion out of DATETIME column in MSSQL?

Posted by kiranpatils on June 5, 2009

Challenge:

One of my colleague was writing a query to get records between start date and enddate.

SELECT EmployeeName From Employees WHERE EmployeeJoiningDate >= @startDate AND EmployeeJoiningDate<=@endDate

it was working fine but some records are not showing up in the list because it was checking time also. Which he don’t want to compare..So, how to get just date part and compare it with provided params?

Solution:

We found the way for it using

SELECT CONVERT(VARCHAR(10),GETDATE(),101) --101 = mm/dd/yyyy

it made his work simple!!. So, just convert your date and then compare..for brevity i left up to you to write a new sql statement :)

Here 101 is one of the style to get date. for list of style go to MSDN

Happy Programming!

Posted in SQL SERVER 2005 | Leave a Comment »