SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
Diving into Visual Studio 2015 (Day #3): Renaming
Assistance
Introduction
In this part of the article series on learning Visual Studio 2015 we’ll cover topic named renaming in Visual Studio 2015.
Yes Visual Studio 2015 provides a great capability of refactoring/renaming the code. It helps developer to optimize and
refactor the code as per the development or best practices need. This feature enables developer to follow best practices
by giving refactoring suggestions as well as helping in fixing and optimizing the code. Renaming the variables, methods,
properties, classes or even projects has always been a challenge to a developer when working on large code base.
Another challenge that most of the developers face is w.r.t. code comments and writing an optimized method. Visual
Studio 2015 helps in code refactoring and renaming as well in a very easy and friendly way.
Code Renaming
There are a lot of features that this capability of renaming covers in visual Studio 2015.Change preview,inline and
modeless rename windows, renaming on the fly, detecting and resolving conflicts, renaming code comments are few of
them. Let us discuss each one in detail via practical examples. I am using Visual Studio 2015 Enterprise edition and have
created a console application named VS2015ConsoleApplication having an interface named IProducts and a class named
MyProducts that implements the interface.IProducts contains two methods, one to return product based on product
code and another to return complete list of products. Product.cs is another class containing Product entity. This class
acts as a transfer object or entity. We’ll use Main method of Program.cs class to invoke methods of MyProducts class.
IProducts
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: interface IProducts
10: {
11: Product GetProduct(string productCode);
12: List<Product> GetProductList();
13: }
14: }
Product
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: public class Product
10: {
11: public string ProductName { get; set; }
12: public string ProductCode { get; set; }
13: public string ProductPrice { get; set; }
14: public string ProductType { get; set; }
15: public string ProductDescription { get; set; }
16:
17: }
18: }
MyProducts
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: public class MyProducts :IProducts
10: {
11: List<Product> _productList = new List<Product>();
12: public MyProducts()
13: {
14: _productList.Add(new Product
{ProductCode="0001",ProductName="IPhone",ProductPrice="60000",ProductType="Phone",ProductDescription="Apple
IPhone" } );
15: _productList.Add(new Product { ProductCode = "0002", ProductName = "Canvas", ProductPrice =
"20000", ProductType = "Phone", ProductDescription = "Micromax phone" });
16: _productList.Add(new Product { ProductCode = "0003", ProductName = "IPad", ProductPrice =
"30000", ProductType = "Tab", ProductDescription = "Apple IPad" });
17: _productList.Add(new Product { ProductCode = "0004", ProductName = "Nexus", ProductPrice =
"30000", ProductType = "Phone", ProductDescription = "Google Phone" });
18: _productList.Add(new Product { ProductCode = "0005", ProductName = "S6", ProductPrice =
"40000", ProductType = "Phone", ProductDescription = "Samsung phone" });
19:
20: }
21:
22: public Product GetProduct(string productCode)
23: {
24: return _productList.Find(p => p.ProductCode == productCode);
25: }
26:
27: public List<Product> GetProductList()
28: {
29: return _productList;
30: }
31: }
32: }
Program.cs
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: class Program
10: {
11: static void Main()
12: {
13: var myProducts = new MyProducts();
14: Console.WriteLine( String.Format("Product with code 0002 is : {0}",
myProducts.GetProduct("0002").ProductName));
15: Console.WriteLine(Environment.NewLine);
16: var productList = myProducts.GetProductList();
17: Console.WriteLine("Following are all the products");
18:
19: foreach (var product in productList)
20: {
21: Console.WriteLine(product.ProductName);
22: }
23: Console.ReadLine();
24: }
25: }
26: }
Our code is ready. Program file’s main method calls both the interface methods from MyProducts class to test the
functionality.
We’ll use this code base to learn code renaming features.The renaming experience may vary w.r.t. what actual
operation is being performed. For example in MyProducts class we are using _productList as a variable containing list of
all products, and this variable is widely used throughout the class.
Let us try to rename this variable to a new name called _allProducts.
Notice that as soon as _productsList is changed to _allProduct, a dotted box is shown around the changed variable name
and a light bulb icon appears at the left. One can see one more change, that all the instances where _productList was
used has a red line below them. This means that all the instances should be changed accordingly. You can see here the
power of Visual Studio. Visual studio is smart enough to understand and communicate that the change that a developer
is making has to be reflected to other places too. Let us see what Light bulb icon says. Let us click on light bulb icon
appeared at the left margin.
The light bulb icon shows some suggestions that we learnt in Day #1 and Day #2 of this article series. There is one new
suggestion that Light bulb icon is showing now and that is regarding “Rename”. In the suggestion window Light bulb icon
shows all the _productList instances highlighted and says to rename all the instances to new name i.e _allProducts.
When you preview the changes by clicking “Preview Changes ” link shown at the bottom of suggestion window, it shows
the resultant changes that you’ll get once variable is renamed.
In preview you can clearly see the changes that will take place once the variable is renamed. Let us click on apply
changes, and you’ll see the method has a new changed variable now at all the instances.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: public class MyProducts :IProducts
10: {
11: List<Product> _allProduct = new List<Product>();
12: public MyProducts()
13: {
14: _allProduct.Add(new Product
{ProductCode="0001",ProductName="IPhone",ProductPrice="60000",ProductType="Phone",ProductDescription="Apple
IPhone" } );
15: _allProduct.Add(new Product { ProductCode = "0002", ProductName = "Canvas", ProductPrice =
"20000", ProductType = "Phone", ProductDescription = "Micromax phone" });
16: _allProduct.Add(new Product { ProductCode = "0003", ProductName = "IPad", ProductPrice =
"30000", ProductType = "Tab", ProductDescription = "Apple IPad" });
17: _allProduct.Add(new Product { ProductCode = "0004", ProductName = "Nexus", ProductPrice =
"30000", ProductType = "Phone", ProductDescription = "Google Phone" });
18: _allProduct.Add(new Product { ProductCode = "0005", ProductName = "S6", ProductPrice =
"40000", ProductType = "Phone", ProductDescription = "Samsung phone" });
19:
20: }
21:
22: public Product GetProduct(string productCode)
23: {
24: return _allProduct.Find(p => p.ProductCode == productCode);
25: }
26:
27: public List<Product> GetProductList()
28: {
29: return _allProduct;
30: }
31: }
32: }
Now let’s run the application to check if the changes had an impact on the functionality of the application.Press F5.
It is clearly seen that application has no build error and produces the same result as earlier. There is one thing that a
developer needs to take care of, sometimes renaming may be risky and tricky in large code base, so while renaming it is
suggested to have a glance over preview i.e. given by suggestion window.
Let us take another scenario.Open the Program.cs file and perform rename on myProducts object.
This time we’ll do renaming through context menu. Right click on myProducts object name and you’ll see the context
menu open. There is an option of rename on the opened context menu.
In front of Rename option, there is a shortcut available too Ctrl+R, Ctrl+R. When you select Rename, you’ll notice that
the renaming experience here is different , all the instances of the renaming gets highlighted.There is a new window that
appears at the right corner of code window having few other options. Now if you rename the object name, the other
highlighted variables get renamed on the fly while typing. To close the Rename window you can click cross button on
that window. Notice that this option of renaming through context menu is much faster that the earlier one, and enables
you to rename on the fly in a single step with live preview while typing. Once the variable is renamed and you close the
window, all the highlighting will be gone and you get a clean renamed variable at all the occurrences.
I changed the object name from myProducts to products.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: class Program
10: {
11: static void Main()
12: {
13: var myProducts = new MyProducts();
14: Console.WriteLine( String.Format("Product with code 0002 is : {0}",
myProducts.GetProduct("0002").ProductName));
15: Console.WriteLine(Environment.NewLine);
16: var productList = myProducts.GetProductList();
17: Console.WriteLine("Following are all the products");
18:
19: foreach (var product in productList)
20: {
21: Console.WriteLine(product.ProductName);
22: }
23: Console.ReadLine();
24: }
25: }
26: }
Rename Conflicts
Let us take another scenario where we try to rename a variable to another name that is already assigned to any other
variable in the same method or try to rename a property of a class having another property having same name as of new
name. Let us open Product class for example. Product class contains the Product properties, let us try to rename
ProductName property. Right click on ProductName property and open Rename window by clicking Rename from
context menu.
We’ll change the name of ProductName property to ProductCode.We already have ProductCode property available in
this class. Let us see what happens.Notice that when you start typing the new name of ProductName property to
ProductCode, the rename window shows error with Red color, and the already exiting ProductCode propert also shows a
red box around it.
Here Visual Studio 2015 smartly tells that the new property name already exists in the class and this change may result
in having conflicts. Now you know that this change may cause your application to break, so just press escape and the
rename window will be gone with your new name reverted to old one.
Therefore Visual Studio helps to detect any renaming conflicts and suggest to resolve them.
Rename Overloads, Strings, Code Comments
Let us take one more scenario. Add an overload method named GetProduct to IProduct interface and implement that
menthod in MyProducts class.
1: interface IProducts
2: {
3: Product GetProduct(string productCode);
4: Product GetProduct(string productCode,string productName);
5: List<Product> GetProductList();
6: }
1: /// <summary>
2: /// GetProduct
3: /// </summary>
4: /// <param name="productCode"></param>
5: /// <returns></returns>
6: public Product GetProduct(string productCode)
7: {
8: return _allProduct.Find(p => p.ProductCode == productCode);
9: }
10:
11: /// <summary>
12: /// GetProduct with productCode and productName
13: /// </summary>
14: /// <param name="productCode"></param>
15: /// <param name="productName"></param>
16: /// <returns></returns>
17: public Product GetProduct(string productCode, string productName)
18: {
19: return _allProduct.Find(p => p.ProductCode == productCode && p.ProductName==productName);
20: }
21:
Now try to rename the GetProduct method in MyProducts class. Put the cursor in between the GetProduct method
name and press Ctrl+R, Ctrl+R.The rename window will be opened as shown below.
You see here the Rename window opens having few more options as shown below.
If you select the checkbox to include overloads, the overloads of that method which we are renaming also gets renamed,
in this case if we choos thos option the overloaded method of GetProduct() also gets renamed.
If we also choose the second option then the code comments also get renamed when we rename the method to new
name. The name if exists in code comments also gets renamed to new name.
The renaming option also allows to rename related strings for that name, i.e. the third option. You can also preview the
changes before renaming. preview changes window shows you all the occurences that will remain, and provides you an
option again to review and select un-select the change you want to take place at particular instance.Here I am trying to
change GetProduct name to FetchProduct . Let us check Preview changes check box and press Apply button.
A preview window will get opened. Notice that not only for particular file but this window accumulates all the possible
areas where this change may take place and affect code like in MyProduct.cs file, IProducts.cs interface and program.cs
file. it says that when method name is changed, it will reflect in these files as well. Now it is the choice of a developer,
whether to let that change happen or not. So preview window gives an option to developer to check or un-check the
checkbox for corresponding affected file for that change to take place or not. The code suggestion and code assistance
mechanism of Visual Studio is so string that it takes care of all these modifications and automations very smartly.
In this case I didn’t un-select any of the file and let that change happen. it automatically renamed GetProduct to Fetch
Product to all the areas shown including Comments, Interface and Program file as well.
In a similar way you can also rename the parameters passed in a method, this will also include all the possible renaming
options like rename in comments and methods.Like shown in the following image, if I try to rename the parameter of
FetchProduct method, it highlights all the possible renaming changes.
Put the cursor between productCode and press Ctrl+R, Ctrl+R, the rename window will appear and all instances of
parameter gets highlighted, even the comment too.Change the name to pCode and click on apply.
We see the parameter name is changed along with the name in comment too.
Conclusion
In this article we covered Renaming assistance provided by Visual Studio 2015. We learnt about the renaming
experience in various ways that includes following bullet points.
 Renaming assistance through light bulb actions
 Change preview with smart suggestions.
 Rename window and its renaming options.
 On the fly , live renaming experience. Rename as you type.
 Conflict detection and resolution while renaming.
 Renaming code comments.
