Monday, December 28, 2009

IIS 7 – Managed pipeline mode – Global.asax redirect not working

I installed Windows 7 and I really like it. I migrated all my applications from my old machine to new. And my old machine is running WS 2003 [iis 6] and new machine is Windows 7 [IIS 7]. In all applications everything ran successful except one. I implemented exception handling in my application. I have Global.asax page and in the Application_Error event, I log the exception details and redirecting the user to the error page. Whenever there is an exception in my application the page never redirect to the error page, it stays there in the same page with exception details on the screen.

The same code ran very successful on my old server and in Windows 7 it's not. I just started thinking what could be the issue. The analysis went in this way. Code not changed, DB not changed and the only part changed is the IIS. Windows 7 has IIS7. So, The problem would be either the isapi dll or the application pool. So, started researching on those and found interesting points.

In IIS 7, application pool has a separate feature named "Managed pipeline mode". This will tell the pool the pipeline mode. [which is of type sint32 in c# and the possible values for it are 0 and 1.]

  • 0 is managed pipeline runs in integration mode.
  • 1 is managed pipeline runs in classic or ISAPI mode. [IIS 6].

In Classic mode, managed application events are executed by using ISAPI. In Integrated mode, ASP.NET request processing integrates directly into the IIS 7 request-processing pipeline. Integrated mode enables you to configure managed modules for Web sites that are developed with unmanaged code.

So, to work your logic correct, go to your site and see under what application pool your site running. Now, go to that application pool, properties and change the pipeline mode to classic mode. Now, you see everything works fine and the page starts redirecting to error page when any exception in your application.

For more details: http://msdn.microsoft.com/en-us/library/microsoft.web.administration.managedpipelinemode.aspx

Hope this helps and new tip today. Do you like this post?

Sunday, December 27, 2009

SharePoint timer job and settings or configuration file

I got a question that what is the case when a SharePoint timer job needs a configuration file? Because, I really need the configuration settings for a timer job which I deployed. Because I got a requirement where I need to use the web service in a timer job and it needs the httpBindings and the endpoints. I can't place them in web.config of the web site as I can't access it here. But, I can access the web.config file as I discussed it in my previous post. I can get all the bindings and endpoints from web.config and create a c# bindngs object. And for the web service I passed the binding and that didn't solve the problem. Somehow, I got the below exception.

WSE012: The input was not a valid SOAP message because the following information is missing: action.

So, I started thinking in different ways and out of box. Below is the way how I approached towards the solution.

  • Everyone knows that all the timer job runs with the help of the OWSTIMER.EXE.
  • If you take a look at the console application, c# project and if you add the app.config file to the project then in your bin folder, you will see two files like if it is c# project then projectname.dll and projectname.dll.config and if it is console application then projectname.exe and projectname.exe.config.
  • So, what you understood from it? for dll or exe there is associated config file if that project contains app.config file.
  • What will happens when we use the dll or try to run the exe, the related config file also loads into memory and you can use the config file in the dll or exe.
  • There my thought starts and I want to repeat the same concept for the OWSTIMER.EXE too. 
  • Find the location of where OWSTIMER.EXE is reside in. Generally, the location is at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN\OWSTIMER.EXE". So, go to that location and create a file named OWSTIMER.EXE.CONFIG.
  • Open it in notepad and place all the settings code in it. Save it.
  • Now, it's time to restart the timer service. So, go to services and find SharePoint Timer Service. And restart it.
  • Now, run the timer service and you see everything is running successful. I mean all the settings will be loaded and run.

Note: Try to include all the settings in the config file within these tags.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

Hope this detailed post will help you to improve knowledge and how to think out of box. Love to hear comments.

Access web.config in SharePoint timer job

In SharePoint customization we have the requirements to write custom code for web parts, timer jobs etc. In this post I want to tell you some interesting things in SharePoint. I have written some timer jobs to deploy into my SharePoint server to match some requirements or to solve some problems.

My requirement is, I want to access the web application or web site configuration [web.config] file in the SharePoint timer job. But, the limitations in SharePoint stops me to access the configuration files in timer job. Below are the problems I faced.

  • SharePoint timer job is running in different process named OWSTIMER.EXE.
  • SharePoint web application or site will run with the help of process W3WP.EXE.
  • So, the application configuration file is associated with the W3WP.EXE, so there is no way to access the web.config file in the owstimer.exe process at all. The context is completely different and out of domain. So, we need to call or access the web.config file explicitly in timer job. How to?
  • Remember, always C# is completely object oriented and you can access everything through objects.
  • Usually the timer job installed as a feature. And all the logic of the timer job will go inside the Execute() method. So, write below statements in that method and access the complete web.config file. Below is the example of accessing appsettings.
SPWebApplication webApplication = this.Parent as SPWebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);
String appValue = config.AppSettings.Settings["appSettingKey"].Value;

WebConfigurationManager is the class which is in the namespace Systen.Web.Configuration. This way, you can access the config settings from a web.config of a SharePoint web site. Hope you understood this well and please let me know what you think.

How to get or access master page in user control

My requirement is I want to get the reference to the master page and access the public property of a master page in user control. As we know that master page is also inherited from the user control, I can say this is simple and we can easily get the reference.

I am using master page in my web application and all pages are using that master page. And there are user controls in the application and my requirement is how to access the master page property inside a user control. Below is the solution how I resolved the problem.

In user control ASCX file declare the below line to establish the reference to the master page.

<%@ Reference Control="~/DefaultMaster.Master" %>

IN the ASCX.CS file, we need to fill the master page object to access it's properties. For this,

  • Declare a master page class variable as the user control class variable as shown below.

DefaultMaster masterpage = null;

NOTE: Remember the DefaultMaster is the class of DefaultMaster.master class.

  • In Page_Load event of user control, fill the masterpage object as shown.

masterpage = this.Page.Master as DefaultMaster;

Now, you are all set to use master page object and access everything inside it. If you observed, everything is simple object model. I am just accessing the objects. I think, you got better idea and the way I used. Hope this helps and any comments always welcome.

How to get the current row in the grid view command event

This is what I faced a small problem when using GridView. I have a LinkButton element in the gridview and my goal is when user clicks on the button, I need to raise the grid view command event and in that event, I need to get the row values. But, the questions is how to get the current row in the grid view command event?  Below is the solution for it.

GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;

Note: Remember LinkButton class I used in the above code is assuming that the command event raised when clicked on the LinkButton control. If your requirement is not linkbutton then please place the corresponding control name.

Most of the times and most of the developers never use the property available to each and every object named NamingContainer. But, there are lot of advantages with this property. Especially when we write and render controls to page dynamically then this property will help a lot. And there are many properties which will help us to solve so many problems. Use the intellisense and try to know most of the properties available for a .NET control.

Hope, this will help you and you got what you need. Please let me know what you think on this post.

C# display date time with milliseconds

By default, in c# DateTime object will display the values in the 12 hours format with AM and PM. Which don't include the milliseconds. But how to display the date and time with milliseconds? Use the below format to display it.

DateTimeObject.ToString("yyyy-MM-dd HH:mm:ss.fff")

f is for the format for printing the milliseconds. Remember when you try to convert the date time with milliseconds back to C# Date time, then just use Convert.ToDateTime().

Hope this helps.

Request format is unrecognized for URL unexpectedly ending in methodname

This is the exception I am getting when I try to access web services from my web site. I just created a web service and tried to access the service from the browser using the get request. But I got the invalid operation exception. See complete exception details below:

System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/MethodName'

So, Before we will go to know the solution for it, I want to explain the reason behind this.

A .NET web service supports three protocols named HTTPGET, HTTPPOST and SOAP. When .NET released I mean, ASP.NET v1.0 all these three protocols enabled by default. So, any requests which made from the browser which belongs to a web service will be responded without any issues. But when come to ASP.NET 1.1 version the protocols HTTPGET and HTTPPOST are disabled by default. The only reason is SECURITY issue. So until you explicitly enable them no web service request will be processed if you call them in the format domain/webservice.asmx/methodname [Get/Post].

But, where as if you call direct web service from browser using SOAP request that will work and will give result what you need. But, if you make any GET or POST request then only the problem will come. 

RESOLUTION:

To enable these protocols in the application level simply we need to change the application config file. Web.config. Add below lines to the web.config to enable these protocols.


    
    
        
            
            
        
    
    

So, this webservices tag will go inside the <system.web> namespace. With the above lines, the protocols enabled and they listen the request and respond accordingly for that application. Sometimes you may need to enable these protocols in system level. I mean to all applications in the server should have these protocols enabled. Then below is the solution for it.

