.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

SPContext.Current returns a null

Posted By:      Posted Date: October 22, 2010    Points: 0   Category :SharePoint

ok, I am new to the wonder world of WSS and Sharepoint.   The objective of my code is to upload a file into a particular folder into a document library.   Well, I was able accomplish this task ( ONCE ) on a Virtual machine but something happened somewhere and the code below no longer works:


public string UploadFile(string folderName, string fileName, byte[] contents)

{            String retVal = "File : " + fileName + " Upload Successfull.";


View Complete Post

More Related Resource Links

properties of SPContext.Current returns null after migration



I use stsadm export to migrate my site from one machine to another. After migration, I found one of my webpart does not work. It throws a null reference exception.

I logged my webpart and found it cannot get SPContext.Current.Web and SPContext.Current.List, the both returns null and cause the exception. I removed the webpart and added it again but the exception still occured. However, I created a new List on the new site then put my webpart in and it works fine.

I think it is because my migration operattion, is there anything need attention during migration?  Why SPContext.Current cannot get properties?

SPContext.Current is null in a WebService in the 12 hive layouts



  I do not understand why I cannot get the SPContext.Current instance.  It must be an IIS Setting because I get it on one machine and not on another, using identical code.

SPContext.Current is null In Custom Membership ValidateUser


Hi,I just get a problem getting SPContext.Current in Custom membership Provider.

We have successfully plugin the custom membership into Sharepoint foundation 2010. We tried to programmically update the user's full name after user logs in and it failed in 2010 version. (good in 2007)

This is the simplified code. The class is a custom membership provider.Strangely, this only happens in 2010 version and never raised a problem in 2007.

public override bool ValidateUser(string username, string password)
   bool isvalid = false;

    if(username=="admin" && password="pwd")
      isvalid = true;
     var webContext = SPContext.Current.Web; //this returns null

   catch (System.Web.Services.Protocols.SoapException exp)
    Logger.WriteLog(exp.InnerException.ToString(), "wss login error");
   return isvalid;


Please Help. Thank you.



SPContext.Current.Web.CurrentUser is null


I am using FBA in an internet zone of sharepoint site.

I am getting null in Current.Web.CurrentUser object even when i am logged in as FBA User. The welcome message is shown on top to ensure that FBA is working, but CurrentUser is giving null.

The same code works perfectly when logged in as Domain user in Intranet Zone.


SPContext.Current.Web.CurrentUser null in application page on 2008 r2 server

With my current situation I have:
a wss3 development environment on a 2003 R2 server
then a production 2008 r2 server.

For some reason on the 2008 server the SPContext.Current.Web.CurrentUser object is null for users who are site collection administrators but may not have permission to log into the server itself; however, on the 2003 R2 server the code works fine for those users.
When googling around, I had seen something about nt permissions on the bin folder sometimes being and issue until asp.net cache picks up the dll but this is a page in the _layouts directory and the code is in the .aspx page itself. It works fine for me as a system administrator on either machine.

Any suggestions? Thanks.

SPContext.Current.Web.CurrentUser returns inconsistent username (With different characters)



We are using MOSS 2007 with browser enabled Infopath forms. We have a user with username "DOMAINNAME\fakgul" (Active Directory also displays the user as this). However when the user opens an Infopath form  the code line behind the form below:

SPUser openedByUser = SPContext.Current.Web.CurrentUser;

returns "DOMAINNAME\fakgül" (with "U-umlaut"). When we enter the "User information" page of that user, "Account" field also displays as "DOMAINNAME\fakgül" (with "U-umlaut").

What is more strange is this is not the consist

SPContext.Current.Web.CurrentUser.Name returns complete value claims


Hi All, 

I just had another interesting issues in claims !

I was using this property SPContext.Current.Web.CurrentUser.Name in my webpart to show user name. 

Before it was working fine but all of a sudden it is showing complete string like this: 


before it was just showing 'name' only.

So, now i have this ugly formatted username in my welcome control !!

anyone faced the same issue? 





Users getting logged out because HttpContext.Current is null


We've  been trying to fix this one for a couple years, and I'm just out of ideas, so any help is really appreciated!

We've got a fairly large, complex web application that uses Forms Authentication to authenticate users.  Throughout the application we store and retrieve information about users in the Session object, and in some cases in cookies.  In a couple places we check for the existence of the context, and if it's null we send the user back to the login page to re-establish the session. 

Just a quick run-down of this web app: C#, .NET 3.5, IIS 6, ASP.NET State Service to manage session

As for the session timer, we use our own home-grown timer, which is basically a client-side timer, which is backed up by a check to the SQL database to see when their last activity was.  This seems to work well for us.  It's not perfect, but it allows us to notify the user before the session times out, and allows us to be certain we're not logging a user out before their 60 minutes of inactivity is up.

What's happening is that certain users are being logged out after just a few minutes.  We've eliminated the timer as a cause and believe what's happening is the HttpContext.Current is null, so the user is logged out.  We do not know why the HttpContext.Current is null, and I underst

Linq to SQL returns null for DateTime fields.


I have a linq to sql entity class in which I declared some DateTime fileds like this:

[Column(DbType = "smalldatetime")]
public DateTime? StartDate { get; set; }

And this is how I fetch data form repository:

return repository.Logs.OrderByDescending(l => l.LogID).FirstOrDefault();

All non DateTime fields are filled properly but all datetimes are null.

[Column(DbType = "smalldatetime")]

        public DateTime? StartDate { get; set; }

BuildManager.GetType returns null until application pool recycles

Our application uses the Enterprise Library's PropertyProxyValidator class to validate user input (v4.1 - Oct 2008).  On occassion, the code will raise an exception saying the source type cannot be found.  This error persists until the application pools recycle at night, at which point everything works again.  It tends to only affect one of the web front ends at a time (there are two). I tracked down where the exception was being raised, and this is the section of code:Type IValidationIntegrationProxy.ValidatedType { get { if (string.IsNullOrEmpty(this.sourceTypeName)) { throw new InvalidOperationException(Resources.ExceptionNullSourceTypeName); } Type validatedType = BuildManager.GetType(this.SourceTypeName, false, false); if (validatedType == null) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentUICulture, Resources.ExceptionInvalidSourceTypeName, this.sourceTypeName)); } return validatedType; } } (As you can see, the value for this.SourceTypeName is shown in the exception and I've checked that it matches exactly.) We have never been able to reproduce this exception and at this point don't have any ideas left as far as causes.  For a while, my suspicion was that it was related to the Temporary ASP.NET Files folder.  The last

