Monday, January 27, 2014

SharePoint Prompt for Login

One of my pet peeves with SharePoint has been that whenever I navigate to a SharePoint site on my local domain, it still prompts me for my login credentials. I have to provide the credentials with which I am already logged onto my computer, and then I'm in.

Another issue is that even though I'm logged into SharePoint when I try to open a document for editing, I am again prompted for my credentials. What happened to the idea of a single sign on?

Well, I found an article that helps solve this problem. It solves the initial site login problem, but also addresses the problem of being prompted for login each time I need to edit a document too.

http://blogs.c5insight.com/Home/tabid/40/entryid/245/Tips-to-Avoid-Login-Prompts-in-SharePoint.aspx

The article also refers to a hotfix that can be applied, and additional registry entries that may need to be made. That KB article is found here.

http://support.microsoft.com/?id=943280

This fixed my problems, hope it fixes yours :)

Friday, January 17, 2014

SQL Server Map Login to User

I often find myself restoring databases from backup so that I can move a database from one server to another. The problem is that the backup has users that have permissions associated with them, but those users don't link to the same logins on the new machine. Here is the stored procedure that links them together.

   EXEC sp_change_users_login 'Auto_Fix', '[[db user name]]';

There are other options to the sp_change_users_login, but this is the one that I usually need. This is because the login names on my server and the usernames on the database are the same. If those names do not match and you want to link them, you need to run this script.


 EXEC sp_change_users_login 'Update_One', '[[db user name]]', '[[server login name]]';

Hope this helps.

Saturday, October 5, 2013

Adding Controls to an ASP.NET form Dynamically

Dynamically added controls disappear on postback

At first glance it appears that adding a control to a form dynamically is quite simple. In fact, adding a control to a form is simple. The problem is when you need to perform a postback the control disappears. This module discusses why a dynamically added control disappears on postback and how to stop it from disappearing.
I also discuss how to get the values out of a dynamically created control.

How to add and persist controls dynamically

First I need to create a page that has a placeholder for the dynamically added controls. The page below has the following controls:
 AddControlButton
 This is the button used to create new textboxes dynamically.
 DynamicControlsHolder
 This is s placeholder control that is used to hold all newly added textboxes.
 Submit
 Another button used to submit the form. This button click event will read the values of all the dynamically added textboxes.
 ContentMessage
 A label control that will display the values of the textboxes that were added dynamically.


<%
@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Button ID="AddControlButton" runat="server" Text="Add Control"
            onclick="AddControlButton_Click" />
   
        <br />
        <asp:PlaceHolder ID="DynamicControlsHolder" runat="server"></asp:PlaceHolder>
   
        <br />
        <br />
        <asp:Button ID="Submit" runat="server" Text="Submit Form"
            onclick="Submit_Click" />
   
        <br />
        Form Contents:
        <br />
        <asp:Label ID="ContentsMessage" runat="server"></asp:Label>
   
    </div>
    </form>
</body>
</html>


Next I create a button click event for the AddControlButton. In the click event I will add a simple textbox. After creating the textbox I add it to the controlHolder placeholder control. Notice that I also add a <br> tag after the textbox. This is just to make sure that only one textbox is added on each line.


using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void AddControlButton_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
DynamicControlsHolder.Controls.Add(txt);
DynamicControlsHolder.Controls.Add(new LiteralControl("<br>"));
}
    protected void Submit_Click(object sender, EventArgs e)
{
}
}



Since the DynamicControlsHolder is stored in the pages ViewState it is easy to assume that all controls that are added to the placeholder are also automatically added to the ViewState. This is not the case however. The contents of the placeholder control are discarded once the page has been sent to the requesting browser. When a page is posted back it has to be loaded back into memory from the .aspx file. Since my dynamically added files are not listed on the .aspx page they are not re-created at post back. Each time I click the "add control" button, a new textbox is created and added to an empty placeholder control. Therefore, with each click I only see one empty textbox.