Find machine.config file and open it in nice editor like visual studio. Before do any changes please take a backup of the file. Now find the protocols section and add the below lines if they are not already there.






Hope, you understood it well and you are now knew the reason behind of the above exception message. Please know me the feedback.

Friday, December 11, 2009

Could not load type Microsoft.TeamFoundation.WorkItemTracking.Client.workItemTypeDeniedOrNotExistException

This is the exception we are getting when we try to view the workitems from the Team explorer in visual studio. The problem is, you installed the team explorer after you installed the Visual studio 2008 SP1. Because of this, all the workitem related dll’s are not referenced correctly. And result is below exception message.image

Resolution:

To fix this issue, we just need to reinstall the visual studio sp1. So, the order should be

  • Visual Studio
  • Team Explorer
  • Visual Studio SP1

Hope this helps to the people who are facing the same issue.

Saturday, November 28, 2009

How to detect clicked on outside of a particular div?

This is the part of my work on java script. I need to detect in my code, whether I clicked on a particular div or out of a div. So, what is the best way? Get he user clicked position and compare them with div coordinates? No that's not a good solution. Then how we need to do? Below is the best way of implementing it.

document.onclick = clickEvent;
function clickEvent(e) {
    var targ;
    if (!e) var e = window.event;

    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;

    //if (targ.nodeType == 3) // defeat Safari bug

        if (targ.nodeName != "HTML") {
        while (targ.nodeName != "BODY") {
            if (targ.id && targ.id == 'divGrid') {
                return false;
            } else {
                targ = targ.parentNode;
            }
        }
    }    //This is the place where you need to write code when you click outside of the div.
}

Hope this helps in solving some problems. Look for more.

How to detect tab key is pressed in javascript?

Recently I was working for a client and they needs plenty of functionality to be implemented in the javascript. And on the way of writing the code, I need to check whether user pressed on the tab key. When user on a particular div and hit the tab key then I need to do some logic. So, is there any event like tab clicked in javascript? NO… So,how to detect it. Below is the code I used for it.

document.onkeydown = keydown;

function keydown(event) {
        var code;
        var e;
        if (document.all) {
            if (!event) {
                var e = window.event;
                code = e.keyCode;
            }
        }
        else if (event.which) {
        code = event.which;
        e = event;
        }
        if (code == 9) {//Write some logic
        }
    }

Note: keycode 9 is for tab key.

Hope this helps you.

How to, Jquery DatePicker Enable, Disable, Remove, attach

After worked with Jquery and their related plug ins in the web applications thought of writing nice posts on rare findings.

In some requirements we need to attach and remove the datepicker to a control or to a division. So, how to attach datepicker to a control or div dynamically… After read the jquery datepicker documentation, got to know the way to do that. The same case with Remove, enable, disable… So, below are the ways to do them.

Attach:
$(".datepicker").datepicker();

Remove:
$(".datepicker").datepicker("destroy");

Enable:
$(".datepicker").datepicker('enable');

Disable:
$(".datepicker").datepicker('disable');

NOTE: The selector I used [.datepicker] is just for example…. You need to give the id or class selector according to your requirement in place….

Do you like this post? Do you want to know anything more? Please post all here….

Tuesday, November 24, 2009

Download SharePoint 2010 BETA 2

It’s the time to download the latest version of SharePoint 2010 BETA2. I am downloading and will check whether they have made any changes to the BETA1. I faced so many problems in BETA 1 as it is not giving support to import user profiles from Active Directory. Will install it today and will let you know if I find anything interesting.

http://www.microsoft.com/downloads/details.aspx?FamilyID=3ed6e43b-22da-4021-8e90-56e47536d772&DisplayLang=en

Friday, November 20, 2009

Download Sql Server 2008 R2 November CTP

Get the new version of Sql Server 2008 R2 edition and play with it. It is more enhanced version of the Sql server 2008. Just downloaded and found some options are nice. Try it out and enjoy the new features.
http://www.microsoft.com/sqlserver/2008/en/us/R2Downloads.aspx

Thursday, November 19, 2009

Silverlight 4 BETA is ready

Wow, this is completely unexpected and nice. They are calling it as a developer release. Plenty of features and tools. Check it right now.

http://www.silverlight.net/getstarted/silverlight-4-beta/

But some important points you need to know is, Silverlight 4 development is only on Visual Studio 2010. But, no problem Visual Studio 2010 can be installed side by side with Visual Studio 2008 SP1. So, get it and start play with it. Enjoy!!! with new finding and learning.

Wednesday, November 18, 2009

Installation guide SharePoint 2010

Today, I got latest build public BETA from MSDN, I installed on my laptop. So, what are the prerequisites and how to install it on the server? For this I want to post a simple, light weight post which walk you through the installation.
Before start installation, I have allocated a minimum of 50GB space for SharePoint 2010 on the hard drive. I completely cleaned/formatted it.

What is the best supported OS: Windows Server 2008 R2 [64-bit].
What is system version and hardware support: 64-bit
So, I started with installing the OS first.
STEPS:
1. Installed Windows server 2008 R2 [64-bit] on the system.
2. Enabled all features needed by SharePoint 2010. Below are the features/services.
IIS, .NET 3.5, IE Security, Wireless LAN etc. [Go to server manager and find add features]
3. Now, we need backend support, so installed Sql Server 2008.
4. What are the componets you need? Management Studio, Analysis services, BI[If Needed], Sql Server Book Online, and others as you needed.
5. Installed Sql Server 2008 SP1.
6. Now, we are ready with all the basic needs and ready to install SharePoint 2010. Start SharePoint installation file.
7. You will see the first nice screen with all the options available on the window. Now, select the option "Install software prerequisites'
8. Below are the ones it needs to proceed.
> Application Server Role, Web Server (IIS) Role
• Microsoft SQL Server 2008 Native Client
• Microsoft "Geneva" Framework Runtime
• Microsoft Sync Framework Runtime v1.0 (x64)
• Microsoft Chart Controls for Microsoft .NET Framework 3.5
• Microsoft Filter Pack 2.0
• Microsoft SQL Server 2008 Analysis Services ADOMD.NET
9. Agree the License Terms.
10. Now, you will see the preparation tool window which configures above services. So one by one all services/features will be installed successfully.
11. Now, from the main menu window, choose install SharePoint Server 2010.
12. If it asks for any product key then go to the MSDN link and check for the keys available and enter the key. If didn't ask then no problem.
13. After entered the key, it will ask you which installation you need. Standalone/Farm.
What my choice here is Standalone because, it is in BETA and first time installation so, first go for standalone. Later you can install FARM.
14. Now, you will see the progress bar installing SharePoint 2010. First it will install SharePoint 2010 and then applying updates. Which will take about 10-20 minutes.
15. We are almost completed and time for running SharePoint Products Configuration Wizard.
16. Click Next on the screen and it will give a warn that it needs some services to be restarted like IIS, SharePoint administration v4 etc.. Click OK and proceed.
17. It has all of 10 steps in the wizard, one by one slowly runs and completes. This is actually the part where the configuration database, sample data etc.. will created.
18. After completed all steps then it will automatically opens the browser with central administration application. If you see any errors in browser just do IISRESET or restart your machine once.

Note: There may be chances that you get exceptions while installing the SharePoint 2010 public BETA. Please check these posts to resolve the issues.
Exception 1
Exception 2
I hope this will help you to install the SharePoint 2010 very successfully without any problems. Please let me know, if you are facing any issues or any issues which you resolved while installing.

Microsoft.Office.Server.UserProfiles.UserProfileException: The request channel timed out

This is the continuation of Part 1. I have written a post on solving the issues while installing SharePoint 2010 in my previous post. So, As I said in my previous article, the new exception message I got in my system is below.

Microsoft.Office.Server.UserProfiles.UserProfileException: The request channel timed out while waiting for a reply after 00:00:19.9340000. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: The request channel timed out while waiting for a reply after 00:00:19.9340000. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: The HTTP request to 'https://myserver:32844/d31735f8a1b34f3a8263707181c7e298/ProfilePropertyService.svc' has exceeded the allotted timeout of 00:00:19.9990000. The time allotted to this operation may have been a portion of a longer timeout. ---> System.Net.WebException: The operation has timed out

So, what the above error message means? I also don't know anything about it at first glance. But, how did I resolv it?

I read the exception message 4 times continuously and understood again that this is the problem because of the WCF service. I copied the above given url in IE, waited for the response. But bad luck, didn't get any response.

