Quantcast
Channel: DataSource Controls - SqlDataSource, ObjectDataSource, etc.
Viewing all 956 articles
Browse latest View live

I uploaded a video file into the SQL database converting into binary data.

$
0
0

I Have a Problem that to Retrieve Video File (.MP4) From SQL Server 2012 DataBase and which has toPlay on Media Player.

In this i am going to upload a Video in DataBase and Display the Link in Listview, and by clicking the Link the Video have to playFOR EXAMPLE : YOUTUBE 

PLZ  Help Me any one .

This is My Code

YouTube_WebForm.aspx :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Data;
using System.IO;

public partial class YouTube_WebForm : System.Web.UI.Page
{
      protected void Page_Load(object sender, EventArgs e)
     {
           if (!IsPostBack)
          {
                 BindGrid();
          }
    }

private void BindGrid()
{
            string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strConnString))
           {
                 using (SqlCommand cmd = new SqlCommand())
                 {
                       cmd.CommandText = "select Video from TBL_YouTube";
                       cmd.Connection = con;
                       con.Open();
                      Listviewid.DataSource = cmd.ExecuteReader();
                      Listviewid.DataBind();
                      con.Close();
                 }
           }
}


protected void uploadbtn_Click(object sender, EventArgs e)
{
            string k = FileUploadbtn.PostedFile.FileName.ToString();
            using (BinaryReader br = new BinaryReader(FileUploadbtn.PostedFile.InputStream))
            {
                     byte[] bytes = br.ReadBytes((int)FileUploadbtn.PostedFile.InputStream.Length);
                     string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(strConnString))
                    { 
                            using (SqlCommand cmd = new SqlCommand())
                            {
                                     cmd.CommandText = "insert into TBL_YouTube(ID, FileType, Video) values (@ID, @FileType, @Video)";
                                     cmd.Parameters.AddWithValue("@ID",FileUploadbtn.PostedFile.FileName.ToString() + DateTime.Now.ToLongDateString().ToString());
                                     cmd.Parameters.AddWithValue("@FileType", "video/mp4");
                                     cmd.Parameters.AddWithValue("@Video", bytes);
                                     cmd.Connection = con;
                                     con.Open();
                                     cmd.ExecuteNonQuery();
                                    con.Close();
                            }
                   }
           }
Response.Redirect(Request.Url.AbsoluteUri);
}

protected void LinkID_Click(object sender, EventArgs e)
{
          LinkButton linkplayvideo = sender as LinkButton;
          this.aPlayer.Visible = true;
         this.aPlayer.HRef = linkplayvideo.CommandArgument;

}
}

YouTube_WebForm.aspx

<body>
           <form id="form1" runat="server">
                      <div>
                               <asp:FileUpload ID="FileUploadbtn" runat="server" CssClass="myButton" />
                               <asp:Button ID="uploadbtn" runat="server" Text="Upload" CssClass="myButton" OnClick="uploadbtn_Click" />
                              <asp:ListView ID="Listviewid" Visible="true" runat="server" AutoGenerateColumns="false" RepeatColumns="1" CellSpacing="15">
                              <ItemTemplate>
                                            <table>
                                                        <tr>
                                                                 <td>
                                                                        <asp:LinkButton ID="LinkID" runat="server" Text="Play" CommandArgument='<%# Eval("Video", "Generic_Handler.ashx?Id={0}")%>' OnClick="LinkID_Click"></asp:LinkButton>
                                                                 </td>
                                                        </tr>
                                              </table>
                           </ItemTemplate>
     </asp:ListView>
     <a class="player" id="aPlayer" runat="server" visible="false" style="height: 300px;  width: 300px; display: block;"></a>
     <script src="FlowPlayer/flowplayer-3.2.12.min.js" class="player" type="text/javascript"></script>
     <script type="text/javascript">

    flowplayer("a.player", "FlowPlayer/flowplayer-3.2.16.swf",
   {
         plugins:
         {
             pseudo:
               {
                     url: "FlowPlayer/flowplayer.pseudostreaming-3.2.12.swf"
               }
          },
   clip:
   {
        provider: 'pseudo', autoPlay: false
   },
});
</script>

</div>
</form>
</body>

DataBase:

ID : varchar(MAX)  ----> In ID have to store FileName and Upload Current DataTime

FileType : Varchar(50)

Video : varbinary(MAX)

Generic Handler.ashx

<%@ WebHandler Language="C#" Class="Generic_Handler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

public class Generic_Handler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
         int id = int.Parse(context.Request.QueryString["ID"]);
         byte[] bytes;
        string FileType;
        string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                 cmd.CommandText = "select Video, FileType from TBL_YouTube where ID=@ID";
                 cmd.Parameters.AddWithValue("@ID", id);
                 cmd.Connection = con;
                 con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                sdr.Read();
                bytes = (byte[])sdr["Video"];
                FileType = sdr["FileType"].ToString();
                con.Close();
           }
    }
    context.Response.Clear();
    context.Response.Buffer = true;
    context.Response.AppendHeader("Content-Disposition", "attachment; ID=" + id);
   context.Response.ContentType = FileType;
   context.Response.BinaryWrite(bytes);
   context.Response.End();
  }

public bool IsReusable
{
     get
    {
         return false;
    }
}

}

In this Video is not Playing

Thanks in Advance

Regards Deepak


I Have a Problem that to Retrieve Video File (.MP4) From SQL Server 2012 DataBase and which has to Play on Media Player.

$
0
0

