Results 1 to 14 of 14

Thread: [RESOLVED] Create Download Counter On Website

  1. #1

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Resolved [RESOLVED] Create Download Counter On Website

    This should be pretty simple but I don't work on my website code too often so I thought I would ask about this. I have a download link for an application of mine on my website and I wanted to keep track of how many downloads are taking place so I want to create a counter. I added a table to the SQL database I already have on my website with the columns Downloads and CountID which is listed in the column properties as identity specification. At first I just had the column Downloads but when doing a query I was having problems so I added CountID and that made the query easy to do.

    When the link on the download page on my website is clicked I wanted Downloads to increment by 1 each time. I used Visual Web Developer to build my site. Should I use a Web Method to increment that or is there a more direct method. I also noticed when I'm working in Visual Web Developer and I have the designer open for a webpage that in the toolbox items you have table and the icon looks the same as a table for an SQL Database. Should I perhaps use that? Add a table to this webpage and work with that?
    Attached Images Attached Images  
    Last edited by EntityX; Sep 30th, 2011 at 06:20 PM.
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  2. #2
    Frenzied Member brin351's Avatar
    Join Date
    Mar 2007
    Location
    Land Down Under
    Posts
    1,293

    Re: Create Download Counter On Website

    Is the download link a hyperlink to the URL of the file to be downloaded... I'm guessing yes and there will be no event raised in the code behind for you to do your thing. What you can do is use a button/ linkbutton that "postback" the page and in the button click event update the database and send the file in the response stream.

    Code:
    sub button1_click(.....bla) handles button1.click
    
    'Update counter table
    bla bla
    
    
    'Send file in response stream
    
    'Set the appropriate ContentType.
    Response.ContentType = "application/octet-stream"
    
    'Get the physical path to the file.
    Dim FilePath as string = server.mappath("/folder/myApp.exe")
    
    'Write the file directly to the output stream.
    response.clear()
    response.writeFile(FilePath);
    response.End();
    
    
    end sub

    Generally you'd do this on a dedicated dowload page, one that doesn't have other controls doing postbacks etc.
    The problem with computers is their nature is pure logic. Just once I'd like my computer to do something deluded.

  3. #3
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,763

    Re: Create Download Counter On Website

    One observation on response.writeFile. You can use response.transmitfile instead that does not load the file to the application memory of the server prior of downloading it.
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  4. #4

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Re: Create Download Counter On Website

    I've pretty much figured out what I'm going to do here. I was using a book Visual Web Developer Step by Step and it was using C# so I built my website using C# but I know Visual Basic much better. I want to redo my download page using Visual Basic and then use a Visual Basic Web Method to increment a value in my database to keep track of downloads.

    I could do the Web Method in C# but I know little about doing that so I figure it'll be easier for me to do it in Visual Basic. What I found out is you can't have both C# and Visual Basic Web Methods in your Ap Code folder. It doesn't allow it so I'll just redo the page and do all the Web Methods in Visual Basic. Here's some code I used for the download link that is in C# that I'll have to convert to Visual Basic. Maybe someone could help me on that.

    This is on my download page and is used when the download link is clicked.

    Code:
             <%
        
            WebServiceForDownloads mydownloads = new WebServiceForDownloads();
            string[] downloadList = mydownloads.GetThing().Split(';');
          //  for (int i = 0; i < downloadList.Length; i++)
             
            {
                Response.Write("<a href='RayRoverDownload/" + downloadList[0] + "'>Ray Rover Computer Graphics Program</a><br/>");
            }// Response.Write("<a href='RayRoverDownload/" + downloadList[0] + "'>" + downloadList[0] + "</a><br/>");
          
              %>
    This is the Web Method in C# which is called in the above code.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    /// <summary>
    /// Summary description for WebServiceForDownloads
    /// </summary>
    [WebService(Namespace = "http://TaylorEntertainmentDownloads.biz/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class WebServiceForDownloads : System.Web.Services.WebService
    {
    
        public WebServiceForDownloads()
        {
    
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
    
        [WebMethod]
        public string GetThing()
        {
    
            string filenames = "";
            string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/RayRoverDownload"),
                "*.*");
    
            foreach (string s in files)
            {
                // Create the FileInfo object only when needed to ensure
                // the information is as current as possible.
                System.IO.FileInfo fi = null;
                try
                {
                    fi = new System.IO.FileInfo(s);
                }
                catch (System.IO.FileNotFoundException e)
                {
                    // To inform the user and continue is
                    // sufficient for this demonstration.
                    // Your application may require different behavior.
                    Console.WriteLine(e.Message);
                    continue;
                }
                        
                filenames = filenames + fi.Name + ";";
              }
    
            return filenames;
         }
    
        [WebMethod]
        public string IncrementDownloads()
        {
            string filenames = "";
    
    
            return filenames;
           
        }
    
    }
    The code is designed for having a list of different download items but I just use one item for download. If you can show me how to create a simpler Web Method for just a single item then great. I have very little knowledge in this area. I just want the .exe to be downloaded when you click the link on my download page.
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  5. #5
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Create Download Counter On Website

    As another suggestion, you might want to think about using something like Google Analytics. This service is free and can be used to provide the type of information that you are looking for, as well as much more.

    Gary

  6. #6

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Re: Create Download Counter On Website

    Because of your suggestion I looked into Google Analytics and I might use it but I wanted to go ahead and see if I could do a few basic things on my own. I was reading the terms of use for Google Analytics and it doesn't look too bad but it made me think perhaps I'll see what I can do on my own even if I end up using it.

    I was able to convert the download page on my website to Visual Basic as well as the download link code and C# Web Method. There are a couple of sites I found that are very useful for doing the conversions.

    http://converter.telerik.com/

    http://www.developerfusion.com/tools.../csharp-to-vb/

    Anyway I got everything working the way I want it to. I have another question but it's on another subject though it's related to the download link so I'll mark this thread resolved and start another thread.
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  7. #7
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [RESOLVED] Create Download Counter On Website

    Hello,

    Sounds good. I use Google Analytics on all my sites, it is very good at what it does, and very easy to set up.

    Gary

  8. #8

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Re: Create Download Counter On Website

    I eliminated RESOLVED because I just discovered things weren't working the way I wanted them to. The problem is that my increment download total code is running when the download page is visited whether or not the download link is clicked or not. I want the increment download code to run only if the download link is clicked.

    So I thought I'd move from a link to a button for download. I was trying the code that Brin351 posted in post #2 but was having problems with it. When I clicked the button I got a big page with lots of unintelligible script but it said at the start, "This program cannot be run in DOS mode." Everything after that looks like nonsense. Here's what I put inside the button click event sub.

    Code:
         ' My code here to call increment download web method 
    
         Response.ContentType = "application/octet-stream"
    
            'Get the physical path to the file. 
            Dim FilePath As String = Server.MapPath("~/FolderForDownloadItem/MyProgramToDownload.exe") 
    
            'Write the file directly to the output stream.
            Response.Clear()
            Response.WriteFile(FilePath)
            Response.End()
    Brin351 you had ; after Response.WriteFile(FilePath) and the line below it but the editor in Visual Studio didn't like that so I took it out.

    The screenshot shows what it looks like when I click the button but there's a lot more than that. It scrolls quite a ways down.
    Attached Images Attached Images  
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  9. #9

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Re: Create Download Counter On Website

    Another thought here is that I could stay with the download link code I'm using which works fine for me. I just want my increment download code to run only if the link is clicked. It's not clear to me how to do that. Here's the code on my download page for the download link which has now been converted to VB and works fine. I tried putting the call for the increment download count web method inside the If True Then block but it would run if the web page is visited and the download link isn't clicked.

    Code:
       <%
                 ' Code for download link
                 Dim mydownloads As New WebServiceForDownloads()
                 Dim downloadList As String() = mydownloads.GetThing().Split(";"c)
                                      
                 If True Then
                       Response.Write("<a href='RayRoverDownload/" + downloadList(0) + "'>Ray Rover Computer Graphics Program</a><br/>")
                 End If
              %>
    Here's the Web Method that is called in the above code.
    I had at one point the call for the increment download count function below Next and above Return filenames in the below block of code but again the increment download total function was run even if the download page was just visited and the download link wasn't clicked.
    Code:
      <WebMethod()> _
        Public Function GetThing() As String
    
            Dim filenames As String = ""
    
            Dim files As String() = System.IO.Directory.GetFiles(Server.MapPath("~/RayRoverDownload"), "*.*")
    
    
            For Each s As String In files
                ' Create the FileInfo object only when needed to ensure
                ' the information is as current as possible.
                Dim fi As System.IO.FileInfo = Nothing
                Try
                    fi = New System.IO.FileInfo(s)
                Catch e As System.IO.FileNotFoundException
                    ' To inform the user and continue is
                    ' sufficient for this demonstration.
                    ' Your application may require different behavior.
                    Console.WriteLine(e.Message)
                    Continue For
                End Try
    
                filenames = filenames + fi.Name + ";"
    
            Next
            Return filenames
        End Function
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  10. #10
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [UNRESOLVED] Create Download Counter On Website

    Hello,

    What you are seeing there is the binary content of the exe file rendered onto the client.

    When you hit the download button, did you get a pop up save whether you wanted to open or save the file?

    Gary

  11. #11

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Re: [UNRESOLVED] Create Download Counter On Website

    After I click the button the entire page is filled with the binary content and you don't see anything else. If you close the page you don't see anything else related to that page. This is what happens when I'm running my website in Visual Studio and the URL is a localhost address. I tried uploading a test page that is a duplicate of the other to my site and the result is different but still not what I'm looking for. After clicking the download button it says :

    The XML page cannot be displayed
    Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.


    --------------------------------------------------------------------------------

    An invalid character was found in text content. Error processing resource 'http://www.taylorentertainment.biz/DownloadRayRo...

    MZ




    The page isn't in the sitemap for my website but the url is http://www.taylorentertainment.biz/D...RoverTest.aspx

    I have the download link and a download button below it with the code that I posted in a preceding post in the button click event sub. I figure if I can just get the button click code right I'll be set because then the download count and other info will be added to my download table only when the download button is clicked.

    Do I perhaps need a certain Imports statement in my page that has the button click sub?

    Here's all the code for DownloadRayRoverTest.vb which has the button click sub.

    Code:
    Partial Class DownloadRayRoverTest
        Inherits System.Web.UI.Page
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
           ' Increment DownloadTotal in Database table and enter other info
             Dim MyDownloadsIncremented As New WebServiceForDownloads()
            MyDownloadsIncremented.IncrementDownloadTotal()
    
            'Send file in response stream
    
            'Set the appropriate ContentType.
            Response.ContentType = "application/octet-stream"
    
            'Get the physical path to the file. (Server.MapPath("~/RayRoverDownload")
            Dim FilePath As String = Server.MapPath("~/RayRoverDownload/Ray Rover Computer Graphics Program.exe")
    
            'Write the file directly to the output stream.
            Response.Clear()
            Response.WriteFile(FilePath)
            Response.End() 
        End Sub
    End Class
    Again as I said before another approach to a solution to this problem is to use the download link code which works perfectly now for downloading and have an If Then statement that went like this.

    Code:
    If downloadlink.clicked = True Then  
        ' code to call increment download total function here
    End If
    That's not accurate code but is there a way to code that properly? I know how to call the function but not how to write the If Then.
    Last edited by EntityX; Sep 30th, 2011 at 05:59 PM.
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  12. #12
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,763

    Re: [UNRESOLVED] Create Download Counter On Website

    Hi.
    Try this for downloading:
    Code:
     Protected Sub Linkbuttondownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Linkbuttondownload.Click       
            Dim FilePath As String = Server.MapPath("RayRoverDownload/Ray Rover Computer Graphics Program.exe")
            Dim myfile As New System.IO.FileInfo(FilePath)
            If myfile.Exists Then
                Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name)
                Response.AddHeader("Content-Length", myfile.Length.ToString())          
                Response.ContentType = "application/octet-stream"
                Response.TransmitFile(myfile.FullName)              
                Response.End()             
            Else
                Exit Sub
            End If
           
    
        End Sub
    Note.Do some test with server.mappath, if you need to use ~/ so to be sure you actually get the file from the directory.
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  13. #13

    Thread Starter
    Fanatic Member EntityX's Avatar
    Join Date
    Feb 2007
    Location
    Omnipresence
    Posts
    798

    Re: [UNRESOLVED] Create Download Counter On Website

    Sapator, you nailed it. It works perfectly and what I noticed is that if I have ~/ at the start of the mappath or not it works ok either way. Thanks a million. I tried to give you some reputation but I must have given you some not too long ago so it wouldn't let me.
    Make as many mistakes as you can as quickly as you can. We want to make sure that we make a great enough number of mistakes in a given amount of time so that we can be successful.

    "Persistence is the magic of success." Paramahansa Yogananda

  14. #14
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,763

    Re: [RESOLVED] Create Download Counter On Website

    Nice!
    No problem about the rep.
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width