In the next section of this series, I’ll cover code refactoring in Visual Studio 2015.
For more technical articles you can reach out to my personal blog, CodeTeddy.
Read More
 Diving into Visual Studio 2015 (Day #1) : Code Assistance
 Diving into Visual Studio 2015 (Day #2): Code Analyzers

Contenu connexe

Tendances

Coded ui - lesson 3 - case study - calculator
Coded ui - lesson 3 - case study - calculatorCoded ui - lesson 3 - case study - calculator
Coded ui - lesson 3 - case study - calculatorOmer Karpas
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAlfa Gama Omega
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guideFahad Shiekh
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAhsanul Karim
 
Gui builder
Gui builderGui builder
Gui builderlearnt
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentA comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentKaty Slemon
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivitiesmaamir farooq
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1Akhil Mittal
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7Cosmina Ivan
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4Akhil Mittal
 
Android User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAhsanul Karim
 
Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008Yudep Apoi
 
Visual studio ide componects dot net framwork
Visual studio ide componects dot net framworkVisual studio ide componects dot net framwork
Visual studio ide componects dot net framworkDipen Parmar
 
Coded ui - lesson 2 - coded ui test builder
Coded ui - lesson 2 - coded ui test builderCoded ui - lesson 2 - coded ui test builder
Coded ui - lesson 2 - coded ui test builderOmer Karpas
 
Salesforce connector Example
Salesforce connector ExampleSalesforce connector Example
Salesforce connector Exampleprudhvivreddy
 

Tendances (20)

Coded ui - lesson 3 - case study - calculator
Coded ui - lesson 3 - case study - calculatorCoded ui - lesson 3 - case study - calculator
Coded ui - lesson 3 - case study - calculator
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guide
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
 
Gui builder
Gui builderGui builder
Gui builder
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentA comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter component
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7
 
Hats tutorial custom widget
Hats tutorial   custom widgetHats tutorial   custom widget
Hats tutorial custom widget
 
Active x
Active xActive x
Active x
 
RUP - aula prática 9 e 10
RUP - aula prática 9 e 10RUP - aula prática 9 e 10
RUP - aula prática 9 e 10
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
 
Android User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form Widgets
 
Android calculatortest
Android calculatortestAndroid calculatortest
Android calculatortest
 
Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008
 
Visual studio ide componects dot net framwork
Visual studio ide componects dot net framworkVisual studio ide componects dot net framwork
Visual studio ide componects dot net framwork
 
Coded ui - lesson 2 - coded ui test builder
Coded ui - lesson 2 - coded ui test builderCoded ui - lesson 2 - coded ui test builder
Coded ui - lesson 2 - coded ui test builder
 
Self Tester
Self TesterSelf Tester
Self Tester
 
Salesforce connector Example
Salesforce connector ExampleSalesforce connector Example
Salesforce connector Example
 

En vedette (10)

Starting with why
Starting with whyStarting with why
Starting with why
 
PDFArticle
PDFArticlePDFArticle
PDFArticle
 
First principles of brilliant teaching
First principles of brilliant teachingFirst principles of brilliant teaching
First principles of brilliant teaching
 
Pedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HEPedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HE
 
The human face of feedback
The human face of feedbackThe human face of feedback
The human face of feedback
 
Эффективные каналы коммуникации в сфере недвижимости
Эффективные каналы коммуникации в сфере недвижимостиЭффективные каналы коммуникации в сфере недвижимости
Эффективные каналы коммуникации в сфере недвижимости
 
It's ok to lecture: from boredom to brilliance
It's ok to lecture: from boredom to brillianceIt's ok to lecture: from boredom to brilliance
It's ok to lecture: from boredom to brilliance
 
Бюджетирование маркетинга
Бюджетирование маркетингаБюджетирование маркетинга
Бюджетирование маркетинга
 
Эффективность печатных и интернет СМИ
Эффективность печатных и интернет СМИЭффективность печатных и интернет СМИ
Эффективность печатных и интернет СМИ
 
Demystifying Research Informed Teaching: parallel universes?
Demystifying Research Informed Teaching: parallel universes?Demystifying Research Informed Teaching: parallel universes?
Demystifying Research Informed Teaching: parallel universes?
 

Similaire à Diving into VS 2015 Day3

Volley lab btc_bbit
Volley lab btc_bbitVolley lab btc_bbit
Volley lab btc_bbitCarWash1
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Getting started with test complete 7
Getting started with test complete 7Getting started with test complete 7
Getting started with test complete 7Hoamuoigio Hoa
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Oracle General ledger ivas
Oracle General ledger ivasOracle General ledger ivas
Oracle General ledger ivasAli Ibrahim
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Haitham Raik
 
Swift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for DevelopersSwift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for DevelopersAzilen Technologies Pvt. Ltd.
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1Dipendra Shekhawat
 
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0Haytham Ghandour
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 
Programming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) EnvironmentProgramming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) EnvironmentMahmoud Samir Fayed
 

