Glowing WPF Buttons

Someone asked on Stack Overflow:

After clicking the WPF buttons in our app they glow blue, back to original color, back to blue, etc. This appears to be default behavior on Windows Vista/7. It does not happen on XP. Any advice?

I posted the following answer, which was chosen as the accepted answer and received 9 upvotes:

You need to override the default button template — http://mark-dot-net.blogspot.com/2007/07/creating-custom-wpf-button-template-in.html should get ya started.

Specifically Section 3:

<ControlTemplate.Triggers>
    <Trigger Property="IsMouseOver" Value="True">
        <Setter TargetName="border" Property="BorderBrush" Value="#FF4788c8" />
        <Setter Property="Foreground" Value="#FF4788c8" />
    </Trigger>
    <Trigger Property="IsPressed" Value="True">                   
       <Setter Property="Background" >
           <Setter.Value>
               <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                   <GradientStop Color="#FFFFD190" Offset="0.35"/>
                   <GradientStop Color="Orange" Offset="0.95"/>
                   <GradientStop Color="#FFFFD190" Offset="1"/>
               </LinearGradientBrush>
            </Setter.Value>
        </Setter>
        <Setter TargetName="content" Property="RenderTransform" >
            <Setter.Value>
                <TranslateTransform Y="1.0" />
            </Setter.Value>
        </Setter>
    </Trigger>
    <Trigger Property="IsDefaulted" Value="True">
       <Setter TargetName="border" Property="BorderBrush" Value="#FF282828" />
    </Trigger>
    <Trigger Property="IsFocused" Value="True">
       <Setter TargetName="border" Property="BorderBrush" Value="#FF282828" />
    </Trigger>
    <Trigger Property="IsEnabled" Value="False">
       <Setter TargetName="border" Property="Opacity" Value="0.7" />
       <Setter Property="Foreground" Value="Gray" />
   </Trigger>
</ControlTemplate.Triggers>
Notable comments

Nate (1 upvotes): @markmnl Feel free to post an alternate answer if there is a better approach! There has been no accepted answer here. The Style option may very well be the best option. If anything else it will help others who find this post, even if OP has solved and shipped his code.


Originally posted on Stack Overflow — 9 upvotes (accepted answer). Licensed under CC BY-SA.

Building an ASP.NET MVC Master Page Menu Dynamically, Based on the current User&#39;s &quot;Role&quot;

I asked this on Stack Overflow:

I’ve seen some similar questions, but none that look like what I’m trying to do.

This is my current implementation w/out any security:

<div id="menucontainer">
    <ul id="menu">              
        <li><%= Html.ActionLink("Main List", "Index", "AController")%></li>
        <li><%= Html.ActionLink("Product List", "Index", "BController")%></li>
        <li><%= Html.ActionLink("Company List", "Index", "CController")%></li>
        <li><%= Html.ActionLink("User List", "Index", "DController")%></li>
    </ul>
</div>

This is fine, and the above works. I have [Authorize] Attributes setup on the Actions for CController and DController to prevent unauthorized access — but I’d like to remove those items from the menu for users who don’t have the correct Role, because when they see it and click on it and it tells them they don’t have permission, they’ll want it. If they don’t know it’s there, that’s just better for everyone involved…

Something like this is ultimately the goal I’m trying to get at, but I’m looking for the more MVC Flavored aproach, where the “view” is “dumb”:

<div id="menucontainer">
    <ul id="menu">              
        <li><%= Html.ActionLink("Main List", "Index", "AController")%></li>
        <li><%= Html.ActionLink("Product List", "Index", "BController")%></li>
        <% If(Role = Roles.Admin) { %>
        <li><%= Html.ActionLink("Company List", "Index", "CController")%></li>
        <li><%= Html.ActionLink("User List", "Index", "DController")%></li>
        <% } %>
    </ul>
</div>

jeroenh answered (15 upvotes):

I have done something like this:

  • use a common base class for my controllers (‘layer supertype’)
  • in the BaseController, override OnActionExecuted (you could also define an ActionFilter attribute for this)

