How to save text of FCKEditor on database? - asp.net

I am using FCKEditor on my page.
and i want to save its content on database..but on doing this error A potentially dangerous Request.Form value was detected from the client (LongDescriptionVal="<p>hello..</p>"). occur on my page..
what i am doing is here:-
aspx.cs:-
protected void btnadd_Click(object sender, EventArgs e)
{
string _detail = Request["LongDescriptionVal"].ToString();
string query = "insert into Description(description) values('" + _detail.Trim() + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and aspx:-
<strong>Full Description :</strong>
<br />
<!--Editor Code comes here -->
<script type="text/javascript">
<!--
var oFCKeditor = new FCKeditor( 'LongDescriptionVal') ;
oFCKeditor.BasePath = 'fckeditor/';
oFCKeditor.Height = 300;
oFCKeditor.Value = '<%=FullDescription%>';
oFCKeditor.Create() ;
//-->
</script>
<br />
<asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
anyone can tell me that how can i save data on database...
Thanks in advance..

add validateRequest="false" into your page;
Sample;
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" ValidateRequest="false" Inherits="MyApp.Default" %>

Have a look at this question:
A potentially dangerous Request.Form value was detected from the client
The gist of the answer is that you can suppress the warning by setting validateRequest="false" in the <#Page directive of your aspx file.
There is a reason for that warning however, by doing so you could in your case open yourself up to all sorts of attacks. Given the nature of your database access code can I suggest that you read up on using Parameterized Queries

in aspx page, set the property ValidateRequest="False", but don't forget to encode input before saving in database.

Related

Load DropDownList from Database, then get the Value

I'm not sure how ASP.NET works since I'm still very new to it, coming from a PHP background where most things are done with POST. I'm using VB.NET behind the code. Mainly because the main program used here is written in VB.NET and I want to keep the code portable without compiling a library.
My issue is as follows. I have a DropDownList on the page. I populate it with data from the database. That seems to work fine.
I have a button that should change the CLIENTCODE to whatever has been selected in the DropDownBox. This doesn't work. Instead the Index is always -1.
Page Code
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/MasterPage.Master" CodeBehind="Admin.aspx.vb" Inherits="WOTC_CP.Admin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="RightBody" runat="server">
<%
Load_UserList_List()
%>
<h1 class="sub-header">Administration Toolbox</h1>
<p>If you are not an Administrator, please send us an alert and leave this page at once.</p>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<asp:Label ID="Label1" runat="server" Text="Label">Change my Clientcode;</asp:Label>
<asp:DropDownList ID="cboClientList" class="form-control" runat="server" >
</asp:DropDownList>
<asp:Button ID="cmdChangeClientCode" class="btn btn-primary" runat="server" Text="Change" />
</div>
</div>
</div>
Behind Code
Public Sub Load_CLIENTCODE_List()
If IsPostBack = False Then
Using DB As New wotcDB
Dim r = (From t In DB.client_main Order By t.CLIENTCODE Select t.CLIENTCODE).Distinct
For Each Client In r
Dim input As New ListItem
input.Text = Client
input.Value = Client
cboClientList.Items.Add(input)
Next
End Using
End If
End Sub
Private Sub cmdChangeClientCode_Click(sender As Object, e As EventArgs) Handles cmdChangeClientCode.Click
Dim CLIENTCODE As String = CType(Session("CLIENTCODE"), String)
Dim UserName As String = CType(Session("UserName"), String)
Using DB As New wotcDB
Dim u = (From t In DB.website_users Where t.UserName = UserName).FirstOrDefault
If u IsNot Nothing Then
Dim TempID As Integer = cboClientList.SelectedIndex
Dim TempValue As String = cboClientList.SelectedValue
u.CLIENTCODE = cboClientList.SelectedValue
DB.SaveChanges()
End If
End Using
End Sub
I've tried other answers here on stack, but nothing seems to work. Any Ideas?
In asp.net the dropdown list has two key properties that you want to set. DataTextField = Display Name and DataValueField = value to store to DB.
With that said, you need to capture the "SelectedValue" if you want to get the DataValueField.
The issue was that I was loading the script that populated the DropDownList before getting it's value. So it was always empty. The solution was to load the list on Page_Load instead.

AJAX cascading dropdownlist not populating

I'm following the tutorial here to try to implement cascading drop down lists using the AJAX toolkit in VS2012, however, I am using MySQL as my database instead. I created a webservice (as the tutorial describes - seen below),
<WebMethod()>
Public Function GetComplex(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim conn As New MySqlConnection("Server=localhost; database=lockout; User ID=root; Pwd=123let?")
conn.Open()
Dim comm As New MySqlCommand("SELECT complex_id, complex_name FROM complex ORDER BY complex_name", conn)
Dim dr As MySqlDataReader = comm.ExecuteReader()
Dim l As New List(Of CascadingDropDownNameValue)
While (dr.Read())
l.Add(New CascadingDropDownNameValue(dr("complex_name").ToString(), dr("complex_id").ToString()))
End While
conn.Close()
Return l.ToArray()
End Function
and I am able to connect to my database and invoke my function. Invoking the function returns the following in my web browser:
<ArrayOfCascadingDropDownNameValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<CascadingDropDownNameValue>
<name>14 Line</name>
<value>1</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>16 Line</name>
<value>2</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>Converting</name>
<value>3</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>F&E</name>
<value>4</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>Water Quality</name>
<value>5</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
</ArrayOfCascadingDropDownNameValue>
I can see that I am generating the necessary array, but for some reason, the array does not appear in my drop down list and I'm not sure why. It looks as though I have covered everything in the tutorial, but I just can't seem to get it to work. Shown below is my .aspx file.
<%# Page Title="LockoutNew" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="LockoutNew.aspx.vb" Inherits="Lockout.LockoutNew" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div>
Complex: <asp:DropDownList ID="ComplexList" runat="server" /><br />
<!-- Machine: <asp:DropDownList ID="MachineList" runat="server" /><br /> -->
</div>
<ajaxToolkit:CascadingDropDown ID="ccd1" runat="server"
ServicePath="lockoutService.asmx" ServiceMethod="GetComplex"
TargetControlID="ComplexList" Category="Complex"
PromptText="Select Complex" />
<!-- <ajaxToolkit:CascadingDropDown ID="ccd2" runat="server"
ServicePath="lockoutService.asmx.vb" ServiceMethod="GetMachine"
TargetControlID="MachineList" ParentControlID="ComplexList"
Category="Machine"
PromptText="Select Machine" /> -->
</asp:Content>
Any help is greatly appreciated...
I had the same exact issue.
The thing is that when building cascading logic u need to know that the first element is different from the rest.
The first in the chain element does not have any parameters to pass to the method !
Thus your method for the first drop down list must contain no parameters :
Public Function GetComplex() As CascadingDropDownNameValue()
Dim conn As New MySqlConnection("Server=localhost; database=lockout; User ID=root; Pwd=123let?")
conn.Open()
Dim comm As New MySqlCommand("SELECT complex_id, complex_name FROM complex ORDER BY complex_name", conn)
Dim dr As MySqlDataReader = comm.ExecuteReader()
Dim l As New List(Of CascadingDropDownNameValue)
While (dr.Read())
l.Add(New CascadingDropDownNameValue(dr("complex_name").ToString(), dr("complex_id").ToString()))
End While
conn.Close()
Return l.ToArray()
End Function

Problem with asp.net page results

hey guys,
recently while creating a webpage with a gridview, while binding the gridview with sql database, once when i run the site, it shows me the proper results, but when i make any changes and attempt to run the site again, it does not displays the latest changes, instead it displays the results from the previous cache, but when i clears the history, then when i refresh the page, it shows proper results.
Below is my code which i am using to bind my gridview.
SqlConnection con = new SqlConnection(#"[connection string goes here]");
public void FillGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select m.ModuleID, md.FriendlyName from Modules m inner join dbo.ModuleDefinitions md on m.ModuleDefID = md.ModuleDefID", con);
DataTable dt = new DataTable();
adap.Fill(dt);
FunGrid.DataSource = dt;
}
protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
FunGrid.DataBind();
}
Below is the source of the gridview as i am using boundfields to bind gridview.
<form id="form1" runat="server">
<div>
<asp:GridView ID="FunGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" PageSize="10">
<Columns>
<asp:BoundField DataField="ModuleId" HeaderText="Module ID" />
<asp:BoundField DataField="FriendlyName" HeaderText="Module Name" />
</Columns>
</asp:GridView>
</div>
</form>
This is the first time i have got some issues like that, Please if anyone guys have came accross such issues please revert back with the resolutions...
Thanks and Regards
Abbas Electricwala
You can disable caching for the page:
<%# OutputCache Location="None" VaryByParam="None" %>
or add this to your page response:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

How to make an ASP.NET TextBox fire it's onTextChanged event fire in an AJAX UpdatePanel?

I am trying to get an textBox to fire it's onTextChanged event every time a keystroke is made rather than only firing only when it loses focus. I thought that adding the AsyncPostBackTrigger would do this but it's still not working. Is what I'm trying to do even possible? The code is below:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Items.aspx.cs" MasterPageFile="~/MMPAdmin.Master" Inherits="MMPAdmin.Items" %>
<asp:Content ID="content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp:ScriptManager ID="sm_Main" runat="server" />
<div style="left:10px;position:relative;width:100%;overflow:hidden">
<asp:UpdatePanel ID="up_SearchText" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tb_Search" EventName="TextChanged" />
</Triggers>
<ContentTemplate>
<div style="position:relative;float:left">
<b style="font-size:xx-large">Items</b>(Add New)
</div>
<div style="right:25px;position:absolute; top:30px">
Search: <asp:TextBox ID="tb_Search" runat="server" Width="200" OnTextChanged="UpdateGrid" AutoPostBack="true" />
</div>
<br />
<div>
<asp:GridView runat="server" AutoGenerateColumns="true" ID="gv_Items" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
You need to call the _postback() function for your textbox control when the onkeyup is raised using javascript.
However, since your textbox is inside your update panel, the textbox will get re-rendered everytime the user hits a key, causing the cursor to loose focus.
This will not be usable unless you get your textbox out of the the updatepanel. That may work out for you, as update panels tend to be a bit slow, you may still have usability issues. - I would suggest using an autocomplete component.
P.S : there is one in the asp.net control toolkit or you could use the jquery autocomplete plugin which I have found to be a bit better.
AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"
Both events are required to trigger text change event.
Dont Need use AJAX controls for checking the availability.. Its is not Compulsory to use it AJAX Controls..
We can use the Following Code..
<iframe>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
RequiredFieldValidator1.ErrorMessage = "";
Label1.Text = "";
string name = TextBox1.Text.ToString();
string constr = "data Source=MURALY-PC\\SQLEXPRESS; database=Online; Integrated Security=SSPI";
SqlConnection con = new SqlConnection(constr);
con.Open();
string query = "select UserName from User_tab where UserName='" + name + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label1.Text = "UserName Already Exists";
}
else
{
Label1.Text = "";
Label1.Text = "UserName Available";
}
con.Close();
}
</iframe>
All the AsyncPostBackTrigger does is make sure only that portion of the page refreshes when the event is fired, it does not change when the event is fired.
I think it's possible to do what you want, but you'd need to write some javascript code to manually fire the event... and I don't even want to think about making that work.