If I want to persist a textbox from one postback to the next I need to manage how it will be persisted. This can be done in a number of ways, for example it can be stored in a database, in a Session variable or in ViewState. This example uses ViewState, but I will discuss [using a database as storage mechanism in another lesson|Adding Controls to an ASP.NET Form Dynamically from a Database].

A page that has all controls provided at design time can remember what all of the controls are with each post back because they are loaded by the runtime at each post back. As noted above, controls that are added dynamically are not automatically added back to the runtime with each post back. In the following code example notice that I've modified the code to override the LoadViewState event. This event fires before the forms Load event but after the OnPreInit event. Since I am storing my dynamic controls in ViewState I cannot use the OnPreInit event to access them. They are inaccessible because the ViewState has not yet been initialized in the OnPreInit event.

Now when I add a control to the placeholder, I also need to add it to the ViewState. I've modified the code to both store and retrieve the dynamic controls to and from ViewState as follows.

  1. I added a generic list of strings to store the id's of the dnamically added textboxes (if you need to add multiple different types of controls you may want to use a hashtable, store the control id as the key and the control type as the value)
  2. I stored the list of controls in the pages ViewState
  3.  I added the overriden LoadViewState function. This function serves the purpose of reading the forms viewstate into memory. Since I want to load my controls from viewstate before any other events occur this is the appropriate function (as it happens before the Page_Load event) I use this function to load and loop through the generic list that I stored in the viewstate. On each loop I load an instance of the control into memory and give it the appropriate id. The ASP.NET engine then maps it to the object found in the viewstate.
  4.  Finally I added code to the submit buttons click event to loop through and read the values of each of the dynamically added textboxes. Since I loaded both textboxes and <br> tags into the placeholder, I have to check to make sure that the control I'm trying to read from is in fact a textbox.

using
System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    //private property to access the ControlsList in ViewState
    private List<string> ControlsList
    {
        get
        {
            if (ViewState["controls"] == null)
            {
                ViewState["controls"] = new List<string>();
            }

            return (List<string>)ViewState["controls"];
        }
    }

    //Determines what the ID shoulld be for the next control
    private int NextID
    {
        get
        {
            return ControlsList.Count + 1;
        }
    }

    //LoadViewState fires before Page_Load but after OnPreInit
    protected override void LoadViewState(object savedState)
    {
        //MAKE SURE TO LEAVE THIS CALL TO THE BASE CLASS
        // this is what loads the ViewState into memory
        base.LoadViewState(savedState);

        foreach (string txtID in ControlsList)
        {
            TextBox txt = new TextBox();
            txt.ID = txtID;
            DynamicControlsHolder.Controls.Add(txt);
            DynamicControlsHolder.Controls.Add(new LiteralControl("<br>"));

        }

    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void AddControlButton_Click(object sender, EventArgs e)
    {
        TextBox txt = new TextBox();
        //assign a value to the ID of each control
        // so that each control can be uniquely identified
        txt.ID = "TextBox" + NextID.ToString();
        DynamicControlsHolder.Controls.Add(txt);
        DynamicControlsHolder.Controls.Add(new LiteralControl("<br>"));

        ControlsList.Add(txt.ID);

    }
    protected void Submit_Click(object sender, EventArgs e)
    {

        StringBuilder sb = new StringBuilder();

        foreach (Control ctl in DynamicControlsHolder.Controls)
        {
            if (ctl is TextBox)
            {
                TextBox txt = ctl as TextBox;
                if (ctl != null)
                {
                    sb.Append(txt.ID);
                    sb.Append(": ");
                    sb.Append(txt.Text);
                    sb.Append("<br>");
                }
            }
        }

        //display contents of all texboxes in label
        ContentsMessage.Text = sb.ToString();
    }
}










The form now operates as desired, each button click will dynamically add a textbox that is persisted on each postback.


So What?