I Have a Problem that to Retrieve Video File (.MP4)  From SQL Server 2012 DataBase and which has to Play on Media Player.

In this i am going to upload a Video in DataBase and Display the Link in Listview, and by clicking the Link the Video have to play FOR EXAMPLE : YOUTUBE 

PLZ  Help Me any one .

This is My Code

YouTube_WebForm.aspx :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Data;
using System.IO;

public partial class YouTube_WebForm : System.Web.UI.Page
{
      protected void Page_Load(object sender, EventArgs e)
     {
           if (!IsPostBack)
          {
                 BindGrid();
          } 
    }

private void BindGrid()
{
            string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strConnString))
           {
                 using (SqlCommand cmd = new SqlCommand())
                 {
                       cmd.CommandText = "select Video from TBL_YouTube";
                       cmd.Connection = con;
                       con.Open();
                      Listviewid.DataSource = cmd.ExecuteReader();
                      Listviewid.DataBind();
                      con.Close();
                 }
           }
}


protected void uploadbtn_Click(object sender, EventArgs e)
{
            string k = FileUploadbtn.PostedFile.FileName.ToString();
            using (BinaryReader br = new BinaryReader(FileUploadbtn.PostedFile.InputStream))
            {
                     byte[] bytes = br.ReadBytes((int)FileUploadbtn.PostedFile.InputStream.Length);
                     string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(strConnString))
                    { 
                            using (SqlCommand cmd = new SqlCommand())
                            {
                                     cmd.CommandText = "insert into TBL_YouTube(ID, FileType, Video) values (@ID, @FileType, @Video)";
                                     cmd.Parameters.AddWithValue("@ID",FileUploadbtn.PostedFile.FileName.ToString() + DateTime.Now.ToLongDateString().ToString());
                                     cmd.Parameters.AddWithValue("@FileType", "video/mp4");
                                     cmd.Parameters.AddWithValue("@Video", bytes);
                                     cmd.Connection = con;
                                     con.Open();
                                     cmd.ExecuteNonQuery();
                                    con.Close();
                            }
                   }
           }
Response.Redirect(Request.Url.AbsoluteUri);
}

protected void LinkID_Click(object sender, EventArgs e)
{
          LinkButton linkplayvideo = sender as LinkButton;
          this.aPlayer.Visible = true;
         this.aPlayer.HRef = linkplayvideo.CommandArgument;

}
}

YouTube_WebForm.aspx

<body>
           <form id="form1" runat="server">
                      <div>
                               <asp:FileUpload ID="FileUploadbtn" runat="server" CssClass="myButton" />
                               <asp:Button ID="uploadbtn" runat="server" Text="Upload" CssClass="myButton" OnClick="uploadbtn_Click" />
                              <asp:ListView ID="Listviewid" Visible="true" runat="server" AutoGenerateColumns="false" RepeatColumns="1" CellSpacing="15">
                              <ItemTemplate>
                                            <table>
                                                        <tr>
                                                                 <td>
                                                                        <asp:LinkButton ID="LinkID" runat="server" Text="Play" CommandArgument='<%# Eval("Video", "Generic_Handler.ashx?Id={0}")%>' OnClick="LinkID_Click"></asp:LinkButton>
                                                                 </td>
                                                        </tr>
                                              </table>
                           </ItemTemplate>
     </asp:ListView>
     <a class="player" id="aPlayer" runat="server" visible="false" style="height: 300px;  width: 300px; display: block;"></a>
     <script src="FlowPlayer/flowplayer-3.2.12.min.js" class="player" type="text/javascript"></script>
     <script type="text/javascript">

    flowplayer("a.player", "FlowPlayer/flowplayer-3.2.16.swf",
   {
         plugins:
         {
             pseudo:
               {
                     url: "FlowPlayer/flowplayer.pseudostreaming-3.2.12.swf"
               }
          },
   clip:
   {
        provider: 'pseudo', autoPlay: false
   },
});
</script>

</div>
</form>
</body>

DataBase:

ID : varchar(MAX)  ----> In ID have to store FileName and Upload Current DataTime

FileType : Varchar(50)

Video : varbinary(MAX)

Generic Handler.ashx

<%@ WebHandler Language="C#" class="Generic_Handler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

public class Generic_Handler : IHttpHandler 
{
    public void ProcessRequest (HttpContext context) 
    {
         int id = int.Parse(context.Request.QueryString["ID"]);
         byte[] bytes;
        string FileType;
        string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                 cmd.CommandText = "select Video, FileType from TBL_YouTube where ID=@ID";
                 cmd.Parameters.AddWithValue("@ID", id);
                 cmd.Connection = con;
                 con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                sdr.Read();
                bytes = (byte[])sdr["Video"];
                FileType = sdr["FileType"].ToString();
                con.Close();
           }
    }
    context.Response.Clear();
    context.Response.Buffer = true;
    context.Response.AppendHeader("Content-Disposition", "attachment; ID=" + id);
   context.Response.ContentType = FileType;
   context.Response.BinaryWrite(bytes);
   context.Response.End();
  }

public bool IsReusable
{
     get 
    {
         return false;
    }
}

}

In this Video is not Playing

Thanks in Advance

Regards Deepak

Our Favorite Issue - procedure or function has too many arguments specified

$
0
0

Battling with this issue in both VB and C#, SQLDatasource and DetailsView data component. Insert/add method works fine, no errors reported. However the update functionality fails with the titled error. I have reviewed all postings concerning this issue and found none of them fit my scenario using stored procedures with the SQLDataSource and avoiding the updating method.