Resolution:
As it is a service[.svc], What the idea I got here is, this path should exists some where on the file system. So, What I did? I search the file system for the file ProfilePropertyService.svc. And luckily I found the file in a location at "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\d31735f8a1b34f3a8263707181c7e298\5902e8c4\679035c5" with the file name "profilepropertyservice.svc.cdcab7d2.compiled'. So, this is what helped me and felt very happy by seeing it. You know what? First time when I ran the configuration wizard the service compiled and I was stuck because of first exception I got[Resolved in previous article.] After that I reran the configuration wizard then it again compiled but didn't updated the temporary ASP.NET files folder. So, I just did IISRESET on the server and started the configuration wizard again and everything completed successfully.

Now, I have everything setup and running. I felt very happy and started playing with SharePoint 2010. Hope this helps you to solve the problems and I think you like the way I approached to resolve these issues. Let me know your ideas and feel free to ask me if you are facing any problems.

Microsoft.Office.Server.UserProfiles.UserProfileException: Unrecognized attribute allowInsecureTransport

Today, I got SharePoint 2010 Public BETA downloaded and installed on my laptop. It is very smooth and run very fast and total size is very less. All the prerequisites ran complete and while running the Product Configuration Wizard I got an exception and below is the detailed message of it.


Microsoft.Office.Server.UserProfiles.UserProfileException: Unrecognized attribute 'allowInsecureTransport'. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config line 56) ---> System.Configuration.ConfigurationErrorsException: Unrecognized attribute 'allowInsecureTransport'. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config line 56)

There is a hotfix released on kb. Check this. http://support.microsoft.com/kb/976462

So, this is the best part of the wizard. It completely given me very clear and wonderful message so that I can understood by reading it once. So, I went to the path above given in message and looked for the client.config file.

In the section, I found the line allowInsecureTransport="true". I don't know what to do with that. Because, As it said, it is case sensitive in error message, I tried with different combinations like camel case, pascal case, all lower, all upper etc..... But nothing worked.
After thought about it for a while, I just removed the attribute from the config file and saved the config.

Now, I reran the configuration wizard, there I see that this problem won't exist any more.

So, how this worked? When I deeply look into the config file, I understood that it is the WCF service setting. So, as you all know SharePoint 14 is supporting WCF services they have implemented some services based on it. In this BETA version, somehow that attribute is missing and it's not finding by the system.

So, now I resolved the issue and didn't get this problem again. But, this time I got a new and unexcepted exception message on my screen. See this post for more details.

But above both messsages came while running 8 of 10 step in configuration wizard while creating sample data.

Keep an eye on my blog for more solutions and updates from the technologies you like. Love to hear comments.

Tuesday, November 17, 2009

SharePoint 2010 public BETA is available on MSDN- Download

Hi all,

It's the time to download the SharePoint 2010 public BETA version which is available on MSDN. For this so many people are awaiting from long time and now the time comes. So, go to the link

https://msdn.microsoft.com/en-us/subscriptions/securedownloads/default.aspx?PV=42%3a393%3aEXE%3aen%3ax64

And search for SharePoint and find SharePoint 2010 link. Now, you will get the download panel to start download.

NOTE: Remember somehow the link is not visible for all public users. To view or to access the site you need to login first with your msdn or any hotmail account. Right now there are some problems and the link is disabled for the normal sign ins. If your account is paid one, then only you will get access to it. According to the release it is public BETA it may available for download soon for all users.

Let me know, if you are having any trouble to get it or any issues.

Different grid implementations for view, edit, add records

I have a requirement to show the existing  records from database and give options to user for edit, add, delete. So, I thought some of them already implemented and searched for them and found some good examples. But, most of them are not really good at editing the row and submit changes. Some of them are submitting data back to server when column edit complete and some of them are having some problems.

Here the list of grids I have found which are very good start for everyone who are looking for the same.

Please let me know, if you know any more grids which are available on the net.

Hope this helps to find the best one which matches your requirements. What do you say?

Friday, November 6, 2009

SharePoint Designer 2010 is also free download

I think, most of you already knew it. But, I want to tell my readers that SharePoint designer 2010 is also Microsoft releasing for free. As SharePoint Designer 2007 is freely available they are continuing the same and saving some $ to their customers. But, you need to wait for another 4-5 months to get it.

SharePoint 2010 complete features here

Today, I read an article which explains all the features of SharePoint 2010 product. You should have to look at this and learn what the new and nice features available in the upcoming release.

http://blogs.msdn.com/sharepoint/archive/2009/10/19/sharepoint-2010.aspx

Thursday, November 5, 2009

Add Dotnetshoutout button in all blog posts blogger blogs

This is another blog tip I want to tell you as I just added it recently to my blog. I think, you have seen my post on "how to add dotnetkicks kick it icon to all posts in blogger blog". So, by taking that as initiative created this code for DotnetShoutout and working great.

How to add it?

  • Go to edit html option of your blog, by login into your blogger blog and under layout and then Edit HTML.
  • Download full template before start editing the html code.
  • Now check the option "Expand Widget Templates".
  • Search in your browser for the keyword "data:post.body".
  • I think you found one instance as "<data:post.body/>".
  • Please add the below code exactly below the line you just found.

<a expr:href='&quot;http://dotnetshoutout.com/Submit?url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' expr:id='data:widget.instanceId + &quot;_kickit&quot;' rel='nofollow' rev='vote-for'> <img alt='Shout it' expr:src='&quot;http://dotnetshoutout.com/image.axd?url=&quot; + data:post.url' style='border:0px'/></a>

  • Save the template and just view your blog now.
  • I think, you will see the Shout it icon under each blog post body. Now you can add any formatting code to make it more stylish by adding p tags, css to look good on your page and positioning.

Hope it helps!!! Do you like this post?

Wednesday, November 4, 2009

Does SharePoint designer 2010 support SharePoint 2007 and earlier?

SharePoint designer 2010 is not supporting backward compatibility. Means won't support Windows SharePoint Services v3 or earlier versions. I think you got what I am going to say now… Yes, SharePoint designer 2010 only works for SharePoint 2010. I think this news is hard for you, but this will be good for us only. Because in this way, they will build very good version of product without any mess-up. By taking this as the advantage they will only concentrate on the SharePoint 2010 support and will make really a very good product. So, how to get the support for SharePoint 2007 sites? Is there no other way to edit the earlier version sites? I know this is the question in your mind now.

Don't fear. There is an option. By thinking these questions in mind, the SharePoint designer team is developing the software/product to install the designer side by side. So, you can install the SharePoint designer side by side the both versions on the same machine without having any issues. So, this will solve all the problems. If any site which is of earlier than SharePoint 2010 you can use SharePoint Designer 2007, for SharePoint 2010 you can use SharePoint designer 2010.

Are there any requirements for side by side installation? Yes, it has some requirements. You know a big change from previous version to current version is bit [32 bit vs 64 bit]. As SharePoint Designer 2007 is came only on 32-bit[x86], you will only install SharePoint Designer 2010[X86] 32 bit version side by side on a server. And if you install SharePoint Designer 64-bit on a server which has installed 32-bit MS Office, then it won’t give good result. So, Don’t install mismatched version of any. Please install everything of same version.

SharePoint Designer 2010 login as another user

Everyone knows that this is a big problem in SharePoint designer 2007 which doesn't have option to change the current logged in user. But, it is changed. Now SharePoint designer 2010 has the option to see who logged in and change the current logged in user. Good news!!!

So, as they are still working on similar issues to fix so many problems we have faced, hope the coming version of 2010 package will solve so many issues and make our life easy. I guess it will take few more months for the complete development of SharePoint designer 2010 and will release BETA around April 2010. Let's await for it.

How to:

In SharePoint designer 2010 there is an option at very bottom left corner which shows the current logged in user information and options to change user. See below figure.

image

So, this is it!!! Do you like this post?

sharepoint.microsoft.com is built on SharePoint 2010 BETA

Do you believe this? Very nice UI and navigation. I really like the site and the way they organized the data. I thought it was built upon SharePoint 2007. But no, it was built on SharePoint 2010 BETA edition. Check the site and feel the sense of SharePoint 2010.

http://sharepoint2010.microsoft.com/Pages/default.aspx

Isn’t it looks great?

Tuesday, November 3, 2009

SharePoint 2010 release BETA2 in November 2009

I know, all the SharePoint lovers waiting for this release. The current version released is very buggy and not able to test all features available. So everyone concentration is now on BETA version releasing in this month. Microsoft should test it thoroughly and release it with all features are functioning. To get more news and the beta release I refer you to register for letting you know by yourself.

