SharePoint RunWithElevatedPrivileges Example

The following example sends an email using elevated privileges.  This will elevate the privileges to execute using the service account.

The SPSecurity.RunWithElevatedPrivileges method taks a delegate method as its argument and executes that code with the service account.

SPSecurity.RunWithElevatedPrivileges( 
    delegate()
    {
        // Your code needing elevated permissions goes here.
    }
)

Example:

public void SendEmail(Email email) 
{ 
   SPSecurity.RunWithElevatedPrivileges(delegate() 
   { 
        SmtpClient mail = new SmtpClient();    MailMessage message = new MailMessage(); 
        message.From = new MailAddress(this.SenderAddress); 
        message.To.Add(email.To); 
        message.IsBodyHtml = email.IsHtml; 
                    
        if (!string.IsNullOrEmpty(email.Cc))            
            message.CC.Add(email.Cc); 
                    
        if (!string.IsNullOrEmpty(email.Bcc))            
            message.Bcc.Add(email.Bcc); 
                    
        if (!string.IsNullOrEmpty(this.ReplyToAddress))             
            message.ReplyTo = new MailAddress(this.ReplyToAddress); 
                    
        if (!string.IsNullOrEmpty(email.Subject))            
            message.Subject = email.Subject; 
                    
        if (!string.IsNullOrEmpty(email.Body))            
            message.Body = email.Body; 

        mail.Host = this.CentralAdminOutboundServerAddress; mail.Send(message); 
    });
}

Logging to the SharePoint Log Files

Thanks to Brad Younge for sharing this a while back.  Below is an example on how to write to the SharePoint log files (located in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS folder).

catch(Exception e) 
{
   Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception: {0} - {1}", e.Message, e.StackTrace);
}

You’ll likely want to prefix your log entries with a date and time stamp.

Convert a string to an enumerated (enum) value.

Using the Enum.Parse method, you can easily convert a string value to an enumerated value.  Doing this requires the type of the enum and string value.  Adding the true argument will cause the case to be ignored.

Using the following enum for this example:

private enum Aircraft 
{
   Beech,
   Cessna,
   Piper
}

You can easily convert the string to an enum value like this:

Aircraft air = (Aircraft) Enum.Parse(typeof(Aircraft), "Cessna", true); 

Ideally you should wrap a try-catch around the Enum.Parse statement.

Simple String Date Validation

Simple string date validation.

Updated: Use DateTime.TryParse() method instead (which was introduced after this original posting which was originally posted during the .NET version 1.x days and moved from my old blog)

Example:

DateTime testDate; 
bool isValidString = DateTime.TryParse(myDateString, out testDate);

Original (Obsolete) Posting during .NET 1.0:
I am a big fan of maintaining a library of simple and clean helper methods.  Here is a simple and clean way to verify if a string formatted date is a valid date.  This allows you to encapsulate the exception handling making it easy to use and very readable – another important coding practice.

private static bool IsDate(string sDate) 
{ 
    DateTime dt; 
    bool isDate = true;

    try
    {
        dt = DateTime.Parse(sDate); 
    }
    catch 
    { 
        isDate = false; 
    }     return isDate; 
}

Why C# is used more or preferred over VB.NET?

I recently received a question from someone asking:
Why C# is used more or preferred over VB.NET?

I believe the answer to this question has mostly to do with perception and history.

Although VB.NET is an excellent language, the problem with VB.NET has more to do with the history of BASIC than what VB.NET is today. I can tell you that I prefer C# over VB.NET, and I programmed with Visual Basic versions 3 through 6 with much success. However, as any ex-Visual Basic developer an attest to, Visual Basic was always viewed as a second-rate language by C++ and Java developers. There were certainly a number of things that the C++ language would allow over Visual Basic, and not all of them were necessarily positive. Much of the flexibility allowed by C++ was also the demise of many C++ applications.

I viewed C++ like a surgeon’s scalpel. With a scalpel, it can take a long time to carve out a piece of art. And, in the wrong hands you can do more damage than good, as I have seen. However, in the right hands, you can do very good things. With C++ a developer could do virtually anything since C++ was the core language on which most operating systems were written, and the core for the Microsoft libraries.

