Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > C# and C > C# 1.0 > C#
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
C# Programming questions specific to the Microsoft C# language. See also the forum Beginning Visual C# to discuss that specific Wrox book and code.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C# section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old April 24th, 2008, 07:08 AM
Authorized User
 
Join Date: Nov 2007
Location: , , Ireland.
Posts: 67
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hughesie78
Default conver VB function to c#

i have a VB function that i want to convert to c#, relatiely new to C# at the mo, any ideas?
Function FilterForImages(images() as FileInfo) as FileInfo()

Dim newImages as New ArrayList(images.Length)


Dim i as Integer

For i = 0 to images.Length - 1

If Path.GetExtension(images(i).Name.ToLower()) = ".jpg" OrElse _

Path.GetExtension(images(i).Name.ToLower()) = ".jpeg" OrElse _

Path.GetExtension(images(i).Name.ToLower()) = ".png" OrElse _

Path.GetExtension(images(i).Name.ToLower()) = ".bmp" OrElse _

Path.GetExtension(images(i).Name.ToLower()) = ".JPG" OrElse _

Path.GetExtension(images(i).Name.ToLower()) = ".gif" Then

newImages.Add(images(i))

End If

Next


Return CType(newImages.ToArray(GetType(FileInfo)), FileInfo())

End Function
__________________
Thank You
Reply With Quote
  #2 (permalink)  
Old April 24th, 2008, 07:25 AM
samjudson's Avatar
Friend of Wrox
Points: 8,687, Level: 40
Points: 8,687, Level: 40 Points: 8,687, Level: 40 Points: 8,687, Level: 40
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2007
Location: Newcastle, , United Kingdom.
Posts: 2,128
Thanks: 1
Thanked 189 Times in 188 Posts
Default

OK, well first off this isn't a terrible efficient way to do it in VB.Net, especially the line that says ".JPG" since you've just converted the format to lower case so that will never be true.

I'd recommend using regular expressions as well.

Code:
Function FilterForImages(images() as FileInfo) as FileInfo()