Register here:

http://sharepoint2010.microsoft.com/try-it/Pages/Trial.aspx

Thursday, October 29, 2009

Hardware virtualization check in WINDOWS – How to

Today at my work, I want to install VPC for Windows server 2008 64-bit. I don’t have any idea on how to install WS 2008 on VPC, because VPC by itself won’t support. It need Hyper-V installed on the server. So, googled and found some good free tools or utilities to check the hardware compatibility for the virtualization. Below are the tools used to find them out in simple way.

1. SecureAble: It is a simple tool which is really very light weight and shows us the system bit version, Hardware D.E.P support and hardware virtualization support. Download it here.

2. Cpu-z [CPUID]: which gives you complete hardware details. Download it here.

Check them to test your hardware.

I think, now you got to know how to check hardware compatibility for virtualization.

How to check what updates are installed on my machine?

This is a general question for administrators and windows users. We have two ways to test it. One is through GUI and another is through command prompt.

  • If your windows installed in full installation mode, then you can directly go to Start –> Windows Update –> View Update History. In that window you can check all the list of updates installed in your machine.
  • If your windows installed in core installation then open command prompt –> type the below command in it and hit enter.

wmic qfe list

Now, in the list it will shows all the list of updates installed in the server. Tested in Windows Vista and Windows Server 2008.

Is this post helpful to you?

Tuesday, October 27, 2009

How to drag and drop entities from server explorer to EDMX file Entity Framework?

I know for adding the tables/entities to the EDMX file from database, everyone should do this. You will open server explorer, connect to database, expand to tables and select tables you want to add and tried to drag and drop them to EDMX file. But you never succeeded… Am I right? So, Everyone thinks like this by default because we are well used the LINQ files these days. We have the drag and drop support in it. But in Entity framework we don’t have that option as far as I know. Then how to add new database objects to the edmx file? There are two ways one is manual and another is tool.

  • Manual: Open the edmx file in the xml editor to see the code and edit the changes as you needed. Which is complex and won’t yield good results.
  • Tool: We have an option from the diagram file edmx designer to update the model through designer. Which is very simple and we can add/remove objects as we need.

Note: For entity framework there is a special explorer in visual studio 2008 which helps us to see only entity framework related objects which is called "Model Browser". Which is really very simple to use and helps a lot if your DB is big.

image

How to add entities/database objects to EDMX file?

  • Open the EDMX file in design mode.
  • Right click on the designer surface. You have lot of options and among them choose the option "Update Model from Database.." as shown below.
  • image
  • Now, you will see the usual screen which has all the database objects in new window which you have seen while creating EDMX file.
  • image
  • That's it!!! This way you can add/remove/edit database objects in an EDMX file. Usually the drag and drop is the good user experience as it in is in Linq to SQL file. Hope Microsoft include this option in upcoming releases.

I think, you knew about how to add or update db objects in EDMX file now. Love to hear comments.

Unable to update the EntitySet Table because it has a DefiningQuery and no InsertFunction element exists in the ModificationFunctionMapping element to support the current operation

ASP.NET MVC is the technology released from Microsoft long time back. But I didn’t get time to dig into it and research on it. Now, I need to learn it as my next project is in ASP.NET MVC. So, I thought to give a try and want to show all records in a table and insert a new record in a table. On the way, The above is the exception which blocked me to go proceed. I didn’t do any mistake and always the above exception come into picture when I try to create a new record in table.

So, frustrated and started research on the error and debugging. After a long research found the issue in the Entity framework. The whole thing is only because I forgot to add primary key to the table in the database. Once I added the primary key and reconstructed the edmx file with new changes, All works fine and record added to table in database. So, what is happening inside is, entity framework is looking for a key in each and every table [Primary key]. So, don’t forget to add a primary key to each and every table which you want to use in entity framework file [.edmx]. Otherwise you always see this exception when you try to insert or update a record.

"Unable to update the EntitySet 'Table' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation."

Is this helpful? Follow me if you want to learn ASP.NET MVC framework. I started learning and will place all my experiences and problems I face in my blog. So, keep an eye on my blog for more updates.

Wednesday, October 21, 2009

Visual Studio 2010 BETA 2, Download now

Visual Studio 2010 BETA 2 is released. Get it and start researching on new things added in this version. We know it has more features and explorers in it and lot of options to simplify and faster development and .NET 4.0. So, why to wait. Get some time and download it now.

http://msdn.microsoft.com/en-us/vstudio/default.aspx

Monday, October 12, 2009

Install the latest Messenger security update!

"Microsoft has just released a new version of Messenger which includes important security updates to help keep you and your friends safe while you chat online. All Messenger users will be required to have the latest version to continue using the service."

Get it from here.

http://download.live.com/messenger

Thursday, October 8, 2009

Set Focus to ASP.NET control

This is the question I received from developers on how to set the focus to an ASP.NET control from server side. Because once page is posted back to server or when request sent to server, from the response we need to set the focus to some x control on the page from server side.

There are requirements like this. For example, we have multiple panels on the page and when you saved the data successfully of a panel then you need to show the user the panel they submitted with some successful message instead of showing them the top section of  page always. :) Otherwise, user always needs to scroll down to the panel where he edited the changes and see whether the data saved successfully or not. An user experience problem.

Usually, the way the developers will do is, catch the control in client side either using javascript or jquery, then they will write logic to set the focus to it. But it's not needed. We can simply use the existing functions available in ASP.Net and C# and implement the behavior without any pain. See below example on how to do that.

C# language by default providing some options to set the focus to an ASP.NET control on the page. There are two ways to do that.

  • You can directly use Focus() method to set focus to a control. 
    tbName.Focus();
  • You can use the Page object function named "SetFocus" to set the focus to a control as shown below. 
    Page.SetFocus(tbName);
Note: Assuming "tbName" is the textbox control id on the page.

So, by using any of the above ways we can set the focus to a control from server side code itself. I hope this will help you. Please provide your comments on it.

NOTE: Don't try to set the focus to the control when it is in disable mode or invisible. This will give some problems in the client side.

Wednesday, October 7, 2009

Ajax and JQuery libraries with Microsoft CDN

This is the wonderful announcement from Microsoft that they have placed the Ajax and JQuery libraries with Microsoft CDN[Content Delivery Network]. This will surely save huge amount of bandwidth all over the net as ajax and jquery is using by most of the people on the net. Now, it will download faster as it is coming from the cache. They have placed these libraries on the domain ajax.microsoft.com. So, if your site is on the net then use the urls from CDN and use them. Your browser downloads these files real quick than ever.

Example script for downloading jquery minified version:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>

For more details: http://www.asp.net/ajax/CDN/

Isn't it nice? Don't you say wow after reading it? It really saves so much of bandwidth. Please provide your comments on this announcement.

Import excel data to SharePoint list

This is one of the nice and best SharePoint feature that we have implemented. By default SharePoint will provide us an option to edit in spreadsheet or download list items in spread sheet. But, it doesn't have the option to import the excel data to SharePoint list. When we have data in excel format and want to import that data to a sharepoint list, then how to do. That is why we took it as a challenge and implemented this.

And second reason is, this feature has a nice and wonderful feature of column mapping. You can manually choose column to column mapping, so that the column names not needed to be exactly same. This is one of the best option in this feature.

This feature works for both SharePoint and WSS.

The installation is simple and it is using the codeplex sharepoint installer package to install the feature. As it is developed as a SharePoint feature, you can get this feature associated with each list under the actions tab once you activated it. You can call this feature by going to specific list, under actions menu item just click on the feature name. Then it will take to a page which has a nice user interface to upload an excel, then choose specific sheet and then map the fields as you want.

You can take a look at it here on CodePlex.

http://spreadsheet2splist.codeplex.com/

I think, this will help you out to import data from excel to SharePoint list problem. Isn’t it?

Tuesday, October 6, 2009

SharePoint list view web part wildcard search

I know, most of the SharePoint developers are looking for this. As everyone knows we can do partial search on data view web part by passing a parameter to it and by using the expression "contains" we can implement partial search on a field or column. But, when you come to list view web part you can't pass the parameters [There is no support for list view web part like web part parameters] and no way we can implement the partial keyword search. Today I have spent time on it to solve this problem with the help of my colleague Durga and found a wonderful way. This is giving really wonderful result and doing wild card search even on very big document libraries fast. Below are the steps I followed to solve this. [I will post detailed post on it with screen shots and nice explanation soon in this blog.]

  • Created an ASPX web part page in a SharePoint site.
  • Added two web parts to the page. One is for content editor web part and another is for list view web part of a SharePoint library or list.
  • Now, open the page in IE browser and add a text box, button to the content query web part.
  • Written simple logic to button click event of the button and reload the page with the below formatted url. The url should be of the format

