• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1112
  • Last Modified:

use web address parameters in TXT file title

Hi,
I have a ASP.NET C# web-page that has two form fields called:
WebAddress
WebAddressContents

When user clicks the SAVE button the contents of the form is saved to a TXT file, with the WebAddress as the TXT file name and also as the first line in the body of the TXT file along with the contents of the WebAddressContents field in the body of the TXT file.

This I have working please see code example.
 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
<div>
        <asp:TextBox ID="WebAddress" runat="server" style="width:300px; Height:20px;" value="http://www.google.com"></asp:TextBox><br /><br />
        <asp:TextBox ID="WebAddressContents" runat="server" style="width:300px; Height:200px;" value="7+ GB of storage, less spam, and mobile access. Gmail is email that's intuitive, efficient, and useful. And maybe even fun."></asp:TextBox>
    </div>
    <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
<asp:Label id="lblSuccess" runat="server" />

    </form>
</body>
</html>



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter("c:\\temp\\" + WebAddress.Text.Replace("http://", "") + ".txt");
        sw.WriteLine(WebAddress.Text);
        sw.WriteLine(WebAddressContents.Text);
        sw.Close();
        lblSuccess.Text = "The file has been saved successfully.";
    }
}

Open in new window


My problem is when a URL has a / in the address my page crashes or if the URL is extremely long as in over 260 characters it crashes, TXT files wont allow for / to be in the name of the file.

I would like to use the DATE and only certain parameters from the URLS in the WebAddress field in the txt files title, the user saves information from the 4 intranet sites each with different URLs:

Intranet 1
URL:http://student.intranetA.com/ajax/serv/searchresult/web?v=3.0&q=research%20notes%20math%20g7&set=large&SN=TexasEN&ln=en1&gloc=TX&session=sdafk392293kd302ffds9320d0302020298381kd19349402lcakdi283949193ldmcnvdeiwa23o03bm3&cn=wan_en&resultpage=8&ipaddress=000.000.000.0
Text File Name:20110221_student.intranetA.com_q=research_notes_math_g7_resultpage=8.txt

Intranet 2
URL:http://student.researchintraB.com/research/webaccess/v2/english%20papers%20class%20AM1?sessid=_fk39283039dkvaks392ldflx_3_3kdkdkal2039dkx2ekdldskfieow02203zdls03.39dlgu203c0-
&resultform=dfr&spec=in&georegion=TX&Pagestart=0&numresuts=90&setsize=noc1&css=tru
Text File name:20110221_student.researchintraB.com_english_papers_class_AM1_Pagestart=0.txt

WAN Intranet 3
URL:http://intra.search.liveregister.com/xml.aspx?sessionID=3939392838dkf30ld20dka020340520dfl203021&lanaccess=g2-tx&Query=lit%20reviews%20austin
%20texas&soc:ea&lang:es&db=main+check&res.Count=15&page.start=0
Text File name:200110221_intra.search.liveregister.com_Query=lit%20reviews%20austin%20texas.page.start=0.txt

Intranet 4
URL:http://main.frame.com/fix?startresult=0&q=geography+research+volcanic+fuse&eg=statetx&fl=in&le=gang_xd&returnnum=50&wanaccess=main-g912&ln=dleo39203ldk392sa2o13:39eo3n212fn&ip=000.000.000.0
Text File name:200110221_main.frame.com_q=geography_research_volcanic_fuse_startresult=0.txt


Do I need some sort of case statement to check the webaddress, if it starts with a particular address then to use the certain parameters in the file name title?
I'm not sure how to do this.

Thanks
0
jay_eire
Asked:
jay_eire
  • 20
  • 16
  • +1
1 Solution
 
Manoj PatilSr. Software EngineerCommented:
0
 
käµfm³d 👽Commented:
It seems as thought there is no consistency between the "certain parameters," so how will you know which ones to pull from the URL?
0
 
jay_eireAuthor Commented:
@kaufmed

