Friday, January 20, 2012
Here is an easy way to retrieve the user ID from who ever
is logged on to a PC using ASP.Net. This is handy for ASP.Net applications where
you want to put a "Welcome joe user" label at the top, auto populate a form with
the user's ID or add the user ID to some data you are storing back into a
database if you keep track of who edited a record last.
The code below assumes you have an aspx page with two labels on it, lblFName
and lblLName. It grabs the user ID with HttpContext and then splits the ID into
two values for the two names. It also assumes the user ID would be along the
lines of yourdomain\joe.user. You can do more string manipulation on the two
values if you want (i.e. like capitalizing the first letter) once you have the
values in the string array.
protected void Page_Load(object sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
lblFName.Text = "";
lblLName.Text =
"";
try
{
if
(HttpContext.Current.User.Identity.Name.IndexOf(".") >
0)
{
string uname;
uname =
HttpContext.Current.User.Identity.Name.Split('\\')[1].ToString();
string[]
splitname = new string[1];
splitname =
uname.Split('.');
lblFName.Text = splitname[0];
lblLName.Text =
splitname[1];
}
}
catch
{
//found no name, put your
error code here
}
}
}
Tags: ASP.Net, CSharp
Wednesday, January 18, 2012
This post is an example of how to write a WCF Service using a class. The example uses Visual Studio 2010, written in C#, SQL Server 2008 and hosted in IIS. So lets have at it.
Friday, December 23, 2011
Here is one way to access a control in a GridView right after a user clicks a button to change from view to edit mode. This example shows a TextBox that gets populated with today's date. The GridView is setup like this:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="TestID" DataSourceID="SqlDataSource1" onrowdatabound="GridView2_RowDataBound" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTest1" runat="server" Text='<%# BIND("TestID") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTest4" runat="server" Text='<%# BIND("TestID") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTest2" runat="server" Text='<%# BIND("Value1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtTest1" runat="server" Text="test" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTest3" runat="server" Text='<%# BIND("Value2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtTest2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The txtTest2 TextBox is the one that we want to put today's date in. To enter that information during the switch into edit you can add the following:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState.HasFlag(DataControlRowState.Edit))
{
TextBox txtBox2 = (TextBox)e.Row.FindControl("txtTest2");
txtBox2.Text = DateTime.Now.ToShortDateString();
}
}
The little trick lies in the DataControlRowState.Edit line. When that is true you can use the normal FindControl methods to grab the control you need. Probably not a common thing to do with a GridView but you never know.
Technorati Tags:
ASP.Net,
CSharp,
GridView
Thursday, November 03, 2011
In SQL Server 2008 you can use table valued parameters which can be pretty useful. In the example I use a very simple one to overcome SQL Server’s lack of having a parameter as an array. The example goes through creating the new type, using it in a stored procedure and calling it from an application (VB.Net in this example). You start off with creating the new type. Under Programmability/Types/User-Defined Table Types create a new table. Here I created a table with a single column to hold an int
Thursday, October 20, 2011
To print multiple int variables on one line you need to CAST them first. Otherwise the PRINT command will add them up (at least it does for me anyways using SQL 2008). In the example I needed to have two ID variables print out while I was working on a sproc so I could see if I was getting the correct IDs before adding in my update code.
This did not work, it adds the two variables together:
PRINT @FirstID + ‘ – ‘ + @NextID
This does work, it prints each variable with the dash in-between:
PRINT CAST(@FirstID AS Varchar(20)) + ‘ – ‘ + CAST(@NextID AS Varchar(20))
Monday, July 18, 2011
Setting up formatting when using a XmlWriter is pretty easy. Declare a XmlWriterSettings variable and set the formatting options you want. The two main items are for indenting and new lines. You add the XmlWriterSettings variable as the second parameter in the XmlWriter.Create function.
VB.Net Example
Dim mySettings As New XmlWriterSettings()
mySettings.Indent = True
mySettings.NewLineOnAttributes = True
Using writer As XmlWriter = XmlWriter.Create("c:\test.xml", settings)
C# Example
XmlWriterSettings mySettings = new XmlWriterSettings();
mySettings.Indent = true;
mySettings.NewLineOnAttributes = true;
using (XmlWriter writer = XmlWriter.Create("c:\test.xml", mySettings))
Technorati Tags:
VB.Net,
CSharp
Friday, June 17, 2011
Sometimes you need to access a control within a GridView, but it isn’t quite as straight forward as just using FindControl to grab the control like you can in a FormView. Since the GridView builds multiple rows the key is to specify the row. In this example there is a GridView with a control for a player’s errors. If the errors is greater than 9 the GridView should display the control (lblErrors) in red so it stands out. Here is the GridView:
<asp:GridView ID="gvFielding" runat="server" DataSourceID="sqlFielding" DataKeyNames="PlayerID" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="PlayerName" HeaderText="Player Name" />
<asp:BoundField DataField="PlayerNumber" HeaderText="Player Number" />
<asp:TemplateField HeaderText="Errors">
<ItemTemplate>
<asp:Label ID="lblErrors" runat="server" Text='<%# EVAL("Errors") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind you can add the code to change the label’s ForeColor property to red based on the amount of errors. In this case 10 or more errors triggers the color change.
Protected Sub gvFielding_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvFielding.DataBound
Dim errorLabel As Label
Dim errors As Integer
Dim i As Integer = 0
For Each row As GridViewRow In gvFielding.Rows
errorLabel = gvFielding.Rows(i).FindControl("lblErrors")
If Not errorLabel.Text = Nothing Then
Integer.TryParse(errorLabel.Text, errors)
If errors > 9 Then
errorLabel.ForeColor = Drawing.Color.Red
End If
End If
i += 1
Next
End Sub
The main points in the DataBound sub is use a For Each statement to loop through the rows and to increment the variable i so you loop through every row. That way you check each one and if the value is greater than 9 the label changes to red. The If Not errorLabel.Text = Nothing line is there as a check in case no data comes back at all for Errors.
Friday, May 27, 2011
Using a CTE to help with an update can be pretty handy. In this simple example the CTE is to select SiteIDs for a specific sales rep. The update is to change the address code to ‘Street’ since the rep entered them all in as ‘Mailing’ by mistake. In the update code you use an inner join to match up the SiteIDs from the CTE with the ones in tblAddress so you only update the specific sales rep’s sites and not all of them in the table.
WITH CTE(SiteID) AS
(
SELECT srs.SiteID
FROM tblSalesRepSites srs
WHERE srs.SalesRepID = '12345'
)
UPDATE tblAddress
SET AddressCode = 'Street'
FROM tblAddress addr INNER JOIN CTE ON addr.SiteID = CTE.SiteID
Monday, May 02, 2011
If nobody else but me reads this that is OK, this is just something I forget from time to time when working in VB.Net. To short circuit an expression the && or || operators in many other languages are AndAlso or OrElse in VB.Net.
Two really simple examples:
If a > b AndAlso a < c Then
If a > b OrElse a > c Then
Wednesday, April 13, 2011
A great benefit of using a CTE is their ability to replace some uses of Cursors. Sometimes you may need a Cursor to fetch an ID value from a table. Use that ID in a Select statement. Then fetch the next ID value, use that in the same Select statement over and over again until you ran through all the ID values. A CTE can help eliminate that and from what I can see is generally a bit faster than using a Cursor.
This example is using a table to hold purchase orders (tblPO) and another table to hold invoices (tblInv). tblPO has columns for the purchase order ID (POID), the purchase order number (PONum) and the amount of funds in the purchase order (POAmt). tblInv has columns for the associated purchase order (POID) and an amount for the invoice (InvAmt). The scenario is that you need a list of all purchase order IDs, numbers, amount of the PO and the amount that is still available. To calculate the amount available you need to total up all the invoice amounts for a purchase order and then subtract them from the purchase order amount.
WITH cte(POID, PONum, POAmnt) AS (
SELECT POID, PONum, POAmt FROM tblPO )
SELECT POID, PONum, POAmt,
(POAmt - (SELECT SUM(InvAmt)FROM tblInv WHERE POID = cte.POID)) AS 'Available'
FROM cte
You setup the CTE with the values you want except for the one that needs each POID individually (the amount available calculation). Then when you run a select from the CTE you can put the current POID from the CTE in the where clause. This ends up being a lot simpler and faster than setting up a Cursor and fetching each POID from tblPO.
A second way to set this up which accomplishes the same would be to create the CTE with just the ID you want to cycle through. Either way it works the same it just depends on how you like to write it.
WITH cte(POID) AS (
SELECT POID FROM tblPO)
SELECT cte.POID, po.PONum, po.POAmnt, (POAmt - (SELECT SUM(InvAmt)FROM tblInv WHERE POID = cte.POID)) AS 'Available'
FROM cte
INNER JOIN tblPO po ON po.POID = cte.POID
Technorati Tags:
SQL