"you aspx page url?FilterName=FieldName&FilterMultiValue=*valuefromtextbox*".

  • In above url, we are using two key value pairs to solve our problem.
  • First one is FilterName: which is for in which field of the list view we need to search the value. For example the value may be Title, ID etc…
  • Second one is the FilterMultiValue: Which is for what is the value we need to search. i.e. keyword. So, here you can pass multiple values too separated by semi-colon ';'.
  • So, example url should like this
  • http://mosssite/pages/listviewcustomwildcardsearch.aspx?FilterName=Title&FilterMultiValue=*prav
  • Now the above url will search all the records in the given list view for the keyword "prav". So, wherever it exists in the given field name it will return all records.

Then how it is working?
Generally, If you research on query strings for a list view web part, it expects some query strings to filter and sort. I am SharePoint developer and got to know the two query strings which SharePoint list view web part uses for filtering. FilterName and FilterMultiValue. So, with that my research continued and tried long time with so many operators like %, single quotes, double quotes etc… in the value of the FilterMultiValue. Finally, I tried with * character before and end of the keyword, there I succeeded. Example: *prav* to FilterMultiValue.

  • That’s it…. Working simply great.
  • With that, You are done implementing the wild card search in a column in list view web part.

Happy by doing SharePoint customization. I know, this will solve so many problems to SharePoint dev’s.  Isn’t it? Please let me know if you have any questions, issues and write your valuable feedback and comments.

Will post more descriptive explanation of this post with screenshots soon in this blog. Follow me!!!

Monday, October 5, 2009

SharePoint, WSS feature for DocuSign signature for free

This is one of the great feature that we have developed in SharePoint for document signature. Which is compatible with WSS too.

Signup at DocuSign website for a free account and use this SharePoint feature available at CodePlex to sign documents without any cost.
This is a simple/basic Version 1.0 of the tool that lets you sign or send requests for signature from a SharePoint library.
http://esignspdocuments.codeplex.com/
Lot more can be done. Please try this feature and provided your feedback and suggestions in Codeplex. 

Sunday, October 4, 2009

Client side validation of ASPX validation controls

This is the nice post under validating the ASPX validations in client side like java script. The concept behind is,

  • Some times we need to validate the .NET controls in client side whether they have correct values or not. We can do them in client side logic by using some existing functions available in javascript which are handled by ASP.NET framework.
  • And another requirement is on the page some controls are .NET controls and some are HTML controls. And all .NET controls are using the server side validation controls and html controls are using client side validation. So, when click on submit button, you need to detect whether form is valid or not on client side. So, you need to write some custom logic to detect all HTML controls are valid or not and then you need to detect all ASP.NET controls are having valid values or not. How will you detect that? You should validate both of them in javascript. So, this logic will help you to find the form is valid or not. 
function Page_ClientValidate(validationGroup) {
   Page_InvalidControlToBeFocused = null;
   if (typeof(Page_Validators) == "undefined") {
      return true;
   }
   var i;
   for (i = 0; i < Page_Validators.length; i++) {
      ValidatorValidate(Page_Validators[i], validationGroup, null);
   }
   ValidatorUpdateIsValid();
   ValidationSummaryOnSubmit(validationGroup);
   Page_BlockSubmit = !Page_IsValid;
   return Page_IsValid;
}

The above function is taking an argument named validationGroup. This is the validation group of the server side validation control. And the output or return value returning is the boolean value. If it is returning true then it passes the server side validation and false then it fails the server side validation. So, along with it's value you can write your own logic to validate the html controls and test whether form is valid or not.

Hope this helps and you can solve so many problems with this logic. Always welcome your valuable feedback and comments. Do you know any other ways to implement it?

Wednesday, September 30, 2009

Dotnetkicks.com kick it for blogger blogspot blogs

I know most of bloggers are searching for this…. If you are writing ASP.NET related posts in your blog then you should need it to publish your posts to dotnetkicks.com. So, here is a nice tip to add kick it for your blogspot blogs.
  • Go to your blog. After you sign in, in admin section you have a tab named "layout".
  • Under layout tab select "Edit HTML".
  • Before you do any changes, please download full template.
  • Then tick the checkbox "Expand Widget Templates."
  • In your browser, press Control+F and find the keyword "data:post.body".
  • Go to that line [<data:post.body/>] and hit enter and add the below code as is.
<p><a expr:href='&quot;http://www.dotnetkicks.com/kick/?url=&quot; + data:post.url'><img alt='kick it on DotNetKicks.com' border='0' expr:src='&quot;http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=&quot; + data:post.url'/></a></p>

Note: expr: is the syntax for expression and it will execute by blogger code and replace the correct values before send response to browser.
  • Now, save the template and view blog for the changes.
  • I think, you are smiling now by seeing kick it icon on your blog for each post.
  • Enjoy!!!
Love to hear comments from you. Is this helpful?

Wednesday, September 23, 2009

Jquery intellisense in Visual Studio 2008

This is a small tip I want to tell to my readers. I know, most of the dev's think like if Jquery intellisense is available in visual studio then that will be good :). So, this post will help you to solve that problem.
Below are the steps we need to follow to get the intellisense working in Visual studio 2008. Before start with the steps I will tell you how it helps us.
  • Learn more and implement more: Because of having this intellisense support in vs 2008, we can solve so many problems and can implement so much in JQuery. It will be very difficult for everyone to remember all the functions and members for the Jquery objects. So, This will give more support to learn more and implement more.
  • Fast and rapid development of the client side scripting. Until you don't know what methods and properties it has you can't write program fast and efficient.
  • Time saving: Complete documentation for all Jquery objects, methods and properties. The inline description is more than enough to understand it well. Till these days, every time need to go to Jquery documentation site and need to search for what we need and read about them. But, now everything is in visual studio. Big time saving here.
  • Load time: I know, at this point you may think how it will effect load time by adding the Jquery documentation file to page. By adding the vsdoc file [~188Kb] to the page won't increase the page size or won't effect the load time at all. We will refer the documentation file while coding or at development time only but it won't render on the client side. How? I will explain it later in this post.
Requirements:
  • Install Visual Studio SP1.
  • We need to download the vsdoc file from here.
  • Install the hotfix for visual studio before proceed.
Steps to refer the documentation file(vsdoc):

  • Refer the documentation file to js file: If you need jquery intellisense on the js file then you need to write the below declaration as the first line of your js file.
/// <reference path="jquery-1.3.2-vsdoc.js" />
Note: the path value is the actual path of the vsdoc file.
  • Refer documentation file in ASPX page: This is what we need most of the times for writing inline scripting on the page. So, add below code to the <head> tag of the page for JQuery intellisense.
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<% if (false) { %>
<script src="jquery-1.3.2.min-vsdoc.js" type="text/javascript"></script>
<% } %>

Note: The Jquery file reference should always be the top of the Jquery documentation file reference. And if you install Visual studio SP1 and the hot fix then there is no need to place the complete IF block from the above code. And the vsdoc file should be in the same folder where the jquery file is.
Note: The short cut for the update intellisense in Visual Studio is Ctrl + Shift + J. So, once reference added please done it once to update the intellisense.

How, Jquery intellisense work in Visual Studio?
It's simple. What JQuery –vsdoc.js file contains? Nothing but the description text for all the defined methods and properties. So, when you refer the vsdoc file in js file, it will load that file into memory and set the meta data for the Jquery methods and properties. If you refer the vsdoc file in ASPX pages, then it will set the metadata as follows.
First, Visual studio will look for the JQuery file, example jquery-1.3.2.js. And then it will look for the file which has the format jquery-1.3.2-vsdoc.js. If it matches then only visual studio loads the meta data and intellisense will work, otherwise not. So, your jquery file and documentation file should be having the same name with –vsdoc at end of the documentation file name.
Note: Jquery file: jquery-1.3.2.js and Jquery visual studio documentation file name: jquery-1.3.2-vsdoc.js
Lastly, I want to explain about the load time from above mentioned bullet. If you observe the code I have given, it has some server-side code integrated in it. I wrote if condition which always fails to execute the code inside the if block because I am passing false always to it. So, it never runs the code inside the if block and nothing loads on the client side related to vsdoc file. At the time of development, server-side code won't run but all the meta data will load because there is a script tag on the page. So, at development time, the vsdoc file will load, but when you browse the page, vsdoc file won’t render.
That's it!!! I hope this will give nice idea of how Jquery documentation work in visual studio and how to add the reference to your files. Isn’t it? Please give your valuable feedback or comments on this post.

