Thursday, April 14, 2011

Is there a way to check if all defined functions are called?

Is there a way to figure out if every function defined in code is called somewhere?

I have been doing a major code update to a large project of mine and I want to make sure the old functions that are no longer used are removed from the code.

Is there a better way then searching for each function in the solution?

From stackoverflow
  • Code coverage tool like NCover?

    EDIT: This assumes you have sufficient tests for functionality and are determined to get rid of every unnecessary function. Delete-then-compile would work but isn't scalable.. regardless, the point is that you're going to want some kind of source analysis tool (either static or runtime analysis).

  • Here's a way that will catch everything but reflection.

    1. Delete the method
    2. Compile

    This seems a bit overkill but it has the advantage that you can "batch" queries by deleting multiple functions.

    Andrew Coleson : Order could matter here, though? If A() calls B() but nothing calls A(), deleting B() first will be misleading since it won't compile.
    JaredPar : @Andrew I didn't say it was easy :).
    Sung Meister : @JaredPar: I think, I have read about that process from "Working Effectively with Legacy Code" by Michael Feathers on how to refactor legacy code with no tests.
  • FxCop should be able to find orphaned/unused methods. I think static analysis is what you're looking for, not code coverage.

  • Two suggestions:

    • Depending on your development tools, you may be able to generate warnings for functions that are declared but never called.

    • You may be able to generate a linker map, then compare its list of functions with a list you generate (with grep or ctags?) directly from your source.

  • See earlier question: What tools and techniques do you use to find dead code in .NET?

  • Mark each method you are trying to remove as Obsolete with IsError set to true. When you mark a method as such, you will get a compilation error and will be able to find out if you can safely remove the method.

        [Obsolete("Don't use this method", /* IsError */ true)]
        public void Foo () {}
    
    Sung Meister : I tend to turn on IsError for my own internal libs. For other cases, I leaeve it off
    Svish : I do that too. And often leave them like that for a while, until I am absolutely certain I don't need them anymore. Unless I really am absolutely certain I don't need it anymore already of course :p
    Sung Meister : @Svish: Turning on IsError seems to be obtrusive sometimes but sometimes when it's gotta go, it's gotta go.

ssis : how to insert into oledb destination from oledb command

Hi I'm trying to insert in a ole db destination the result of a sp for each record in an ole db source,

the sp returns a record set

I have found this how to call a stored procedure in SSIS

but i still can't see the outpout columns in OleDb Command Output Columns

here is my sp: create PROCEDURE [dbo].[GetData] ( @user varchar(50) ) AS set nocount on -- Publish metadata for ssis if 1=0 begin select '' x, '' y, '' z end

declare @user_tmp table ( x varchar(max), y varchar(max), z varchar(max) )

insert into @user_tmp select 'x1' x, 'y1' y, 'z1' z

select distinct * from @user_tmp set nocount off

From stackoverflow

Convention over configuration with Spring MVC using ControllerClassNameHandlerMapping?

Following the directions from Spring Source and the book Spring in Action, I am trying to set up Spring MVC in a way that minimizes xml configuration. However according to Spring Source this is how you set up the ControllerClassNameHandlerMap

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="viewShoppingCart" class="x.y.z.ViewShoppingCartController">
    <!-- inject dependencies as required... -->
</bean>

Which strikes me as being completely useless, as it is actually simpler to use the handlers to just set the beans manually, as it is about the same amount of XML.

Now the book Spring in Action makes it sound like all you need is the first line from that code block to use the ControllerClassNameHandlerMapping, which would make it far more useful. However, I have not yet been able to get this to work.

Can anyone with Spring experience help me out?