Something like this:

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // build list of menu items based on user's permissions, and add it to ViewData
        IEnumerable<MenuItem> menu = BuildMenu(); 
        ViewData["Menu"] = menu;
    }

In the master page:

    <% var model = ViewData["Menu"] as IEnumerable<MenuItem>; %>
    <% Html.RenderPartial("Menu", model); %>

(Note: in reality, I have a MasterViewModel that contains among others the menu model)

Notable comments

Nate (0 upvotes): I am… I think. There are two levels of user, Normal and Admin. Only admin can see Company and User lists, the [Authorize] attributes on the controller prevent unauthorized access, but I want to hide the view from non-Admin’s so they don’t even get the idea that its there in their head.


Originally posted on Stack Overflow — 15 upvotes. Licensed under CC BY-SA.

Relative Paths in Javascript in an external file

I asked this on Stack Overflow:

So I’m running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.

This is in an external .js file, folder structure is

Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg

then this is where the js file is included from

Site/Views/ProductList/Index.aspx

$("#toggle").click(function() {
    if (left.width() > 0) {
        AnimateNav(left, right, 0);
        $(this).css("background", "url('../Images/filters_expand.jpg')");
    }
    else {
        AnimateNav(left, right, 170);
        $(this).css("background", "url('../Images/filters_collapse.jpg')");
    }
});

I’ve tried using '/Images/filters_collapse.jpg' and that doesn’t work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.

Basically, I want have the same functionallity as the ASP.NET tilda — ~.

update

Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?


Juraj Blahunka answered (146 upvotes):

JavaScript file paths

When in script, paths are relative to displayed page

to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:

Solution, which was employed on StackOverflow around Feb 2010:

<script type="text/javascript">
   var imagePath = 'http://sstatic.net/so/img/';
</script>

If you were visiting this page around 2010 you could just have a look at StackOverflow’s html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section

Notable comments

Nate (0 upvotes): Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?

Nate (0 upvotes): I’m using javascript to dynamically change the background image of a div tag. I’d like to avoid putting the code back into the master page file, since it’s much more clean its own external .JS file…

Nate (0 upvotes): That is exactly the problem! Depending on where the virtual directory is located, I don’t want to have to update my javascript every time I switch from dev to production…


Originally posted on Stack Overflow — 97 upvotes. Licensed under CC BY-SA.

Bind WPF control to SQL server through repository pattern

Someone asked on Stack Overflow:

How can I bind a wpf control to a SQL Server property. Like say a Listbox

 <ListView>
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name">
                <GridViewColumn Header="Date Assigned">
                <GridViewColumn Header="Date Due">
            </GridView>
        </ListView.View>
        <!-- iterate through all the Names in the database and output under GridViewColumn Name -->
        <!-- iterate through all the DateAssigned in the database and output under GridViewColumn Date Assigned -->
        <!-- iterate through all the DateDue in the database and output under GridViewColumn Date Due -->
    </ListView>

I am using the entity framework and the repository pattern. So I’d call all the names to a list by _repository.ToList();

I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:

Try this: listViewName.ItemsSource = _repository.ToList();

I’d also simplify the Xaml, like this:

<ListBox x:Name="listViewName">
    <ListBox.Resources>
        <DataTemplate>
            <Grid Height="22" Width="Auto">
                <TextBlock Text="{Binding Name}" />
                <TextBlock  Text="{Binding DateAssigned}" />
                <TextBlock Text="{Binding DateDue}" />
            </Grid>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

