Andrew Taylor's Blog

How to save changes to your web.config appSettings section

by Andrew Taylor on Feb.06, 2010, under ASP.NET Programming

From time to time you may need to be able to save settings to your web.config file. Yesterday I had a need to do this, and I thought I would check the internet and see if I could find any good examples of how to save settings back to the web.config file.

After viewing the first couple dozen entries, I found one thing in common. Most of the ideas were either “don’t do it” or very complex without the need to be.

The fact is that there are many times when you may want to save changes to your web.Config or other config files. Most open source applications for example save settings to a config file rather than a database file. This makes it easier for people to make changes to the config file without direct access to the database. Perfect case in point is this WordPress Blog which has a config file.

So today I want to show you in just 5 lines of code, how you can save a setting back to your appSettings section of your web.config file.

//Save to Existing Key
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

AppSettingsSection appSettings = config.AppSettings;

appSettings.Settings["UserName"].Value = txtUsername.Text;

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

And there you have it, 5 lines of very uncomplex code, and we’ve saved a value back to our appSettings section of our web.Config file.

In this case the appSettings collection that we have defined works like any standard collection, I can do appSettings.Settings.Add(Key, Value) to add a new key, I can remove, I can clear, etc.

Of course you will need to make sure that your IIS User has write permissions to the folder for this to work properly.

  • Share/Bookmark
2 Comments :, , more...

Creating ASP.NET Master Pages from a purchased template – Part 1 (for Sitefinity)

by Andrew Taylor on Feb.04, 2010, under ASP.NET Programming, Sitefinity

This is the first video in a series of videos that are geared to teaching you how to use a purchased website template in combination with Adobe Photoshop, Microsoft Visual Studio, Telerik Sitefinity, CSS, and HTML to create a real usable ASP.NET Masterpage and Theme.

During this tutorial series we will examine each part of the creation process from the beginning PSD file in Photoshop to the last line of CSS, and combining it all together in Sitefinity to make a real live website.

You can view this video here through Silverlight HD, or you can download the full size video by choosing a version: AVI (250MB) or WMV (60MB).


Get Microsoft Silverlight


  • Share/Bookmark
2 Comments :, , , , more...

To Web Site or Web App, that is the Question

by Andrew Taylor on Jan.12, 2010, under ASP.NET Programming

No doubt since Visual Studio 2005 came out, you’ve probably wondered whether you should choose to use a Web Site Project or Web App Project when creating your next website. You might have even been so brave as to do a Google search and read some of the many articles on the subject.

So what did you decide to do? And more importantly why?

Personally I always use the Web App vs the Web Site, and I have many reasons for doing this, most of them are personal preference, but some are performance and security.

Personal

I personnally like the more structured design of the app. I like being able to put my classes where I want them, not just in the App_Code folder, and I guess I just find it more clean and probably a bit more of the style I’m used to. (This from someone that used to be a diehard VB 6 programmer).

Technically

On a more technical note, I have a few reasons for preferring the Web App to Web Site.

DLL’s: I like my site in a DLL vs individual code files, there is a small performace boost I’m told, and it gives me the ability to access that DLL through other tools if I need to.

Security: DLL’s can be obfiscated and it’s easier to secure 1 folder than dozens or hundreds. If your site is hacked, it’s going to be a lot easier to change you .cs file, than it will be to figure out an obfiscated DLL, modify it, rebuild it, and post it back your server.

Keeping Busy Bodies Out: Even without obfiscation, it helps keep busy bodies out of my code. Last thing I need is some junior HTML guy deciding he can modify my code behind. (No offense Junior HTML guys)

So now you know my thoughts on it, share with me your thoughts and why you do what you do?

  • Share/Bookmark
Leave a Comment :, , more...

The Proper Way to Run a Query (Preventing SQL Injection Attacks)

by Andrew Taylor on Jan.08, 2010, under ASP.NET Programming

It amazes me to this day how many programmers I come across that have absolutely no understanding of what of what an SQL Injection attack is, or how to prevent it and protect their clients.

Primer:


An SQL Injection attack takes place when someone inserts SQL code into a field on a web page that is then passed on to the database. For example if I had a grudge against some company and their site wasn’t secure, I could insert an SQL Injection attack on their unsecured website and delete all the data in their database, or possible steal all their credit card numbers.