From stackoverflow
  • There are actually two different things going on here:

    1. the mapping between URLs and controllers
    2. the definition of controllers as Spring beans

    For #1, if you define the ControllerClassNameHandlerMapping as you've done, that takes care of the URL-to-controller mapping. E.g., http://example.com/context/home -> HomeController

    For #2, you can define the controller beans as you've done. Or you can go down the path of using the Spring 2.5-style annotations for @Controllers and auto-wiring, which eliminates the need for XML bean definitions. Or not, the choice is up to you.

    What you avoid by using ControllerClassNameHandlerMapping is having to explictly map all your potential URLs to Controllers. We have used this successfully.

    One other thing you might want to use is the DefaultRequestToViewNameTranslator:

    <!-- Generates view names based on the request url (e.g. "/home.htm" => "home", "/user/list.htm" => "user/list", etc.) -->
    <bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/>
    

    We also use the UrlBasedViewResolver:

    <!-- Maps view names to tiles view definitions files.  E.g., "home" => "home", etc.  -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
    </bean>
    
    James McMahon : Thanks for the response Jeff. What I am trying to accomplish is just #1 for now, however without the additional bean definition none of my URLs are mapping to my controllers.
    Jeff Olson : Right, that's likely because Spring doesn't know about your controllers unless you make them Spring beans. You can do that with defs, or by using annotations.
    James McMahon : Even with the @Controller annotation it isn't working, but I might be missing something from my configuration.
    Jeff Olson : To use the annotations you have to use and ...see the Spring docs for more details (caveat: I have not used these...in my projects I've declared all the beans explicitly)
  • I don't think using ControllerClassNameHandlerMapping is a good engineering practice, as it is really preventing you from doing refactoring work on the Controller java class.

    James McMahon : I prefer the convention over configuration approach, it is just a matter of preference. I disagree that it prevents refactoring, you just have to keep your view and your controller names in sync, versus the configuration method, where you have to keep your view, your controller and your configuration in sync.

How can I look up IIS site id in C#?

I am writing an installer class for my web service. In many cases when I use WMI (e.g. when creating virtual directories) I have to know the siteId to provide the correct metabasePath to the site, e.g.:

metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
for example "IIS://localhost/W3SVC/1/Root"

How can I look it up programmatically in C#, based on the name of the site (e.g. for "Default Web Site")?

From stackoverflow
  • Maybe not the best way, but here we do it the following way :

    1. loop through all the sites under "IIS://servername/service"
    2. for each of the sites check if the name is "Default Web Site" in your case
    3. if true then you have your site id

    In Visual Basic 6 (sorry, all the code I have at hand just now) this would be it :

    Dim oSite As IADsContainer
    Dim oService As IADsContainer
    Set oService = GetObject("IIS://localhost/W3SVC")
    For Each oSite In oService
        If IsNumeric(oSite.Name) Then
            If oSite.ServerComment = "Default Web Site" Then
                Debug.Print "Your id = " & oSite.Name
            End If
        End If
    Next
    
  • Here is how to get it by name. You can modify as needed.

     public int GetWebSiteId(string serverName, string websiteName)
            {
                int result = -1;
    
                DirectoryEntry w3svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", serverName));
    
                foreach (DirectoryEntry site in w3svc.Children)
                {
                    if (site.Properties["ServerComment"] != null)
                    {
                        if (site.Properties["ServerComment"].Value != null)
                        {
                            if (string.Compare(site.Properties["ServerComment"].Value.ToString(), websiteName, 
    
                             false) == 0)
                            {
                                result = site.Name;
                                break;
                            }
                        }
                    }
                }
    
                return result;
            }
    
    MattH : On my system I had to update the above with the following to get it to compile "result = Convert.ToInt32(site.Name);"
  • You can search for a site by inspecting the ServerComment property belonging to children of the metabase path IIS://Localhost/W3SVC that have a SchemaClassName of IIsWebServer.

    The following code demonstrates two approaches:

    string siteToFind = "Default Web Site";
    
    // The Linq way
    using (DirectoryEntry w3svc1 = new DirectoryEntry("IIS://Localhost/W3SVC"))
    {
        IEnumerable<DirectoryEntry> children = 
              w3svc1.Children.Cast<DirectoryEntry>();
    
        var sites = 
            (from de in children
             where
              de.SchemaClassName == "IIsWebServer" &&
              de.Properties["ServerComment"].Value.ToString() == siteToFind
             select de).ToList();
        if(sites.Count() > 0)
        {
            // Found matches...assuming ServerComment is unique:
            Console.WriteLine(sites[0].Name);
        }
    }
    
    // The old way
    using (DirectoryEntry w3svc2 = new DirectoryEntry("IIS://Localhost/W3SVC"))
    {
    
        foreach (DirectoryEntry de in w3svc2.Children)
        {
         if (de.SchemaClassName == "IIsWebServer" && 
             de.Properties["ServerComment"].Value.ToString() == siteToFind)
         {
          // Found match
          Console.WriteLine(de.Name);
         }
        }
    }
    

    This assumes that the ServerComment property has been used (IIS MMC forces its used) and is unique.

    Kev

  • private static string FindWebSiteByName(string serverName, string webSiteName)
    {
     DirectoryEntry w3svc = new DirectoryEntry("IIS://" + serverName + "/W3SVC");
     foreach (DirectoryEntry site in w3svc.Children)
     {
      if (site.SchemaClassName == "IIsWebServer"
       && site.Properties["ServerComment"] != null
       && site.Properties["ServerComment"].Value != null
       && string.Equals(webSiteName, site.Properties["ServerComment"].Value.ToString(), StringComparison.OrdinalIgnoreCase))
      {
       return site.Path;
      }
     }
    
     return null;
    }
    
  • public static ManagementObject GetWebServerSettingsByServerComment(string serverComment)
            {
                ManagementObject returnValue = null;
    
                ManagementScope iisScope = new ManagementScope(@"\\localhost\root\MicrosoftIISv2", new ConnectionOptions());
                iisScope.Connect();
                if (iisScope.IsConnected)
                {
                    ObjectQuery settingQuery = new ObjectQuery(String.Format(
                        "Select * from IIsWebServerSetting where ServerComment = '{0}'", serverComment));
    
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(iisScope, settingQuery);
                    ManagementObjectCollection results = searcher.Get();
    
                    if (results.Count > 0)
                    {
                        foreach (ManagementObject manObj in results)
                        {
                            returnValue = manObj;
    
                            if (returnValue != null)
                            {
                                break;
                            }
                        }
                    }
                }
    
                return returnValue;
            }
    
    Grzenio : Does it work with IIS version <7? Unfortunately I am stuck with Win2k3
    Helephant : This method works for IIS6. I used it to find app pools.
  • Do you guys know how IIS 6.0 actually generates this ID number for each site? My server admin person is worried that if I set up a site using a random ID number, that IIS might in the future try to use that same number to generate a different site.

    Thanks

    Grzenio : You have to ask a new question. This is not a standard discussion site, noone is going to answer this one.

Why do inner classes make private methods accessible?

I don't understand why this compiles. f() and g() are visible from the inner classes, despite being private. Are they treated special specially because they are inner classes?

If A and B are not static classes, it's still the same.

class NotPrivate {
    private static class A {
        private void f() {
            new B().g();
        }
    }

    private static class B {
        private void g() {
            new A().f();
        }
    }
}
From stackoverflow
  • Java compiles in special accessors with $ in them. So you can't write Java that access the private methods. Explained here:

    http://www.retrologic.com/innerclasses.doc7.html

    There is one more category of compiler-generated members. A private member m of a class C may be used by another class D, if one class encloses the other, or if they are enclosed by a common class. Since the virtual machine does not know about this sort of grouping, the compiler creates a local protocol of access methods in C to allow D to read, write, or call the member m. These methods have names of the form access$0, access$1, etc. They are never public. Access methods are unique in that they may be added to enclosing classes, not just inner classes.

  • I think this quote sums it up nicely:

    ...inner classes can access all members of the declaring class, even private members. In fact, the inner class itself is said to be a member of the class; therefore, following the rules of object-oriented engineering, it should have access to all members of the class.

    And following from that, since both inner classes are really just part of the containing class, they should be able to access each others private members as well.

    Michael Myers : "As a matter of fact, when your class is compiled all the inner classes are actually 'collapsed' to become part of the containing class." -- What do you mean by this?
    Lou Franco : I'm pretty sure that isn't true. Usually classes of the form Outer$Inner are created. You can't really do what you said because you can have different numbers of objects of the inner and outer class.
    Eric Petroelje : You are right, that was a bit misleading. Removed that part from my answer.
    eglasius : @Eric and now the current version doesn't explains why those would have access - they are sibling classes, not contained one in the other
    Eric Petroelje : @Freddy They are sibling classes, but both in the same containing class, and thus in the same scope. So, the idea is that they can access each other just as one private method in a class can call another private method in the same class.
  • (Edit: expanded on the answer to answer some of the comments)

    The compiler takes the inner classes and turns them into top-level classes. Since private methods are only available to the inner class the compiler has to add new "synthetic" methods that have package level access so that the top-level classes have access to it.

    Something like this (the $ ones are added by the compiler):

    class A 
    {
        private void f() 
        {
            final B b;
    
            b = new B();
    
            // call changed by the compiler
            b.$g();
        }
    
        // method generated by the compiler - visible by classes in the same package
        void $f()
        {
            f();
        }
    }
    
    class B
    {
        private void g() 
        {
            final A a;
    
            a = new A();
    
            // call changed by the compiler
            a.$f();
        }
    
        // method generated by the compiler - visible by classes in the same package
        void $g()
        {
            g();
        }
    }
    

    Non-static classes are the same, but they have the addition of a reference to the outer class so that the methods can be called on it.

    The reason Java does it this way is that they did not want to require VM changes to support inner classes, so all of the changes had to be at the compiler level.

    The compiler takes the inner class and turns it into a top level class (thus, at the VM level there is no such thing as an inner class). The compiler then also has to generate the new "forwarding" methods. They are made at the package level (not public) to ensure that only classes in the same package can access them. The compiler also updated the method calls to the private methods to the generated "forwarding" methods.

    You can avoid having the compiler generate the method my declaring the methods as "package" (the absence of public, private, and protected). The downside to that is that any class in the package can call the methods.

    cbrulak : so, you declare a method private and compiler turns it public instead of generated an error?
    TofuBeer : well it isn't public it is package. And, yes, that is what it does. This is because the VM has no knowledge of inner classes... so the compiler does all of the work instead of making the VM do special things.
    cbrulak : package being the class that contains the inner class?
    Lou Franco : package access -- accessible by all classes in the same package (namespace). It doesn't change yours, it adds another method that calls yours with a $ in it. It's not possible to call it with Java, but it can be called with bytecode you generate or maybe reflection, but I'm not sure about that.

How to load varbinary(max) fields only when necessary with ADO.NET Entity Framework?

I have a varbinary(max) field in one of my tables but I don't need it every time and I'm looking for a way to fetch it from the database only when necessary. I'm using ADO.NET Entity Framework. How to do that?

From stackoverflow
  • One way would be to project your result set into an anonymous type when you don't need the blob:

    from entity in context.Entities
    select new 
    {
        Field1 = entity.Field1,
        Field2 = entity.Field2
    }
    

    In this example, only Field1 and Field2 will be loaded.

    This method has the disadvantage that you cannot update the returned instance and do context.SaveChanges. Though I would argue that saving an instance without full knowledge of the instance is borderline unsafe. This method is good when you want a long list of return the instances, but will be querying for a single instance, varbinary field and all, before you actually update.

    Emil : Thank you for your assistance. I was looking for something similar to lazy loading of the varbinary field :) but it seems that this isn't possible.
  • The solution was to create a separate table with the varbinary field and make 1-to-1 relationship between the tables