Where the text after {Binding is the name of the property of the item in the collection you return from _repository.


Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.

C# Express: How to publish project for use with 3rd party installer (msi)?

Someone asked on Stack Overflow:

I want to publish my c# project (c# 2008 express edition) and create an (msi) installer with Inno Setup Compiler. How can I do this?

I posted the following answer, which was chosen as the accepted answer:

Set build mode to “Release” and then take everything inside the \bin directory and toss it into you MSI.

The VS Express editions do NOT include a built-in method for creating an MSI like the VS Pro/Ultimate do.


Originally posted on Stack Overflow — 0 upvotes (accepted answer). Licensed under CC BY-SA.

Can VSTO projects built using, for example, Microsoft.Office.Interop.Excel be run on machines without Office installed?

Someone asked on Stack Overflow:

We’re currently using a thing from SoftArtisans to generate Excel spreadsheets from data the mainframe FTPs down to our document server.

The doc server has the .Net frameworks through 3.5 on it, as does my development box. The difference is my machine has Office 2007 as well.

So, I built a service this morning with a filewatcher using Interop.Excel to make the spreadsheets without the need for the SoftArtisans piece.

When I install and run on the document server, the app chokes when I drop a file in for conversion, saying “Could not load file or assembly ‘Microsoft.Office.Interop.Excel, Version=12.0.0.0”

Is there no redistributable package or something I can use? Management doesn’t want Office installed on the server.

I posted the following answer, which was chosen as the accepted answer and received 3 upvotes:

As far as I know, the only way to use the Office Interop assemblies, is to have full office client installed on the server.


Originally posted on Stack Overflow — 3 upvotes (accepted answer). Licensed under CC BY-SA.

REST api pagination: make page-size a parameter (configurable from outside)

Someone asked on Stack Overflow:

we are having a search/list-resource:

[http://xxxx/users/?page=1](http://xxxx/users/?page=1)

Internally the page-size is static and returns 20 items. The user can move forward by increasing the page number. But to be more flexible we are now thinking also to expose the size of a page:

[http://xxxx/users/?page=1&size=20](http://xxxx/users/?page=1&size=20)

As such this is flexible as the client can now decide network-calls vs. size of response, when searching. Of course this has the drawback that the server could be hit hard either by accident or maliciosly on purpose: [http://xxxx/users/?page=1&size=1000000](http://xxxx/users/?page=1&size=1000000)

For robustness the solution could be to configure an upper limit of page size (e.g. 100) and when it is exceeded either represent an error response or a HTTP redirect to the URL with highest possible page-size parameter.

What do you think?

I posted the following answer, which was chosen as the accepted answer and received 17 upvotes:

Personally, I would simply document a maximum page size, and anything larger than that is simply treated as the maximum.


Originally posted on Stack Overflow — 17 upvotes (accepted answer). Licensed under CC BY-SA.

Access Windows Share under Network Service account

Someone asked on Stack Overflow:

I have two computers with Windows Server 2003. One computer has some shared folders on the network, and the other has a Windows Service (written in C#, running under the Network Service account) that needs to access those shared folders.

The following code works fine as a logged-in user, but throws an exception when executed under the Network Service account.

File.WriteAllText(@"C:\temp\temp.txt", File.ReadAllLines(@"\\NetworkServer\Test\test.txt")[0]);

The exception message is Logon failure: unknown user name or bad password. How do I get this code to work under the Network Service account? Is it a setting in Windows Server 2003, or do I need to add some code to this to make it work?

I posted the following answer, which was chosen as the accepted answer and received 3 upvotes:

On the network share, you’ll need to add permissions for the “Network Service” account on the server running the service. While this will work, @nicholas points out that this may provide an overly broad group of users access to the share.

Another option, and in my opinion the better option, is to create a domain account and then give that account read/write permission on the share. Then you configure the service to “run as” the domain account with proper permissions.

Notable comments

Nate (0 upvotes): @nicholas Yes, I believe so. Creating a domain account is, IMHO, the best way to go. I’ve edited to make that clear.


Originally posted on Stack Overflow — 3 upvotes (accepted answer). Licensed under CC BY-SA.

Add row dynamically to table in ASP.NET?

Someone asked on Stack Overflow:

I’m trying to add rows dynamically to a System.Web.UI.WebControls.Table control in ASP.NET. I found some sample code that does what I’m seeking, but it only adds a single row.

It seems like the table row count does not carry from one page load to the next. The user should be able to add as many rows as desired, and I need to capture the data from each row.

What am I missing? Code below.

<%@ Page Language="VB" %>
<script runat="server">

    Sub btnAddEmail_Click(ByVal Sender As Object, ByVal e As EventArgs)

        Dim tr As New TableRow
        Dim tcLabel As New TableCell
        Dim tcTextBox As New TableCell
        Dim newLabel As New Label
        Dim newTextBox As New TextBox

        Dim i As Integer = Table1.Rows.Count + 1

        newLabel.ID = "Email" + Convert.ToString(i)
        newLabel.Text = "Email" + Convert.ToString(i)

        newTextBox.ID = "txtEmail" + Convert.ToString(i)

        tcLabel.Controls.Add(newLabel)
        tcTextBox.Controls.Add(newTextBox)

        tr.Cells.Add(tcLabel)
        tr.Cells.Add(tcTextBox)

        Table1.Rows.Add(tr)

    End Sub

</script>

<form id="form1" runat="server">
<div>
    <asp:Button runat="server" Text="Add Email" ID="btnAddEmail"
        onclick="btnAddEmail_Click" />
    <asp:Table ID="Table1" runat="server">
        <asp:TableRow>
            <asp:TableCell>
                <asp:Label ID="Email1" runat="server" Text="Email1"></asp:Label></asp:TableCell>
            <asp:TableCell>
                <asp:TextBox ID="txtEmail1" runat="server"></asp:TextBox></asp:TableCell>
        </asp:TableRow>
    </asp:Table>
</div>
</form>

I posted the following answer, which was chosen as the accepted answer and received 4 upvotes:

ASP.NET is stateless — you need to persist any data you want between pages loads into a Session variable.

You’ll need to store the DataTable/DataSet in a session variable, and assign the Datasource property of Table1 to that DataSet in your “PageLoad” event. Then, in your “Click” event, add the row to the DataSet in your Session variable.

update

You maybe able to set ViewState="true" on the control you wish to have persist data through postbacks.


Originally posted on Stack Overflow — 4 upvotes (accepted answer). Licensed under CC BY-SA.

Which is the most common ID type in SQL Server databases, and which is better?

I asked this on Stack Overflow:

Is it better to use a Guid (UniqueIdentifier) as your Primary/Surrogate Key column, or a serialized “identity” integer column; and why is it better? Under which circumstances would you choose one over the other?


marc_s answered (11 upvotes):

I personally use INT IDENTITY for most of my primary and clustering keys.

You need to keep apart the primary key which is a logical construct - it uniquely identifies your rows, it has to be unique and stable and NOT NULL. A GUID works well for a primary key, too - since it’s guaranteed to be unique. A GUID as your primary key is a good choice if you use SQL Server replication, since in that case, you need an uniquely identifying GUID column anyway.

The clustering key in SQL Server is a physical construct is used for the physical ordering of the data, and is a lot more difficult to get right. Typically, the Queen of Indexing on SQL Server, Kimberly Tripp, also requires a good clustering key to be uniqe, stable, as narrow as possible, and ideally ever-increasing (which a INT IDENTITY is).

See her articles on indexing here:

A GUID is a really bad choice for a clustering key, since it’s wide, totally random, and thus leads to bad index fragmentation and poor performance. Also, the clustering key row(s) is also stored in each and every entry of each and every non-clustered (additional) index, so you really want to keep it small - GUID is 16 byte vs. INT is 4 byte, and with several non-clustered indices and several million rows, this makes a HUGE difference.

In SQL Server, your primary key is by default your clustering key - but it doesn’t have to be. You can easily use a GUID as your NON-Clustered primary key, and an INT IDENTITY as your clustering key - it just takes a bit of being aware of it.

Notable comments

Lisa (3 upvotes): Just an aside: Possibly we need to think about better ways to search the SO knowledge base then. I have just been searching for this with but out much success. It seems to come down to the different ways you can word the same question.


Originally posted on Stack Overflow — 13 upvotes. Licensed under CC BY-SA.

signed letter b

Dad. Geek. Gamer. Software developer. Cloud user. Old Car enthusiast.  Blogger.


Top Posts


profile for Nate on Stack Exchange, a network of free, community-driven Q&A sites
a proud member of the blue team of 512KB club
Thoughts, opinions, and ideas shared here are my own. © 2026 Nate Bross.