Suggestions or pointers to forums that address this specific issue without lengthy work around would be greatly appreciated, as well as the reason why, when building this functionality as shown in Microsoft tutorials etc., this continues to be a problem in the Visual Studio environment.

Thank you

ALTER procedure sp_RefActivities_update
@iActivity_UID
int,
@vActivity  varchar(25),
@vActivity_Description
varchar(255)
AS
UPDATE RefActivities
SET [Activity] = @vActivity, [Activity_Description] = @vActivity_Description
WHERE [Activity_UID] = @iActivity_UID

ALTER PROCEDURE sp_RefActivities_add
@vActivity        varchar(25),
@vActivity_Description varchar(255)
AS
INSERT INTO dbo.RefActivities(Activity, Activity_Description, Expert_System_UID)
VALUES(@vActivity, @vActivity_Description, 1)
<asp:SqlDataSource ID="sqldsActivityTypeDetail" runat="server" 
     ConnectionString="<%$ ConnectionStrings:MedexprdConnectionString %>"
     InsertCommand="sp_RefActivities_add" InsertCommandType="StoredProcedure" 
     SelectCommand="sp_RefActivities_get_details" SelectCommandType="StoredProcedure" 
     UpdateCommand="sp_RefActivities_update" UpdateCommandType="StoredProcedure"><SelectParameters><asp:ControlParameter ControlID="grdvwActivities" Name="vActivity_UID" PropertyName="SelectedValue"
             Type="Int32" /></SelectParameters><UpdateParameters><asp:Parameter Name="iActivity_UID" Type="Int32" /><asp:Parameter Name="vActivity" Type="String" /><asp:Parameter Name="vActivity_Description" Type="String" /></UpdateParameters><InsertParameters><asp:Parameter Name="vActivity" Type="String" /><asp:Parameter Name="vActivity_Description" Type="String" /></InsertParameters></asp:SqlDataSource><asp:DetailsView ID="dvwActivityTypeDetail" runat="server" Height="50px" Width="100%"
     BackImageUrl="~/App_Themes/blue/image/gradient.gif" EmptyDataText="No Records."
     AutoGenerateRows="False" DataKeyNames="Activity_UID" DataSourceID="sqldsActivityTypeDetail"><RowStyle VerticalAlign="Middle" /><FieldHeaderStyle HorizontalAlign="Left" /><Fields><asp:BoundField DataField="Activity_UID" HeaderText="Activity_UID" InsertVisible="False"
              ReadOnly="True" SortExpression="Activity_UID" Visible="False" /><asp:TemplateField HeaderText="Activity" SortExpression="Activity"><EditItemTemplate><asp:TextBox ID="txtbxActCode" runat="server" Text='<%# Bind("Activity") %>' ReadOnly="True"
                     SkinID="TextBoxCss" ToolTip="Activity Code" TabIndex="1"></asp:TextBox></EditItemTemplate><InsertItemTemplate><asp:TextBox ID="txtbxActivityCode" runat="server" Text='<%# Bind("Activity") %>'
                     SkinID="TextBoxCss" ToolTip="Activity Code" TabIndex="1"></asp:TextBox><asp:RequiredFieldValidator ID="rfvActivityCode" runat="server" ErrorMessage="* Required"
                      ControlToValidate="txtbxActivityCode" SetFocusOnError="True"></asp:RequiredFieldValidator></InsertItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="Activity_Description" SortExpression="Activity_Description"><EditItemTemplate><asp:TextBox ID="txtActivityDescription" runat="server" Height="150px" SkinID="TextBoxCss"
                      TabIndex="2" Width="300px" ToolTip="Activity Description" TextMode="MultiLine"
                      MaxLength="255" Text='<%# Bind("Activity_Description") %>'></asp:TextBox></EditItemTemplate><InsertItemTemplate><asp:TextBox ID="txtActDescr" runat="server" Height="150px" SkinID="TextBoxCss" TabIndex="2"
                        Width="300px" ToolTip="Activity Description" TextMode="MultiLine" MaxLength="255"
                        Text='<%# Bind("Activity_Description") %>'></asp:TextBox></InsertItemTemplate></asp:TemplateField></Fields></asp:DetailsView>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    if (dvwActivityTypeDetail.CurrentMode == DetailsViewMode.Insert)
                    {
                        dvwActivityTypeDetail.InsertItem(false);
                    }
                    else
                    {
                        if (dvwActivityTypeDetail.CurrentMode == DetailsViewMode.Edit)
                        {
                            dvwActivityTypeDetail.UpdateItem(false);
                        }
                    }
                    dvwActivityTypeDetail.ChangeMode(DetailsViewMode.Edit);
                    dvwActivityTypeDetail.Visible = false;
                    mdlPopup.Hide();
                    ScriptManager.GetCurrent(Page).RegisterDataItem(grdvwActivities, grdvwActivities.SelectedIndex.ToString());
                    grdvwActivities.PageIndex = grdvwActivities.PageCount - 1;
                    grdvwActivities.DataBind();
                    updtpnlActivityTypeList.Update();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message.ToString());
            }
        }




How to Use UNION (Combine data from two table for bind GridView)?

$
0
0

Hello

I have similar two table and need to combine them before bind to GridView.

Googled and found UNION command but I dont know how to use it with my SqlDataSource.

Any help?

Here is my SqlDataSource.

