Archive for category .NET Development

Crucial is giving away SSD drives in a contest

Here is the URL.

http://bit.ly/XHsjTw

You can win some pretty cool SSD hard drives.

,

No Comments

How to programmatically change your Windows domain password using C# (.NET)

Ever wanted to write a program that would change your password for you? Why on earth would you want this? Well, imagine you have a password policy that requires you to change your password every X days. Well, maybe you like your password and think it dumb to have to keep changing it. Maybe you would forget your new password and resort to writing it down.

Ideally, you should come up with a good password to begin with, then changing it would not be really necessary. Unless of course you are under attack by the Chinese.

So, I wrote a program that changes the password in code. Moreover, it does it multiple times then the puts it back to the original. My problem solved. Here is the code for your education and amusement. Now that you know how to change your password, will you use this for purposes of good or evil? Try leaving the world a better place.

using System;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.Windows.Forms;

namespace KeepMyPassword
{
    public partial class fKeepMyPassword : Form
    {
        public fKeepMyPassword()
        {
            InitializeComponent();
        }

        private void cmdChangePassword_Click(object sender, EventArgs e)
        {
            txtCurrentPassword.Enabled = false;
            cmdChangePassword.Enabled = false;
            try
            {
                ChangePassword(txtCurrentPassword.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred:" + ex.Message);
            }

            txtCurrentPassword.Enabled = true;
            cmdChangePassword.Enabled = true;
        }

        private string currentPassword;
        private void ChangePassword(string p)
        {
            var currentUser = WindowsIdentity.GetCurrent().Name;
            currentPassword = p;
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain))
                using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, currentUser))
                {
                    for (int ix = 0; ix < 10; ix++)
                    {
                        var newPassword = p + (char)(((int)'a') + ix);
                        user.ChangePassword(currentPassword, newPassword);
                        currentPassword = newPassword;
                    }
                    user.ChangePassword(currentPassword, p);
                    currentPassword = p;
                    MessageBox.Show("Password has been reset and back to original");
                }
                //set back to normal
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred:" + ex.Message + "\nYour password is now: " + currentPassword);
            }
        }
    }
}

Happy Coding!

 

KeepMyPassword <- you can download the compiled exe if you wish. Needs .NET 4.0 to run.

, , , , ,

No Comments

How to handle action on enter key press in textbox in WPF

Did you want your OK button or your commit action to take place when you hit enter in a text field in a WPF dialog? You may have implemented a Find dialog, or maybe you have a one field text entry and you want the Enter key to commit the action.

Well, its actually really easy once you learn the simple trick to wiring up the commands.

I have a command called SaveProcessCommand on my viewmodel. I have it wired to my dialogs “OK” button. I also wanted the user to just hit Enter when they were done typing, since that is how my usability study determined users expect.

Enter the simple InputBinding. Pretty cool.

  <TextBox Margin="10,0,0,0" HorizontalAlignment="Stretch" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1">
                 <TextBox.InputBindings>
                    <KeyBinding Command="{Binding SaveProcessCommand}" Key="Enter"/>
                 </TextBox.InputBindings>
 </TextBox>

I have the binding to the property update on each keystroke, so it is always up to date. The InputBinding then wires up the Enter key to a command. The command can do whatever you want, you are using MVVM right? Happy Coding!

, , , , ,

No Comments

How to reclassify your project into a WPF project in Visual Studio

Are you looking to change your project from a normal C# class library to a Window Presentation Framework project?

Well, it is not that hard once you learn the trick. It took me a little while to dig up the info, so hopefully this saves you some time.

Open your csproj file in notepad. Look for the ProjectTypeGuids key. If not found, add it.

Here is what it should look like when your done.

