July 2013 Entries

Query to database information

Prashanth Jayaram provided a blog post about a script he has to get information about databases on your server. This is a perfect script for keeping up with what’s going on in your environment or getting an idea about what’s going on a client’s site. The script Prashanth provided had some errors, so I corrected those you can just copy the code below, paste it in SSMS and run it. This is the information returned: Servername Database Name ...

What little I know about SQL Bulk Insert

I’ve got a stored procedure to upload a csv file to a database table.  From what I’ve read that’s the fastest way to load csv data to SQL. Cool, but I’ve had errors when I went to deploy to production. Here are just a few things I’ve learned. 1. The permissions used are different when using windows login vs sql login (to call the stored procedure). 2. If you use a windows login to call the stored...

Access denied error with MVC site

If your new MVC site throws an access denied error you probably don’t have windows authentication setup.  The first thing is checking if you are hosting your site on IIS 7 or better. (Otherwise this section won’t help). Right click on your project in Visual Studio, click Properties. Click the web tab. If you Use IIS Express checked THEN SKIP TO THE BOTTOM OF THIS ARTICLE. Open IIS Manager (Start –>...

How to setup windows authentication on Windows

Here on the steps to enable windows auth on Windows 7:       a) In Control Panel open "Programs and Features".               b) Select "Turn Windows features on or off".                  c) Navigate to Internet Information Services > World Wide Web Services > Security          and make sure the Windows authentication node is checked.                To enable Windows authentication on Windows Server: ...

How to offer remote assistance with Windows 7 on your network

1) Go to your start menu and type “assistance” in the search box (see below). 2) Windows will find the Windows Remote Assistance program. Select that program. 3) You will now have 2 choices, ask for assistance or offer assistance. Choose the second choice “Help someone who has invited you” (Doesn’t matter that no one has invited you.) 4) On this screen...

How to add an item to the quick launch in SharePoint