How do I optimize a Linq to Xml query againist attributes?

Given the following Xml fragment:

<root>
  <sheetData>
    <row r="1" />
    <row r="2" />
    <row r="3" />
    <row r="4" />
    <row r="5" />
    <row r="6" />
    <row r="7" />
  </sheetData>
</root>

Which can be created with the following code:

XElement testElement = new XElement("root",
    new XElement("sheetData",
        new XElement("row",
            new XAttribute("r", 1)),
        new XElement("row",
            new XAttribute("r", 2)),
        new XElement("row",
            new XAttribute("r", 3)),
        new XElement("row",
            new XAttribute("r", 4)),
        new XElement("row",
            new XAttribute("r", 5)),
        new XElement("row",
            new XAttribute("r", 6)),
        new XElement("row",
            new XAttribute("r", 7))));

Is this the best way to find the row where the r attribute is 2? This works, but I am repeating the Where clause in the select statement, and I am wondering if there is a better way and more efficent method.

int rowNumber = 2;

XElement rowElement = testElement
    .Descendants("sheetData")
    .Where<XElement>(item => item.Descendants("row")
                                  .Where<XElement>(i => i.Attribute("r").Value == rowNumber.ToString())
                                  .FirstOrDefault<XElement>() != null)
    .Select<XElement, XElement>(item => item.Descendants("row")
                                  .Where<XElement>(i => i.Attribute("r").Value == rowNumber.ToString())
                                  .FirstOrDefault<XElement>())
    .FirstOrDefault<XElement>();

