I recently found myself wanting to rename all the fields in several large projects to conform to a new naming scheme. Sadly Resharper was not helpful here, so I turned to a combination of Regex and Powershell.
Our team has recently revised our 7 year-old coding guidelines. One of the guidelines that was changed concerned field naming. Our previous guideline stated that fields should use an ‘m’ prefix with Pascal Casing, creating fields of the form “mFieldName”. At the time the guidelines were written, .NET was still young, and the community hadn’t yet settled on a widely accepted standard. Since then, most of the community seems to have gravitated towards using an underscore prefix for fields with camel casing, creating fields of the form “_fieldName”. We finally decided to bite the bullet and switch our guideline to conform to the more generally accepted convention. The problem is that we have a lot of code that uses the old style. By “a lot”, I mean probably in the neighborhood of 100k lines of code across the various projects.
One solution we discussed was to just leave existing fields alone, and only use the new convention when creating new code. This would work, but since we use Resharper to enforce the naming conventions, it would create a lot of false warnings. It also meant that we would be introducing some inconsistency into our code base, which we wanted to avoid.
One avenue that we explored was using Resharper to update all existing field names. The Patterns functionality introduced in Resharper 5.0 might be able to accomplish this, but I was unable to figure out how.
When that failed, James suggested that I try using Regex. It took a bit of Powershell hacking, but I managed to come up with a script that worked. I’ve applied it across thousands of classes, and it *appears* to rename things correctly. Here’s the script:
1: $regex = New-Object System.Text.RegularExpressions.Regex "(?:\W(?<name>m[A-Z][a-zA-Z0-9_]+))"
2: Get-ChildItem * -Recurse -Include *.cs | ? {$_ -notmatch 'Resharper' } | ? {$_ -notmatch 'DecompilerCache' } | ForEach-Object {
3: $text = [System.IO.File]::ReadAllText($_.FullName)
4: $matches = $regex.Matches($text)
5: $matches | ForEach-Object {
6: $toReplace = $_.Groups["name"].Value
7: $newValue = "_" + [System.Char]::ToLower($toReplace[1]) + $toReplace.Substring(2)
8: $text = [System.Text.RegularExpressions.Regex]::Replace($text, "(?:(?<prefix>\W)" + $toReplace + ")", "`${prefix}$newValue")
9: }
10: [System.IO.File]::WriteAllText($_.FullName, $text)
11: }
The first line creates a new Regex object that will match things of the form “mFieldName” that are prefixed by a non-word character. Next, the script recursively iterates through C# files, ignoring the contents of the Resharper directory as well as the DecompiledSources directory. For each matched file, the script grabs the full text from the file, finds the field names that need to be changed (if any), then uses a different regex to replace the field name in the text. Note that simple string.Replace won’t work here since the replacement must account for the non-word character that prefixes the filed name, otherwise things such as “NumWhatever” will be transformed as well (as I found out with an earlier version of this script). Finally, the modified text is written back to the file.
It’s not terribly pretty, and it certainly isn’t innovative, but it did save me quite a bit of time this morning. 🙂
Thanks for sharing lots of information.
Senuke Backlinking Software
Hey guys
I was researching the best tools for online marketing, then I found a website that has Senuke, Link Farm Evolution, the best spinner and more for a mere 27 dollars per month.
It seemed to be a totally private forum, and so i PM’d the admin and asked about the $27 VIP package. It sounded like a wonderful package as it included absolutely everything for only $27. Accordingly, I made up my mind to join VIP yesterday, just for one month to see if it was as good as they claimed it was. I ought to say that I’m quite pleased. They have anything there you could ever ask for with regards to Search engine marketing software programs and everything is updated and working perfectly. It’s truly worth the cost, considering, Senuke alone is $127 a month. I definitely recommend them. If you desire to investigate yourself, you can sign up free initially, after that one would be able to take a look around the place. You can also PM an admin or even a mod there to get a lot more important information.
[code][url=http://tinyurl.com/yblc7dq]SENuke For $27 | Click Here Now!!![/url][/code]
http://tinyurl.com/yblc7dq
Thanks! That’s what I need to know.
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
Well, I read it all…come back tomorow for more great posts!
They have their own inimitable personalities and styles of talking and writing, so it would end up reading differently, but in terms of creating the outline of a blog post, that’s exactly all they have to do.
Thank you for the great information. I look forward to seeing more articles and what else you have to offer!
FYI, your site isn’t loading right in Lynx. Could be your theme? But other than that, I’m going to say this isnt the first I’ve seen this. But yes, it’s pretty much the way it is and the way it will be.
I couldn’t agree more, thanks for writing.
I agree with Tom, there is no place for that and if everybody bound together all would be well and in the world of <A href="http://www.775creditscore.com/">how to get a new credit file</A> everybody needs guidance and good information.
really good point, you must got another subscriber 😉
Hope you like feedback. You’re gonna get a few on this post.
Finally a smart blogger…I love how you’re thinking and writing!
Thanks for your post and for every article you write! I get real pleasure while looking and reading through your resource.
Thanks for such a nice blog.
Happy Easter! Do you have any other sites other than Try-Catch-FAIL – Using Powershell to apply new C# field naming conventions? It’s like Hells Kitchen with Ramsey. I mean he’s with this cooks and merchants and they just dont even know how to run their businesses. Ya know?
excellent post, you must got another subscriber 😉
excellent post, you must got another subscriber 😉
Nice post. I put you in google rss reader now so I can read more from you again.
Nice Post. It’s really a very good article. I noticed all your important points. Thanks!
I had problem reading this blog from my iphone, whats the cause?
Hmmm. Interesting point of view. Ought to be Dugg.
Finally a smart blogger…I love how you’re thinking and writing!
Playing with RSS. I can stay up to speed with this site now- such a neat feature
I wanted to hop in and say I’m feelin’ what you’re thinkin’! You’ve made some strong ideas and while I don’t like everything you’ve said I think you make a strong case. Keep up the good work ‘cus I’ll be checkin’ up on you later. You’re on my radar now and I’m interested to see where things go.
Thanks! That’s what I need to know.
Just my 2 cents, but your website will look much more colorful if you can throw in some pictures.
Fine information, many thanks to the author. It is puzzling to me now, but in general, the usefulness and importance is overwhelming. Very much thanks again and good luck!
Exceptiontal post! I have bookmarked your blog – do you have an rss feed I can add?
Why do I have to connect my satellite tv receiver to my telephone line? The phone connection allows DIRECTV customers to be authorized so that they can order Pay Per View movies and events with their remote control and get popular sports subscriptions. Please keep in mind that you cannot connect with a cell phone. It has to be a land-based phone line. http://www.4pcsatellitetv.com.
Many Thanks for the post. I was quite confused about this particular issue, however your post has made it much clearer 🙂
great share, thanks
Hey, I’ve read loads of your posts and have enjoyed them 😀 Would you like to maybe swap blogroll links?
Very good post! I have bookmarked your web site – do you have an rss feed I can subscribe to?
Really good post. Can I ask if you are using any search engine optimisation plugins? The reason I ask is that your page title seems a bit strange.
Well, I read it all…come back tomorow for more great posts!
Your site is loading very slowly for me. Might just be my computer but i am unsure… anyways brilliant post. Very helpful, many thanks. Will be sure to save your site for future reference
Great Post. I would love to read more in future. keep up the good work.
Thank you for the sensible critique. Me & my neighbour were preparing to do some research about that. We got a good book on that matter from our local library and most books where not as influensive as your information. I am very glad to see such information which I was searching for a long time.This made very glad
Awesome post! I like your website, and am a loyal reader. I will return sunday!
Yet again you come out with content. It isn’t easy material am glad I found customer, and similar information.
Hi guys if you need to build your own application and find the best value ISO coders at prices you may find only in your dreams, check this out : <A href="http://www.codingate.com">mobile, web, desktop apps programming</A>
Very interesting find Thor. Hoping to see more posts from you soon.
loved most posts in your blog,but i cant tell what to buy? <A href="http://www.generic4u.com">online viagra</A> brand or generic…
Excellent info and thanks so much for the post. -Kate
Really damn good post, keep up the good work mate, I’m gonna add your site to my rss feeds!
(…) OK good to see- new blogs are always welcome! See yas. (…)
I was on this community forum and one guy was talking involving your website. My curiosity brought me on this website. I don’t have a single thing poor to say regarding your weblog, Infact I believe this is an excellent web site! Keep writing!
I can’t say that I agree with you on this completely, but you definitely make some valid points.
Like it … a lot!
Is it ok to use some info from the site?
I am favorableto find so many usefulinformation here in the post, we need increasemore strategies in this regard, thanks for sharing.
thank you for the usefull post
Just my 2 cents, but your website will look much more interesting if you can put in some pictures.
(Salut | Bienvenue | Salut HI) Try-Catch-FAIL – Using Powershell to apply new C# field naming conventions premičre fois (sauté | borné | houblonné |) sauté ici sur votre site, Founde sur (Google | Yahoo | Bing | ASK). C’est ma premičre impression avant de commenter le contenu. Je suis ravie de trouver votre site en ligne magnifique. Je cherche manusl utilisateur (| manuels en PDF | manuel du propriétaire). J’ai trouvé magasin avec manusl utilisateur (| manuels en PDF | manuel du propriétaire) par regarder gratuitement manusl (utilisateur | manuels en PDF | manuel du propriétaire). Avez-vous actuellement un site Web gratuit avec PDF? incident Envoyez-moi des nouvelles de [email protected]
That is a very clever post. Continue doing what you do dear.
Ich liebe Try-Catch-FAIL – Using Powershell to apply new C# field naming conventions dieser Seite! Ich bin so froh, dass ich es gefunden und ich vorgemerkt haben, und kommen wieder! Hallo (| Willkommen | Hallo HALLO) (Zum ersten Mal sprang | begrenzt | hüpfte | übersprungen) hier auf Ihrer Website, auf founde (Google | Yahoo | Bing | ASK). gezwegen Sie mich über Aktuelles zu [email protected]
i tried to post a comment, but your site show me a blank page. now can you read me? thanks for the information.
Intimately, the post is in reality the greatest on this worthy topic. I fit in with your conclusions and will thirstily look forward to your coming updates. Just saying thanks will not just be adequate, for the extraordinary clarity in your writing. I will immediately grab your rss feed to stay abreast of any updates. Authentic work and much success in your business efforts!
This is an excellent design. Who did it?
Great thread. Enjoyed the posts…
Haha!!! Excellent work! Those dudes at your competition (you know who) don’t even have a clue! Keep it up!
Finally, a good post about this subject! I can not believe I had to go thru like 20 blogs just to come across this excellent post. All their content together still can not equal the content of this article. I have learned a lot and will bookmark your web page. Maintain up the good job!
Your site is one of my favorite blogs I’ve ever seen so far and man , I tell ya , I’ve seen a lot of great informational blogs. I’m glad that i found such great news here. Keep up the good work dude.
What is FXOnline Mobile Forex Trading? FXOnline Mobile Forex Trading is a forex transaction system which brings desktop currency trading to your mobile phone. FXOnline fs Mobile Trading Forex Platform makes use of Docomo fs i-Appli mobile platform, available on all Docomo 900 Series handsets. FXOnline fs mobile platform has many functions available on PC desktop trading systems, such as trade verification, limit orders, stop-loss orders, real-time rates and account balance information. http://www.forextradingbrotherhood.com.
What a cool story. Love the website! Keep up the great work 🙂
I hate my apple iphone internet browser simply because I am unable to see this article correctly