Similaire à Diving into VS 2015 Day3 (20)

Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
 
Volley lab btc_bbit
Volley lab btc_bbitVolley lab btc_bbit
Volley lab btc_bbit
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Getting started with test complete 7
Getting started with test complete 7Getting started with test complete 7
Getting started with test complete 7
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Oracle General ledger ivas
Oracle General ledger ivasOracle General ledger ivas
Oracle General ledger ivas
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 
Ms vb
Ms vbMs vb
Ms vb
 
Swift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for DevelopersSwift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for Developers
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1
 
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 
Programming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) EnvironmentProgramming Without Coding Technology (PWCT) Environment
Programming Without Coding Technology (PWCT) Environment
 

Plus de Akhil Mittal

Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release PlanningAkhil Mittal
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4Akhil Mittal
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questionsAkhil Mittal
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Akhil Mittal
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Akhil Mittal
 
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Akhil Mittal
 
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Akhil Mittal
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Akhil Mittal
 
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Akhil Mittal
 

Plus de Akhil Mittal (20)

Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
 
RESTfulDay9
RESTfulDay9RESTfulDay9
RESTfulDay9
 
PDF_Article
PDF_ArticlePDF_Article
PDF_Article
 
RESTful Day 7
RESTful Day 7RESTful Day 7
RESTful Day 7
 