Dim newImages as New ArrayList(images.Length)
Dim r As New Regex("^[.](jpg|jpeg|png|bmp|gif)$", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
For i = 0 To image.Length - 1
  If r.IsMatch(Path.GetExtension(images(i).Name)) Then
    newImages.Add(images(i))
  End If
Next

Return CType(newImages.ToArray(GetType(FileInfo)), FileInfo())

End Function
or in C#

Code:
public FileInfo[] FilterForImages(FileInfo[] images)
{
ArrayList newImages = new ArrayList(images.Length);

Regex r = new Regex("^[.](jpg|jpeg|png|bmp|gif)$", RegexOptions.Compiled || RegexOptions.IgnoreCase);
foreach(FileInfo image in images)
{
   if( r.IsMatch(Path.GetExtension(image.Name)) )
   {
     newImages.Add(image); 
   }

   return (FileInfo[])newImages.ToArray(typeof(FileInfo));
}
If you are using .Net 2.0 or higher then you can simplify this even more by using generics, so your newImages array becomes:

Code:
VB.Net
Dim newImages As New List(Of FileInfo)

C#
List<FileInfo> newImages = new List<FileInfo>();
And the last line then becomes

Code:
VB.Net
Return newImages.ToArray()

C#
return newImages.ToArray();

/- Sam Judson : Wrox Technical Editor -/
Reply With Quote
  #3 (permalink)  
Old April 24th, 2008, 09:10 AM
Authorized User
 
Join Date: Nov 2007
Location: , , Ireland.
Posts: 67
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hughesie78
Default

I am getting this error now when i compile:
'Gallery.FilterForImages(System.IO.FileInfo[])': not all code paths return a value

my code is:
    public FileInfo[] FilterForImages(FileInfo[] images)
    {
        try
        {

            ArrayList newImages = new ArrayList(images.Length);
            Regex r = new Regex("^[.](jpg|jpeg|png|bmp|gif)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            foreach (FileInfo image in images)
            {
                if (r.IsMatch(Path.GetExtension(image.Name)))
                {
                    newImages.Add(image);
                }

                {
                    return (FileInfo[])newImages.ToArray(typeof(FileInfo));
                }
            }

        }
        catch (Exception e)
        { e.Message.ToString(); }
    }
Reply With Quote
  #4 (permalink)  
Old April 24th, 2008, 09:28 AM
samjudson's Avatar
Friend of Wrox
Points: 8,687, Level: 40
Points: 8,687, Level: 40 Points: 8,687, Level: 40 Points: 8,687, Level: 40
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2007
Location: Newcastle, , United Kingdom.
Posts: 2,128
Thanks: 1
Thanked 189 Times in 188 Posts
Default

firstly - your 'return' statement should be outside of the foreach loop - and it doesn't need the { } before and after. The way you currently have it it would return after checking only 1 fileinfo. Also, if there where no fileinfo's passed in it would never return.

Code:
foreach()
{
   if()
   {
   }
}

// return goes here
return ...
Secondly as I mentioned above if an empty array was passed in it would never return (this is what the error is saying).

Also, if you catch an error you a) should do something with the error and b) you still have to either return from the function or throw another exception.

If you don't know why you are catching the exception then I'd recommend NOT catching an exception.

Code:
try
{
 ... do stuff
}
catch(Exception ex)
{
  // what to do with the exception?

  // output to console? Is that helpful?
  Console.WriteLine(ex.ToString());

  // rethrow? In which case why catch it in the first place?
  throw ex;
}
If you don't throw an exception then you need to return something, e.g. return null; or return new FileInfo[0];



/- Sam Judson : Wrox Technical Editor -/
Reply With Quote
  #5 (permalink)  
Old April 24th, 2008, 11:04 AM
Authorized User
 
Join Date: Nov 2007
Location: , , Ireland.
Posts: 67
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hughesie78
Default

cool.thanks that worked.
Reply With Quote
  #6 (permalink)  
Old April 24th, 2008, 11:05 AM
Authorized User
 
Join Date: Nov 2007
Location: , , Ireland.
Posts: 67
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hughesie78
Default

ok.. i now need to convert this VB to C#:
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ''Get list of images
        Dim dirInfo As New DirectoryInfo(Server.MapPath(""))
        ' Dim dirInfo As New DirectoryInfo(Request.PhysicalApplicationPath + "\\Images")

        Dim images() As FileInfo = FilterForImages(dirInfo.GetFiles())



        'Determine the current image to show
        Dim imgIndex As Integer = 0
        If Not Request.QueryString("N") Is Nothing AndAlso IsNumeric(Request.QueryString("N")) Then
            imgIndex = CInt(Request.QueryString("N"))
        End If

        currentImgTitle.Text = "" & _
 Right(Path.GetFileNameWithoutExtension(images(imgI ndex).Name),
 Len(Path.GetFileNameWithoutExtension(images(imgInd ex).Name)) - 4) '& _

        '" (" & imgIndex + 1 & " of " & images.Length & ")"
        currentImg.ImageUrl = Path.GetFileName(images(imgIndex).Name)

        If imgIndex > 0 Then
            lnkPrev.NavigateUrl = "Default.aspx?N=" & imgIndex - 1
        End If

        If imgIndex < images.Length - 1 Then
            lnkNext.NavigateUrl = "Default.aspx?N=" & imgIndex + 1
        End If

        dlIndex.DataSource = images
        dlIndex.DataBind()
    End Sub
Reply With Quote
  #7 (permalink)  
Old April 24th, 2008, 07:10 PM
Authorized User
 
Join Date: Jul 2003
Location: , , .
Posts: 13
Thanks: 0
Thanked 0 Times in 0 Posts
Default

(Instant C#)

You'll have to replace the call to IsNumeric - there's no direct .NET equivalent:

public void Page_Load(object sender, EventArgs e)
{
        //'Get list of images
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(""));
        // Dim dirInfo As New DirectoryInfo(Request.PhysicalApplicationPath + "\\Images")

        FileInfo[] images = FilterForImages(dirInfo.GetFiles());



        //Determine the current image to show
        int imgIndex = 0;
        if (Request.QueryString["N"] != null && Microsoft.VisualBasic.Information.IsNumeric(Reques t.QueryString["N"]))
        {
            imgIndex = System.Convert.ToInt32(Request.QueryString["N"]);
        }

        currentImgTitle.Text = "" + Path.GetFileNameWithoutExtension(images[imgIndex].Name).Substring(Path.GetFileNameWithoutExtension( images[imgIndex].Name).Length - (Path.GetFileNameWithoutExtension(images[imgIndex].Name).Length - 4)); //&
        //" (" & imgIndex + 1 & " of " & images.Length & ")"
        currentImg.ImageUrl = Path.GetFileName(images[imgIndex].Name);

        if (imgIndex > 0)
        {
            lnkPrev.NavigateUrl = "Default.aspx?N=" + imgIndex - 1;
        }

        if (imgIndex < images.Length - 1)
        {
            lnkNext.NavigateUrl = "Default.aspx?N=" + (imgIndex + 1);
        }

        dlIndex.DataSource = images;
        dlIndex.DataBind();
    }

Reply With Quote
  #8 (permalink)  
Old April 25th, 2008, 02:29 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hampshire, United Kingdom.
Posts: 432
Thanks: 0
Thanked 1 Time in 1 Post
Default

I have a feeling this is going to continue until the entire app is converted :)