<asp:SqlDataSource ID="sqlDataSourceGridView" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT dia.*, Girdles.*, Shapes.*, Colors.*, ColorsLot.*, Cuts.*, Clarity.*, Polish.*, Sym.*, Fluo.*, Culet.*, Reports.*, Categories.*           
            FROM Diamonds AS dia      
            LEFT JOIN Shapes ON Shapes.ShapeID = dia.ShapeID             
            LEFT JOIN Categories ON Categories.CategoryID = dia.CategoryID             
            LEFT JOIN Colors ON Colors.ColorId = dia.ColorID            
            LEFT JOIN ColorsLot ON ColorsLot.ColorLotId = dia.ColorID                       
            LEFT JOIN Cuts ON Cuts.CutID = dia.CutID             
            LEFT JOIN Clarity ON Clarity.ClarityID = dia.ClarityID             
            LEFT JOIN Polish ON Polish.PolishID = dia.PolishID             
            LEFT JOIN Sym ON Sym.SymID = dia.SymID             
            LEFT JOIN Fluo ON Fluo.FluoID = dia.FluoID             
            LEFT JOIN Culet ON Culet.CuletID = dia.CuletID             
            LEFT JOIN Reports ON Reports.ReportID = dia.ReportID             
            LEFT JOIN Girdles ON Girdles.GirdleID = dia.Girdle             
            WHERE            
            (dia.ReportID IN (SELECT Value FROM dbo.Split(@ReportIDs, ',') AS Split_1)) AND            
            (dia.ShapeID IN (SELECT Value FROM dbo.Split(@ShapeIDs, ',') AS Split_2)) AND             
            (            (Price > @MinimumPrice AND Price < @MaximumPrice) AND            
            (dia.ColorID >= @MinimumColorID AND dia.ColorID <= @MaximumColorID) AND              
            (Carat > @MinimumCarat AND Carat < @MaximumCarat) AND            
            (dia.CutID >= @MinimumCutID AND dia.CutID <= @MaximumCutID) AND              
            (dia.ClarityID >= @MinimumClarityID AND dia.ClarityID <= @MaximumClarityID)) AND             
            ([DeliveryTime] <= @DeliveryTimeDDL) AND            
            dia.StatusID = @Status  AND            
            dia.CategoryID = @Category AND            
            dia.Operation = @Operation  AND
            dia.[Function] = @Function
            ORDER BY dia.DateAdd DESC"
            OnSelecting="sqlDataSourceGridView_Selecting"><SelectParameters><asp:Parameter Name="Category" DefaultValue="2" /><asp:Parameter Name="Status" DefaultValue="2" /><asp:Parameter Name="Function" DefaultValue="1" /><asp:Parameter Name="Operation" DefaultValue="0" /><asp:Parameter Name="ReportIDs" /><asp:Parameter Name="ShapeIDs"/>                <asp:ControlParameter ControlID="PriceSlider" PropertyName="SelectionStart" Name="MinimumPrice" /><asp:ControlParameter ControlID="PriceSlider" PropertyName="SelectionEnd" Name="MaximumPrice" /><asp:ControlParameter ControlID="ColorSlider" PropertyName="SelectionStart" Name="MinimumColorID" /><asp:ControlParameter ControlID="ColorSlider" PropertyName="SelectionEnd" Name="MaximumColorID" /><asp:ControlParameter ControlID="CaratSlider" PropertyName="SelectionStart" Name="MinimumCarat" /><asp:ControlParameter ControlID="CaratSlider" PropertyName="SelectionEnd" Name="MaximumCarat" /><asp:ControlParameter ControlID="CutQualitySlider" PropertyName="SelectionStart" Name="MinimumCutID" /><asp:ControlParameter ControlID="CutQualitySlider" PropertyName="SelectionEnd" Name="MaximumCutID" /><asp:ControlParameter ControlID="ClaritySlider" PropertyName="SelectionStart" Name="MinimumClarityID" /><asp:ControlParameter ControlID="ClaritySlider" PropertyName="SelectionEnd" Name="MaximumClarityID" /><asp:ControlParameter ControlID="DDDList" PropertyName="SelectedValue" Name="DeliveryTimeDDL" /></SelectParameters></asp:SqlDataSource>

How to compare original and changed values when updating with ObjectDataSources

$
0
0

Hi All,

I have a general query about SQL and object datasources in ASP.NET which I hope someone can shed light upon.

Suppose I have a simple database table with just two fields:

CountryCode - such as "UK", "US", "FR" and
CountryName - such as "United Kingdom", "United States", "France".

(1) It’s easy to use a SQLDataSource and a gridview to display and update the data in this table. I can look at, change and even remove parameters in the Updating event of the datasource e.g.

e.Command.Parameters("@CountryCode").Value = “ESP”
e.Command.Parameters("@CountryName ").Value = “Spain”

(2) And it’s easy to set the ConflictDetection property of the datasource to "CompareAllValues". Then you’ll be able to see the following four parameters in the Updating event:

@CountryCode
@CountryName
@original_CountryCode
@original_CountryName

Couldn’t be easier.

(3) But… I’d prefer to use an ObjectDataSource with a custom data access class and there-in lies my problem.

Oh it’s still easy to do the first part - use an ObjectDataSource and a gridview to display and update the data in this table via a data access class - cCountry. I can even look at and change the parameters in the Updating event of the ObjectDataSource - with a bit of direct casting:

Dim oCountry As New DatabaseComponent.cCountry
oCountry = DirectCast(e.InputParameters(0), DatabaseComponent.oCountry)
oCountry.CountryName = "Brazil"

(4) But if I set the ConflictDetection property of the datasource to "CompareAllValues" I get the less than helpful:

"ObjectDataSource 'odsCountry' could not find a non-generic method 'UpdateCountry' that takes parameters of type 'DatabaseComponent.cCountry'."

It could certainly find one a moment ago - before I changed the ConflictDetection property so I’m assuming that I can’t take that message at face value?

(4.1) I imagine what’s happening is that, before I make the change to the ConflictDetection property the datasource is sending two parameters to create thecCountry object:

CountryCode
CountryName


(4.2) Then, after I changed the ConflictDetection property I would guess that it was sending four parameters to create acCountry object and failing:

CountryCode
CountryName
original_CountryCode
original_CountryName

I’m sure I’m approaching this all wrong. You simply must be able to do this sort of thing (be able to compare original and updated values before committing the changes) with ObjectDataSources. But I’m jiggered if I can see it. If anyone can help I’d be extremely grateful.

TIA

Select the same field from a Table more than once

$
0
0

Hello

I have a table to store Contacts (ID, Name, ....)

ID: is the primary key

In another Table I store a School data (SchoolID, SchoolName, Supervisor, Manager, ....)

Supervisor and Manager are foreign keys (connected to the previous table)

I need to select data from this table for both Supervisor and Manager in one select statement

any Ideas Please

thank you

How to call Eval by column index?

$
0
0

Hello,

My resultset comes from a dynamic query, so that the column names are not known in advance.

When binding those up with the GridView, I can't call Eval by name, how do I call them by column index?

Thanks

Jack

How best to code hierarchy controls bound to sqldatasource for search feature on Listview

$
0
0

 On my main product  page I am having trouble getting my search controls to work in sequence.

They  rely on other control for parameter values according to product selected from main menu. Each product can have variable properties from which to search in Listview.

 such as: Name, Category, Type , Colour, Size, Gender , Age , Material....

Some items only have two properties to search on.


Repeater controls dynamic display

$
0
0

Hi

I have database of users,items and bookmarks tables.

When user bookmarks an item it stores user id and item id into bookmarks table

I have a repeater that shows many items list using data binding and it have an bookmark button on it.

If the item is already bookmarked by logged in user it should be of green color else red color.

How can i achieve this using repeater control.

TSQL SELECT Question

$
0
0
I want to get results from a specified row to another specified row like: row 1 to row 10 row 11 to row 20 i don't know how the TSQL code would look like: SELECT FROM [myTable] FROM ROW 1 TO ROW 10 first i tried a column with the following info: Datatype: int Identity: Yes Seed: 1 Identity Increment: 1 and tried the following TSQL code: SELECT [id], [Column1], [Column2], [Column3] FROM [myTable] WHERE [id] >= '1' AND [id] >= '10' But it failed when i deleted some rows. Now I wanna change the SELECT form to an appropriate one. Thanks

Sql question( select the first, second row in the table)

$
0
0
In MS Sql server, no "first" function,

how to select only the first row?

By the way, how to select only the seoncd row?

Thx

This code executes but the record does not change

$
0
0

Any ideas why this is not updating the record?

        Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("cerberusConnectionString").ConnectionString)
            Dim strDocids As String = Request.QueryString("blogno")
            Dim SQL As String = "update [tbl_WIKIblog] set [Title]=@title,[author]=@author,[post]=@post,[published]=@published,bdate=@bdate where blogno=" + strDocids

            Dim myCommand As New SqlCommand(SQL, Conn)
            myCommand.Parameters.Add("@published", Data.SqlDbType.Int).Value = CheckBox2.Checked
            myCommand.Parameters.Add("@title", Data.SqlDbType.VarChar).Value = TextBox2.Text
            myCommand.Parameters.Add("@author", Data.SqlDbType.VarChar).Value = DropDownList1.Text
            myCommand.Parameters.Add("@post", Data.SqlDbType.VarChar).Value = FreeTextBox1.Text
            myCommand.Parameters.Add("@bdate", Data.SqlDbType.DateTime).Value = bdate.Text
            Conn.Open()
            myCommand.ExecuteNonQuery()
            Conn.Close()
            Dim nurl As String = "blogview.aspx?blogno=" + strDocids
            Response.Redirect(nurl)
        End Using

Uploading images through the ObjectDataSource control

$
0
0

Question? Why is it when I use the SqlDataSource control that hard codes the SQL insert statement will allow me to add images in the database but when I use the ObjectDataSource control pointing to my vb class file I have issues inserting images? 

My vb class code:

Public Shared InsertRecord(ByVal Myimage As Byte, ByVal Fullname As String)