RESTful Day 6
RESTful Day 6RESTful Day 6
RESTful Day 6
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
IntroductionToMVC
IntroductionToMVCIntroductionToMVC
IntroductionToMVC
 
RESTful Day 5
RESTful Day 5RESTful Day 5
RESTful Day 5
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questions
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
 
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
 
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
 
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...
 

Diving into VS 2015 Day3

  • 1. Diving into Visual Studio 2015 (Day #3): Renaming Assistance Introduction In this part of the article series on learning Visual Studio 2015 we’ll cover topic named renaming in Visual Studio 2015. Yes Visual Studio 2015 provides a great capability of refactoring/renaming the code. It helps developer to optimize and refactor the code as per the development or best practices need. This feature enables developer to follow best practices by giving refactoring suggestions as well as helping in fixing and optimizing the code. Renaming the variables, methods, properties, classes or even projects has always been a challenge to a developer when working on large code base. Another challenge that most of the developers face is w.r.t. code comments and writing an optimized method. Visual Studio 2015 helps in code refactoring and renaming as well in a very easy and friendly way. Code Renaming There are a lot of features that this capability of renaming covers in visual Studio 2015.Change preview,inline and modeless rename windows, renaming on the fly, detecting and resolving conflicts, renaming code comments are few of them. Let us discuss each one in detail via practical examples. I am using Visual Studio 2015 Enterprise edition and have created a console application named VS2015ConsoleApplication having an interface named IProducts and a class named MyProducts that implements the interface.IProducts contains two methods, one to return product based on product code and another to return complete list of products. Product.cs is another class containing Product entity. This class acts as a transfer object or entity. We’ll use Main method of Program.cs class to invoke methods of MyProducts class. IProducts 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: interface IProducts
  • 2. 10: { 11: Product GetProduct(string productCode); 12: List<Product> GetProductList(); 13: } 14: } Product 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: public class Product 10: { 11: public string ProductName { get; set; } 12: public string ProductCode { get; set; } 13: public string ProductPrice { get; set; } 14: public string ProductType { get; set; } 15: public string ProductDescription { get; set; } 16: 17: } 18: } MyProducts 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: public class MyProducts :IProducts 10: { 11: List<Product> _productList = new List<Product>(); 12: public MyProducts() 13: { 14: _productList.Add(new Product {ProductCode="0001",ProductName="IPhone",ProductPrice="60000",ProductType="Phone",ProductDescription="Apple IPhone" } ); 15: _productList.Add(new Product { ProductCode = "0002", ProductName = "Canvas", ProductPrice = "20000", ProductType = "Phone", ProductDescription = "Micromax phone" }); 16: _productList.Add(new Product { ProductCode = "0003", ProductName = "IPad", ProductPrice = "30000", ProductType = "Tab", ProductDescription = "Apple IPad" }); 17: _productList.Add(new Product { ProductCode = "0004", ProductName = "Nexus", ProductPrice = "30000", ProductType = "Phone", ProductDescription = "Google Phone" }); 18: _productList.Add(new Product { ProductCode = "0005", ProductName = "S6", ProductPrice = "40000", ProductType = "Phone", ProductDescription = "Samsung phone" }); 19: 20: } 21: 22: public Product GetProduct(string productCode)
  • 3. 23: { 24: return _productList.Find(p => p.ProductCode == productCode); 25: } 26: 27: public List<Product> GetProductList() 28: { 29: return _productList; 30: } 31: } 32: } Program.cs 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: class Program 10: { 11: static void Main() 12: { 13: var myProducts = new MyProducts(); 14: Console.WriteLine( String.Format("Product with code 0002 is : {0}", myProducts.GetProduct("0002").ProductName)); 15: Console.WriteLine(Environment.NewLine); 16: var productList = myProducts.GetProductList(); 17: Console.WriteLine("Following are all the products"); 18: 19: foreach (var product in productList) 20: { 21: Console.WriteLine(product.ProductName); 22: } 23: Console.ReadLine(); 24: } 25: } 26: } Our code is ready. Program file’s main method calls both the interface methods from MyProducts class to test the functionality.
  • 4. We’ll use this code base to learn code renaming features.The renaming experience may vary w.r.t. what actual operation is being performed. For example in MyProducts class we are using _productList as a variable containing list of all products, and this variable is widely used throughout the class. Let us try to rename this variable to a new name called _allProducts.
  • 5. Notice that as soon as _productsList is changed to _allProduct, a dotted box is shown around the changed variable name and a light bulb icon appears at the left. One can see one more change, that all the instances where _productList was used has a red line below them. This means that all the instances should be changed accordingly. You can see here the power of Visual Studio. Visual studio is smart enough to understand and communicate that the change that a developer is making has to be reflected to other places too. Let us see what Light bulb icon says. Let us click on light bulb icon appeared at the left margin. The light bulb icon shows some suggestions that we learnt in Day #1 and Day #2 of this article series. There is one new suggestion that Light bulb icon is showing now and that is regarding “Rename”. In the suggestion window Light bulb icon shows all the _productList instances highlighted and says to rename all the instances to new name i.e _allProducts. When you preview the changes by clicking “Preview Changes ” link shown at the bottom of suggestion window, it shows the resultant changes that you’ll get once variable is renamed.
  • 6. In preview you can clearly see the changes that will take place once the variable is renamed. Let us click on apply changes, and you’ll see the method has a new changed variable now at all the instances. 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: public class MyProducts :IProducts 10: { 11: List<Product> _allProduct = new List<Product>(); 12: public MyProducts() 13: { 14: _allProduct.Add(new Product {ProductCode="0001",ProductName="IPhone",ProductPrice="60000",ProductType="Phone",ProductDescription="Apple IPhone" } ); 15: _allProduct.Add(new Product { ProductCode = "0002", ProductName = "Canvas", ProductPrice = "20000", ProductType = "Phone", ProductDescription = "Micromax phone" });
  • 7. 16: _allProduct.Add(new Product { ProductCode = "0003", ProductName = "IPad", ProductPrice = "30000", ProductType = "Tab", ProductDescription = "Apple IPad" }); 17: _allProduct.Add(new Product { ProductCode = "0004", ProductName = "Nexus", ProductPrice = "30000", ProductType = "Phone", ProductDescription = "Google Phone" }); 18: _allProduct.Add(new Product { ProductCode = "0005", ProductName = "S6", ProductPrice = "40000", ProductType = "Phone", ProductDescription = "Samsung phone" }); 19: 20: } 21: 22: public Product GetProduct(string productCode) 23: { 24: return _allProduct.Find(p => p.ProductCode == productCode); 25: } 26: 27: public List<Product> GetProductList() 28: { 29: return _allProduct; 30: } 31: } 32: } Now let’s run the application to check if the changes had an impact on the functionality of the application.Press F5. It is clearly seen that application has no build error and produces the same result as earlier. There is one thing that a developer needs to take care of, sometimes renaming may be risky and tricky in large code base, so while renaming it is suggested to have a glance over preview i.e. given by suggestion window. Let us take another scenario.Open the Program.cs file and perform rename on myProducts object.
  • 8. This time we’ll do renaming through context menu. Right click on myProducts object name and you’ll see the context menu open. There is an option of rename on the opened context menu. In front of Rename option, there is a shortcut available too Ctrl+R, Ctrl+R. When you select Rename, you’ll notice that the renaming experience here is different , all the instances of the renaming gets highlighted.There is a new window that appears at the right corner of code window having few other options. Now if you rename the object name, the other highlighted variables get renamed on the fly while typing. To close the Rename window you can click cross button on that window. Notice that this option of renaming through context menu is much faster that the earlier one, and enables you to rename on the fly in a single step with live preview while typing. Once the variable is renamed and you close the window, all the highlighting will be gone and you get a clean renamed variable at all the occurrences.
  • 9. I changed the object name from myProducts to products. 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: class Program 10: { 11: static void Main() 12: { 13: var myProducts = new MyProducts(); 14: Console.WriteLine( String.Format("Product with code 0002 is : {0}", myProducts.GetProduct("0002").ProductName)); 15: Console.WriteLine(Environment.NewLine); 16: var productList = myProducts.GetProductList(); 17: Console.WriteLine("Following are all the products"); 18: 19: foreach (var product in productList) 20: { 21: Console.WriteLine(product.ProductName); 22: } 23: Console.ReadLine(); 24: } 25: } 26: } Rename Conflicts Let us take another scenario where we try to rename a variable to another name that is already assigned to any other variable in the same method or try to rename a property of a class having another property having same name as of new name. Let us open Product class for example. Product class contains the Product properties, let us try to rename ProductName property. Right click on ProductName property and open Rename window by clicking Rename from context menu.
  • 10. We’ll change the name of ProductName property to ProductCode.We already have ProductCode property available in this class. Let us see what happens.Notice that when you start typing the new name of ProductName property to ProductCode, the rename window shows error with Red color, and the already exiting ProductCode propert also shows a red box around it. Here Visual Studio 2015 smartly tells that the new property name already exists in the class and this change may result in having conflicts. Now you know that this change may cause your application to break, so just press escape and the rename window will be gone with your new name reverted to old one.
  • 11. Therefore Visual Studio helps to detect any renaming conflicts and suggest to resolve them. Rename Overloads, Strings, Code Comments Let us take one more scenario. Add an overload method named GetProduct to IProduct interface and implement that menthod in MyProducts class. 1: interface IProducts 2: { 3: Product GetProduct(string productCode); 4: Product GetProduct(string productCode,string productName); 5: List<Product> GetProductList(); 6: } 1: /// <summary> 2: /// GetProduct 3: /// </summary> 4: /// <param name="productCode"></param> 5: /// <returns></returns> 6: public Product GetProduct(string productCode) 7: { 8: return _allProduct.Find(p => p.ProductCode == productCode); 9: } 10: 11: /// <summary> 12: /// GetProduct with productCode and productName 13: /// </summary> 14: /// <param name="productCode"></param> 15: /// <param name="productName"></param> 16: /// <returns></returns>
  • 12. 17: public Product GetProduct(string productCode, string productName) 18: { 19: return _allProduct.Find(p => p.ProductCode == productCode && p.ProductName==productName); 20: } 21: Now try to rename the GetProduct method in MyProducts class. Put the cursor in between the GetProduct method name and press Ctrl+R, Ctrl+R.The rename window will be opened as shown below. You see here the Rename window opens having few more options as shown below. If you select the checkbox to include overloads, the overloads of that method which we are renaming also gets renamed, in this case if we choos thos option the overloaded method of GetProduct() also gets renamed.
  • 13. If we also choose the second option then the code comments also get renamed when we rename the method to new name. The name if exists in code comments also gets renamed to new name. The renaming option also allows to rename related strings for that name, i.e. the third option. You can also preview the changes before renaming. preview changes window shows you all the occurences that will remain, and provides you an option again to review and select un-select the change you want to take place at particular instance.Here I am trying to change GetProduct name to FetchProduct . Let us check Preview changes check box and press Apply button.
  • 14. A preview window will get opened. Notice that not only for particular file but this window accumulates all the possible areas where this change may take place and affect code like in MyProduct.cs file, IProducts.cs interface and program.cs file. it says that when method name is changed, it will reflect in these files as well. Now it is the choice of a developer, whether to let that change happen or not. So preview window gives an option to developer to check or un-check the checkbox for corresponding affected file for that change to take place or not. The code suggestion and code assistance mechanism of Visual Studio is so string that it takes care of all these modifications and automations very smartly. In this case I didn’t un-select any of the file and let that change happen. it automatically renamed GetProduct to Fetch Product to all the areas shown including Comments, Interface and Program file as well. In a similar way you can also rename the parameters passed in a method, this will also include all the possible renaming options like rename in comments and methods.Like shown in the following image, if I try to rename the parameter of FetchProduct method, it highlights all the possible renaming changes. Put the cursor between productCode and press Ctrl+R, Ctrl+R, the rename window will appear and all instances of parameter gets highlighted, even the comment too.Change the name to pCode and click on apply.
  • 15. We see the parameter name is changed along with the name in comment too. Conclusion In this article we covered Renaming assistance provided by Visual Studio 2015. We learnt about the renaming experience in various ways that includes following bullet points.  Renaming assistance through light bulb actions  Change preview with smart suggestions.  Rename window and its renaming options.  On the fly , live renaming experience. Rename as you type.  Conflict detection and resolution while renaming.  Renaming code comments. In the next section of this series, I’ll cover code refactoring in Visual Studio 2015. For more technical articles you can reach out to my personal blog, CodeTeddy. Read More  Diving into Visual Studio 2015 (Day #1) : Code Assistance  Diving into Visual Studio 2015 (Day #2): Code Analyzers