Tuesday, September 22, 2009

Check/Uncheck all checkboxes in Jquery

This is simple, but want to show you how to get it working in simple and efficient way. Usually we have a parent check box and then some child checkboxes. Depends on the parent check box selection, all the child checkboxes should behave exactly same. So, below is the Jquery function which will do that magic for you.
function CheckUncheckAllCheckBoxes(objID, checkedValue) {
if (objID == null || objID == undefined )
return;

$(objID + " input[type=checkbox]").each(function() {
this.checked = checkedValue;
});
}
If you observe, I am using two parameters for the function named objID and checkedValue. objID is the parameter for knowing which checkbox group or list we need to check or uncheck? Like, on a page we may have many checkboxes and groups or lists. So, we need a way to find out which group or list we need to check or uncheck? For this reason I added a parameter for the function to check only the checkboxes under that ID or Class. Possible values for the objID are
  1. #parent Control ID of the element which has the check boxes declared. Example: #ageList
  2. .parent control class of the element under which all the check boxes defined. Example: .edit
And second parameter, it is for passing the parent selected check box value. If it is ON, then logic will loop through and set the each checkbox to checked otherwise unchecked.

Usage - How to call this method:
Code for check/Uncheck all in ASP.NET
$("#<%=cbAllStates.ClientID %>").click(function() {
   CheckUncheckAllCheckBoxes("#<%=cblState.ClientID %>", this.checked);
});
Note: cblAllStates is the parent ASP.NET check box which is controlling child. cblState is the asp.net checkboxlist and in our terms child check boxes.

Code for Check/Uncheck all in HTML:
$("#cbAllStates").click(function() {
   CheckUncheckAllCheckBoxes("#divChilds", this.checked);
});
Note: cbAllStates is the parent check box control and divChilds is the division <DIV< tag which has all the child check boxes present in it.

**UPDATED** 06/22/2010
This is the small update for the check/uncheck the all check box depends on the child check box selection. If any of the child check box is unchecked or the all child check boxes are selected then the all check box will toggle depends on it. Below is the work around.

Example:
Code for  Toggling the all check box depends on the child check boxes:
function ToggleSelectAllCheckBox(allCheckBox, checkedValue, obj) {
    if (allCheckBox == null || allCheckBox == undefined)
        return;
    if (!checkedValue) 
        $(allCheckBox).attr("checked", false);
    else {
        var areAllChecked = true;
        $(obj + " input[type=checkbox]").each(function() {
            if (!this.checked) {
                areAllChecked = false;                
            }
        });
        $(allCheckBox).attr("checked", areAllChecked);
    }
}
In the above function param1 is the all child check boxes, param2 is the current child check box selection and param3 is the all check box selector.

How to use:
ASP.NET Checkbox list:
$("#<%=cblAge.ClientID %> input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox("#<%=cbAllAges.ClientID %>", this.checked, "#<%=cblAge.ClientID %>");
 });
Note: cblAges is the check box list id and the cblAge is the all check box for the age group. So, the click event is for the all check boxes inside the check box list.

HTML Check boxes:
$(".ageGroup  input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox(".ageGroup", this.checked,  "#allAgeCheckbox");
 });
Note: ".ageGroup" is the div or some parent element which holds all the checkboxes in HTML. "#allAgeCheckbox" is the id of the all checkbox for that age group.

**End of Update**

Hope this will help you to understand how to write code in efficient way and which helps for us in multiple scenarios. Always welcome your valuable comments.

ASP.NET Checkboxlist get values in client side [JQuery]

See my other post, which explains "how to set the value attribute for a single check box through c# code" before proceed to this post.

I know, this is the question most of the ASP.NET developers will ask or look for an answer on why there is no value attribute set for check box when it generates from the ASP.NET checkbox list? Where as the Radio button list, Drop down list and other controls has this value attribute set when you set the data source for them. But why there is no value attribute set for check box list control. Below is the nice explanation and will help you to understand the concept well.

If we assign some data source to the check box list control, then the HTML output is with two controls for each check box as input control with type checkbox and another is label with the text. So, This is the problem. How to get the value of the checkbox in client side using some javascript library? Here we need to think a way of how to set a attribute which holds the value for each checkbox and how to get it.

Below is the solution I found. In your C# code, after you bind the data source for the checkbox list, then need to add extra piece of code below to get our problem solved.

C# code:

foreach (ListItem li in checkBoxList.Items)
li.Attributes.Add("someValue", li.Value);

So, What happening here is, I am just adding extra attribute "someValue" for each check box in a check box list[checkBoxList] and looping through them and assign the actual value to that custom attribute. So that HTML for each checkbox on the page will render like this.

HTML rendered output:


If you observe, there is an extra parent control for each check box control named <SPAN> with the attribute we have set in c# code for each checkbox. Now you have some value set with each checkbox and you can get it on client side easily. [There is no change in C# code accessing values.]

How to access the values on client side?

I am using JQuery, so I will give an example of how to get the values using the JQuery.

To get all checkboxes which are checked under a checkbox list are accessed as follows.

JQuery code:

$("#<%=checkBoxList.ClientID %> input[type=checkbox]:checked").each(function() {
var currentValue= $(this).parent().attr('someValue');
if(currentValue != '')
values += currentValue + ",";
});

So, values is the string which holds all the selected checkbox values in a check box list which are selected with comma separated. I think, now you got an idea of how to access the values in client-side. Hope it will help you to understand what I am trying to say. Please add your valuable comments on it.

Sunday, September 13, 2009

Detect asynchronous postback in ASP.NET

Everyone need to know about this. When no Ajax implementation in ASP.NET [older versions] asp.net developers know about only one post back. That is full page postback. We have a property to detect it in c# code with Page.IsPostBack. But, day to day technology is growing and we need to know/follow everything up to date. This is not new one or I didn't find it just recent. All these posts are my experience and part of sharing information.

Now a days everyone knows what is Ajax and how it will work. Everything is Asynchronous calls. So, in developing Ajax integrated applications in ASP.NET we need to know which is page full post back and which is asynchronous partial post back. So, This post will help you to understand it well.

As we know, ASP.NET Page Object has a property named IsPostBack, ScriptManager class also has a property named IsInAsyncPostBack and which returns true if page raised the async partial postback event.

Now, take a look at the usage of both.

//Checking for page postback
if (IsPostBack)
{
if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
//Aynchronous postback raised.
}
else
{
//Normal page full postback.
}
}

Remember, Here whatever postback raised like full page postback or async partial postback IsPostBack set to true in both cases.

Hope you understood well about the both postback types and how to know which one raised. Please add your valuable comments.

Cross page postback in ASP.NET

This is the blog post I want to present you something that you need to know. When I was new to IT industry and ASP.NET programming, I believe the ways to access the page1 variables on page2 are as follows.

  • Querystring parameters
  • Session management using session etc..

So, when I want to access the values of page1 on page2, I will store them in a session by creating session variable and will use it in the page2. And another method is, by passing values to page2 in query string parameters from page1. But this need some extra processing on server side to redirect them to that page.

After got little bit experience and when I came to the same situation where I need to pass the parameters from one page to another page, there cross page post back option helped me. So, I want to share the feature with you. This is the third way of passing values from one page to another page.

ASP.NET framework default supports it. There are some parameters to the Page object which helps us to get the logic work.

  • PreviousPage
  • IsCrossPagePostBack

When you want to call server side programming, usually we will write server side control with click event or command event which does the postback and execute server side logic for that event. But when you want to call different page in click event, then you need to use a special property called "PostBackUrl" and to it you need to set the url of the destination page. So, that post back event call that page. This is what the concept called Cross page PostBack.

In programming point of view how to implement this?

ASPX Code: [Page1.aspx]

<asp:TextBox runat="server" ID="tbCrossPageTest"></asp:TextBox>
<asp:Button runat="server" Text="Submit" PostBackUrl="~/Page2.aspx" />

C# Code: [Page2.aspx]

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            TextBox tb = (TextBox)PreviousPage.FindControl("tbCrossPageTest");
        }

Here, we need to check for some conditions as best practice. One is for whether to know PreviousPage object is null or not and second, is current page from cross page post back. PreviousPage is the object which holds the page1 object and from it, you can find any control on the page and access the values. I know, we don’t use this in many times, but you need to know this option is available in ASP.NET. Please let me know you ideas on it and provide your feedback. Hope this will help you better in understanding the cross page post back.