Dim MyConnection As String = WebConfigurationManager.ConnectionStrings("MiscConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(MyConnection)
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "INSERT acctinfo (Image, FullName) VALUES (@Myimage, @Fullname)"
cmd.CommandType = CommandType.Text

cmd.Parameters.AddWithValue("@Image", Myimage)
cmd.Parameters.AddWithValue("@Fullname", Fullname)

Using conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw
End Try
conn.Close()
End Using

End Sub

Client side code & Object Data Source:

<div class="Box"><table><tr><td><label>Full Name:</label></td> <td><asp:TextBox ID="txtFull" runat="server" /></td></tr><tr><td><label>Upload Photo:</label></td><td><asp:FileUpload ID="Upload" runat="server" /></td></tr></table><div><asp:Button ID="btnSave" runat="Server" Text="Save" Class="main_buttons" /></div></div><asp:ObjectDataSource
     ID="odsEmployeeSearch"
     runat="server"
     TypeName="GotData"
     SelectMethod="DisplayPeople"
     InsertMethod="InsertRecord"><SelectParameters><asp:ControlParameters ControlID="txtSearch" Name="Search" PropertyName="Text" ConvertEmptyStringToNull="false" ></SelectParameters><InsertParameters><asp:ControlParameter ControlID="UpImage" Name="Myimage" PropertyName="FileBytes" /><asp:ControlParameter ControlID="txtFull" Name="Fullname" PropertyName="Text" /> </InsertParameters>

Code behind:

Protected Sub Save_Details()

odsEmployeeSearch.Insert()

End Sub

When I run the code I get the "Object of type 'System.Byte[]' cannot be converted to type 'System.Byte" error message.

What can I do to make this work?

Please don't send links to similar issues. I have read too many links that don't show a 3 tier setup.

Thank you in an advance for those trying to help me,

xyz789

SQL report to change data from all data in one column to display in one row per grouped PROD #

$
0
0

If I have the below data in one table

What I need is a SQL query that would GROUP all items from the PRODUCT column, and show each ID in a separate column, I could predetermine the max columns needed

So ABC below would look like this

PROD      ID1      ID2      ID3      ID4      ID5

abc         111      222    333

cde        1212    1313

productid
abc111
abc222
abc333
cde1212
cde1313
fgi1213
fgi1314
fgi1415
fgi1516
fgi1718
fgi1810

SQLDataSource/webform date fields access

$
0
0

Hallo,

I got a problem trying to manage date fields using SQLDataSource inside a webform.

I got a very simple page with some text fields and a datefield. I'm using a SQLDataSource control to feed the webform with data.

Form widgets are bound to sqldatasource data fields trough #Bind() directives. In particular I would like the date field to be bound trough a #Bind("date", "{0:dd/MM/yyyy}") to properly format date for italian users.

The SelectCommand is defined as a simple "SELECT" statement.

The UpdateCommand is defined in this way: 

UPDATE table SET `text_field` = @text_field, `date_field` = @date_field WHERE id=@id;

I got a number of problems using this form since when I try to update data I can run into a number of different errors:

1) if I leave the date_field empty I got format error:

2) if I use a date format different from those used by SQL backend (yyyy-MM-dd) I got format errors;

I tried to use the OnUpdating event changing the e.Parameters["@date_field"].Value with a properly formatted value but without luck.

There's a working 'strategy' to manage update of date fields that allows to display and edit data in formats different from standard SQL format?

Best Regards,

 Weirdgyn


Duplication of record in store procedure when I add the second 2nd Stored Procedure

$
0
0