Visual Basic was intended to address the need to rapidly develop applications for the largest share of applications needed, such as business applications. Business applications are more about good business process logic and intuitive user interfaces, not complex user interfaces or algorithms. Visual Basic was Microsoft’s initial attempt at providing a development language to improve programmer productivity. Visual Basic addressed this need well.

With this little bit of history, programmers who used Visual Basic were not considered by some (C++ and Java developers) to be “professional” developers. The fact that Visual Basic had the word “Basic” in it was probably the single most dominating reason – in my opinion. Anything that is “Basic” is probably not powerful – as viewed by many who never really ever used Visual Basic. I must confess, I had the same biases about other database-related languages like FoxPro and DBase – and I was probably overly critical about those and other tools as well.

I personally have a great deal of respect for Visual Basic and its place in history. For me, it was the right tool for many solutions at that time. Visual Basic versions 3 through 6 existed during a time when companies were only beginning to see the advantages of Local Area Networks (LAN), the wide-spread introduction of the Internet and the explosion of the Internet, all of which happened during the timeline of Visual Basic.

If I may deviate a bit, during this time most companies; except for the large Fortune 1000 type companies), viewed personal computers and LAN’s as an expensive investment with very little return on investment (ROI). This close scrutiny of Information Technology investments eventually proved to be a good investment in productivity for the average company.  The investment in technology then began to swing the other direction at a pace where many companies and investors could not throw enough money into the advancement of technology and new technology companies; and as we all know, this ended with the DOT-COM boom and bust.

Back to the original question about VB.NET or C#. The important thing to remember is that both VB.NET and C# get their muscle from the .NET Framework. Other than a few minor differences in functionality between the two, the decision becomes mostly driven by syntax. I do not include functional because all .NET languages are interoperable with one another. Again this is provided by the .NET Framework.  I personally prefer the C# syntax. It is more like C++, JavaScript, and Java. Although I don’t use Java, I like developing in a syntax that is more widely adopted. I use JavaScript occasionally and as a creature of habit I like that C# and JavaScript are similar in basic syntax. I also prefer the terminology or keywords used by C# because they are more object oriented in nature.

This is my preference from a non-technical approach. Your comments are welcome.

Page Events: Order and PostBack (by Paul Wilson)

This is a “must have” article by Paul Wilson.  I have copied it to my site for easy reference for myself.
Paul Wilson
www.WilsonDotNet.com
www.ASPAlliance.com/PaulWilson
 

Initialization

The first method that executes when a page is requested is always the constructor. You can initialize many of the custom properties or objects in the page at this time, although there are a few limitations since the page hasn’t fully initialized yet. In particular, you will have to use the HttpContext.Current object to access the Request QueryString, Form, and Cookies collections, along with the Cache object. However, there is no way to access the Session collection within the constructor.

The next method that executes is the AddParsedSubObject method, which actually adds all the individual controls that make up a page into the control collection tree. This method is typically overridden by some of the advanced page template solutions in order to add the page contents into a particular control in the page template. This method is recursively called on all children controls for each page control, and each of these controls is initialized at this time, starting with the innermost.

The next method that executes is the DeterminePostBackMode method of the page class. This method allows you to affect the value of IsPostBack and all the related events, which might be useful if you need to load ViewState from a database for a redirect, since we will see that ViewState is only restored when IsPostBack is actually true. Just return null to force non-PostBack and return Request.Form to force a PostBack. This is not recommended, except in special cases, since it affects other events too.

The page’s OnInit method is executed next, which is typically the first method used. By the time this occurs, all the controls defined in your page will be initialized, which means that all the original values specified in the aspx page will be applied. However, ViewState and any posted values will not have been applied to controls yet, so anything that changed as a result of the code or user will not yet be restored. This is usually the best place to create, and recreate, any dynamic controls used.

Restore and Load

The next method, LoadPageStateFromPersistenceMedium, only executes for PostBacks. This method is overridden when you have altered how the page’s ViewState was saved, later in the SavePageStateToPersistenceMedium, when using Session or Custom Stores. The default implementation assumes ViewState is a Base64 encoded hidden form field, but this can be changed in these two methods using code found in this related article. Note that this method does not actually restore ViewState to the page or its controls.

After ViewState is retrieved, the next method, LoadViewState, restores it to the page, and then recursively to each control and their children, but again only on PostBacks. After this executes, each control will now be restored to the state it was last time, but user posted values will still not be applied, since this is not part of ViewState. The best use of this method is to restore any dynamic controls you created in events, based on values you must manually save in ViewState, which is now available to use.

The next method, ProcessPostData, only executes for PostBacks, and it is not able to be overridden, since it is a private method implemented by the base page class. This method finally restores the user’s posted form values by matching up controls with the names of the values, which means your page will finally be fully restored. The only catch is that dynamic controls must be created prior to this page method. This is also the method that records changes in values for the changed events later.

The page’s OnLoad method is executed next, which is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method, and all the control’s methods will be executed to catch up, including ViewState, but posted values would not be.

Raised Events

The next method, ProcessPostData, is actually a second pass of the earlier method, which still only executes for PostBacks and is not overridable since private method. This second pass always seems a little odd when you first notice it in the page trace, but it occurs because dynamic controls recreated in OnLoad need their posted values. Any controls that are dynamically created after this method, while having ViewState restored, will not get their posted values nor be able to trigger any changed events.

The next method, RaiseChangedEvents, also occurs only for PostBacks, and it too is a private method that is implemented in the base page class that cannot be overridden. This is the time in the page lifecycle that the changed events are actually raised, based on the differences that ProcessPostData noted before and after posted values. You may also want to call Validate and check the value of IsValid, if not already. There is no guarantee about the order that multiple changed events will be raised.

The next method, RaisePostBackEvent, also occurs only for PostBacks, and it too is a private method that is implemented in the base page class that cannot be overridden. This is where the event that actually submitted the form, unless using AutoPostBack, is actually raised, typically a button, or a control that uses javascript to submit. If not manually called already, Validate is also called, when using some Validators. Note a bug in IE sometimes allows the Enter key to submit without triggering an event.

The page’s OnPreRender method is executed next, which is typically the last chance to affect the page and its controls before it is rendered to the client’s browser. You can also create dynamic controls in this method, and all the control’s methods will be executed to catch up, including ViewState, but the earlier private methods will not receive another pass, meaning no posted values are restored and no events. This is a good place to catch a PostBack without an event due to the bug noted in IE.

Save and Render

The next method that executes, regardless whether PostBack or not, is SaveViewState which recursively runs for each control and their children, to create the ViewState. ViewState basically stores any property values that are different from the original values that are defined in the aspx page, whether changed in the code or by the user. Note that control values are saved according to their location in the control tree, so ViewState can get corrupted if dynamic controls are later added in wrong positions.

The next method, SavePageStateToPersistenceMedium, actually saves the page ViewState. This method is overridden, along with LoadPageStateFromPersistenceMedium, to save the ViewState either to Session or a Custom Store, instead of using the hidden field. This is useful for low bandwidth cases, and Session is the default for Mobile Pages. See the code found in this related article for details of using these two methods, and note that a bug in ASP.NET requires a __VIEWSTATE field to be sent, even if empty.

The page’s Render method is executed next, which recursively runs for each control and their children, to actually create and send the resulting html to the browser. This method is used in some page template solutions to add common headers and footers to the page without using server controls, which always have a little extra overhead. Note that changes made here must be pure html, since controls are done at this time. You can capture the html output using StringBuilder, StringWriter, and HtmlTextWriter.

The very last method to be executed is OnUnload, which also calls the Dispose method. This method gives you a chance to cleanup any unmanaged resources used in the page, typically things like closing any open files or database connections open earlier. Note that this method runs only after the page has been sent to the client’s browser, so it will only affect server objects, and it will not show up in a trace of the page. And that’s the page lifecycle — everything runs all over again with each new request.

Listing 1: Page Events Summary


Method PostBack Controls

Constructor Always All
AddParsedSubObject Always All
DeterminePostBackMode Always Page
OnInit Always All

LoadPageStateFromPersistenceMedium PostBack Page
LoadViewState PostBack All
ProcessPostData1 PostBack Page
OnLoad Always All

ProcessPostData2 PostBack Page
RaiseChangedEvents PostBack Page
RaisePostBackEvent PostBack Page
OnPreRender Always All

SaveViewState Always All
SavePageStateToPersistenceMedium Always Page
Render Always All
OnUnload Always All

Author Bio

Paul Wilson is a software architect in Atlanta, currently with a medical device company. He specializes in Microsoft technologies, including .NET, C#, ASP, SQL, COM+, and VB. His WilsonWebForm Control allows Multiple Forms and Non-PostBack Forms in ASP.NET. He is a Microsoft MVP in ASP.NET and is also recognized as an ASPFriend’s ASPAce/ASPElite. He is a moderator on Microsoft’s ASP.NET Forums, as well as one of the top posters. He is certified in .NET (MCAD), as well as also holding the MCSD, MCDBA, and MCSE. Please visit his website, www.WilsonDotNet.com, or email him at Paul@WilsonDotNet.com.

Mutable or Immutable? (String and StringBuilder)

An object qualifies as being called immutable if its value cannot be modified once it has been created. For example, methods that appear to modify a String actually return a new String containing the modification.  Developers are modifying strings all the time in their code.  This may appear to the developer as mutable – but it is not.  What actually happens is your string variable/object has been changed to reference a new string value containing the results of your new string value.  For this very reason .NET has the System.Text.StringBuilder class.  If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class.

Vladimir Roubtsov has an excellent article the covers this topic in more detail.

GetPageHTML – Get the HTML code for a given URL

GetPageHTML – C# code sample to get the HTML code for a given page URL

public class SampleCode 
{ 
    public SampleCode() 
    { }

    // Download the HTML source code at the specified URL
    // You can optionally specify the username/password credentials, 
    // in case the page uses Basic Authentication 
    // Returns a null string if any error occurs 
    public static string GetHtmlPageSource(string url) 
    { 
        return GetHtmlPageSource(url, null, null); 
    }

    public static string GetHtmlPageSource(string url, string username, string password)
    { 
        System.IO.Stream st = null; 
        System.IO.StreamReader sr = null;

        try
        { 
            // make a Web request 
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);

            // if the username/password are specified, use these credentials 
            if (username != null && password != null) 
                req.Credentials = new System.Net.NetworkCredential(username, password);

            // get the response and read from the result stream 
            System.Net.WebResponse resp = req.GetResponse(); 
            st = resp.GetResponseStream(); 
            sr = new System.IO.StreamReader(st);

            // read all the text in it 
            return sr.ReadToEnd(); 
        } 
        catch (Exception ex) 
        { 
            return string.Empty; 
        } 
        finally 
        { 
            // always close readers and streams 
            sr.Close(); 
            st.Close(); 
        } 
    } 
}

Calling A Page Using ShowPage vs. Response.Redirect

Calling A Page Using ShowPage vs. Response.Redirect

Mark Wagner
May 21, 2004

Applies to

  • Response.Redirect
  • Calling a page
  • State Management

Summary

This article shows how you can call a page using strongly typed parameters just as you would call any common method.

Contents

  • Introduction
  • Response.Redirect
  • Creating Page Parameters
  • Using ShowPage and PageUrl

Introduction

The typical technique used to call a page is using the Response.Redirect method.  This often involves passing relative data in the form of a query string.  The query string is just as it implies, a string of data.  Additionally, the query string is a very unsecure method often requiring the query string to be encrypted.

Another technique is to provide a method on each page called ShowPage.  The ShowPage method provides a number of benefits.  This article will cover how simple you can accomplish this.

  • Strongly typed parameters.
  • Exposure of required parameters via the interface
  • Encapsulated parameter state management
  • Improved security (no query string visibility)
  • Page mobility within the web application

Response.Redirect