Note: This cross page post back won't change any of current page properties. For example, page2.IsPostBack is false only, when cross page post back is raised on page1. So, don't confuse.

Monday, September 7, 2009

Access IFrame content using Jquery

This is really helpful post for so many people who are using frames in their pages and want to access content inside it from main[parent] page. I really faced so many problems to read the data inside a frame and use it on the current page. So, it's simple and nice to know this tip for JQuery lovers.

HTML:

In Parent file, for example iFrame is declared as below.

<iframe id="uploadIFrame" scrolling="no" frameborder="0" hidefocus="true" style="text-align: center;vertical-align: top; border-style: none; margin: 0px; width: 100%; height: 60px;" src="IFrameExample.htm"></iframe>

In IFrameExample.htm, assume there is a hidden control as shown below.

<input type="hidden" id="hiddenExample" name="hiddenExample" />

So, now I will tell you how to set the "hiddenExample" hidden control value from the parent file. Because, we can’t directly access it through java script/HTML. We need to use below logic to get it working.

var $currentIFrame = $('#uploadIFrame');
$currentIFrame.contents().find("body #hiddenExample").val("Value from parent file.");

That's it!!! You are done with assigning some value to hidden variable inside IFrame. And in that iFrame you can access this hidden control on server side[C# or VB etc..] too. For it, you need to follow my other post. Very simple, but hard to find. Below is the nice explanation of above code. [How it will work.]

So, we are using Jquery, you know how to define JQuery object and use it in DOM. I created a variable[Object] currentIFrame which holds the whole IFrame reference. And in the second line, I am using the contents() method, which actually returns me all the HTML code of the frame. So, as we already know, find is the method we need to use to find out any element in a given scope/context. So, it tries to find out the occurrence of given criteria in current frame. I think you understood well how it works. If you are having multiple IFrames then you can define class for <iframe> instead of id and you can catch it in Jquery by using "." operator instead of "#". Is it a new and good find? Please let me know, if this helps you or any questions if you have.

Sunday, September 6, 2009

How to write your own functions in JQuery

This post is also part of learning jquery. When I was new to learn Jquery, I was facing lot of problems in creating my own functions in JQuery. Because I want to create one function at one place and use it everywhere by calling directly JqueryObject.function(). After got some experience then I started writing my own Jquery functions and using them in my projects.

Syntax of how we can create a new function is as below.
jQuery.fn.myownfunction = function() {
var currentObject = $(this) ; //currentObject holds the current object.
};

Example function for centering an element is shown below.

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / $(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / $(window).scrollLeft() + "px");
return this;
}

How to call it?
$("#popupDiv").center();

Ok, now you are good at how to write your own functions in JQuery. Enjoy by learning.

Jquery making synchronous call

These days I am completely concentrating on JQuery, I want to share the knowledge I am gaining with you. In this post, I want to tell you how can we make synchronous calls. Everyone knows all the ajax calls are asynchronous. Whatever we are making calls in Jquery to server through clientproxy are the asynchronous calls. So, how to make synchronous calls? That is why I am posting here.

$.ajax({
type: "POST",
url: "url of the page",
processData: false,
success: function(msg) {alert("success")},
async:false
});

If you see the last line, the attribute declaration async:false which is the key for the telling the Jquery client proxy to make asynchronous call or not. If it is true then asynchronous otherwise synchronous.
Hope this helps you to understand it well.

Jquery $ and how to declare variables

Today, I got little bit of time and want to share with you small things I learn in JQuery. I know, most of the people who are new to Jquery don't know what is $ in JQuery.

$ is the symbol which is the initialization of Jquery object. You can pass selector, function, string etc to execute or implement some functionality. So, $("#idOfElement") or JQuery("#idOfElement") both are same.

I saw many people are declaring the Jquery variables as shown below.
var currentObject = null;
currentObject = $("#someID");

So, I don't say this is the best practice to use it. Instead you can do the below.
var $currentObject = null;
$currentObject = $("#someID");
And if you want to use it, you can directly use it as shown below.
$currentObject.val() or any other function supported for the current object.

So, the advantage here is, for easily identifying the Jquery variables. If you are working on a project where it needs lot of Jquery coding, then you must use this practice. Hope this helps!

Thursday, September 3, 2009

Jquery datepicker problem on date select in IE - 'length' is null or not an object

I am working on a project which includes the technologies like ASP.NET, Jquery, Sql server. I solved so many problems in Jquery and posted on my blog some. Now, I am posting a wonderful post on Jquery datepicker.
Because I am using Jquery in ASP.NET application, I added a regular expression for date to validate whether user entered date is valid or not. Because of adding the validation on the text box, whenever I select a date from datepicker, the datepicker events are firing like onselect, change etc.. So, generally what validation framework is doing, whenever some event fires on the page, validations will execute. The same thing happening here. Whenever I change or select date from the date picker, it will fire some events and at the same time validation framework trying to validate the validations. But, it is not the right event to do validations. So, always we will get the exception at "vals.length" in a for loop of the built-in code. vals is the object of all the validators on the page. It always fails to load in Jquery date picker event trigger, because it is not the right event for validation. And the result is vals is undefined, you always get exception at vals.length as "length is null or not an object". I think now you got very clear idea of why it is happening. Now, move to the next step i.e. solution for it.

Solution is very simple, I read all the documentation of Jquery datepicker and found an event named onSelect. So, whenever I select date this is the event firing. So, there I got a clue and started thinking towards it. And below is the result.

$(".datepicker").datepicker({ onSelect:function(){}});

In your datepicker initialization statement add onSelect event which don't do anything means empty function as shown above. There problem solved. Isn't a good find? Please let me know your thoughts on this.

Wednesday, August 26, 2009

How do i know my system version. 32 bit or 64 bit?

Hi Guys,

From long time many people asked me about how do I know my system version whether 32 bit or 64 bit. When I was very new to IT industry, at that time I too don’t have any idea about it. But some things will come with experience. Please follow the below points to know your system version.

  • Go to Start button.
  • Type sysdm.cpl and click OK or press enter.
  • Now, it will open a new window. Click on General tab. Here you will find the information about the OS.
  • The only clue that you know, whether my OS is 32-bit or 64-bit is, For 64-bit specially the OS name displayed as "Windows server 2003 64-bit Operating system". Where as 32-bit is simply Windows server 2003.

If you are using Windows Vista OS, then you can directly see the version details by going to computer properties from Start button.

  • Directly go to Start button, and right click on Computer and select Properties. There you find an entry for System Type.
  • OR, you can go to Control Panel and then Go to System.

This information is very helpful many times before install any software to check for version validation. Now, you know what your system type is. Don’t you?

Tuesday, August 18, 2009

Get Querystring parameters in Page Webmethods ASP.NET

Today, at my work I have to find a way on how to get the query string parameters and use them in logic. I mean, I can get them in javascript side and send them as parameters, but I don’t want to implement it that way as I have everything in query string, I can get it from URL and use it in server side code. And second thing is, the query string parameters are not plain text, they are encrypted with a strong algorithm. So, below is the small function I written which work perfect.

//Get Querystring name value collection
    public static NameValueCollection GetQueryStringCollection(string url)
    {
        string keyValue = string.Empty;
        NameValueCollection collection = new NameValueCollection();
        string[] querystrings = url.Split('&');
        if (querystrings != null && querystrings.Count() > 0)
        {
            for (int i = 0; i < querystrings.Count(); i++)
            {
                string[] pair = querystrings[i].Split('=');
                collection.Add(pair[0].Trim('?'), pair[1]);
            }
        }
        return collection;
    }

So, this function is a static one because, we are calling it from a Webmethod. And this function is expecting url as the parameter. Actually, it is not complete url, it is just the complete querystring url which starts from the character '?'. Now, how to call and use this function? Find below.

NameValueCollection collection = GetQueryStringCollection(HttpContext.Current.Request.UrlReferrer.Query);
        if (collection != null && collection.Count > 0)
        {
            string id = HttpContext.Current.Server.UrlDecode (collection["id"]);
        } 

The above statement returns the querystring value which has the key "id". This way you can get any querystring value, just by passing it's key name to the collection.

HttpContext.Current.Request.UrlReferrer.Query – Which holds the complete querystring url starts from '?'. So, this way you can get the query string data and use it where ever you want in Page Webmethods.

Is this what you are looking for? Or do you have any other ways to get the querystring data? Please post your ideas on it here.