<ProjectTypeGuids>{60DC8134-EBA5-43B8-BCC9-BB4BC16C2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Visual Studio 2012 and Visual Studio 2010 use these to identify the project type. The settings above make it a C# WPF app.

Example:

SNAGHTML77868191

 

Happy Coding!

, , , ,

No Comments

Application file lock after debugging with Visual Studio 2012

I had a small WPF application that I was developing and every time I would stop it, make a quick small change then restart it would wait for a file lock then fail.

error message is : error LNK1168: cannot open [Yourfile].exe for writing

i.e. Visual Studio said it couldn’t open the file for writing. I just got used to waiting for about 30-60 seconds each iteration hoping the lock would go away. It was always the system that had the file handle.

Well, it seems that the issue was related to the fact I disabled the Application Experience service.

How random, right? Well, reenabling it has stopped the issue, for now.

image

Happy Coding!

, ,

No Comments

T4 Templates for Entity Framework Break when upgrading to Visual Studio 2012

I upgraded to Visual Studio 2012 and consequently upgraded to version 4.5 of the .NET framework. It turns out, this made our T4 templates very unhappy.

See, we use T4 templates for generating our Entity Framework(EF) models. A bunch of very fancy template coding that automagically creates our edmx and other code files from a reference database.

This worked very well in .NET 4.0, but simply upgrading to .NET 4.5 made it throw all sorts of fun errors.

The root cause turned out to be it was generating EF3 schema data which completely hosed the template code which was looking for EF2 schemas. Not to mention, I tried converting the template processing code to use the new schemas and then realized that since we target .NET 4.0, that we couldn’t compile after the templates worked.

So, I was stuck in a catch 22. Fix the templates, and can’t build the assembly, or only build the templates on a machine with .NET 4.0 and VS 2010. Both options suck.

Well, I reached out into the forums and got a little advice at least on targeting the right framework.

I changed the headers to target 4.0. That turned out to be Step 1.

<#@ template debug=”true” hostspecific=”false” language=”C#v4.0″ #>

<#@ output extension=”.edmx” #>

<#@ Assembly Name=”System.Core, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Data, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Data.Entity, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Xml, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Xml.Linq, Version=4.0.0.0, Culture=neutral” #>

 

Now, step 2. I discovered through hours of staring at code and hoping for hope to find an overload, setting,property or something to say….Damn it, I wan’t EF 2 code. Yeah, you would think running in 4.0 framework mode would do that for me, right? Nothing can be simple.

I finally found it. The overloads I needed.

EntityContainer entityContainer = this.storeItems.GetItems<EntityContainer>()[0];
    this.modelGenerator = new EntityModelSchemaGenerator(entityContainer, ModelNamespace, this.entityContainerName);
    this.modelGenerator.GenerateForeignKeyProperties = true;
    this.modelGenerator.PluralizationService = this.pluralizationService;

    this.modelGenerator.GenerateMetadata(EntityFrameworkVersions.Version2);

Generate MetaData has a Version overload.

So does the schema generator.

  var generator = new EntityStoreSchemaGenerator(this.provider, this.connectionString, ModelNamespace + "." + StoreNamespace);

    IList<EdmSchemaError> errors = generator.GenerateStoreMetadata(this.filters,EntityFrameworkVersions.Version2);

 

So, now we have the fix. All is well in the world. Only lost a day or two of headbanging my screen and yelling at how much T4 is an undocumented piece of crap. Well, it least I have a stronger understanding of it now.

Hopefully this saves you some headache, since not one damn google search result explained this.

Happy Coding!

, , , ,

No Comments

The remote certificate is invalid according to the validation procedure for FTP

I was testing a C# FTP application of mine and got this lovely gem of an error when connecting using SSL. I had a self signed certificate in the trusted store, but the FTP library kept screaming that the certificate was invalid.

Well, I found a great workaround for the time being. It should only be used by configuration or conditional compiling though.

Disable Certificate Chain Checking

ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

Using the code above, your certificate checks will always be considered good. The channel will still be SSL protected, you just won’t be looking for man in the middle attacks nor identity mismatches. Something you don’t care about in development, just production.

Happy Coding!

, , , , ,

No Comments

How to get command line args in WPF?

Are you looking how to get the command line arguments in WPF?

It is actually really easy. Simple call Environment.GetCommandLineArgs()

You will be returned a string array (string[]). Remember, the first value is that of the exe being called. i.e your app.

 

   Environment.GetCommandLineArgs() 

Happy Coding!

, , ,

No Comments

How to change the casing of the Visual Studio 2012 Menu

IF YOU ARE LIKE ME, THEN YOU DON’T WANT TO BE SHOUTED AT BY A MENU. UPPERCASE SEEMS A BIT LOUD!!!!!!!!

Well, looks like the developer who implemented the shouting case for VS 2012 put in a backdoor. I’ll be he thought it was a stupid decision, so he put in an opt-out. Clever I think.

MSDN put up a nice little description of how to disable it. Here is the key thought for ease.

Yes, you have to add the key yourself.

Open the registry editor and go to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\General\

SNAGHTML5ab24db

SuppressUppercaseConversion REG_DWORD value 1

 

HAPPY CODING!!!!

No Comments

.NET 4.5 in-place upgrade might confuse you and your users

I learned something new today, something I strive to do everyday. I learned that the new .NET 4.5 Framework doesn’t just install side by side with 4.0 but it actually “upgrades” it for you. This doesn’t sound terrible, until you realize that if you are developing an application for 4.0 (many of need to as we support XP clients, which 4.5 won’t run on).

Why the issue, well one is that you run you application and you may not get the quirks you would on a machine with just 4.0. You get the bug fixes that were done for 4.5. Why is this bad? Well, you can’t reproduce the issues your customers face, and worse you won’t see them in development. Hence, you first learn about the issue after it hits your customers. No bueno!.

The issue I am facing is more insidious. I use reflections to reach inside the bowels of the framework to do things that they won’t expose to me publicly. Sealed classes, private initializers, etc. Well, they can rename these things since they aren’t public. You see where I am going. In 4.5, my method isn’t there anymore.

So, user installs 4.5, boom goes the app. Yeah, could have happened with any bug fix, sp, or update. I just didn’t expect a new framework edition to crumble the empire.

Well, just watch out and test your apps on both 4.0 and 4.5 systems. Even if, especially if, you are writing targeted 4.0 applications.

Happy Coding!

More details I read about at Hanselman’s blog.

, , , ,

No Comments