select top 20 ROW_NUMBER() OVER (Order by Sum(TB1.TT) Desc) as Srno, @CompanyName AS CompanyName,@RegistrationNumber AS RegistrationNo,@ParentCompanyName AS ParentCompanyName,
@MOHFacilityCode AS MOHFacilityCode,@CompanyState as DisState,DateName( month , DateAdd( month ,CAST(@paMonthIn AS INT) , -1 )) AS DisMonth,@paYearIn as DisYear
, isnull(sum(TT),0) AS TT,isnull(procedureid,0) AS ProcedureID,
CA_ProcedureMaster.ProcedureCode,CA_ProcedureMaster.Description,(select isnull(sum(TT),0) from (SELECT isnull( count(CA_InPatientDischargeSummary.MRN),0) AS TT

FROM dbo.CA_DischargeDetails LEFT OUTER JOIN
dbo.CA_InPatientDischargeSummary ON dbo.CA_DischargeDetails.MRN = dbo.CA_InPatientDischargeSummary.MRN AND
dbo.CA_DischargeDetails.VisitNumber = dbo.CA_InPatientDischargeSummary.VisitNumber RIGHT OUTER JOIN
dbo.CA_Registration ON dbo.CA_InPatientDischargeSummary.MRN = dbo.CA_Registration.MRN
where CA_Registration.VisitTypeID = 34 AND CA_Registration.Chargetypeid=2 And Month(CA_DischargeDetails.DischargeDate)=@paMonthIn AND year(CA_DischargeDetails.DischargeDate)=@paYearIn AND CA_InPatientDischargeSummary.procedureid is not null group by procedureid

UNION ALL

SELECT count(CA_SurgicalAlliedDischargeSummary.MRN) AS TT,procedureid
FROM dbo.CA_DischargeDetails LEFT OUTER JOIN
dbo.CA_SurgicalAlliedDischargeSummary ON dbo.CA_DischargeDetails.MRN = dbo.CA_SurgicalAlliedDischargeSummary.MRN AND
dbo.CA_DischargeDetails.VisitNumber = dbo.CA_SurgicalAlliedDischargeSummary.VisitNumber RIGHT OUTER JOIN
dbo.CA_Registration ON dbo.CA_SurgicalAlliedDischargeSummary.MRN = dbo.CA_Registration.MRN
where CA_Registration.VisitTypeID <> 3 AND CA_Registration.Chargetypeid=2 And Month(CA_DischargeDetails.DischargeDate)=@paMonthIn AND year(CA_DischargeDetails.DischargeDate)=@paYearIn AND CA_SurgicalAlliedDischargeSummary.procedureid is not null group by procedureid )
AS TB1 Right outer join CA_ProcedureMaster ON CA_ProcedureMaster.id =TB1.procedureid
group by TB1.procedureid,CA_ProcedureMaster.ProcedureCode,CA_ProcedureMaster.Description order by sum(TT) desc
END

Output:

22

22

22

35

35

37

Duplication of record in staore procedure 1

$
0
0

select top 20 ROW_NUMBER() OVER (Order by Sum(TB1.TT) Desc) as Srno, @CompanyName AS CompanyName,@RegistrationNumber AS RegistrationNo,@ParentCompanyName AS ParentCompanyName,
@MOHFacilityCode AS MOHFacilityCode,@CompanyState as DisState,DateName( month , DateAdd( month ,CAST(@paMonthIn AS INT) , -1 )) AS DisMonth,@paYearIn as DisYear
, isnull(sum(TT),0) AS TT,isnull(procedureid,0) AS ProcedureID,
CA_ProcedureMaster.ProcedureCode,CA_ProcedureMaster.Description,(select isnull(sum(TT),0) from (SELECT isnull( count(CA_InPatientDischargeSummary.MRN),0) AS TT

FROM dbo.CA_DischargeDetails LEFT OUTER JOIN
dbo.CA_InPatientDischargeSummary ON dbo.CA_DischargeDetails.MRN = dbo.CA_InPatientDischargeSummary.MRN AND
dbo.CA_DischargeDetails.VisitNumber = dbo.CA_InPatientDischargeSummary.VisitNumber RIGHT OUTER JOIN
dbo.CA_Registration ON dbo.CA_InPatientDischargeSummary.MRN = dbo.CA_Registration.MRN
where CA_Registration.VisitTypeID = 34 AND CA_Registration.Chargetypeid=2 And Month(CA_DischargeDetails.DischargeDate)=@paMonthIn AND year(CA_DischargeDetails.DischargeDate)=@paYearIn AND CA_InPatientDischargeSummary.procedureid is not null group by procedureid

UNION ALL

SELECT count(CA_SurgicalAlliedDischargeSummary.MRN) AS TT,procedureid
FROM dbo.CA_DischargeDetails LEFT OUTER JOIN
dbo.CA_SurgicalAlliedDischargeSummary ON dbo.CA_DischargeDetails.MRN = dbo.CA_SurgicalAlliedDischargeSummary.MRN AND
dbo.CA_DischargeDetails.VisitNumber = dbo.CA_SurgicalAlliedDischargeSummary.VisitNumber RIGHT OUTER JOIN
dbo.CA_Registration ON dbo.CA_SurgicalAlliedDischargeSummary.MRN = dbo.CA_Registration.MRN
where CA_Registration.VisitTypeID <> 3 AND CA_Registration.Chargetypeid=2 And Month(CA_DischargeDetails.DischargeDate)=@paMonthIn AND year(CA_DischargeDetails.DischargeDate)=@paYearIn AND CA_SurgicalAlliedDischargeSummary.procedureid is not null group by procedureid )
AS TB1 Right outer join CA_ProcedureMaster ON CA_ProcedureMaster.id =TB1.procedureid
group by TB1.procedureid,CA_ProcedureMaster.ProcedureCode,CA_ProcedureMaster.Description order by sum(TT) desc
END

Output:

22

22

22

35

35

37

Trouble while passing DataTable from .Net to SQL Server 2008

$
0
0
I am trying the new feature in SQL Server 2008 where you can pass in a DataTable to a stored procedure.I am using the SQLHelper class to pass the datatable formed to the DataBase.Here's the example:SqlParameter parameter= newSqlParameter("@TabModuleColumnSetting",SqlDbType.Structured);parameter.Value = tabModuleColumnSetting;SqlHelper.ExecuteNonQuery(this.ConnectionString,"SP_Name",parameter);I Face the following issue in the above line:"The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect.Table-valued parameter 6 (\"@TabModuleColumnSetting\"), row 0, column 0: Data type 0xF3 (user-defined table type)has a non-zero length database name specified. Database name is not allowed with a table-valued parameter,only schema name and type name are valid."}

I have got the solution to the above problem:

1.

            SqlConnection sqlConn =newSqlConnection(ConnectionString);               sqlConn.Open();               SqlCommand sqlCmd = sqlConn.CreateCommand();               sqlCmd.CommandText = spLoad;//                sqlCmd.CommandType = CommandType.StoredProcedure;                SqlParameter[] parameters = newSqlParameter[1];               parameters[0] = new SqlParameter("@LoadSPParam",                          SqlDbType.Structured);               parameters[0].Value = loadSPParams;               sqlCmd.Parameters.Add(parameters[0]);                sqlCmd.ExecuteNonQuery();2.SqlParameter parameter=newSqlParameter("@TabModuleColumnSetting",SqlDbType.Structured);parameter.Value = tabModuleColumnSetting;SqlHelper.ExecuteNonQuery(this.ConnectionString,CommandType.StoredProcedure"SP_Name",parameter);But I am not sure about the exact reason why this happens. It will be great if somebody can explain me the exact reason for the above error and how is that solved with the above solutions.Thanx in Advance.

 

 

How do you retrieve a control value in a FormView onItemUpdating?

$
0
0

I want to update the users email address in an asp.net identity table when saving. The issue that I see is in the method UserProfileFormView_ItemUpdating. I am not able to retrieve the new entered value in the TextBox with ID="email_txt". How do you get the value?

Thanks in advance

Brad

<asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" DataSourceID="ProfileEDS" DefaultMode="Edit" OnItemUpdating="UserProfileFormView_ItemUpdating"><EditItemTemplate><asp:TextBox ID="firstName_txt" runat="server" Text='<%# Bind("firstName") %>'></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="firstName_txt" ErrorMessage=" - first name is required" CssClass="text-danger small" Display="Dynamic"></asp:RequiredFieldValidator><asp:TextBox ID="lastName_txt" runat="server" Text='<%# Bind("lastName") %>'/><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="lastName_txt" ErrorMessage=" - title is required" CssClass="text-danger small" Display="Dynamic"></asp:RequiredFieldValidator><asp:TextBox ID="email_txt" runat="server"  /><asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="email_txt" ErrorMessage=" - email is required" CssClass="text-danger small" Display="Dynamic"></asp:RequiredFieldValidator><asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" CssClass="btn btn-primary" /><asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" Text="Cancel" CssClass="btn btn-default" OnClick="UpdateCancelButton_Click" /></EditItemTemplate></asp:FormView><asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=modelContainer" DefaultContainerName="modelContainer" EnableFlattening="False" EntitySetName="UserProfiles" EnableUpdate="true" Where="it.[Id] = @nId"><WhereParameters><asp:QueryStringParameter Name="nId" QueryStringField="profileid" DbType="Int32" /></WhereParameters></asp:EntityDataSource>

Code Behind C#

    protected void UserProfileFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        TextBox emailTxt = (TextBox)UserProfileFormView.Row.FindControl("email_txt");
        string email = emailTxt.Text;

        UserManager Manager = new UserManager();
        var user = Manager.FindById(userId);

        user.Email = email.ToString();

        var result = Manager.Update(user);

    }

How to use parameter with IN operator in SQL query

$
0
0

I am trying to use a parameter in a query in conjunction with an IN operator.  I'm finding that the query works when the parameter works out to as single value...

EOOI

...returning the expected dataset but when the parameter works out to be multiple values...

All, Customer Service, EOOI, Finance, Supply Chain

...the result set is returned empty.  There is no sql exception thrown just no result set returned.  The value of the parameter is built by loading the content of the items  of  a dropdownlist into a string and then loading the string into the parameter (if the 'All' option of the dropdownlist is selected) or just using the one selected value of the dropdownlist (if the 'All' selection of the dropdownlist is not selected).

My code is below...Can someone kindly show me what I need to do to get this to work?  Thanks tonnes for any help, Roscoe

The parameter is @YTDChartOBU .  The Query looks like...

           string query = "with" +
                            " CTE_Amount as" +
                            " (" +
                            " select CAST([Initiative] AS NVARCHAR(MAX)) as Initiative, sum(Amount) as TotalAmount" +
                            " from SavingsDetail where Year = @YTDChartYear" +
                            " and CAST([Originating_Business_Unit] AS NVARCHAR(MAX)) in (@YTDChartOBU)" +
                            " and Month between @YTDChartStartMonth and @YTDChartEndMonth" +
                            " group by CAST([Initiative] AS NVARCHAR(MAX))" +
                            " )," +
                            " CTE_Baseline as" +
                            " (" +
                            " select CAST([Initiative] AS NVARCHAR(MAX)) as Initiative, sum(BaselineAmount) as TotalBaselineAmount" +
                            " from Baselines where Year = @YTDChartYear" +
                            " and CAST([Originating_Business_Unit] AS NVARCHAR(MAX)) in (@YTDChartOBU)" +
                            " group by CAST([Initiative] AS NVARCHAR(MAX))" +
                            " )" +
                            " select" +
                            " coalesce(a.Initiative, b.Initiative) as Initiative," +
                            " IsNull(a.TotalAmount, 0)," +
                            " IsNull(b.TotalBaselineAmount, 0)" +
                            " from CTE_Amount as a" +
                            " full join CTE_Baseline as b" +
                            " on b.Initiative = a.Initiative" +
                            " order by" +
                            " Initiative";

...YTDChartOBU is dropdownlist and the build of the parameter @YTDChartOBU looks like...

                String Y = YTDChartYear.Text;
                String S = YTDChartStartMonth.Text;
                String E = YTDChartEndMonth.Text;
                String B = YTDChartOBU.Text;
                String Bx = "";

                try
                {
                    cmd.Parameters.Add("@YTDChartYear", SqlDbType.Int).Value = Y;
                    cmd.Parameters.Add("@YTDChartStartMonth", SqlDbType.Int).Value = S;
                    cmd.Parameters.Add("@YTDChartEndMonth", SqlDbType.Int).Value = E;
                    if (B == "All")
                    {
                        foreach (ListItem li in YTDChartOBU.Items)
                        {
                            Bx = Bx + li.Value + ", ";
                        }
                        Bx = Bx.TrimEnd(' ');
                        Bx = Bx.TrimEnd(',');
                        cmd.Parameters.Add("@YTDChartOBU", SqlDbType.NVarChar).Value = Bx;
                    }
                    else
                    {
                        cmd.Parameters.Add("@YTDChartOBU", SqlDbType.NVarChar).Value = B;
                    }             
                    DataTable dt = new DataTable();
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = cn;
                        sda.SelectCommand = cmd;
                try
                {
                        sda.Fill(dt);
                }
                catch (Exception ex)
                {
                    // Handle the error
                    if (ex.Source != null)
                        Console.WriteLine("IOException source: {0}", ex.Source);
                    throw;
                }

Viewing all 956 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>