Call ASP.NET server side event in JQuery

For one of my requirement, I need to implement this functionality on how to call server side event in JQuery. There are many scenarios on why we need to implement it or what is the need for it. I have a button and when user click on it, I need to show a client side light box which exactly functioning as window confirm box. If user selects OK, then I need to do some client side validations and if everything passed, then i need to make a call to server to execute the actual server side click event. I think this is general scenario. There are many cases other than this. So, here is a simple solution on how to call server side event in JQuery. Enjoy this interesting blog post.

1. Create a protected page variable in Server side ASPX.cs file as shown below.

protected string serversideEvent = string.Empty;

2. In Page_Load event, set the serversideEvent variable to the button click event as below.

serversideEvent = Page.ClientScript.GetPostBackEventReference(btnSubmit, string.Empty);

3. In your JQuery, use this function to evaluate on specific condition as shown in below line.

eval(<%=serversideEvent %>);

"btnSubmit" is the ID of the control <asp:Button in ASPX page. and GetPostBackEventReference will get the click event of the related button and return it in the form of string.

That's it. Whenever the line mentioned in 3rd step called, it will call server side event and execute it.

How awesome it is? Very simple and nice way to do it. Isn’t a good and valuable find?

Get difference between Dates in Java script

It is very simple and easy to implement the difference between two dates. I received some queries on how to do it. So, this is the post for them.

function parseDate(str) {
    var date = str.split('/');
    return new Date(date[2], date[0] - 1, date[1]);
}

function GetDaysBetweenDates(date1, date2) {
    return (date2 - date1) / (1000 * 60 * 60 * 24)
}

"parseDate" is the function which is for converting a string to Date object. And the method "GetDaysBetweenDates" is expecting two date parameters which calculate the difference between the dates and return the result in number of days. You can change the formula as you want to return in time, months, weeks etc…

Enjoy!!!

Jquery – How to set a value in Drop down as selected

You know, sometimes small things will take long time to implement. Usually this will happen if we are not familiar with them. For this, plenty of documentation is available around, we should read it before starting it. So, here I am talking about JQuery and the features of it. I know how to select a value in a drop down and populate it using plain javascript. But when comes to JQuery, for me it took sometime to find a way to do that. Below is the way on how to populate a dropdown value as selected.

$("#ddlSource option[value='1']").attr("selected", "selected");

Here, ddlSource is the ID of the HTML select [drop down list] control. The meaning of the above statement is, find the control which has the ID "ddlSource" and in it find the option which has give value and select it. "1", I am using for example. You can pass any value.

If you are using the server side controls, and want to populate the value in JQuery, then use below statement.

$("#<%=ddlSource.ClientID %> option[value='1']").attr("selected", "selected");

But this is not the right way of doing it. You can change the server side drop down values on client side, but which results you the error message "Invalid Postback or Callback event" when submitting data to server. So, take care when you deal with server side controls in javascript.

For best practice Please try to use <select runat="server" ID="ddlSource" ></select> instead of <asp:DropDownList /> to avoid the invalid callback error messages. I know, the immediate question in your mind, how to get the value using <select> control in C# code. Use below code for it.

string selectedValue = Request.Form[ddlSource.UniqueID]; //UniqueID is because Form is expecting name instead of ID.

Is this helpful?

Tuesday, August 11, 2009

JQuery dialog open only first time problem, solution

This is a big problem to me for long time in JQuery. I downloaded the Jquery UI min file and started using in my projects. On the way, there are some requirements where I need to show the dialog box and execute some logic. But, whenever I click some button to open a dialog, very first time only it opens like a charm. From the time when I close it, it will never open again by clicking on open dialog link. This gave me lot of frustration and I don’t know where the exact problem is. After reading all the documentation in JQuery docs, finally found the problem and fixed it in seconds.

Solution:

$("#dialog").dialog({ modal: true, resizable: false,
draggable: false, width: 515, height: 245 });

$("#dialog").dialog('open');

I know everyone is declaring only the first statement in their code and no one will write the second statement to open the dialog. Below is the explanation for it.

As far as I understood, what JQuery framework doing internally is, When we write the first statement, it is treating it as the initiation of the dialog for the div or HTML control. Because of adding "model:true", it will open for the first time, when you click on a link and never open again once you closed. Because no where we mentioned to open the dialog in the first statement.

And about second statement, JQuery is calling the dialog property and forcibly loading the dialog to the DOM and shows it on the screen. So, open property/attribute will do the trick. So, whenever you want to use a dialog box in JQuery, this is the code you need to use to open it as many times as you want.

Is this what you are looking for? Or do you know any other ways to implement it? Please post all your ideas here.

Wednesday, July 15, 2009

input Checkbox or Radio button with runat server and checked property

Usually, when we actually don’t need of ASP.NET controls, we will use HTML control with runat="sever" for better processing. So, if you use the input checkbox/radio button control, it has the checked attribute, by default it look for the value "checked" for checked attribute in HTML. But because we made it server-side control by adding runat="sever" to it, it won't allow the "checked" value to "checked" attribute. The possible values for it is only True or False.

<input type="radio" runat="server" id="radioTech" checked="true" />

So, instead of "checked" value, use true or false.

Blocked file types in SharePoint 2007 – Custom web services 2.0 in SharePoint 2007 – Part 3

Please read the post "Steps to implement custom web services in SharePoint" before continue here.

I think, most of the people don't know about blocked file types and where can we set them. SharePoint by default, won't allow all the file extensions because of some security issues.

Why the SharePoint team didn't allow them by default. There is a strong reason behind it. i.e. not other than Security reasons. For example, EXE extension file, script files etc.

How to remove a blocked file type?

  • Open central administration site.
  • Go to Operations tab.
  • Find a section named "Security Configuration".
  • Under this section, you can find a link for "Blocked file types".

    Blocked file types

  • On this page, you can see a text box area which displays all the file extensions one per line, which SharePoint blocked by default.

      image

  • You can edit and delete the extension. Then SharePoint allows user to upload the file or access the file.

So, if you are facing the problem of not able to upload the files of type .asmx, .exe, .chm etc.. This is the place where you set it. Happy SharePointing.

Steps to add a Web service 2.0 in SharePoint 2007

Today at my work, I need to implement JQuery in SharePoint on a module. I need to make AJAX calls to get the data from the database depending on the value in a text box. So, I choose JQuery, because I know it well and it will take very less time to implement. But for JQuery I need to create page web methods. But SharePoint doesn’t support Page web methods because SharePoint is completely built upon ASP.NET 2.0.

So, what is the solution, how can I make a call to the server and get the data from DB? After thought some time about it, finally I got a brilliant and better idea of using web services. Please follow the steps below to implement Web services in SharePoint.

  • We are using client side technologies like JQuery etc to call Web service to get the data from server. By default, it is not supported. For that, we need the supporting DLL's[System.Web.Script.Services] for the Web service script on the SharePoint server. These DLL's are needed to process the web service request and send the response[JSON]. For those DLL, you need to install the Ajax extensions 1.0.
  • Create a web service using Visual studio. It will generate two files webservice.asmx and webservice.cs. Write all the web methods required inside the webservice.cs file. I will explain you with an example more detail later in this post.
  • Now, we need a location to keep our *.cs [webservice.cs] file. So, for that, create App_Code folder in the SharePoint site file system virtual directory root [c:\inetpub\…\wss\virtualdirectories\portnumber]. You can find the advantages of using App_code folder, in SharePoint web application in this post.
  • By default SharePoint won't allow the script handlers and http modules. For this reasons, we need to make the web.config changes as explained in this post.
  • Change the settings in central admin to remove asmx extension from blocked file types. See it here.

After you are ready with all the above steps, then please follow the steps below.

  • Check the related dll’s are added in the system, after installed Ajax extensions. Below are the namespaces you required in the webservice.cs file.
  • using System.Web.Services;
    using System.Web.Script.Services;

  • Copy the webservice.asmx file to the SharePoint website virtual directory file system path [c:\inetpub\…\wss\virtualdirectories\portnumber\].
  • Copy the file webservice.cs file, and paste it in the app_code folder of the SharePoint web site.
  • Please follow the post web.config changes as explained.
  • Central administration changes as explained above.

There we are done with the process. This is really working great and we can solve really very difficult problems like all scenarios where we need to communicate with DB without doing post back etc. This is very smooth and fast way of retrieving results. I like to hear feedback. This is the one of the best solutions I found. Please post any problems if you face while implementing this process.

Isn't this a valuable find?