Get current logon user id with SPContext.Current.Web.CurrentUser.LoginName

Hi all,I've been trying to search for the method to display the currently logon user id. So far, most sites I've visited used SPContext.Current.Web.CurrentUser.LoginName.I've tried this in my SharePoint custom application page. Everything works great.I have a test account, when logged in, was displayed as xxx\testacc.For some reasons, I changed the id in AD to xxx\test and did a full import to MOSS.I logged in to the custom application with the changed id, i.e. xxx\test, BUT the value of SPContext.Current.Web.CurrentUser.LoginName still displayed as xxx\testacc!How do I get the latest id? Has anyone encountered this before?Thank you.Kelvin

Registry OpenSubKey returns null

Hi,It seemed to be the right place to post to.My problem is that when I try to read registry key, I get null value, even if it exists (regedit shows it exists).Application is windows service with Log On As Local System and registry key im trying to read is in HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSIDOn my development machine (x64 win7) it works fine. But in live server (x64 windows server 2008 r2) I get NULL. These operating systems should have similar policies or does Local System on server 2008 have any restrictions i should know about?RegardsMax

HttpContext.Current is null

I have an intermittent issue where HttpContext.Current is null.  I do have aspNetCompatibilityEnabled="True".  I can duplicate it by restarting the webservice and make the request.  The first request has the HttpContext.Current set to null but subsequent requests have the proper HttpContext.  I've done some tracing and the messages are exactly the same. What else is weird is that the HttpContext is NOT null in my global.asax but by the time it hits my custom UsernamePasswordValidator, it is set to null.   Any ideas on what i'm doing wrong? HttpRequest from tracing: <HttpRequest> <Method>POST</Method> <QueryString></QueryString> <WebHeaders> <Cache-Control>no-cache</Cache-Control> <Connection>Keep-Alive</Connection> <Content-Length>799</Content-Length> <Content-Type>text/xml; charset=utf-8</Content-Type> <Accept>*/*</Accept> <Accept-Encoding>identity</Accept-Encoding> <Host>mydomain.com</Host> <User-Agent>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; InfoPath.2)</User-Agent> <SOAPAction>"http://tempuri.org/ICategoryService/GetAvailablePickList"</SOAPAction> </WebHeaders> </Htt

Problem with Spcontext.current.web.currentuser.name

Hi all, I am using Spcontext in code to retrive the current user login name. But some times Spcontext.current.web.currentuser.name will return name of the user who is currently logged in it is retruning user name other than the current. When I refresh the page two or three times It will return the proper user name. Can anyone help me to resolve this issue.

FindControl returns null

I am trying to fetch two Labels within a Repeater element to attach data to; which Label is assigned which Data Field depends on the result of a Radio Button List, hence why I need to fetch them in the code behind. This is the ASP.NET code: <asp:View ID="vwSportType" runat="server"> <table> <tr> <td rowspan="2"> <span class="boldtext">Select type of sport:</span><br /><br /> <asp:ListBox ID="lbType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="lbType_OnSelectedIndexChanged" Height="300px" Width="12em"> </asp:ListBox> </td> <td width="70%"> <span class="boldtext">Show by: <asp:RadioButtonList ID="rbSportType" runat="server" RepeatDirection="Horizontal"> <asp:ListItem Text="Date, Sport" Selected="True" Value="0"></asp:ListItem> <asp:ListItem Text="Sport,

Why this returns null

hi friends, i have a table AppUser.UsersUserRole that has the following structure: idx auto ur_id int -- user role id id int    -- user id that has the following data:  From Drop Box  when i ran query to returns a csv: declare @csv nvarchar(max) select @csv = @csv + coalesce( convert(nvarchar(max), ur_id) + ',','' ) from AppUser.UsersUserRoles where id = 28 select @csv it returns:  From Drop Box  but there are three records for 28, why it displays null, how do i fix this? thanks

SCOPE_IDENTITY() returns null after paramerized INSERT


I have a very simple database, without any triggers at this point. One of my tbales has a auto increment key (IDENTITY field). As the record has a string attribute, which valeu is received from the user, I insert a new records with a parametized INSERT statement. After insertion I try to fetch the new record's ID with the sttament SELECT SCOPE_IDENTITY(), but ti return null - while SELECT @IDENTITY and SELECT IDENT_CURRENT returns the valid values.

Moreover, if - for testing purposes - I execute the same insert without parameters, (i.e. providing the string value directly in the INSERT statement), then even SCOPE_IDENTITY() returns the correct value.

I didn't find any reference in the documentation regarding such restriction. Is is a known bug or the result of some misunderstading?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend