Replace XElement with xml in string (C#)

If you want to replace an existing XElement by an new XElement conctructed from a string, you can use the XElement ReplaceWith method:

           XElement element = new XElement("MyName", "MyContent");
           string newValue = "<MyNewName>Some value</MyNewName>";
           element.ReplaceWith(XElement.Parse(newValue));

Exception on Microsoft SQL Server Reporting Services PrepareQuery

If you get the exception:

{"System.Web.Services.Protocols.SoapException: Cannot create a connection to data source ”. —> Microsoft.ReportingServices.Diagnostics.Utilities.DataSourceOpenException: Cannot create a connection to data source ”. —> Microsoft.ReportingServices.DataExtensions.ReportServerDataProvider.RSDPException: You have specified integrated security or credentials in the connection string for the data source, but the data source is configured to use a different credential type. To use the values in the connection string, you must configure the unattended report processing account for the report server.\n   at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.PrepareQuery(DataSource DataSource, DataSetDefinition DataSet, DataSetDefinition& DataSettings, Boolean& Changed, String[]& ParameterNames)\n   at Microsoft.ReportingServices.WebServer.ReportingService2005.PrepareQuery(DataSource DataSource, DataSetDefinition DataSet, DataSetDefinition& DataSettings, Boolean& Changed, String[]& ParameterNames)"}

Removing : integrated security=true from mine connection string solved this exception, but then an other exception occurred:

{"System.Web.Services.Protocols.SoapException: Cannot create a connection to data source ”. —> Microsoft.ReportingServices.Diagnostics.Utilities.DataSourceOpenException: Cannot create a connection to data source ”. —> System.Data.SqlClient.SqlException: Login failed for user ‘TTUser’.\n   at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.PrepareQuery(DataSource DataSource, DataSetDefinition DataSet, DataSetDefinition& DataSettings, Boolean& Changed, String[]& ParameterNames)\n   at Microsoft.ReportingServices.WebServer.ReportingService2005.PrepareQuery(DataSource DataSource, DataSetDefinition DataSet, DataSetDefinition& DataSettings, Boolean& Changed, String[]& ParameterNames)"}

This can be caused by getting a datasourcedefinition instead of creating a datasourcedefinition. When getting a datasourcedefinition the Password will be reset to NULL, resetting the password solves this exception:

// Get the shared datasource.
DataSourceDefinition dataSourceDefinition = rs.GetDataSourceContents(“TestSharedDataSource”);

// Reset password
dataSourceDefinition.Password = “mypassword”;

Lowercase first letter of a string in C# (C sharp)

If you want to lowercase the first letter of a string in C# use:

        /// <summary>
        /// Lowercase first word in string
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string LowercaseFirst(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            char[] a = s.ToCharArray();
            a[0] = char.ToLower(a[0]);

            return new string(a);
        }

Uppercase first letter of a string in C# (C sharp)

To uppercase the first letter of a string in C#, use:

        /// <summary>
        /// Capatilize first word in string
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string UppercaseFirst(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            char[] a = s.ToCharArray();
            a[0] = char.ToUpper(a[0]);

            return new string(a);
        }

Get first day of current week or last week with TSQL

To get the first day of the current week use:

select dateadd(dd, (datepart(dw, getdate()) * -1) + 2, getdate())

To get the first day of previous week and last day of previous week use:

select dateadd(day, -8, dateadd(dd, (datepart(dw, getdate()) * -1) + 2, getdate()))
select dateadd(day, -1, dateadd(dd, (datepart(dw, getdate()) * -1) + 2, getdate()))

You can also, use a variable for the current date and time, like:

declare @currentDateTime as datetime
set @currentDateTime = '2011-01-15 07:47:31.887' 

select dateadd(day, -8, dateadd(dd, (datepart(dw, @currentDateTime) * -1) + 2, @currentDateTime))
-- Result: 2011-01-02 07:47:31.887

select dateadd(day, -1, dateadd(dd, (datepart(dw, @currentDateTime) * -1) + 2, @currentDateTime))
-- Result: 2011-01-09 07:47:31.887

Failed to upgrade Microsoft SQL Server 2008 Standard to Enterprise (x64)

You can upgrade Microsoft SQL Server 2008 Standard (x64) to Microsoft SQL Server 2008 Enterprise (x64), by Start > All Programs > Microsoft SQL server 2009 > Configuration Tools > SQL Server Installation Center (64-bit) > Maintenance > Edition Upgrade, but this can’t be done when there where updates installed on the standard edition. When updates are installed, first repair you’re installation to the original files and then upgrade to Microsoft SQL Server 2008 Enterprise. 

http://msdn.microsoft.com/en-us/library/ms143393.aspx

Microsoft Outlook 2007 Search

General
· Search is not case-sensitive.
· Search for “All Mail Items”, includes all outlook files and includes folders like Inbox, Outbox, Sent Items and Conversation History

If you want to search for a Text “test”:

subject: "test " OR contents:"test " OR attachment:"test "

If you want to search for a Person "Roel van Lisdonk", you could enter only the first name with a space:

from:"roel " OR cc:"roel " OR bcc:"roel " OR to:"roel " OR subject:"roel " OR contents:"roel " OR attachment:"roel "

Microsoft Outlook 2007 How to group by date and not date and time

If you want to search all mail items (Inbox and Sent Items) in Microsoft Outlook 2007 for the text: “test” and group by received date and not date and time:

Click in the Menu on Go > Mail :

image

Click on “All Mail Items”

Click in the Menu on View > Current View > Customize Current View… > Other Settings
image

Check the “Show items in Groups
image

This will group by date and not date and time, the group by box contains a field: Date
image
This will group by: Yesterday, then all days of the current week, then last week, then all weeks of current month, the last month, then older

ASP .NET – C# – How to “Sign in as Different User” like in Microsoft SharePoint with Windows Authentication

If you’re using only Windows Authentication in you’re C# ASP .NET web application, there is no build in support for the user to “log out” or to “Sign in as Different User”, like in Microsoft Office SharePoint Server:

image 

The only way to make this work “cross-browser” (Tested on IE5, IE5.5, IE6, IE7, IE8, FireFox 3.5.5, Google Chrome 3.0.195.33) is to send a 401 HttpResponse to force the browser to re-authenticate it self. Well there are numerous pages describing the fact you should send a 401 HttpResponse within the ASP .NET C# web application, but few give a complete example. This post describers the complete example of sending a 401 HttpResponse to force the browser to re-authenticate it self. In this example I use a IIS server in a domain called “MyDomain”, but this can be replaced by a IIS Server in a workgroup, then you should replace “MyDomain” with the name of the server, eg. “MyIISServer”

– In Microsoft Visual Studio 2008, create a new web application File > New > Project > Visual C# > Web > ASP .NET Web Application
image 

– In Microsoft Visual Studio 2008, make sure you’re website project properties are set to: “Use Local IIS Web server”. Found in menu Project > MyWebSite Properties > Web
image

– Click on “Create Virtual Directory” to make sure the virtual directory exists in IIS.
– In the IIS 7 Manager, click on “MyWebSite” > “Features View” > “Authentication”
image

– Disable “Anonymous Authentication”
image

– Enable “Windows Authentication” (if not shown in Vista, Windows Server 2008 or Windows 7, install it via “Control Panel” > “Programs and Features” > “Turn Windows features on or off” > "Internet Information Services" > "World Wide Web Services" > "Security" > "Windows Authentication")
image 

– Open the Web.config of you’re website in Microsoft Visual Studio 2008 and change the authentication mode to ”Windows” and set the users to allow and deny access.

<system.web>
    <authentication mode="Windows"/>
    <identity impersonate="false" />
    <authorization>
      <allow users="MyDomain\User1,MyDomain\User2"/>
      <deny users="*"/>
    </authorization>

You should at least deny anonymous users by adding <deny users = “?” />. In this example all users are denied access, except for the users: MyDomain\User1 and MyDomain\User2.

– In Microsoft Visual Studio 2008 add 2 pages: Default.aspx and AccessDenied.aspx

– The Default.aspx should look like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyWebsite.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Default page</title>
</head>
<body>
    <form id="mainForm" runat="server">
    <div>
        <div><p>Hello <asp:Label ID="UserLabel" runat="server" Text="Label"></asp:Label></p></div>
        <div><asp:LinkButton ID="SignInAsADifferentUserLinkButton" runat="server" onclick="SignInAsADifferentUserLinkButton_Click">Sign in as a different user</asp:LinkButton></div>
    </div>
    </form>
</body>
</html>

– The Default.aspx.cs should look like:

using System;
using System.Web;

namespace MyWebsite
{ 
public partial class Default : System.Web.UI.Page { /// <summary> /// Event fires on every page load /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { // Show the current logged on user UserLabel.Text = Request.LogonUserIdentity.Name; // Make sure the browser does not cache this page this.DisablePageCaching(); } /// <summary> /// Event fires when user clicks on the "SignInAsADifferentUserLinkButton" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void SignInAsADifferentUserLinkButton_Click(object sender, EventArgs e) { // Redirect to the "log out" page cq "sign in as a different user" page Response.Redirect("AccessDenied.aspx"); } /// <summary> /// Make sure the browser does not cache this page /// </summary> public void DisablePageCaching() { Response.Expires = 0; Response.Cache.SetNoStore(); Response.AppendHeader("Pragma", "no-cache"); } }
}

 

– The AccessDenied.aspx should look like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AccessDenied.aspx.cs" Inherits="MyWebsite.AccessDenied" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>


– The AccessDenied.aspx.cs should look like:

using System;
using System.Web;

namespace MyWebsite
{
    
public partial class AccessDenied : System.Web.UI.Page
    {
        private int _authenticationAttempts = 0;
        public int AuthenticationAttempts
        {
            get
            {
                if (!string.IsNullOrEmpty(string.Format("{0}", Session["AuthenticationAttempts"])))
                {
                    int.TryParse(Session["AuthenticationAttempts"].ToString(), out _authenticationAttempts);
                }

                return _authenticationAttempts;
            }
            set
            {
                _authenticationAttempts = value;
                Session["AuthenticationAttempts"] = _authenticationAttempts;
            }
        }
        private string _currentUser = string.Empty;
        public string CurrentUser
        {
            get
            {
                _currentUser = Request.LogonUserIdentity.Name;
                Session["CurrentUser"] = _currentUser;
                return _currentUser;
            }
            set
            {
                _currentUser = value;
                Session["CurrentUser"] = _currentUser;
            }
        }
        private string _previousUser = string.Empty;
        public string PreviousUser
        {
            get
            {
                _previousUser = string.Format("{0}", Session["PreviousUser"]);
                return _previousUser;
            }
            set
            {
                _previousUser = value;
                Session["PreviousUser"] = _previousUser;
            }
        }

        /// <summary>
        /// This event fires on every page load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Make sure the browser does not cache this page
            this.DisablePageCaching();

            // Increase authentication attempts
            this.AuthenticationAttempts = this.AuthenticationAttempts + 1;


            if (this.AuthenticationAttempts == 1)
            {
                // Change previous user to current user
                this.PreviousUser = this.CurrentUser;

                // Send the first 401 response
                this.Send401();
            }
            else
            {
                // When a browser is set to "automaticaly sign in with current credentials", we have to send two 401 responses to let the browser re-authenticate itself.
                // I don't know how to determine if a browser is set to "automaticaly sign in with current credentials", so two 401 responses are always send when the user
                // does not switch accounts. In Micrososft Office sharepoint the user has to supply the credentials 3 times, when the user does not switch accounts,
                // so it think this is not a problem.
                if (this.AuthenticationAttempts == 2 && this.CurrentUser.Equals(this.PreviousUser))
                {
                    // Send the second 401 response
                    this.Send401();
                }
                else
                {
                    // Clear the session of the current user. This will clear all sessions objects including the "AuthenticationAttempts"
                    Session.Abandon();
                    Session.Clear();

                    // Redirect back to the main page
                    Response.Redirect("Default.aspx");
                }
            }
        }

        /// <summary>
        /// Make sure the browser does not cache this page
        /// </summary>
        public void DisablePageCaching()
        {
            Response.Expires = 0;
            Response.Cache.SetNoStore();
            Response.AppendHeader("Pragma", "no-cache");
        }
        /// <summary>
        /// Send a 401 response
        /// </summary>
        public void Send401()
        {
            // Create a 401 response, the browser will show the log-in dialogbox, asking the user to supply new credentials, 
// if browser is not set to "automaticaly sign in with current credentials"
Response.Buffer = true; Response.StatusCode = 401; Response.StatusDescription = "Unauthorized"; // A authentication header must be supplied. This header can be changed to Negotiate when using keberos authentication Response.AddHeader("WWW-Authenticate", "NTLM"); // Send the 401 response Response.End(); } }
}


– Set the Default.aspx as Start Page and start debugging the website.

   In IE depending on the setting Tools > Options > Security > Local intranet > Custom level… > User Authentication > Logon, the browser will show the windows logon dialog box.

   If the site is not in the “Local Intranet Zone” you adjust the same setting on “Internet” and “Trusted Sites” 
image

– Login to the website

image

– The website will show:

 image

– Click on the “Sign in as a different user”, this will show the windows dialog box

image

– The windows dialog box will always appear, but when the user supplies the same credentials as the logged in user and IE security setting for “User Authentication” > “Logon” is set to “Prompt for user name and password”. The user will be asked to supply the credential 2 times.

– I think this is not a problem, because you want to sign in as a different user, so this will never occur.

– After supplying the correct credentials the new user is logged in.

image

By looking at the MSIL code of the Microsoft.SharePoint.ApplicationPages.dll, I guess this is the way Microsoft Sharepoint does it, using the _layouts\AccessDenied.aspx