Might I suggest getting a "Teach Yourself .NET" Book that is language neutral, most of these books will have both VB and C# code so you can see the code side-by-side, once you have the basic constructs down, conversion becomes a lot easier. You begin to see more the .NET code rather than the VB/C#..

Obviously there are some C# goodies that we have (special constructs to do things slightly "better"/easier - such as "using") but we can assist with those if you need it :)

Rob
http://robzyc.spaces.live.com
Reply With Quote
  #9 (permalink)  
Old April 25th, 2008, 03:54 AM
Authorized User
 
Join Date: Nov 2007
Location: , , Ireland.
Posts: 67
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hughesie78
Default

:):D
thanbks for that, ya got it in one yes im trying to convert an aspx page from VB to C#, here is the very last piece, no more after this i prmise.
Sub dlIndex_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs)

If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then


Dim hl As HyperLink = CType(e.Item.FindControl("lnkPic"), HyperLink)


hl.Text = Right(Path.GetFileNameWithoutExtension(DataBinder. Eval(e.Item.DataItem, "Name").ToString()), Len(Path.GetFileNameWithoutExtension(DataBinder.Ev al(e.Item.DataItem, "Name").ToString())) - 4) '& _

hl.NavigateUrl = "Default.aspx?N=" & e.Item.ItemIndex

End If

End Sub
Reply With Quote
  #10 (permalink)  
Old April 25th, 2008, 03:55 AM
Authorized User
 
Join Date: Nov 2007
Location: , , Ireland.
Posts: 67
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hughesie78
Default

Robzyc, thanks for the book suggestion.
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Function in VB Manisha0605 .NET Framework 1.x 3 February 4th, 2007 11:04 AM
Need some help with a VB function crowsfan31 Beginning VB 6 1 June 19th, 2006 02:36 PM
How to call javascript function from VB function vinod_yadav1919 VB How-To 0 February 13th, 2006 06:03 AM
way to conver docs to pdfs??? DayitaChandani VBScript 5 December 22nd, 2005 11:02 AM
Function Iff in VB 6.0 daninoj Beginning VB 6 2 January 17th, 2005 01:06 PM



All times are GMT -4. The time now is 02:56 PM.


Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.