Preventing an SQL Injection attack is as simple as using proper coding standards when accessing your backend database. Using these methods doesn’t add significantly to your development time and in many cases actually reduces it, because it reduces many opportunities for errors, and allows for better error handling.

Sample Bad Query:

strSQL = “SELECT * FROM CUSTOMERS WHERE EMAILADDRESS = ” + txtEmailAddress.Text;

In the above C# code, basically we are taking input directly from the web field containing the user entered email address and passing it straight into our query without any checks. If for example I had typed in ” 1′; DELETE FROM CUSTOMERS; “, it would have selected the customers where the email address equals “1″ and then deleted all records from CUSTOMERS.

This vunerability is amazingly common even on today’s modern websites and most of them don’t even realize it.

The Solution:

Solving this little problem is as simple as changing the way you make your query. Instead of contactenating your strings to build a query, simply use an SqlCommand object and parameters. Not only are you gaining the added security and protecting your business, you will actually make your site more efficient because queries using parameters are compiled for future use by SqlServer and therefore have better repeat performace.


Sample Proper Code:

cmdTemp.CommandText = “SELECT * FROM CUSTOMERS WHERE EMAILADDRESS = @EMAILADDRESS”;
cmdTemp.Parameters.Add(“@EMAILADDRESS”, SqlDbType.Varchar, 50).Value = txtEmailAddress.Text;

Yes you have one extra line of code, but that line of code actually helps you out. For example if this was an INSERT instead of a SELECT then it would automatically prevent me from sending a string that was to long for the field to the SQL Server, allowing me to catch the error on the business logic side. The same would hold true if for example I was trying to pass a string into an int field.

Take this simple step, it’s not only a better way to code, it could potentially save your company millions in lawsuits and hundreds or thousands of people the pain and suffering of having their credit card numbers stolen.

  • Share/Bookmark
4 Comments :, more...

How do I get a count of all rows from every table?

by Andrew Taylor on Jan.08, 2010, under SQL Server 2008 Tip & Tricks

In previous versions of SQL Enterprise Manager you could simply click on a database and see how large each table was and how many rows were contained within it.  For some reason Microsoft decided not to add this functionality starting with SQL Server 2005 and the SQL Management Studio.  I recently needed to use this functionality for a report and was unable to find any good examples on the internet.  I found examples that either used a method that wasn’t sortable or that only checked records in tables that have clustered indexes.  While this would generally be good enough as you usually have a clustered index, there are times when you have a database that may have unclustered tables.  I also wanted something that would give me more functionality possibilities down the road if I needed it.

The Simplest List:

This code will generate a very simple list with 1 record set for each table.

DECLARE @TABLENAME VARCHAR(255)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM sysobjects WHERE xtype = 'U' ORDER BY name

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @TABLENAME

WHILE @@FETCH_STATUS = 0
BEGIN