there is different URL pattern for each of the four URLS, is it possible to read the URL based by its address as in:


if the web address contains "student.intranetA.com" then add the date_student.intranetA.com. select from &q=research%20notes%20math%20g7& add that to the title then select  &resultpage=8 add that to the title

if the web address contains "student.researchintraB.com/research/webaccess/v2/" then add the date_student.researchintraB.com select from /v2/english%20papers%20class%20AM1 ? add that to the title then select from &Pagestart=0& add that to the title

I know i would end up with a different TXT title for each intranet but thats ok.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Todd GerbertIT ConsultantCommented:
protected void btnSave_Click(object sender, EventArgs e)
{
	string fileName = String.Empty;
	if (Request.Url.Host.ToLower() == "student.intranetA.com")
		fileName = String.Format("{0}{1}{2}_{3}_q={4}",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"]);
	else if (Request.Url.Host.ToLower() == "student.researchintraB.com") ;
		// Etc
		
}

Open in new window

0
 
jay_eireAuthor Commented:
@tgerbert thank you for your reply

for the intranet 1 address there is an additional parameter called resultpage for me to include that in the title do I do this?

string fileName = String.Empty;
      if (Request.Url.Host.ToLower() == "student.intranetA.com")
            fileName = String.Format("{0}{1}{2}_{3}_q={4}_resultpage{5}",
                  DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["resultpage"]);

also how can i identify the query in Intranet 2 its always after student.researchintraB.com/research/webaccess/v2/ english%20papers%20class%20AM1 and finishes at the ?

Where do I add back in my code:

StreamWriter sw = new StreamWriter("c:\\temp\\" + WebAddress.Text.Replace("http://", "") + ".txt");
        sw.WriteLine(WebAddress.Text);
        sw.WriteLine(WebAddressContents.Text);
        sw.Close();
        lblSuccess.Text = "The file has been saved successfully.";

sorry for all the questions.
0
 
jay_eireAuthor Commented:

Ive tried to fill in the parameters based on your example would this work?

 
protected void btnSave_Click(object sender, EventArgs e)
{
	string fileName = String.Empty;
	if (Request.Url.Host.ToLower() == "student.intranetA.com")
		fileName = String.Format("{0}{1}{2}_{3}_q={4}_resultpage={5}",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["resultpage"]);
	else if (Request.Url.Host.ToLower() == "student.researchintraB.com") ;
		fileName = String.Format("{0}{1}{2}_{3}_v2={4}_Pagestart={5}",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["v2"], Request.QueryString["Pagestart"]);

	else if (Request.Url.Host.ToLower() == "intra.search.liveregister.com") ;
		fileName = String.Format("{0}{1}{2}_{3}_Query={4}_page.start={5}",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["Query"], Request.QueryString["page.start"]);

	else if (Request.Url.Host.ToLower() == "main.frame.com") ;
		fileName = String.Format("{0}{1}{2}_{3}_Query={4}_startresult={5}",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["startresult"]);
		
	StreamWriter sw = new StreamWriter("c:\\temp\\" + WebAddress.Text.Replace("http://", "") + ".txt");
        sw.WriteLine(WebAddress.Text);
        sw.WriteLine(WebAddressContents.Text);
        sw.Close();
        lblSuccess.Text = "The file has been saved successfully.";

}

Open in new window

0
 
Todd GerbertIT ConsultantCommented:
That looks about right, you seem to have a handle on the String.Format() method (http://msdn.microsoft.com/en-us/library/system.string.format.aspx).  Now that you have the file name you want to use stored in the string variable fileName, you can use it to open the file:

using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";


Note that I forgot to put a ".txt" at the end of the String.Format lines, and the date part could be made a little easier to read:
fileName = String.Format("{0:yyyyMMdd}_{1}_q={2}_resultpage={3}.txt",
                  DateTime.Today, Request.Url.Host, Request.QueryString["q"], Request.QueryString["resultpage"]);
0
 
Todd GerbertIT ConsultantCommented:
Also, make sure your text comparisons are case-aware, e.g.

Request.Url.Host.ToLower() will never equal "student.intranetA.com" because ToLower() returns an all lower-case string, and the string it's being compared to has an upper-case letter; it should be "if (Request.Url.Host.ToLower() == "student.intraneta.com")"

You could also use a switch statement:

switch (Request.Url.Host.ToLower())
{
  case "student.intraneta.com":
    fileName = String.Format(blah blah blah);
    // etc, etc
    break;
  case "student.researchb.com":
    fileName = String.Format(blah blah blah);
    // etc, etc
    break;
and so on
}
0
 
jay_eireAuthor Commented:
@tgerbert

thanks for your help with this but, im getting some errors, here is how my code behind looks...

   
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void btnSave_Click(object sender, EventArgs e)
{
	string fileName = String.Empty;
	if (Request.Url.Host.ToLower() == "student.intranetA.com")
		fileName = String.Format("{0}{1}{2}_{3}_q={4}_resultpage={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["resultpage"]);
	else if (Request.Url.Host.ToLower() == "student.researchintraB.com") ;
		fileName = String.Format("{0}{1}{2}_{3}_v2={4}_Pagestart={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["v2"], Request.QueryString["Pagestart"]);

	else if (Request.Url.Host.ToLower() == "intra.search.liveregister.com") ;
		fileName = String.Format("{0}{1}{2}_{3}_Query={4}_page.start={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["Query"], Request.QueryString["page.start"]);

	else if (Request.Url.Host.ToLower() == "main.frame.com") ;
		fileName = String.Format("{0}{1}{2}_{3}_Query={4}_startresult={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["startresult"]);
		
using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";

}
}

Open in new window


Error      4      Invalid expression term 'else'      C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite5\Default.aspx.cs      28      2      C:\...\WebSite5\

Error      5      ; expected      C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite5\Default.aspx.cs      28      7      C:\...\WebSite5\
0
 
Todd GerbertIT ConsultantCommented:
Watch your syntax; lines 24, 28 and 32 shouldn't end with a semi-colon.

Valid syntax for i statements:
if (someBooleanConditionIsTrue) thenRunThisMethod();

if (someBooleanConditionIsTrue)
    thenRunThisMethod();

if (someBooleanConditionIsTrue)
{
    thenRunThisMethod();
}

if (someBooleanConditionIsTrue) thenRunThisMethod();
{
    thenRunThisMethod();
    andAlsoThisMethod();
}
0
 
jay_eireAuthor Commented:
thanks Ive removed the semi-colons.

I'm running this code :
 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
<div>
        <asp:TextBox ID="WebAddress" runat="server" style="width:300px; Height:20px;" value="http://student.intranetA.com/ajax/serv/searchresult/web?v=3.0&q=research%20notes%20math%20g7&set=large&SN=TexasEN&ln=en1&gloc=TX&session=sdafk392293kd302ffds9320d0302020298381kd19349402lcakdi283949193ldmcnvdeiwa23o03bm3&cn=wan_en&resultpage=8&ipaddress=000.000.000.0"></asp:TextBox><br /><br />
        <asp:TextBox ID="WebAddressContents" runat="server" style="width:300px; Height:200px;" value="7+ GB of storage, less spam, and mobile access. Gmail is email that's intuitive, efficient, and useful. And maybe even fun."></asp:TextBox>
    </div>
    <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
<asp:Label id="lblSuccess" runat="server" />

    </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void btnSave_Click(object sender, EventArgs e)
{
	string fileName = String.Empty;
	if (Request.Url.Host.ToLower() == "student.intranetA.com")
		fileName = String.Format("{0}{1}{2}_{3}_q={4}_resultpage={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["resultpage"]);
	else if (Request.Url.Host.ToLower() == "student.researchintraB.com") 
		fileName = String.Format("{0}{1}{2}_{3}_v2={4}_Pagestart={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["v2"], Request.QueryString["Pagestart"]);

	else if (Request.Url.Host.ToLower() == "intra.search.liveregister.com") 
		fileName = String.Format("{0}{1}{2}_{3}_Query={4}_page.start={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["Query"], Request.QueryString["page.start"]);

	else if (Request.Url.Host.ToLower() == "main.frame.com") 
		fileName = String.Format("{0}{1}{2}_{3}_Query={4}_startresult={5}.txt",
			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["startresult"]);
		
using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";

}
}

Open in new window


Against the URL

http://student.intraneta.com/ajax/serv/searchresult/web?v=3.0&q=research%20notes%20math%20g7&set=large&SN=TexasEN&ln=en1&gloc=TX&session=sdafk392293kd302ffds9320d0302020298381kd19349402lcakdi283949193ldmcnvdeiwa23o03bm3&cn=wan_en&resultpage=8&ipaddress=000.000.000.0

but its coming back with
Could not find a part of the path 'C:\temp\'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.  
Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\temp\'.

Source Error: 


Line 34: 			DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, Request.Url.Host, Request.QueryString["q"], Request.QueryString["startresult"]);
Line 35: 		
Line 36: using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
Line 37: {
Line 38:   sw.WriteLine(fileName);

Source File: c:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite5\Default.aspx.cs    Line: 36

Open in new window

0
 
Todd GerbertIT ConsultantCommented:
If you're running it on your computer then Request.Url.Host is probably equal to "localhost", which does not match any of the if statements, so the variable "fileName" is never changed from it's initial value (which is an empty string).
0
 
jay_eireAuthor Commented:
Ahh i see, but the user will be copy and pasting / entering the URL into the text field WebAddress on the form,

example:
  <asp:TextBox ID="WebAddress" runat="server" style="width:300px; Height:20px;" value="http://student.intranet.com/ajax/serv/searchresult/web?v=3.0&q=research%20notes%20math%20g7&set=large&SN=TexasEN&ln=en1&gloc=TX&session=sdafk392293kd302ffds9320d0302020298381kd19349402lcakdi283949193ldmcnvdeiwa23o03bm3&cn=wan_en&resultpage=8&ipaddress=000.000.000.0"></asp:TextBox>

when they click save, it will be from the text field WebAddress where the file title should be taken from.

Can I still use the if statements but base the parameters from the value of webAdddress txt field?

0
 
jay_eireAuthor Commented:
would it be Request.Form["WebAddress"]; ?
0
 
Todd GerbertIT ConsultantCommented:
Ahh...sorry I missed that, though you were wanting to base it on the address of your page.

You can pass WebAddress.Text to the constructor of a Uri() object - and use String.Split to parse the query part yourself with this function:

private NameValueCollection GetQuery(string queryString)
{
	NameValueCollection queryCollection = new NameValueCollection();
	string[] queryPieces = queryString.TrimStart('?').Split('&');
	for (int i = 0; i < queryPieces.Length; i++)
	{
		string[] nameValue = queryPieces[i].Split('=');
		if (nameValue.Length == 2)
			queryCollection.Add(nameValue[0], nameValue[1]);
	}
	return queryCollection;
}

Open in new window


protected void btnSave_Click(object sender, EventArgs e)
{
	Uri url = new Uri(WebAddress.Text);
	NameValueCollection query = GetQuery(url.Query);
	string fileName = String.Empty;
	if (url.Host.ToLower() == "student.intraneta.com")
		fileName = String.Format("{0:yyyyMMdd}_{2}_q={3}_resultpage={4}.txt",
			DateTime.Today, url.Host, query["q"], query["resultpage"]);
etc

Open in new window

0
 
jay_eireAuthor Commented:
My code looks like this now.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private NameValueCollection GetQuery(string queryString)
    {
        NameValueCollection queryCollection = new NameValueCollection();
        string[] queryPieces = queryString.TrimStart('?').Split('&');
        for (int i = 0; i < queryPieces.Length; i++)
        {
            string[] nameValue = queryPieces[i].Split('=');
            if (nameValue.Length == 2)
                queryCollection.Add(nameValue[0], nameValue[1]);
        }
        return queryCollection;
    }
protected void btnSave_Click(object sender, EventArgs e)
{
    Uri url = new Uri(WebAddress.Text);
    NameValueCollection query = GetQuery(url.Query);
    string fileName = String.Empty;
    if (url.Host.ToLower() == "student.intraneta.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_q={3}_resultpage={4}.txt",
            DateTime.Today, url.Host, query["q"], query["resultpage"]);
    else if
     (url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_v2={3}_Pagestart={4}.txt",
            DateTime.Today, url.Host, query["q"], query["resultpage"]);
    else if
     (url.Host.ToLower() == "intra.search.liveregister.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_Query={3}_Pagestart={4}.txt",
            DateTime.Today, url.Host, query["Query"], query["page.start"]);

    else if
     (url.Host.ToLower() == "main.frame.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_q={3}_Pagestart={4}.txt",
            DateTime.Today, url.Host, query["Query"], query["startresult"]);
	
using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";

}
}

Open in new window


Im missing an namespace

Error      3      The type or namespace name 'NameValueCollection' could not be found (are you missing a using directive or an assembly reference?)      C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite5\Default.aspx.cs      19      13      C:\...\WebSite5\

I tried using NameValueCollection; but it does not recognize it
0
 
jay_eireAuthor Commented:
I fixed it by putting in, using System.Collections.Specialized;

my code is like this

 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Specialized;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private NameValueCollection GetQuery(string queryString)
    {
        NameValueCollection queryCollection = new NameValueCollection();
        string[] queryPieces = queryString.TrimStart('?').Split('&');
        for (int i = 0; i < queryPieces.Length; i++)
        {
            string[] nameValue = queryPieces[i].Split('=');
            if (nameValue.Length == 2)
                queryCollection.Add(nameValue[0], nameValue[1]);
        }
        return queryCollection;
    }
protected void btnSave_Click(object sender, EventArgs e)
{
    Uri url = new Uri(WebAddress.Text);
    NameValueCollection query = GetQuery(url.Query);
    string fileName = String.Empty;
    if (url.Host.ToLower() == "student.intraneta.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_q={3}_resultpage={4}.txt",
            DateTime.Today, url.Host, query["q"], query["resultpage"]);
    else if
     (url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_v2={3}_Pagestart={4}.txt",
            DateTime.Today, url.Host, query["q"], query["resultpage"]);
    else if
     (url.Host.ToLower() == "intra.search.liveregister.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_Query={3}_Pagestart={4}.txt",
            DateTime.Today, url.Host, query["Query"], query["page.start"]);

    else if
     (url.Host.ToLower() == "main.frame.com")
        fileName = String.Format("{0:yyyyMMdd}_{2}_q={3}_Pagestart={4}.txt",
            DateTime.Today, url.Host, query["Query"], query["startresult"]);
	
using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";

}
}

Open in new window


Ive run it against this URL in the webaddress filed
http://student.intraneta.com/ajax/serv/searchresult/web?v=3.0&q=research%20notes%20math%20g7&set=large&SN=TexasEN&ln=en1&gloc=TX&session=sdafk392293kd302ffds9320d0302020298381kd19349402lcakdi283949193ldmcnvdeiwa23o03bm3&cn=wan_en&resultpage=8&ipaddress=000.000.000.0

but this error is coming back.

Server Error in '/WebSite5' Application.
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Source Error:

Line 37:     string fileName = String.Empty;
Line 38:     if (url.Host.ToLower() == "student.intraneta.com")
Line 39:         fileName = String.Format("{0:yyyyMMdd}_{2}_q={3}_resultpage={4}.txt",
Line 40:             DateTime.Today, url.Host, query["q"], query["resultpage"]);
Line 41:     else if


Source File: c:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite5\Default.aspx.cs    Line: 39
0
 
Todd GerbertIT ConsultantCommented:
Your String.Format is off.  Notice you have {0}, {2}, {3} and {4} but no {1}.  It's having a fit because it's trying to replace {4} with the 5th parameter, but you've only given it four (1: DateTime.Today, 2: url.Host, 3: query["q"] and 4: query["resultpage"]).
0
 
jay_eireAuthor Commented:
Thanks tgerbert, really appreciate your help with this.

Its working for URLS 1, 3 and 4 but not for

URL 2:
http://student.researchintrab.com/research/webaccess/v2/english%20papers%20class%20AM1?sessid=_fk39283039dkvaks392ldflx_3_3kdkdkal2039dkx2ekdldskfieow02203zdls03.39dlgu203c0-
&resultform=dfr&spec=in&georegion=TX&Pagestart=0&numresuts=90&setsize=noc1&css=tru

the file name is missing the query parameters its being outputted as 20110222_student.researchintrab.com_v2=_Pagestart=0.txt


heres how the code looks now.
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Specialized;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private NameValueCollection GetQuery(string queryString)
    {
        NameValueCollection queryCollection = new NameValueCollection();
        string[] queryPieces = queryString.TrimStart('?').Split('&');
        for (int i = 0; i < queryPieces.Length; i++)
        {
            string[] nameValue = queryPieces[i].Split('=');
            if (nameValue.Length == 2)
                queryCollection.Add(nameValue[0], nameValue[1]);
        }
        return queryCollection;
    }
protected void btnSave_Click(object sender, EventArgs e)
{
    Uri url = new Uri(WebAddress.Text);
    NameValueCollection query = GetQuery(url.Query);
    string fileName = String.Empty;
    if (url.Host.ToLower() == "student.intraneta.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_q={2}_resultpage={3}.txt",
            DateTime.Today, url.Host, query["q"], query["resultpage"]);
    else if
     (url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_v2={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["q"], query["Pagestart"]);
    else if
     (url.Host.ToLower() == "intra.search.liveregister.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_Query={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["Query"], query["page.start"]);

    else if
     (url.Host.ToLower() == "main.frame.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_q={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["q"], query["startresult"]);
	
using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";

}
}

Open in new window


how can i get the query parameters from URL 2 into the file title, the query will always come after /V2/ and end at the ?

0
 
Todd GerbertIT ConsultantCommented:
What do you see wrong here?

(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_v2={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["q"], query["Pagestart"]);

Open in new window


String.Format is replacing {0} with what?  {1} with what?  {2} with what?  {3} with what?
0
 
jay_eireAuthor Commented:
(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_v2={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["v2"], query["Pagestart"]);

Open in new window

query["q"] should be query["v2"]
Ive updated the code to reflect that change but its still not writing the query parameters to the file name.

heres how the code looks now.
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Specialized;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private NameValueCollection GetQuery(string queryString)
    {
        NameValueCollection queryCollection = new NameValueCollection();
        string[] queryPieces = queryString.TrimStart('?').Split('&');
        for (int i = 0; i < queryPieces.Length; i++)
        {
            string[] nameValue = queryPieces[i].Split('=');
            if (nameValue.Length == 2)
                queryCollection.Add(nameValue[0], nameValue[1]);
        }
        return queryCollection;
    }
protected void btnSave_Click(object sender, EventArgs e)
{
    Uri url = new Uri(WebAddress.Text);
    NameValueCollection query = GetQuery(url.Query);
    string fileName = String.Empty;
    if (url.Host.ToLower() == "student.intraneta.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_q={2}_resultpage={3}.txt",
            DateTime.Today, url.Host, query["q"], query["resultpage"]);
    else if
     (url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_v2={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["v2"], query["Pagestart"]);
    else if
     (url.Host.ToLower() == "intra.search.liveregister.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_Query={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["Query"], query["page.start"]);

    else if
     (url.Host.ToLower() == "main.frame.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_q={2}_Pagestart={3}.txt",
            DateTime.Today, url.Host, query["q"], query["startresult"]);
	
using (StreamWriter sw = new StreamWriter(@"C:\temp\" + fileName))
{
  sw.WriteLine(fileName);
  sw.WriteLine(WebAddressContents.Text);
}
lblSuccess.Text = "The file has been saved successfully.";

}
}

Open in new window


0 is the date
1 is the URL
2 I think should be trimming from directly after v2/ to the ?
3 is PageStart

should query["v2"] be query["v2/,"?"]
0
 
jay_eireAuthor Commented:
the code needs to select
http://student.researchintrab.com/research/webaccess/v2/english%20papers%20class%20AM1?sessid=_fk39283039dkvaks392ldflx_3_3kdkdkal2039dkx2ekdldskfieow02203zdls03.39dlgu203c0-
&resultform=dfr&spec=in&georegion=TX&Pagestart=0&numresuts=90&setsize=noc1&css=tru

and put that into the file title, so the end result would be
20110222_student.researchintrab.com_v2=english%20papers%20class%20AM1_Pagestart=0.txt

but I cant figure how this would be done, I think maybe constructor might need a modification to do this.
0
 
Todd GerbertIT ConsultantCommented:
Unless I'm not seeing it, there is no v2 QueryString parameter.  HTTP query strings start at the ?, and continue to the end of the address.  They are pairs of names and the corresponding value; pairs are separated by an ampersand, and within each pair the name is separated from the value by an equal sign.  For example: http://somesite.com/somefolder/somepage.aspx?firstName=John&LastName=Doe&Gender=male  The "query" object in your example would break down everything from the question mark to the right - allowing you to write query["firstName"] to get the value John, query["LastName"] is equal to Doe, and so on.

If you want a file or folder name you can check the Uri objects' other properties (http://msdn.microsoft.com/en-us/library/system.uri.aspx), for example the Segments which breaks down the path part of the web address (i.e. the part after the host name, and before the ?) into an array of strings where the right-most part of the path is always the last element in the array.  So the segments array for the address of this question would look like:

Segments[0] = "/"
Segments[1] = "Programming/"
Segments[2] = "Languages/"
Segments[3] = ".NET/"
Segments[4] = "ASP.NET/"
Segments[5] = "Q_26836848.html"
0
 
jay_eireAuthor Commented:
Sorry yes you are right, there is no v2 QueryString parameter, I was describing it wrong, the way this intranet structures the URL the query parameters a user enters appears directly after the V2/ and stops at the ?

http://student.researchintrab.com/research/webaccess/v2/english%20papers%20class%20AM1?sessid=_fk39283039dkvaks392ldflx_3_3kdkdkal2039dkx2ekdldskfieow02203zdls03.39dlgu203c0-
&resultform=dfr&spec=in&georegion=TX&Pagestart=0&numresuts=90&setsize=noc1&css=tru

I guess my question is is there way to select the text from http://student.researchintrab.com/research/webaccess/v2/english%20papers%20class%20AM1? and put that in the file title so end result would be
20110222_student.researchintrab.com_english%20papers%20class%20AM1_Pagestart=0.txt

0
 
Todd GerbertIT ConsultantCommented:
Have you reviewed http://msdn.microsoft.com/en-us/library/system.uri.aspx yet, specifically the Segments property?
0
 
jay_eireAuthor Commented:
Yes, I was looking at that link and trying to follow it I guess this URL has four segments and im interested in the fourth segment.

http://student.researchintrab.com/research/webaccess/v2/english%20papers%20class%20AM1?sessid=_fk39283039dkvaks392ldflx_3_3kdkdkal2039dkx2ekdldskfieow02203zdls03.39dlgu203c0-
&resultform=dfr&spec=in&georegion=TX&Pagestart=0&numresuts=90&setsize=noc1&css=tru

research
webaccess
v2
english%20papers%20class%20AM1

the if statement for student.researchintrab.com Im guessing needs to be a mash up of segments to get the english%20papers%20class%20AM1 part and parsing the query string like what we have been doing to get the remaining parts
0
 
Todd GerbertIT ConsultantCommented:
Right, so you can get the 4th segment with url.Segments[3] (remember that arrays start numbering with zero, so the fourth in the list of 0, 1, 2 and 3 is 3).

You can also get the right-most part with url.Segments[url.Segments.Length - 1], which may be preferable because if the user enters http://student.researchintrab.com/research/blah.blah?blah=blah&blah=blah then url.Segments[3] would fail (because there's only two segments in the array, which makes Segments[1] the highest valid element).
0
 
jay_eireAuthor Commented:
Thanks man, I'm learning this as I go along on this one, you have been an awesome help with this...

so my updated code using segments would be....for URL 2 would be....

 
(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_url.Segments[url.Segments.Length - 1]_Pagestart={3}.txt",
            DateTime.Today, url.Host, url.Segments, query["Pagestart"]);

Open in new window

0
 
Todd GerbertIT ConsultantCommented:
url.Segments is an array, each element in the array being one part of the path.  You want just one of those array elements (specifically the english%20papers... one).
0
 
jay_eireAuthor Commented:
ok so, It would be url.Segments[3] as thats what im after so the code would be

 
(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_url.Segments[url.Segments.Length - 1]_Pagestart={3}.txt",
            DateTime.Today, url.Host, url.Segments[3], query["Pagestart"]);

Open in new window

0
 
Todd GerbertIT ConsultantCommented:
Right.  Just remember, though, that if the user enters something with fewer than 4 segments in the path that code's gonna blow up.  You could explicitly check the length of the segments property first and display an error message, if (url.Segments < 4) then... or use url.Segments[url.Segments.Length - 1] to get whatever the right-most piece is regardless of how many there are.
0
 
Todd GerbertIT ConsultantCommented:
Rather, that should be:

if (url.Segments.Length < 4)
  // Show error
0
 
jay_eireAuthor Commented:
THANKS MAN!  slight edit to what I posted before but this seems to do the trick

 
(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_" + url.Segments[url.Segments.Length - 1] + "_Pagestart={3}.txt",
            DateTime.Today, url.Host, url.Segments[3], query["Pagestart"]);

Open in new window


I like the idea of the
if (url.Segments < 4) then... or use url.Segments[url.Segments.Length - 1]

but where can i factor that into the code? can I have a nested if? or have I missed something

0
 
Todd GerbertIT ConsultantCommented:
(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_" + url.Segments[url.Segments.Length - 1] + "_Pagestart={3}.txt",
            DateTime.Today, url.Host, url.Segments[url.Segments - 1], query["Pagestart"]);
0
 
jay_eireAuthor Commented:

ive added that update in but its hit an error

Error      3      Operator '-' cannot be applied to operands of type 'string[]' and 'int'      

DateTime.Today, url.Host, url.Segments[url.Segments - 1], query["Pagestart"]);
0
 
Todd GerbertIT ConsultantCommented:
Yes, you can't subtract the number 1 from a string[] array.

I made the same typo again, that should be

(url.Host.ToLower() == "student.researchintrab.com")
        fileName = String.Format("{0:yyyyMMdd}_{1}_" + url.Segments[url.Segments.Length - 1] + "_Pagestart={3}.txt",
            DateTime.Today, url.Host, url.Segments[url.Segments.Length - 1], query["Pagestart"]);
0
 
jay_eireAuthor Commented:
Thanks Man, this is awesome I have learned a whole bunch on this question!
0
 
jay_eireAuthor Commented:
Thanks for your patience man!
0

Featured Post

2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

  • 20
  • 16
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now