Below is an example of using the Response.Redirect method.  This looks very simple, and it is for the most part.

Example
string query = "?id=" + someVariable;
Response.Redirect("~/FolderX/PageX.aspx" + query);

Although this method works perfectly well, it can pose a security risk under certain circumstances.  As a rule, the query string should be used with the understanding that the data can be modified by the user.  The query string should always be considered as user input and therefore it should always be subject to the same validation requirements as user input is.  Page parameters address this.

The query string does not support strongly typed values.  Just to be fair, its a good thing the query string doesn’t require strongly typed values, and it is definitely worth having at times.  However, there are several times when the use of strongly typed variables is useful.  Using the query string also forces us to convert all values to a string before calling the page.  Additionally, we must to convert these string values obtained from the query string back to their native data types on the called page.  This requires the developer to research any required parameters, usually by opening the source code for that page and inspecting the page’s Page_Load method or page documentation.  Page parameters provide for strongly typed values as well as exposure via the page’s class interface.

The session object is another mechanism for managing state between page calls.  This also works well, but it requires the calling page to know the name of the session variable(s) to use in storing the value(s).  Page parameters resolve this using encapsulation.

With most web projects the pages are not moved around all that often once they are created.  However, there are times when they do need to be moved.  Page parameters addresses this by encapsulating the page url in a central location and removes the need to hard-code or duplicate this information in other pages.

Creating Page Parameters

Using page parameters involves creating one static property and one static method.  These new methods should be static for optimal performance and ease of use for the developer.  As we know, static methods are available as part of the class definition and do not require the page class to be instantiated.

PageUrl property

The first property we create is the PageUrl property.  This encapsulates the url used to call this page.  The string containing the url should be relative to the root of the application.  Using the HttpContext.Current.Request.ApplicationPath ensures we return the url relative to the web applications root folder.  Additionally, exposing this url as a public method allows the url to be available for use when needed in situations such as for a menu link, hyperlink, or any other url related need.  The following is an example of the PageUrl property to add to you page.

Example
public static string PageUrl
{
  get
  {
    return HttpContext.Current.Request.ApplicationPath + "/FolderX/PageX.aspx";
  }
}

ShowPage Method

The second method needed is the ShowPage method.  This facilitates the need to call (redirect to) this page.  When calling a page it is often necessary to pass data to that page.  This is often done using the query string, session state, or some other mechanism.  Again, although these methods work fine, there are several drawbacks to these methods as discussed above in the Response.Redirect section.

In the example below we allow the user to pass objects such as a dataset to the page.  The calling page does not need to be concerned with how the required page parameters are managed.

Example
public static void ShowPage(int selectedItemPK, DataSet largeDataSet)
{
 SessionState("PageX.SelectedPK") = selectedItemPK; 
 SessionState("PageX.DataSet") = largeDataSet;
 HttpContext.Current.Response.Redirect(PageX.PageUrl);
}

Additionally, you can overload the ShowPage method to expose the acceptable combination of parameters when calling this page.

Example
public static void ShowPage(DataSet largeDataSet)
{
 ShowPage(DataSet largeDataSet);
}

public static void ShowPage()
{
 ShowPage((DataSet) null);
}

Using ShowPage and PageUrl

Having implemented these two simple methods in our page we have reduced the development time for any developer needing to call our page.  The developer simply uses the page class name to access either the ShowPage mothod or the PageUrl property.  As you will see below, using these methods is very simple.

Using the PageUrl property

Obtaining the url used to call a page is easily retrieved at run-time via the PageUrl property.  Again, this is retrieved at run-time and not hard-coded as is usually done.  In this example we are assigning the page url to a menu object.

Example
menuItem.TargetUrl = PageX.PageUrl;

Using the ShowPage method

Using the ShowPage method becomes very easy for any developer needing to call your page.  The available and required parameters are easily visible to the developer at design time via Intellisense.  Additionally, the expected data type for each parameter is easily accessible and visible to the developer.

Example
PageX.ShowPage(newDataSet);

As you can see, providing a strongly typed interface to call your page is very simple and only requires a few lines of code.