In general what is the best way to determine if Linq to Xml query optimized?

From stackoverflow
  • //if sheetData appears multiple times
        XElement rowElement = testElement
            .Descendants("sheetData")
            .SelectMany(s=>s.Descendats("row))
            .Where(i=>i.Attribute("r").Value == rowNumber.ToString());
    //if sheetData appears once
        XElement rowElement = testElement
            .Element("sheetData")
            .Descendants("row))
            .Where(i=>i.Attribute("r").Value == rowNumber.ToString());
    
  • The best way is:

    var row = testElement
       .XPathSelectElements("sheetData/row[@r='2']")
       .FirstOrDefault();
    

    A pure LINQ query that doesn't repeat the Where call:

    var row = testElement
        .Descendants("sheetData")
        .Descendants("row")
        .Where(x => x.Attribute("r").Value == "2")
        .FirstOrDefault();
    
    eglasius : where is the XPathSelectElements defined? if it is an extension method please post the namespace, I would love to have that in XElement :)
    Mehrdad Afshari : I'd use .Where(x => (string)x.Attribute("r") == "2") instead. If no `r` attribute exists, it won't throw NullReferenceException.
    eglasius : found it: http://msdn.microsoft.com/en-us/library/bb342176.aspx ... +1 very nice :) - I will surely use this one quite a bit
  • Isn't the Select clause in your code redundant? Where returns an IEnumerable<XElement> already. I think

    var row = testElements.Descendents("row").Where(e => (int)e.Attribute("r") == rowNumber).SingleOrDefault();
    

    should do what you want