Category Archives: Xml

[RESOLVED] how to post a video on video player

I want to post few videos on a website but i don't want to use youtube or any other website.

I want to have an in-build player on the webpage with video in it - how to accoplish that ?

Object tag????

if you dont prefer that...you got to think of Silverlight...

Thanks.

How I can do this :http://www.asp.net/general/videos/how-do-i-multiple-file-uploads-in-aspnet-2

Could you please help me with the code and things needs to be done in order to accoplish this ?

Complete code....

<%@ Page Language="C#"%>
<%@ Import Namespace="System.IO" %>

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

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        String UpPath;
        UpPath = "C:\\UploadedUserFiles";

        if (!Directory.Exists(UpPath))
        {
            Directory.CreateDirectory("C:\\UploadedUserFiles\\");
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        HttpFileCollection uploads = HttpContext.Current.Request.Files;
        for (int i = 0; i < uploads.Count; i++)
        {
            HttpPostedFile upload = uploads[i];

            if (upload.ContentLength == 0)
                continue;

            string c = System.IO.Path.GetFileName(upload.FileName); // We don't need the path, just the name.

            try
            {
                upload.SaveAs("C:\\UploadedUserFiles\\" + c);
                Span1.InnerHtml = "Upload(s) Successful.";
            }
            catch (Exception Exp)
            {
                Span1.InnerHtml = "Upload(s) FAILED.";
            }
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<p id="upload-area">
   <input id="File1" type="file" runat="server" size="60" />
</p>

<input id="AddFile" type="button" value="Add file" onclick="addFileUploadBox()" />
<p><asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />

<script type="text/javascript">
    function addFileUploadBox() {
        if (!document.getElementById || !document.createElement)
            return false;

        var uploadArea = document.getElementById("upload-area");

        if (!uploadArea)
            return;

        var newLine = document.createElement("br");
        uploadArea.appendChild(newLine);

        var newUploadBox = document.createElement("input");

        // Set up the new input for file uploads
        newUploadBox.type = "file";
        newUploadBox.size = "60";

        // The new box needs a name and an ID
        if (!addFileUploadBox.lastAssignedId)
            addFileUploadBox.lastAssignedId = 100;

        newUploadBox.setAttribute("id", "dynamic" + addFileUploadBox.lastAssignedId);
        newUploadBox.setAttribute("name", "dynamic:" + addFileUploadBox.lastAssignedId);
        uploadArea.appendChild(newUploadBox);
        addFileUploadBox.lastAssignedId++;
    }
</script>
</form>
</body>
</html>



[RESOLVED] Using REQUEST("ListBoxName") to get values

So I have a master page and inside it is a content place holder. In that content place holder is a panel with a bunch of multi select list boxes. Under that panel is a button.

when I click the button, I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine. Could you help explain what I am doing wrong??

This is a section of my code:


Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        

        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request.QueryString("MethodNameLB")
                

        If MethodIDSelection = "" Then
            Label5.Text = "Method was blank"
        Else
            Label5.Text = MethodIDSelection
        End If
        

    End Sub


According to your wording above the button is on the Content Page with the ListBoxes.  Are you passing the query string to this page and you simply want to pre-select the items in the list boxes or you want to generate a query string from the selections to pass to another page?

If you are trying to generate a comma separated list can we see the code you used to create the ListBoxes?  If it is data driven then be sure you are reloading the data after the postback.  I also do not see any code to even loop through the listboxes and create a list.  I do recommend StringBuilder instead of String with a simple += because it is more efficient.

Sudo Code:

Dim MyString As New StringBuilder


For Each Item As ListItem In MyListBox
     If Item.Selected Then
          MyString.Append("," & Item.Text)
     End If
Next


Response.Redirect("NewPage.aspx?selected=" & MyString.ToString, False)

If you are trying to read the query string the above code should be in the Me.Load method handler.  Once the button is clicked it initiates a postback and will most likely loose the query string.

Sorry page lost formatting so I deleted it.

Sorry, I guess I missed out some information. I didn't mean to use the .QueryString. Just use Request("MethodNameLB"). Also, the data in the listbox is from an object datasource attached to a database. Here is the code for the entire ASPX page. Its pretty straightforward.


<%@ Page Title="" Language="VB" MasterPageFile="~/SuperPage.master" %>


<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>


<script runat="server">
    

    Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)


        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request("MethodNameLB")
                

        If MethodIDSelection = "" Then
            MyLabel.Text = "Method was blank"
        Else
            MyLabel.Text = MethodIDSelection
        End If
        

    End Sub
    

</script>


<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="TitleContent" Runat="Server">
Test Page</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">


<div style="font-family: Verdana; font-size: small">
   

    <asp:ObjectDataSource ID="PersonalMethodsData" runat="server"
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetPersonalMethodsDataByActive"
            TypeName="PersonalMethodsBLL"></asp:ObjectDataSource>
            





    <asp:ListBox ID="MethodNameLB" runat="server" DataSourceID="PersonalMethodsData"
                            DataTextField="MethodName" DataValueField="PersonalMethodID"
                            SelectionMode="Multiple"></asp:ListBox>
    <cc1:ListSearchExtender ID="MethodNameLB_ListSearchExtender" runat="server" PromptCssClass="searchExtender"
                            PromptPosition="Bottom" PromptText=""
    TargetControlID="MethodNameLB">
    </cc1:ListSearchExtender>
    <br />
    <asp:Label ID="MyLabel" runat="server" Text="Label"></asp:Label>
<asp:Panel ID="InputPanel" runat="server">
</asp:Panel>
<asp:Button ID="FilterButton" runat="server" Text="Filter View" onclick="FilterButton_Click" />


</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ScriptHolder" Runat="Server"></asp:Content>


Using just Request(key) is not nearly as efficient as specifying the actual source.  The Request(key) command will look through the Request.Forms, Request.QueryString, Request.Cookies, and Request.ServerVariables just to find a match.  If you want the application to create a comma separate list I would suggest using a session variable to maintain the data and not the Request object.  You should use a ViewState if you only need the data on that page.  To create the list though you don't need to assign the object to anything until the end.

Now I am not too familiar with ObjectDataSource controls but I do know for the selected items to remain you need to reload the data on postback from the previous source and not reload the data each time from the database.  If you load it each time it will clear the checked items before it ever runs the button click event.  I always load data in a BindData method similar to the code below.  It allows for easier debugging and less web code.  Hope this helps point you in a different direction that works.

Dim myData As DataTable


Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
     If Not IsPostBack Then
          BindData(True)
     Else
          myData = CType(ViewState("TableData"), DataTable)
     End If
End Sub


Private Sub BindData(Optional ByVal RefreshData As Boolean = False)
     If RefreshData Then
          myData = GetPersonalMethodsDataByActive()
          ViewState("TableData") = myData
     End If


     MethodNameLB.DataSource = myData
     MethodNameLB.DataBind()
End Sub


Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFilter.Click
     Dim MyList As New StringBuilder
     For Each Item As ListItem In MethodNameLB
          If Item.Selected Then
               MyList.Append("," & Item.Value)
          End If
     Next
     If MyList.Length > 0 Then MyList.Remove(0, 1)
     Session("SelectedItems") = MyList.ToString
End Sub


 

This can be done without using Request object. Here's an example, which you may write in codebehind of your content page.


string strTemp1 = "";
foreach (ListItem item in ListBox1.Items)
{
     if (item.Selected == true)
     {
               
        strTemp1 += (strTemp1 == "") ? item.Value : "," + item.Value;
      }

I just figured using the request object would be easiest. But it doesn't seem to work if the listbox in inside of an update panel. My guess is because their is only a partial page postback and the request() never gets called.

My main goal is to try and simplify the code. I don't like the looping through method as it is messy and I have to due this on several list boxes. I have resorted to LINQ as an alternative but have ran into another problem I'm hoping someone can help me out with. I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

Anyhow this is what I have moved toward:

Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItemsText = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Text


Dim selItemsValue = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Value


TextString = Join(selItemsText.ToArray, ",")
ValueString = Join(selItemsValue.ToArray, ",")


'I would like to do this using 1 LINQ statement selecting separate entities like this:


Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItems = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select New With {.itemtext = li.Text, .itemVal = li.Value}


TextString = Join(selItems.itemtext.ToArray, ",")
ValueString = Join(selItems.itemVal.ToArray, ",")


I'm not sure if this is possible or not, or if my code is even accurate as I haven't tested it, but this is what I'm trying to accomplish. So if I had a listbox with the following data I would get the following strings:

listboxText - listboxValue - Selected

A - 1 - YES

B - 2 - NO

C - 3 - YES


TextString = "A,C"

ValueString = "1,3"




Note: I am using VB.net not C# or old versions of VB so an answer in VB.Net would be much appreciated. Thanks

Hi,

Hybird

I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine.
 

According to your description ,for my experience the Request object can retrieve the values that the client browser passed to the server during an HTTP request.

As far as I know you can use Request["nameOfControl"] to get control's value. 

However ,if you use a master page ,the name of control(which is contained in the content page) is not the same as its'ID.

Thus,the code which as you mentioned in your post :Request("MethodNameLB") can not get the value.

I would like to suggest you to check the sample below which shows how to use Request object to get the value of the control which is contained in content page.

1.Code in master page(.master):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


2.Code in content page(.aspx):

 

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:HiddenField ID="HiddenField1" runat="server" />
</asp:Content>


 

3.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            Response.Write(Request(listboxName).ToString())
        End If
    End Sub


 

 

Hybird

But it doesn't seem to work if the listbox in inside of an update panel.

Please just modify the code(in content page) which I mentioned above:

1.Code in content page(.aspx):

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>


 

2.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            'Show Result.
            Me.Label1.Text = Request(listboxName).ToString()
        End If
    End Sub


 

Hybird

I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

You can create an Entity class and pass the entity to an array as below:

Create a new page to demo the sample:

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


2.Code in page(.vb):

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Public list As New List(Of Items)()
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each item As ListItem In Me.ListBox1.Items
            If item.Selected Then
                Dim i As New Items()
                i.ID = item.Value
                i.Text = item.Text
                list.Add(i)
            End If
        Next

        ' Now you can the value like this:
        For Each listitem As Items In list
            Response.Write(("Text:" + listitem.Text & " value:") + listitem.ID & "<br/>")
        Next
    End Sub


End Class

' Entity Class 
Public Class Items
    Private _id As String
    Private _text As String

    Public Property ID() As String
        Get
            Return _id
        End Get
        Set(ByVal value As String)
            _id = value
        End Set
    End Property
    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property
End Class


Hope it can help you.

Wow, thank you Ming, that was an extremely informative post! Thanks for taking the time to actually create the test pages!

A note on some things I had to modify to get it working in case other people happen to stubble upon this informative post:

1.) in order to use the type datatable, at the top of your master page or content page you must include

<%@ Import Namespace="System.Data" %>

2.) I have a separate script content place holder where I generally place all of my scripts, and If I placed the