ASP.NET 2.0 Asynchronous User Control Not Working

I'm trying to get a user control working asynchronously, yet no matter what I do it continues to work synchronously. I've stripped it down to its bare minimum as a test web application. This would be the user control:
<%# Control Language="C#" %>
<script runat="server">
SqlConnection m_oConnection;
SqlCommand m_oCommand;
void Page_Load(object sender, EventArgs e)
{
Trace.Warn("Page_Load");
string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true";
string strSQL = "waitfor delay '00:00:10'; select * from MyTable";
m_oConnection = new SqlConnection(strDSN);
m_oCommand = new SqlCommand(strSQL, m_oConnection);
m_oConnection.Open();
Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true));
Page.ExecuteRegisteredAsyncTasks();
}
IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state)
{
Trace.Warn("BeginHandler");
return m_oCommand.BeginExecuteReader(cb, state);
}
void EndHandler(IAsyncResult ar)
{
Trace.Warn("EndHandler");
GridView1.DataSource = m_oCommand.EndExecuteReader(ar);
GridView1.DataBind();
m_oConnection.Close();
}
void TimeoutHandler(IAsyncResult ar)
{
Trace.Warn("TimeoutHandler");
}
</script>
<asp:gridview id="GridView1" runat="server" />
And this would be the page in which I host the control three times:
<%# page language="C#" trace="true" async="true" asynctimeout="60" %>
<%# register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %>
<html>
<body>
<form id="form1" runat="server">
<uc:mycontrol id="MyControl1" runat="server" />
<uc:mycontrol id="MyControl2" runat="server" />
<uc:mycontrol id="MyControl3" runat="server" />
</form>
</body>
</html>
The page gets displayed without errors, but the trace at the bottom of the page shows each control instance is processed synchronously. What am I doing wrong? Is there a configuration setting somewhere I'm missing?
Looks like I can answer my own question. The user control should not be calling Page.ExecuteRegisteredAsyncTasks. By doing that, the control was adding the async task, running it, and waiting for it to complete.
Instead, each instance of the user control should call only Page.RegisterAsyncTask. After each control instance has done this the page automatically calls RegistereAsyncTask running all three registered async tasks simultaniously.
So here is the new user control:
<%# Control Language="C#" %>
<script runat="server">
SqlConnection m_oConnection;
SqlCommand m_oCommand;
void Page_Load(object sender, EventArgs e)
{
Trace.Warn(ID, "Page_Load - " + Thread.CurrentThread.GetHashCode().ToString());
string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true";
string strSQL = "waitfor delay '00:00:10'; select * from TEProcessedPerDay where Date > dateadd(day, -90, getutcdate()) order by Date asc";
m_oConnection = new SqlConnection(strDSN);
m_oCommand = new SqlCommand(strSQL, m_oConnection);
m_oConnection.Open();
Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true));
}
IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state)
{
Trace.Warn(ID, "BeginHandler - " + Thread.CurrentThread.GetHashCode().ToString());
return m_oCommand.BeginExecuteReader(cb, state);
}
void EndHandler(IAsyncResult ar)
{
Trace.Warn(ID, "EndHandler - " + Thread.CurrentThread.GetHashCode().ToString());
GridView1.DataSource = m_oCommand.EndExecuteReader(ar);
GridView1.DataBind();
m_oConnection.Close();
}
void TimeoutHandler(IAsyncResult ar)
{
Trace.Warn(ID, "TimeoutHandler - " + Thread.CurrentThread.GetHashCode().ToString());
}
</script>
<asp:gridview id="GridView1" runat="server" />
And the unchanged page that creates three instances of the control:
<%# page language="C#" async="true" trace="true" %>
<%# register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %>
<html>
<body>
<form id="form1" runat="server">
<uc:mycontrol id="MyControl1" runat="server" />
<uc:mycontrol id="MyControl2" runat="server" />
<uc:mycontrol id="MyControl3" runat="server" />
</form>
</body>
</html>
If I may add a little to the above post, we should not call the ExecuteRegisteredAsyncTassk explicitly unless there is a compelling reason. once you register the async task, the ASP.NET framework will execute all these tasks right after the OnPrerender event of the page lifecycle.
An example for the usage of ExecuteRegisteredAsyncTasks could be;
Sometimes you may need to ensure that several async operations are completed before calling another async task. in a situation like this it is justifiable to use ExecuteRegisteredAsyncTasks.

Resources