Often it is necessary to dynamically add controls to a form. This may be because you want the user to have the ability to add more fields to a form. Other times you may want to store an entire form in a database and dynamically create it from there.

This lesson showed you how to dynamically add a textbox to a form using the forms ViewState to persist the control on post backs. In [Part 2|Adding Controls to an ASP.NET Form Dynamically from a Database] I will explain how to dynamically create an entire form from a database. [Part 3|Adding Event Handlers to Dynamically Created Web Controls] will discuss adding event handlers to dynamically created controls.

Friday, October 4, 2013

Stack vs. Heap

What are the STACK and the HEAP?

To fully understand how memory is managed in the .NET Framework you need to understand the difference between the Stack and the Heap. This lesson introduces you to those differences and how it affects your development.
  • Variables that are directly managed on the Stack (or Call Stack) are called Value Types.
  • Variables that are managed on the Heap are called Reference Types.

How Do Variables On the Stack and Heap Differ?

The Stack (Value Types)

Value Types are data types that are directly managed on the stack. This means that when a variable is declared it directly contains its data on the stack.
Value Types include...
  • Integral types
    • sbyte
    • byte
    • short
    • ushort
    • int
    • uint
    • long
    • ulong
    • char
  • Floating Point types
    • float
    • double
  • Decimal type
    • decimal
  • Boolean type
    • bool
  • Enumerations
    • any enumeration created using "enum"
  • Structures
    • user defined datatype created using "struct"
The following code sample shows that Value Types directly contain their own data.
static void Main(string[] args)
{
int i; //this declaration allocates memory on the stack
    i = 5; //i is set to the value of 5

int j; //this declaration allocaties memory on the stack
    j = i; //j receives a copy of the value of i

j++; //increment j by one - since j has its own copy, i remains unaffected

//i = 5
//j = 6

}

The Heap (Reference Types)

Reference Types are managed on the heap. This means that when a variable is declared, the stack receives a reference to the memory on the heap. In other word, the variable does not directly contain its own data on the stack.
Reference Types include...
  • All objects that are created usng "class"
The following code sample show that Reference Types do not directly contain their own data.
static void Main(string[] args)
{
ArrayList list1; //this declaration allocates memory on the stack
    list1 = new ArrayList(); //new ArrayList() allocates memory on the heap and points to the reference
list1.Add(5);

ArrayList list2; span class="comment">//this declaration allocaties memory on the stack
list2 = list1; //list2 receives a copy of the value of list1 - however in this case the copy is only a copy of the reference
//both list1 and list2 are pointing to the same memory location on the heap

list2.Add(6); //add another item to list2 - because it is a reference type, both list1 and list2 are affected

//list1 contains 5 and 6
//list2 contains 5 and 6

}

So What?

So why is it important to understand the differences between how memory is managed on the stack and on the heap?
Memory that is allocated on the stack is released immediately when it is no longer referenced. However, memory that is allocated on the heap is not released immediately when it is no longer referenced. Garbage Collection is used to ensure that memory on the heap is released occasionally. See [Intro to Garbage Collection] for more information.

Thursday, October 3, 2013

ASP.NET - Web Sites vs Web Applications

What is the difference between an ASP.NET Web Site and Web Application?

In this lesson I discuss the major differences between an ASP.NET Web Site and an ASP.NET Web Application. I'll help you make a determination which type of project to choose by helping you understand the result that each choice offers.
The major differences include...
  • How sites are deployed and maintained
  • Personal (or team) coding style preference

Project Template Availability by Visual Studio Version

Visual Studio Version Web Application Web Site
VS 2002 (.NET 1.0) X --
VS 2003 (.NET 1.1) X --
VS 2005 (.NET 2.0) -- X
VS 2005  Service Pack 1 (.NET 2.0) X X
VS 2008 (.NET 2.0 - 3.5) X X

Brief History

When ASP.NET was first released the model for creating web sites was dramatically altered from the classic ASP model. Web Applications were the only project type available to .NET developers in .NET 1.x.