<script language="javascript" type="text/javascript">
          function GetNameOfListBox() {
              var listbox = document.getElementById("<%=ListBox1.ClientID %>");
              var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
              hidden.value = listbox.name;
          }  
 </script>

section of code in there it would not work. I had to place it in the same content place holder as the one where the hidden field is located.


Thanks again for your solution! Works wonders.

[RESOLVED] Anyone use BING API 2.0 for site search

I'm looking at options for creating a site search for my institution's website. The "regular" BING site search however leaves some things to be desired: we're a non-profit, so the ads won't fly with us. I also want the results to appear on one of our Web pages ("scraped"), not as the pop-up/out window, and certainly prefer to use our own site's styling.

So I'm looking at the BING API 2.0 instead and wondering if I'llbe able to use it as described. Has anyone else here used it like this? Any tips, recommendations or sample code for me? I'm thinking of using the XML data return option, as I already have a number of scripts in place scraping XML to our pages.

Any help would be greatly appreciated. Thanks!

-_Will

Thanks for the link, Satish! Though I've already got that one tabbed in my browser.   :)


Was really curious though to see if anyone else here has actually used the API for search though...

I'm curious too. Has anyone tried using the API specifically for searching their own site? We've been using Google's site search for a while, but would really like to leverage the ability to use XML for the results without paying the hefty price tag that comes with site search.  