Here is a method to add a node to the quick launch.  You need to pass in the name you want displayed for the link, the Site,  and the path to the page you want the link to open. This method checks if the link already exists and it won’t add the node if it does.  So it’s safe to run multiple time without jacking up your quick launch. private void AddNodeToQuickLaunch(string linkName, string SiteToOpen, string pathtoPage) { ...

How to create a new site based on a custom site template

Here is a method to create a sub site based on a custom site template.  You need to pass in your new site name and the name of the site template.  It will check the available site templates for the one you specified (so you must deploy the site template first).  If it’s not there an error gets displayed.  I put a label on my web part to display the error _lblErrMsg.  You will need that control (or you can remove it and handle errors whatever way you want. private bool CreateSubSite(string newSiteName, string ProjectsiteTemplateName) ...

SharePoint 2013 Forms Based Authentication (FBA)

Here are the instructions for setting up FBA on SharePoint 2013. Install FBA and Setup SharePoint to use FBA The site users and roles will be stored in a SQL database, and the web site will use the FBA provider to authenticate the uses through the database. Create Users/Roles Database The first step is to create the database using the ASP.net SQL server setup wizard. Install the new database on...

How to get a reference to the control that caused a post back

Here is some old code I found (in VB.NET) the will tell you what control caused the post back. ' Return a reference to the control that caused the last postback, ' even from the Page_Load event! ' It requires in input a reference to the posted-back page ' (this is necessary if you want to be able to move this function in a separate ' class ' instead of in a page's codebehind class ' ' Example: ' Private Sub Page_Load(ByVal sender As System.Object, ' ByVal e As System.EventArgs) Handles MyBase.Load ' Dim...

The funniest crystal reports error I ever got.

I got this error one time while using Crystal Reports (back when it was owned by Seagate). Not much you can do with it.

How to remove a feature with PowerShell

Here are the PowerShell commands to remove a feature. Step 1 Uninstall the feature. Uninstall-SPSolution -identity "<WSP FileName>" (For ex, Uninstall-SPSolution -identity "Deploy_Service_Requests_Lists.wsp") Step 2 Remove the solution. Remove-SPSolution -identity "<WSP FileName>" (For ex, Remove-SPSolution -identity "Deploy_Service_Requests_Lists.wsp") * Note pay attention to SPSoluion (farm solution) vs SPUserSolution (sandboxed solution). You need what kind of solution you deployed to know which...

How to deploy a feature through PowerShell

Every time I go to deploy a feature from outside Visual Studio I forget the PowerShell commands. I found the Corey Roth has a great blog entry about it and I end up going there. So I decided to finally write up what I do.  After using stsadmin for so long it’s hard to make the adjustment to PowerShell. Here is the first step to add a Farm Solution. Add-SPSolution <File Path>\<WSP Filename> (For ex, Add-SPSolution C:\Users\Administrator\Desktop\Deploy\Deploy_Service_Lists.wsp) The next step...

How to deploy a workflow through PowerShell

Every time I go to deploy a workflow from outside Visual Studio I forget the PowerShell commands.  So I decided to finally write up what I do.   Here’s what I do. Step 1 add the solution. Add-SPSolution –LiteralPath <FILEPATH\WSP FileName> –Site <URL> (For ex, Add-SPSolution -LiteralPath C:\Users\Administrator\Desktop\Deploy\Service_Request_Workflow.wsp -Site http://win-ate30fn6vk5 ) Step 2 install the solution. Install-SPSolution –Identity <WSP FileName> –Site “<URL>” ...

How to check if a project template exists

If you are creating sites based off custom project templates through code you should if the project template exists.  If you don’t and you try then SharePoint will through an error. Here is a simple method that will return true or false if your project template exists.  You pass in the name of the project template you are looking for. //Check if a site template already exists private static bool templateExists(string title) { ...

How to add your own WebPart properties

If you are creating your own part you might want to add a property for the users to set when editing the webpart. At the top of your web part class add the following code (before any methods). [FriendlyName("Project Site Template")] [Personalizable(PersonalizationScope.Shared)] [WebBrowsable(true)] public string ProjectsiteTemplateName { get; set; } This will add a property (in my case called Project Site Template) for the users to set when editing the web part. This allows the user configure the web part for what you need (instead of hard coding some things).

SharePoint generic handle web part error

If you have web part that has code behind to do something (like add data to a list) and it has an exception during processing you need a way to display that error.  Here is a generic method I use to display the error. I put this in all my catches.  It will add a new literal control with the error.  /// <summary> /// Clear all child controls and add an error message for display. ...

Four Main Reasons That IT Projects Succeed

There 4 reasons that IT projects succeed.  If your looking to have a successful career in IT, look to these reasons. Build them into your thought process behind every project. 1. Users and sponsorship involvement 2. Clear requirements 3. Clear, well structured and understandable design 4. Realistic management expectations If you are work towards these items and keep in mind the 4 reasons IT projects fail your chance of success is great.  You will be unstoppable.

Four Main Reasons That IT Projects Fail

There are 4 main reasons that IT projects fail.  If you address these issues it put you in a great position to be successful. 1. There was a lack of technical sponsorship 2. The users were not involved in the project 3. There was inadequate management of the project 4. There were technical issues If you users don’t care, IT doesn’t care, management doesn’t care, or you attempt something not technically possible YOU WILL FAIL 100% of the time.

Generic handle error method

Here is a generic handle error method I put in my catches.  It will send an email with the inner exception unless it’s null then you get the exception message.  The stack trace is included. You should the subject from “Application Name” to whatever your application is. Also you should check out a previous post about a generic send mail method since this method calls that one. private static void HandleError(Exception ex) { String errorMessage = String.Empty; ...

Enable/Disable table indexes

Sometimes you need to disable indexes (and then re-enable them). Here is the sql to disable indexes on a table. ALTER INDEX ALL ON <TABLENAME> DISABLE; Here is the sql to enable indexes on a table. --Reenable indexes ALTER INDEX ALL ON <TABLENAME> REBUILD ; Notice that to enable the indexes you just need to do a rebuild.

Generic Send mail method

Here is a generic send mail method. You just need to pass in a subject and body. In your web.config you need a key for the from (notification_from), To (notification_to) and mail server (mail_server). You could easily alter it to move the to (or from) to input variables. private static void sendNotification(String Subject, String Body) { MailMessage mailMessage = new MailMessage(); ...

How to insert records to a table with an identity column

If you have a table with an identity column, you can’t just do a simple insert.  That identity column needs to be excluded from your insert statement. There are times when you need to keep the ID values during your insert.  Like moving data between environments. Here is the SQL you need to allow your inserts to work. First turn on identity_insert SET IDENTITY_INSERT <TABLENAME> ON; Then do your insert. Then turn off identity_insert SET IDENTITY_INSERT <TABLENAME> OFF;

Career advice

I have learned a few valuable lessons over my career in IT.  I’ve had the luck of working with some very experienced and smart people. Here are just a few items I have learned (in no particular order): 1.  You're job is to serve The entire point of IT is provide service to the customer (internal or external).  You are there to help improve their lives, not yours.  If you do not help the customer they will look to have their needs met elsewhere and you will be out of a job. 2. Lost data ==...

Undocumented stored procedure for looping through all databases on a server

If need to do something to all your databases there is a stored proc for you.  Its called sp_msforeachdb. This will loop though all your databases and perform a command for you.  It’s similar to the foreach table sp I wrote about here. There is one parameter @command. Let’s get right to an example. EXECUTE sp_msforeachdb 'USE ? IF DB_NAME() NOT IN(''master'',''msdb'',''tempdb'',''model'') BACKUP DATABASE ? TO DISK = ''G:?.bak, WITH INIT''' The ? gets replaced with the database name. So that...

Simple SQL best practices

It’s real easy to go crazy with best practices and then have them become so big no one follows them. Here are a just a couple of quick best practices I follow. 1.Whenever you need to recreate a database object use DROP/ CREATE rather than ALTER.  The reason is that ALTER doesn’t modify the object’s create date time stamp. This makes it harder to trouble shoot when you can’t figure out what has changed recently. ...

Undocumented stored procedure for looping through all tables in a database

I got tired of writing code to loop through all tables in a database.  I found out about an undocumented stored procedure that does most of that for me. The stored procedure name is sp_MSforeachtable it takes one input parameter (@command). This simplifies so much code (no more looping through sysobjects). Here are some examples of how to use it. This command will return a row count for each table in your database. ...

Tulsa SQL Server User Group presentation

I presented at the Tulsa SQL Server user group on 4-9-2013.  I spoke about support scripts for the app developers sql server toolbox. For those that came, thanks for showing up and listening to me. Attached is my presentation. SQL Server Support Scripts You will have to rename it from .pptx to .zip. Wordpress won't let up upload a zip file. I wanted to include the sql scripts with the powerpoint presentation. If you just want the powerpoint here is the link for that....

How to cache data in a SharePoint web part

Here is some sample code to cache a list of strings in a web part. List<String> documentNames = new List<String>();   object cacheddocumentNames = PartCacheRead(Storage.Shared, "DocumentNamesList"); if (cacheddocumentNames != null)   { // cache exists, use it   documentNames = (List<String>)cacheddocumentNames as List<String>; }

Where to find where you click once app is deployed.

Click once applications have many advantages and disadvantages. One of the disadvantages is that it hides where the application gets installed.  So if need to double check something like a connection string in your config file it can be a pain. So next time you need to know where you application is this might help. C:\Documents and Settings\[username]\Local Settings\Apps\2.0\[some folder]\[some other folder]\manifests

Set default page for SharePoint publishing site

Here is a function that will set the default page for a publishing site. Just pass in your web and the new default page name, it will take care of the rest. Works great when creating new sites. public static void SetPageAsDefault(SPWeb web, String pageName)       {           if (PublishingWeb.IsPublishingWeb(web))           {               PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);               SPFile welcomefile = web.GetFile(pageName);               if (null != welcomefile)               {                   publishingWeb.DefaultPage = welcomefile; ...

How to find out the last time your database was restored

Here is a short script that I got from my DBA (John Langston). It will return the date time that your database was restored. 1: DECLARE @DatabaseName as varchar(50) 2:  3: SET @DatabaseName = 'YOUR DATABASE NAME' 4:  5: SELECT destination_database_name,max(restore_date) as restore_date...

Clear Controls on screen

Here is a method that will clear all the controls on your screen (as long as it matches one of the controls in the method).  It recursively calls itself until all the controls are clear. Here is an example of how you call it: ClearControlsOnScreen(this.Page);   public void ClearControlsOnScreen(Control parent) { try { ...

How to programmatically determine the current method name

If you want to determine the current method in code (C#) here is the line of code you need. MethodInfo.GetCurrentMethod().Name This call will return the current method name as a string.  (It is from the namespace System.Reflection). Why is this helpful?  If you write a generic logging routine and want to log the current method this is a big help.  So you don’t need to modify your log error call (in your catch) with anything not generic (like hard coding your method name).   Here is an example of this. String currentMethodName = MethodInfo.GetCurrentMethod().Name;...

SharePoint hide search box

If you need to hide the search box on your site and you don’t want to change the masterpage, you can modify the CSS to hide that section for you. This will set that container for search box to hidden. .ms-searchform {     Visibility:hidden; }

TFS 2008 get latest version automatically

When using  the Visual Studio integration for TFS 2008, you will notice that the latest version will not be retrieved when you start making changes to a file. There is an option that you need to have an option.  To get to this option perform the following steps: Launch Visual Studio 2008 Click Tools->Options Expand the Source Control section Click on Visual Studio Team Foundation Server Ensure that the Get Latest version of item on check out is checked. Now when you check out a file if you don’t have the latest version,...

SQL Server 2008, can’t save changes to tables

When you design a table in a database and then try to make a change to a table structure that requires the table to be recreated, the management tools will not allow you to save the changes. You will get an error stating, “You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table be re-created.” What a pesky problem.  It prevents you from making progress when you making database changes. It’s a good thing you can turn it off. This...

Regular Expressions Tool

A co-worker of mine showed me Expresso, a regular expressions development tool. If you need to create some regular expressions (which are a pain to create) from scratch expresso is the best tool. Of course there is also http://regexlib.com/ if you want a great site to search for regular expressions.

Show desktop icon missing from quick launch

Occasionally I end working on PC that is missing the show desktop icon.  I always end up looking for how to recreate it on Google. In Windows XP, go the run command then type the following command: regsvr32 /n /i:u shell32.dll Then press enter.  A dialog will let you know it was successful. The show desktop won’t be there until you reboot or type the following command: %appdata%\microsoft\internet...

Convert an Array to a generic list

Sometimes you have an array, but a generic list would make better sense. Here is a method to convert from an array to a generic list. This comes in handy if you you get an array back a web service (since they can’t return a generic list). public static List<T> ConvertArrayToList<T>(T[] theArray)         {             try             {                 if (theArray == null)                 { ...

No back button

If your web app just can't tolerate a user clicking the back button, you can tell the browser to not cache the page. Most of the time it will listen if you use this code, which covers all the bases: Response.Expires = 60 Response.ExpiresAbsolute = DateAdd(DateInterval.Day, -1, Now()) Response.AddHeader("pragma", "no-cache") Response.AddHeader("cache-control", "private") Response.CacheControl = "no-cache"

JS to tell if an object is viewable on the screen

    Here is some JavaScript that has a function to tell if an object is viewable on the screen.   This is quite helpful if you have something on the screen you want to make sure the user sees, like a an error or license agreement, etc.     <HTML> <HEAD> <SCRIPT> function isinView(oObject) { var oParent = oObject.offsetParent; var iOffsetTop = oObject.offsetTop; var iClientHeight = oParent.clientHeight; if (iOffsetTop > iClientHeight) { alert("Special Text not in view. Expand Window to put Text in View."); } ...

VS copy instead of paste problem

So in Visual Studio when accidently copy (ctrl-c) instead of paste (ctrl-v) you lose what was on your clipboard. Quite annoying behavior, but you can fix it. Tools-> Options –> check Show All Settings –> expand the Text Editor node –> select All Languages –> under Settings –> clear the Apply cut or copy commands when there is no selection. This will change the behavior in visual studio to work like word when it comes to copy and paste.   This is a tip I read about in the Code magazine for...

Entity Framework call stored proc with code

If you need to call a stored procedure from Entity framework and you can’t add it to the designer (like if it doesn’t return an entity)  you can do with just code. This way you can use the same connection as you model. Here is some example code to use. using (cctEntities ccte = new cctEntities ()) { ...

Entity Framework call stored proc with code

If you need to call a stored procedure from Entity framework and you can’t add it to the designer (like if it doesn’t return an entity)  you can do with just code. This way you can use the same connection as you model. Here is some example code to use. using (cctEntities ccte = new cctEntities ()) { ...

VS copy instead of paste problem

So in Visual Studio when accidently copy (ctrl-c) instead of paste (ctrl-v) you lose what was on your clipboard. Quite annoying behavior, but you can fix it. Tools-> Options –> check Show All Settings –> expand the Text Editor node –> select All Languages –> under Settings –> clear the Apply cut or copy commands when there is no selection. This will change the behavior in visual studio to work like word when it comes to copy and paste.   This is a tip I read about in the Code magazine for...

Where can I find Active Directory Tools

In order to get the option to manage users, computers, etc in AD you need to have the AD tools installed.  This is a 2 step process. The first step is you need to install the Remote Server Administration Tools for Windows 7 with SP 1. The second step is to enable the AD tools in control. From the control panel, click Programs and Features. Select Turn Windows Features on or off (on the left side) Under Remote Server Administration Tools –> Role Administration Tools,...

Tertiary operator

The .NET framework has a cool feature called the Tertiary Operator.  It’s basically a shortcut for  an if/then/else statement. Here’s the format: condition ? first_expression : second_expression; The condition must be something that evaluates to true or false.  The first expression is what get’s returned if the condition is true.  Obviously the second expression gets returned if the condition is false. I make use of then when I’m pulling data from a source and loading an object (ie, handle null from the source). So here...

Command line to lock Windows 7 PC

For security reasons, I would like my PC to lock after I walk away from it. I have a problem where on of Windows 7 PC’s doesn’t start the screensaver (which I have set to require me to log back in). Yeah I can hit windows+L to lock my PC, but I forget sometimes (like when I go home for the weekend). So I setup a schedule task to run the following command: %windir%\System32\rundll32.exe user32.dll,LockWorkStation The task runs every day after 5:30 PM, so my PC will always end up locked. Here is the original article I wrote about this.  

Windows 7 keyboard shortcuts to move windows

You can use the windows key with the arrows key to move your windows around. Windows+Arrow up maximizes your window. Windows+Arrow Right snaps your window to the right. Windows + Arrow Left snaps your window to the left. Windows + Arrow Down minimizes your window. Here is the original article I wrote about this.

Windows 7 GodMode (or 32bit Vista)

Windows 7 (or 32bit Vista) have a God Mode, which gives you all the settings of control panel in one folder (without having to browse around in control panel). WARNING: THIS DOES NOT WORK ON 64bit Vista OR 64bit WINDOWS SERVER 2008.  DO NOT FOLLOW THESE INSTRUCTIONS IF YOU ARE RUNNING 64bit Vista OR 64bit WINDOWS SERVER 2008.  IF YOU DO EXPLORER.EXE WILL REBOOT OVER AND OVER.  Here are the instructions for removing GodMode, http://chrisbarba.wordpress.com/2010/01/06/how-to-remove-godmode-from-vista-64bit/ Here are the instructions for adding a GodMode folder. Right click on the desktop and add a new folder. Name it the following GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} After that you will...

SharePoint workflow how to videos

Here is a link to a blog with some SharePoint workflow how to videos. I  would recommend this for anyone getting started with SharePoint workflow http://www.sheltonblog.com/archive/2007/11/04/series-of-sharepoint-workflow-how-to-videos.aspx   Here is the link to the original article I did.

WPF text blocks

WPF/XAML is still new to me so it feels like every time I do something I learn something new. If you want to apply different fonts styles for some text use the <TextBlock> tag. For example if you part of a sentence bold (like below) here is the code. <TextBlock> <TextBlock.Inlines>      <Run Text="I'm bold" FontWeight="Bold" />      <Run Text="and I'm not"/> </TextBlock.Inlines> </TextBlock> Check out the original article here.