?
Solved

Code to optimize

Posted on 2009-04-28
13
Medium Priority
?
193 Views
Last Modified: 2012-05-06
Hi,

Can someone tell me if the attached code can be improved, shortened or optimized? If so, please make the necessary adjustments for me.

Thanks very much in advance.

using System;
using System.IO;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Xml;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
 
public class RandomImage
{
    public static string ImageUrl
    {
        get
        {
            HttpContext context = HttpContext.Current;
            string imageDir = "images/";
            string physicalPath = context.Server.MapPath("~/images");
            string[] filePath = Directory.GetFiles(physicalPath);
            //string[] filePath = Directory.GetFiles(physicalPath, "*.gif"); //Restrict to gif image files only
            DirectoryInfo dirInfo = new DirectoryInfo(physicalPath);
            FileInfo[] imageFiles = dirInfo.GetFiles();
            string listFiles = "";
            string imageType = "random_";
            int imageTypeLen = imageType.Length;
            int i = 0;
            foreach (FileInfo file in imageFiles)
            {
                string fileName = file.Name;
                if (fileName.Length >= imageTypeLen)
                {
                    string segment = fileName.Substring(0, imageTypeLen);
                    if (String.Compare(segment, imageType, true) == 0)
                    {
                        listFiles += imageDir + fileName + ",";
                        i++;
                    }
                }
            }
            if (i > 0)
                listFiles = listFiles.Substring(0, listFiles.Length - 1); //Knock off the last ","
            //string path = context.Request.ApplicationPath + GetRandomImage(listFiles);
            string path = GetRandomImage(listFiles);
            return path;
        }
    }
 
    private static string GetRandomImage(string files)
    {
        Random r = new Random();
        string[] images = files.Split(','); //Creates an array of strings
         return images[r.Next(0, images.Length)];
    }
}

Open in new window

0
Comment
Question by:WebAppDeveloper
  • 6
  • 4
  • 3
13 Comments
 
LVL 12

Expert Comment

by:williamcampbell
ID: 24255663
Most the File List Creation out of the main Function and only call it one time

Also Use StringBuilder instead of String .. minor
        String _listFiles;
        private String ListFiles ()
        {
            if ( String.IsNullOrEmpty ( _listFiles ) )
            {
                HttpContext context = HttpContext.Current;
                string imageDir = "images/";
                string physicalPath = context.Server.MapPath("~/images");
                string[] filePath = Directory.GetFiles(physicalPath);
                //string[] filePath = Directory.GetFiles(physicalPath, "*.gif"); //Restrict to gif image files only
                DirectoryInfo dirInfo = new DirectoryInfo(physicalPath);
                FileInfo[] imageFiles = dirInfo.GetFiles();
                string imageType = "random_";
                int imageTypeLen = imageType.Length;
                int i = 0;
                foreach (FileInfo file in imageFiles)
                {
                    string fileName = file.Name;
                    if (fileName.Length >= imageTypeLen)
                    {
                        string segment = fileName.Substring(0, imageTypeLen);
                        if (String.Compare(segment, imageType, true) == 0)
                        {
                            listFiles += imageDir + fileName + ",";
                            i++;
                        }
                    }
                }
                if (i > 0)
                    _listFiles = listFiles.Substring(0, listFiles.Length - 1); //Knock off the last ","
            }
 
            return _listFiles;
        }
 
        public static string ImageUrl
        {
            get
            {
                string path = GetRandomImage(ListFiles);
 
                return path;
            }
        }

Open in new window

0
 
LVL 12

Expert Comment

by:williamcampbell
ID: 24255669
string path = GetRandomImage(ListFiles);
should read
string path = GetRandomImage( ListFiles () );
0
 

Author Comment

by:WebAppDeveloper
ID: 24255845
Hi williamcampbell,

What happened to the Random() function, e.g.,  "Random r = new Random();"?  My purpose is to get a randomly selected image from a list (array) of images thru the use of the "Random r = new Random();".

Would you please revise the code to include such requirement!

Thanks very much.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 12

Accepted Solution

by:
williamcampbell earned 2000 total points
ID: 24256013
There yah go .. i just left it out since it didnt change
   public class RandomImage
    {
        String _listFiles;
        private String ListFiles ()
        {
            if ( String.IsNullOrEmpty ( _listFiles ) )
            {
                HttpContext context = HttpContext.Current;
                string imageDir = "images/";
                string physicalPath = context.Server.MapPath("~/images");
                string[] filePath = Directory.GetFiles(physicalPath);
                //string[] filePath = Directory.GetFiles(physicalPath, "*.gif"); //Restrict to gif image files only
                DirectoryInfo dirInfo = new DirectoryInfo(physicalPath);
                FileInfo[] imageFiles = dirInfo.GetFiles();
                string imageType = "random_";
                int imageTypeLen = imageType.Length;
                int i = 0;
                foreach (FileInfo file in imageFiles)
                {
                    string fileName = file.Name;
                    if (fileName.Length >= imageTypeLen)
                    {
                        string segment = fileName.Substring(0, imageTypeLen);
                        if (String.Compare(segment, imageType, true) == 0)
                        {
                            listFiles += imageDir + fileName + ",";
                            i++;
                        }
                    }
                }
                if (i > 0)
                    _listFiles = listFiles.Substring(0, listFiles.Length - 1); //Knock off the last ","
            }
 
            return _listFiles;
        }
 
        public static string ImageUrl
        {
            get
            {
                string path = GetRandomImage(ListFiles);
 
                return path;
            }
        }
 
        private static string GetRandomImage(string files)
        {
            Random r = new Random();
            string[] images = files.Split(','); //Creates an array of strings
            return images[r.Next(0, images.Length)];
        }
    }

Open in new window

0
 

Author Comment

by:WebAppDeveloper
ID: 24256082
Hi williamcampbell,

In your private function "private String ListFiles () {......}", you use "String" with the "S" being capitalized. What's the difference between using small "s" and the big "S", although the result turns out the same?

Thanks.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24256121
There is no difference. "string" is an alias for "String." The same is true for "int" and "Int32" and "bool" and "Boolean."
0
 

Author Comment

by:WebAppDeveloper
ID: 24256187
Great. Thanks.
0
 
LVL 12

Expert Comment

by:williamcampbell
ID: 24256222
I prefer the Color of the String and Int16. I also program in C++ and like to distinguish the keywords .. light Blue C# dark blue C++
0
 

Author Comment

by:WebAppDeveloper
ID: 24256425
williamcampbell,

oh really? For myself, i'm used to the lower case "string".
0
 

Author Comment

by:WebAppDeveloper
ID: 24257063
Hi williamcampbell,

In VS 2008, I'm getting a red underline for "GetRandomImage(ListFiles)" in the line "string path = GetRandomImage(ListFiles)" by Intellisense indicating something is wrong, and when I roll my mouse over the red underline, it says "The best overloaded method for 'RandomImage.GetRandomImage(string) has some invalid arguments".

Thanks.
0
 

Author Comment

by:WebAppDeveloper
ID: 24257404
Hi williamcampbell,

Any suggestion I can fix it?

Thanks.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24259127
You've declared ListFiles to take no arguments, yet you are trying to pass a string. williamcampbell suggested earlier to use ListFiles().
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24259139
Disregard, I read that wrong.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

755 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question