I'm using the Bing API with XML and it works beautifully. The only downside is that you have to wait for Bing to index new pages before they become available. 

Thanks for the reply. How long does it usually take them to re-index? Google site search seemingly catches new pages very quickly. How much volume do you get? 

Indexing was really slow when I first created my website. Now, my new pages are usually indexed within a day or two. You just have to make sure get some quality backlinks and regularly add new content. I get a lot more traffic from Bing than I thought I would, being that my website is mostly personal.

Is the only way to limit search results to your site by adding site:mysite.com to the query? 

It's the only way I know. You can add it to the code behind on your server so the user doesn't have to see it in the URL though. 

[RESOLVED] Import data from text and excel

Hello, I am working on a C# web application under visual studio 2005.

I want to import data from text file or excel file into a SQL 2005 database.
I have 3 columns in the text file separated by |, example of the text file format:

1|11122222|Name1
2|22299809|Name2

Can you tell me how to import data from text or excel file?

Another question, if you provide a solution for the import from excel, can you note which office (2003 or 2007 or 2010)?

Thank you.

lebdeveloper

Another question, if you provide a solution for the import from excel, can you note which office (2003 or 2007 or 2010)?
 

Check this solution..

http://weblogs.asp.net/rajbk/archive/2009/05/02/uploading-an-excel-file-to-sql-through-an-asp-net-webform.aspx

lebdeveloper

I have 3 columns in the text file separated by |, example of the text file format:

Break each line into string array with char separator "|". After that you can use above code to upload.

Hi, firt of all, you need to know the path of the file. I recommend you use cvs files for working with excel.

Any Excel can open this kind of file. Then You should do something like this:

StreamReader sw = new StreamReader("path of file + file + .extension");


while(!sw.EndofStream)
{
string[] partsOfString = sw.ReadLine().split('|');


set a parameter = partsOfString[0];
set a parameter = partsOfString[1];
set a parameter = partsOfString[2];


command.parameters.add(params);
command.ExecuteInsert();
}


All this doing normal process to insert into a database right?


lebdeveloper

Can you tell me how to import data from text or excel file?

You can use OLeDB connection for reading a Xls file...and you can use StreamReader to read the txt file....

When you read xls file, you can fill the dataset using that data and then call a stored proc in Sql DB to make bulk insert....the easient way to do is, convert the dataset to Xml, and give that xml as input to the stored proc...and in the stored proc you can easily parse the xml and make inserts into the DB....

For txt file, you got to parse the string which you get out of streamreader, and then write some code to convert it into DataTable which will be merged to a dataset, then follow the above procedure....

PS - I have given you conceptual idea on how it works...you got read with some articles on line on how to accomplish the above said tasks...may be you can break them into smaller tasks and go one at a time...

Thanks.