EXEC ('SELECT ''' + @TABLENAME + ''' AS TableName, COUNT(*) AS RecordCount FROM ' + @TABLENAME)

FETCH NEXT FROM db_cursor INTO @TABLENAME

END

CLOSE db_cursor
DEALLOCATE db_cursor

All this code does is cursor through each table and select a count for that table.

More Complex but Easier Results:

This query gives you a single resultset with a list of all tables and their counts.  This could be expanded out to provide additional information for example you could add extra columns to gather specific table information.

DECLARE @TABLENAME VARCHAR(255)

CREATE TABLE #TABLECOUNTS
(
TableName varchar(255),
RecordCount int
)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM sysobjects WHERE xtype = 'U' ORDER BY name

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @TABLENAME

WHILE @@FETCH_STATUS = 0
BEGIN

EXEC ('INSERT INTO #TABLECOUNTS (TableName, RecordCount) SELECT ''' + @TABLENAME + ''' AS TableName, COUNT(*) AS RecordCount FROM ' + @TABLENAME)

FETCH NEXT FROM db_cursor INTO @TABLENAME

END

CLOSE db_cursor
DEALLOCATE db_cursor

SELECT * FROM #TABLECOUNTS

DROP TABLE #TABLECOUNTS

As you can see, either method works, I personally prefer the latter as it provides an easier to copy resultset for use in reports and such.

  • Share/Bookmark
Leave a Comment more...

How Important Is Your Website?

by Andrew Taylor on Aug.12, 2009, under Misc

Web URLI have the opportunity to spend a great deal of time speaking with business owners about their websites and their companies.  One thing that absolutely amazes me these days, is how few people truly understand the importance of their website.

Recently I had the honor of meeting with a business owner.  He owns a rather large property management company in Colorado Springs, controlling around 300 properties for their owners.  Through our discussions on his current website, he understood that the site he had was no marvel of modern technology, and didn’t really compete with any of his major competitors sites.  However he was completely unable to understand how a small investment in his site, could help to increase his bottom line.

During the conversation, he mentioned several times, that this was the first year in over 20 years that he had not run his yellow page ad, and that recent advertisements in the newspaper had not been nearly as fruitful as they had in the past.  During this meeting, his business manager and partner were also present.  They made several comments on how they had changed to sites like rentals.com and craigslist.com in their own offerings to bring in renters.

As our meeting progressed, I attempted to explain to him some of the dynamics of the current market place:

- Yellow Page Revenues Are Falling
For the last several years, yellow page advertising has continued to decline.  More and more consumers are sending their yellow pages straight to the landfill.  He even admitted during this part of the conversation that he gets mad when he see’s a new yellow pages sitting on his porch.

- Newspapers Are No Longer Relevant Advertising Sources
Newspaper subscriptions have fallen like a rock in the last few years, it seems that nearly daily we are hearing of yet another newspaper failing.  As an example, 10 years ago, the Denver Post had around 50 pages of classified ads on Sunday, today, they can barely manage 3 pages, and half the ads are for the Denver Post. 

- Television Is No Longer Our Primary Source Of Entertainment
Television viewership on the major 4 networks was down 6 percent last year.  Even though we still watch unhealthy amounts of television in America, there are more and more channels, providing less and less viewers for your advertisements on each channel.

On the flip side of these:

- The Kelsey Group reports 70% of U.S. Adults use the internet as their ONLY source of information when looking for new products and services.

- 73% of all U.S. Households now have internet in the home

- Consumers used the internet on average 5% more last year, than the year before.

- Online advertising spending has continued to grow in double digit percentages even during the economic downturn.

The fact is, that no matter how you look at it, your website is becoming more and more important ever day, and your traditional sources of advertising are becoming less and less important.

As we continued to talk, I explained to him that his website was no longer something he gave only to existing clients to see, but instead had become his first and possibly only point of contact with future customers.  People were no longer looking for his company through the yellow pages, they were Googling his company, and his competitors were now having a clear advantage over his business.  There sites were optimized for search engine traffic, he was listed on page 10 of popular search for his business, they were on page one, his site had very limited features, their’s were full of new features like virtual tours and automated showing scheduling.

Even though he had years of experience, and his current owners and renters loved him, his website was giving people the immediate impression that his company was unable to compete in the current market place.  It looked like he hadn’t touched his website in a decade.  His competitors on the other hand had spent tens of thousands revamping their sites.

I further tried to explain to him, that his website, with the proper care and attention, could quickly become his best sales person.  It was the only agent available 24/7/365 to show customers new homes, it was the only office manager able to help property owners sign up for his service when ever they needed, it was capable of freeing one or two people in his office from their daily tasks of taking service calls, and answering basic questions from tenants and perspective owners.

Yes he was going to have to invest several thousand dollars into his site to compete with his competition, but spending $9,000, as we showed him, could not only increase his potential sales, it would also eliminate $4,000 – $5,000 a month in labor costs in his office.  A return on investment of only two months!

In today’s economy, that makes even more sense than it did a year ago.  Your business needs to increase every dollar coming in, and reduce every dollar going out.  Yes you might have some upfront expenses, but what kind of savings will you have from the proper technologies being in place to help your staff, and what kind of profit potential will you gain, as your customers begin to see you as a leader in the industry, and find it easier to move from potential customer to loyal customer?

Andrew Taylor
Chief Technical Officer
Satori Tech Solutions, Inc.

  • Share/Bookmark
Leave a Comment :, , , more...

What is Grid Hosting, and Why Do I Need it?

by Andrew Taylor on Aug.12, 2009, under Web Hosting Questions

 

Businessman assisting another at computerOne of the questions I get asked day in and day out, usually with a very confused stare is, “What is Grid Hosting?” It’s a question that is somewhat difficult to answer especially when asked by someone that isn’t technical in nature.

First you need to understand how typical shared web hosting works. When you go to a standard web hosting company, and you agree to pay say $9.95 a month to have your site hosted, your site is placed onto a single web server (physical computer) along with hundreds or even thousands of other sites.

Web hosting companies like ours maintain statistics on sites, and are able to fairly accurately estimate how many sites a server can handle. This is because there is a fairly steady ratio of big sites to small sites.

This works well for the web hosting companies because they are able to maximize floor space in their data centers and increase profits per server.

It doesn’t work so well for the website owners for a few reasons. First, your site is now on a server with 1000 other sites, balanced in a way that the server is basically maxed out of it’s resources. If your site takes off, and throws the balance on that server off, or another site on that server takes off, all the sudden the entire server is running slow for everyone. If your site really takes off, it can bring the entire server down, along with the other 999 sites on that server.

Web hosting providers have automatic safe guards in place to prevent this. In their contracts they state that your site may only use the AVERAGE amount of resources, determined by all sites on the server. So if all the sudden you go from 100 users a day, to 100,000, there systems will automatically shut your website down and display a message to all visitors saying your site has exceeded its resource allotment.

Take for example Namaste Solar in Boulder, CO. During Obama’s stimulus package tour of the country he stopped in Denver, CO. During his speech he talked about Namaste and how they would be adding additional staff due to money they were expecting to make from the stimulus package alternative energy credits. This was covered on Fox News, and within minutes their site was taken offline by GoDaddy, Inc. for resource over usage. Just at the time when Namaste was having their 15 minutes of fame, and needed to be ready for the traffic and potential orders.

GoDaddy had no choice, they had to take Namaste down or bring down hundreds or thousands of other customers sites.

At the same time, it’s not easy for Namaste or GoDaddy to move their site to a less populated server, because any kind of site upgrade like that requires that Namaste reinstall their site on an entirely new server, reroute their DNS records to the new server, and more.

The other negative aspect of single server hosting is that if a server suffers a hardware failure, every site on that server is down until the hosting provider can restore the latest backup to a new server, or replace the failed hardware in the existing server. Usually this can take hours.

Grid hosting solves these problems. In a grid hosting environment, your site isn’t stored on a single server, it’s stored on multiple servers simultaniously, and each of those servers is responding to requests for your site.

When an web user requests your site from the server, a routing server determines which of the servers running your site is the least busy, and automatically routes that web user to that server.

This has many advantages for the web hosting provider and the web hosting customer.

First is stability. Because your site is hosted on multiple servers, it’s much more difficult for any single site or even group of sites to effect performance for other websites on the server, since traffic is balanced and delivered to the least busy server. It’s also very difficult in a well designed environment for a single hardware failure to bring a site offline. If a single server or even multiple servers fail, the traffic is usually rerouted within seconds to the other servers.

Second is expandability. As I mentioned with standard hosting, it’s very difficult to upgrade your site’s resources and usually requires you to move your site to a new server which can be difficult and time consuming. With grid hosting, upgrading resources is simply a matter of clicking a few buttons and telling the servers to assign you more resources. If a grid starts to run low on resources, adding a new server to the grid can usually be done in only minutes.

The real benefit comes in what your customers see, and what happens when your site really takes off, be it from getting on the news, to someone posting you on Digg or StumbleUpon, or just from your good hard marketing efforts.

With grid hosting, your site always responds quickly, and can easily handle any kind of traffic you need it to. This costs you a little more, but it improves your customer image and reliability greatly. It’s also very beneficial if you are using your website for mission critical Software as a Service type applications.

In summary, if you need your site to always be available and/or you expect your site to grow beyond a hundred visitors a day, grid hosting is probably well worth the extra few dollars a month that it will cost you for the reliability and upgradability.

Andrew Taylor
Chief Technical Officer
Satori Tech Solutions, Inc.

  • Share/Bookmark
Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...