Included in the major changes to the .NET Framework when .NET 2.0 was released was the "new and improved" way of developing web sites. Visual Studio therefore supported Web Sites, but not Web Applications.

Because so many projects were already live and supporting Web Applications, many developers "requested" that Web Applications would continue to be supported in future versions of .NET. As of Visual Studio 2005 SP1, web applications were again supported.

How should I choose whether to use a Web Site or a Web Application?

Difference in Deployment and Maintenance


ASP.NET Web Site ASP.NET Web Application
  • Site does not have to be pre-compiled
  • Deploy both .aspx file and associated code file (.cs or .vb)
  • Small changes to the site do not require a full re-deployment (i.e. you can upload only the code file that was changed)
  • Site has to be pre-compiled prior to deployment
  • Deploy .aspx page, but not associated code file (the pre-compiled dll will be uploaded)
  • Even small changes require a full re-compile of the entire site (i.e. if the code for a single page changes the whole site must be compiled)

Difference in Development


ASP.NET Web Site ASP.NET Web Application
  • Mixing programming languages is allowed (code for one page can be in C# and another page can be coded in VB.NET)
  • Public functions on a page are not visible to code in other pages
  • Utility classes / functions must be placed in a special ASP.NET folder (the App_Code folder)
  • Web Sites do not have a .csproj/.vbproj file that manages the project (the folder that contains the site becomes the project root)
  • Only one programming language allowed per site (decide on programming language when starting project)
  • Public functions on one page are visible to code in other pages
  • Utility classes / function can be placed anywhere in the applications folder structure
  • Web Applications are treated like other .NET projects and are managed by a project file (.csproj or .vbproj)

More About Web Applications

Since Web Applications are treated like other .NET projects a project file determines which files should be compioled as part of the project. The language of the project must be determined when the project is created and each code file must used the selected language. This is because a single compiler is used to compile all code in the site into one .dll which is stored in the "bin" directory.

Since all compiled code resides in the same dll public functions in one class are visible to the code in another class. This allows developers to call page specific functions from other pages.

Changes to a single code file requires a full re-compile of the Web Application. The .dll in the bin folder can then be uploaded. It requires careful planning to ensure new bugs aren't introduced to the production site when uploading bug fixes or other changes.

More About Web Sites

Web Sites are not treated like other .NET projects. They are not managed by a project file, rather Visual Studio looks at a folder to see which files should be included (all files in the directory are included). This is mainly becuase of the way Web Site projects are compiled. The web.config file indicates to IIS that the site must be compiled. Each pages code file is compiled into its own dll at runtime (i.e. Default.aspx.dll, Login.aspx.dll) and is merged with the associated .aspx page.

Because each page is compiled into its own dll, different compilers may be used (i.e. Default.aspx can use C# while Login.aspx uses VB.NET). However, since each page becomes its own dll, the pages don't have references to each other and can therefore not call functions in another page (even public functions).

To allow developers to create utility classes that have shared code .NET introduced a special folder where shared code is stored (the App_Code folder). All code that is placed into the App_Code folder is compiled into a .dll at run-time which is copied to the bin folder. With the dll in the bin folder it is automatically referenced by all pages making the public classes and functions available to all pages. Page specific functions may be placed in partial classes in the App_Code folder to achieve the same effect as public page functions in Web Applications.

The App_Code folder determines which compiler to use based on the first code file it finds. This means, by default, only one language may be used in the App_Code folder. Developers may create sub-directories in the App_Code folder for [different languages|Adding CS and VB to the App_Code Folder] if desired. Each of these sub-directories must be registered with the web.config file to indicate which compiler should be used (C# or VB.NET). If multiple languages are used, one dll will be generated for each language.

Changes to individual code files are easily deployed to the production web site. Only the changed file needs to be deployed. If the file is a page code file, only that one page will be re-compiled the next time it is requested. If the file is in the App_Code folder only the App_Code dll will be re-compiled. If the web.config file is changed, the entire pre-compiled web site cache is cleared from the server and the whole site is re-compiled.

So does it really make a difference which project type I choose?

Whether you choose to use a Web Application or a Web Site as your project type will have no bearing on the experience that the end user of your site will have. This choice will only affect your development and deployment experiences.

Typically a Web Application is a good choice if you are developing a website to be deployed similar to a software application. You may be developing a web site package that, once deployed you will not directly maintain. Updates to the site may also be handled through an installer which will either update a portion of the site or overwrite the entire site with a newer version.

 Web Site projects are a good choice for sites over which you will have full control. If you are the developer of a custom site which requires constant updates and programming changes, you may want a project that allows you to deploy individual code files. This also requires careful planning. If you upload only a single file but the changes to that file are dependent on other changes, your changes will most likely result in run-time errors.

Wednesday, October 2, 2013

Getting Started with ASP.NET Web Sites


What makes ASP.NET Web Sites Different?

In this lesson I will show you how to create a basic ASP.NET web site. I will also explain the basic structure of a web site as follows.
  • How ASP.NET separates Code from HTML
  • What files are included in an ASP.NET web site
  • Special folders in ASP.NET web sites
At the conclusion of this lesson you will be able to create an ASP.NET Web Site and create a web form with basic functionality.

How are ASP.NET Web Sites Created?

Create an ASP.NET Web Site

Begin by launching Visual Studio (in the video I am using Visual Studio 2008, but Visual Studio 2005 or Visual Studio Web Developer Express Editions will also work).
Click File > New > Web Site.




This will open a New Web Site Dialog box where you will specify...
  1. The project template (select ASP.NET Web Site)
  2. The .NET Framework version (available options are 2.0, 3.0 and 3.5 - for this exercise select 3.5 - the default)
  3. The location of the project files (select File System as type and specify a location)
    • The name of the selected folder acts as the name of the web site as well (you do not select a project name with an ASP.NET template)
    • File System - this allows you to specify a folder on the current machine
    • FTP - this allows you to connect directly to a site via FTP. By selecting this option you modify files directly on the FTP server
    • HTTP - this option allows you to connect directly to a site on the web server. The server must have Front Page Extensions installed for this option to work.
  4. The default programming language - options are Visual Basic and Visual C#
    • Unlike other project types, if you choose the wrong language here, you can change the language later (you can even mix languages - some pages VB some C#)


When you click "OK" it will create the web site at the specified location with the following files and folders.
  • App_Data (folder)
  • Default.aspx
  • Default.aspx.cs (or.vb depending on language)
  • web.config

HTML is separated from Code

Notice that the default page that was created (Default.aspx) has an associated code page (Default.aspx.cs for C# or Default.aspx.vb for Visual Basic). In ASP.NET code is separated from the HTML. This allows designers to more easily focus the look and feel of the page while the developers focus on programming it.
To see how the aspx page is linked to the associated code file, you need to open Default.aspx in Source View (this is done by double clicking Default.aspx in Solution Explorer). Look at the page directive at the top of the page.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
Each attribute in the page directive plays a part in telling the server how to process the page.
  • Language - specifies which compiler the web server should use to compile the code. Each page can only specify one language.
  • AutoEventWireup - specifies whether or not auto page events should be processed (i.e. Page_Load). If a page will not have code in any of the auto events, processing is more efficient if auto events are not wired.
  • CodeFile - specifies the location of the associated code file.
  • Inherits - specifies the name of the class in the code file with which the page should merge.
Now open Default.aspx.cs (or Default.aspx.vb) by double clicking it in Solution Explorer. The file contains a partial class named _default. This is the class that is referenced in the page directive. Both the HTML page and the Code file are partial classes and are therefore merged at runtime.
    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Web;
    5 using System.Web.UI;
    6 using System.Web.UI.WebControls;
    7 
    8 public partial class _Default : System.Web.UI.Page
    9 {
   10     protected void Page_Load(object sender, EventArgs e)
   11     {
   12 
   13     }
   14 }

Why are pages in ASP.NET called WebForms?

Aspx pages in ASP.NET are referred to as WebForms. This is because the each page has to be based on a single form element. Unlike standard HTML form elements however, a WebForm must be a server form control.
    1 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
    2 
    3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    4 
    5 <html xmlns="http://www.w3.org/1999/xhtml">
    6 <head runat="server">
    7     <title></title>
    8 </head>
    9 <body>
   10     <form id="form1" runat="server">
   11     <div>
   12     </div>
   13     </form>
   14 </body>
   15 </html>
The method and action attributes are omitted. This means that default values are used. In other words, the method is Post and the action is that the page will pst back to itself. Notice that the form element has 2 non-standard attributes (runat="server" and ID=form1").
  • runat="server" - makes the form accessible to sever side processing.
  • ID="form1" - specifies that form1 is the name by which server side code can access the form.
Adding Code to the Page
Now we can add a few controls to add basic functionality to the form. We will add 3 [controls|Working with Controls in ASP.NET]. Notice that like the form, each control has a runat="server" attribute.
  • TextBox - a text box in which the user will enter their name.
  • Button - when clicked will execute code to display a greeting to the name entered in the FirstName text box.
  • Label - a placeholder where the greeting will be displayed.
    1 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
    2 
    3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    4 
    5 <html xmlns="http://www.w3.org/1999/xhtml">
    6 <head runat="server">
    7     <title></title>
    8 </head>
    9 <body>
   10     <form id="form1" runat="server">
   11     <div>
   12         Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
   13         <br />
   14         <asp:Button ID="SubmitButton" runat="server" Text="Greet"
   15             onclick="SubmitButton_Click" />
   16         <br />
   17         <asp:Label ID="WelcomeLabel" runat="server" Text="Label"></asp:Label>
   18     </div>
   19     </form>
   20 </body>
   21 </html>
The button control registers a [click event|Introducing Event Handling in ASP.NET] which will be handled by the following server side code. When the button is clicked, the code will take the text of the FIrstName text box as input and display a greeting to the user in the label placeholder.
    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Web;
    5 using System.Web.UI;
    6 using System.Web.UI.WebControls;
    7 
    8 public partial class _Default : System.Web.UI.Page
    9 {
   10     protected void Page_Load(object sender, EventArgs e)
   11     {
   12 
   13     }
   14     protected void SubmitButton_Click(object sender, EventArgs e)
   15     {
   16         WelcomeLabel.Text = "Hello " + FirstName.Text;
   17     }
   18 }
To test the page press the F5 key (you can also launch the page bly clicking Debug > Start Debugging).

So What?

One of the very exciting benefits of programming web sites with ASP.NET is the seperation of HTML and Code. This means that both design teams and development teams can work on projects at the same time. In other web development environments (such as classic ASP or PHP) Code is intermixed with the HTML. This usually means that once programming logic has been introduced, web designers can not make changes to the page directly. Instead, they must submit changes to the development team who must implement the design changes in their programming logic.
With this code separation it is much easier to manage and maintain existing sites. Also, since code is separated, both the HTML and Code files appear much less cluttered and are easier to read.

Monday, April 22, 2013

Adobe Illustrator Saving Issues

On occasion I've had issues with saving my Illustrator files. I create a new file or make changes to an existing one, but when I try to save I get an error message. This happened to me in Illustrator 11 and CS3. I tried saving the file in different formats to see if that would work... no go. The cause is that the Adobe Prefs file  can become corrupted and then there are problems saving files.

The FIX: You need to delete the current Prefs file. Illustrator will create a new one when it runs again. To delete the file...

...hold down CTRL-ALT-SHIFT while starting Illustrator. Make sure that you hold it down until it is completely loaded. If prompted, select "Yes" to delete the current Prefs file.