How to get HTML for ASP.NET webrequest - asp.net

I want to get the source code of this page.
string adres = "https://betorder.com/Sports.html";
WebRequest gelenIstek = HttpWebRequest.Create(adres);
WebResponse gelenCevap;
using (gelenCevap = gelenIstek.GetResponse())
{
using (StreamReader donenDeger = new StreamReader(gelenCevap.GetResponseStream()))
{
string gelenBilgi = donenDeger.ReadToEnd();
string gonder = gelenBilgi;
div.InnerHtml = gonder;
}
}

Use http schema to make a request and add the html to some div, like below:
ASPX page
<form id="form1" runat="server">
<asp:Panel runat="server" ID="pnlHtml"></asp:Panel>
</form>
Your code-behind:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var adres = "http://betorder.com/Sports.html";
var gelenIstek = HttpWebRequest.Create(adres);
WebResponse gelenCevap;
using (gelenCevap = gelenIstek.GetResponse())
{
using (var donenDeger = new StreamReader(gelenCevap.GetResponseStream()))
{
var response = donenDeger.ReadToEnd();
var divcontrol = new HtmlGenericControl
{
TagName = "div",
InnerHtml = response
};
pnlHtml.Controls.Add(divcontrol);
}
}
}

Related

Signalr and Devexpress

I want to create a grid and automatic update it, when data changes in the database. It works with a simple table control.
public partial class index : System.Web.UI.Page
{
static string connectionString = #"Data Source=*******;initial catalog=Test;persist security info=True; Integrated Security=SSPI;";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static IEnumerable<Person> GetData()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
command.Notification = null;
SqlDependency.Start(connectionString);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new Person(x.GetInt32(0), x.GetString(1))).ToList();
}
}
}
private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
public void FillGrid()
{
List<Person> persons = new List<Person>();
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlDataReader rdr = command.ExecuteReader())
{
while (rdr.Read())
{
var id = rdr.GetInt32(0);
var name = rdr.GetString(1);
persons.Add(new Person(id, name));
}
}
}
}
grid.DataSource = persons;
grid.DataBind();
}
}
public class MyHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
And the apsx Page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.myHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData()
{
var $tbl = $('#tbl');
$.ajax({
url: '/index.aspx/GetData',
contentType: 'application/json;charset=utf-8',
datatype: 'json',
type: 'POST',
success: function (data) {
if (data.d.length > 0) {
var newdata = data.d;
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th></tr>');
var rows = [];
for (var i = 0; i < newdata.length; i++) {
rows.push(' <tr><td>' + newdata[i].Id + '</td><td>' + newdata[i].Name + '</td><td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tbl"></table>
<dx:ASPxGridView ID="grid" runat="server"></dx:ASPxGridView>
</div>
</form>
</body>
</html>
However I want to use a Devepress Aspxgridview. The Devexpress Site states they don't support SignalR. However since the Javascript function is triggered when data changes in the database, is it possible somehow to force the client to get the data from the server? Force a postback and/or call the FillGrid method? ( To create the grid from js is not possible since the AspxgridView Control is much more complicated).
SOURCE: https://www.youtube.com/watch?v=30m-7wpmbrc
Although SignalR is not supported out of the box, it should be possible to manually notify the server side about the update using the existing API. You can send a callback to the server using the ASPxClientGridView.PerformCallback method, and handle the server side ASPxGridView.CustomCallback event to reload data from the SQL server.

What is the Most simple way to store image in Data base in MVC

ok, So criticism apart, I'm New to MVC, my Point is how can i store an image in data base that will be uploaded by user.
i'm Creating a simple blog via MVC And what i Want is A form Same like WordPress "ADD NEW POST". Where user can enter title,TAGS,Headings, But What my Part is, I have to store all of them in DB. i can Do the CSS part, but i'm struck in Functionality that will be Getting all values From user (view) And Then Storing it in database also Displaying it.
below is my google-d Code for View in MVC.
#model SimpleBlogg.Models.PostContent
#{
ViewBag.Title = "AddContentToDB";
}
<div class="UploadPicForm" style="margin-top:20px;">
#using (Html.BeginForm("AddContentToDB", "AddNewPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}
</div>
Save as Base64 string:
static string base64String = null;
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
public System.Drawing.Image Base64ToImage()
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
protected void ImageToBase_Click(object sender, EventArgs e)
{
TextBox1.Text = ImageToBase64();
}
protected void BaseToImage_Click(object sender, EventArgs e)
{
Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));
Image1.ImageUrl = "~/Images/Hello.jpg";
}
source: http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64-string-to-image

Asp.net button click event not working

I have a table which is populated programatically. Buttons are also created within the table as it's built. But i can't seem to find a way to get my button click event to work. It just doesn't seem to fire the event.
Any ideas please? I'm new to asp.net.
Here is the code:
using Parse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace FrogPointCMS
{
public partial class Beacons : System.Web.UI.Page
{
string merchantName;
string myMerchantID;
ParseObject merchantObject;
protected void Page_Load(object sender, EventArgs e)
{
merchantName = Request.QueryString["user"];
myMerchantID = Request.QueryString["merchantID"];
// merchantObject = (ParseObject)Session["Merchant"]; // this works to retrieve objects from another screen
merchantObject = Global.merchantObjectStatic;
if (merchantObject != null)
{
getBeacons();
}
}
public async void getBeacons()
{
MyParseQueries myQuery = new MyParseQueries();
var myBeacons = await myQuery.getMyBeacons(); // get all the beacons
foreach (ParseObject beacon in myBeacons)
{
string aliasName = "";
string offerType = "N/A";
string offerTitle = "";
string offerDescription = "";
var merchantOb = beacon.Get<ParseObject>("merchantObjectId");
var merchantID = merchantOb.ObjectId;
if (merchantID == myMerchantID)
{
if (beacon.ContainsKey("contentObjectID"))
{
ParseObject content = beacon.Get<ParseObject>("contentObjectID"); // get the content object from parse.
offerType = content.Get<string>("offerType");
offerTitle = content.Get<string>("offerTitle");
offerDescription = content.Get<string>("offerDescription");
}
aliasName = beacon.Get<string>("aliasName");
//HERE IS THE PROBLEM AREA WITH THE BUTTON CREATION AND CLICK EVENT
Button assignNameBtn = new Button();
assignNameBtn = new Button();
assignNameBtn.ID = "assignName";
assignNameBtn.Text = "Assign Name";
assignNameBtn.Click += new System.EventHandler(this.assignNameBtn_Click);
// assignNameBtn.OnClientClick = "buttonClickTest2()"; //this works to trigger the java in the html page
// assignNameBtn.OnClientClick = "assignNameBtn_Click()";
Button assignActionBtn = new Button();
assignActionBtn.ID = "assignAction";
assignActionBtn.Text = "Assign Action";
var tr = new HtmlTableRow();
var checkBox = new HtmlTableCell();
var tableCellName = new HtmlTableCell();
var tableCellButton1 = new HtmlTableCell();
var tableCellButton2 = new HtmlTableCell();
var tableCellAction = new HtmlTableCell();
checkBox.InnerHtml = "<input type=\"checkbox\"/>";
tableCellName.InnerText = aliasName;
tableCellButton1.Controls.Add(assignNameBtn);
tableCellButton2.Controls.Add(assignActionBtn);
tableCellAction.InnerText = offerType + " - " + offerTitle + " - " + offerDescription;
tr.Cells.Add(checkBox);
tr.Cells.Add(tableCellName);
tr.Cells.Add(tableCellButton1);
tr.Cells.Add(tableCellAction);
tr.Cells.Add(tableCellButton2);
beaconTable.Rows.Add(tr);
}
}
}
void assignNameBtn_Click(object sender, EventArgs e)
{
var btn = (Button)sender; // testing
HtmlTableRow row = (HtmlTableRow)btn.NamingContainer; //testing
// System.Diagnostics.Debug.WriteLine("Clicked");
// assignNameBtn.OnClientClick = "buttonClickTest2()";
Response.Write("It worked");
}
}
}
The table in question startes like this in the .aspx file
<form id="mainform" runat="server">
<table border="0" cellpadding="0" cellspacing="0" id="beaconTable" runat="server" >
<tr>
<th class="table-header-check"><a id="toggle-all" ></a> </th>
<th class="table-header-repeat line-left minwidth-1">Beacon Name </th>
<th class="table-header-repeat line-left minwidth-1" style="width: 113px"></a></th>
<th class="table-header-repeat line-left">Assigned Action</th>
<th class="table-header-repeat line-left"></a></th>
</tr>
You should use without parentheses
assignNameBtn.Click += assignNameBtn_Click;

How to pass image to Eval method from handler.ashx to imageurl?

I want to retrieve image from database and display in an aspx page. I use Linq to SQL. And a Generic handler.
Handler2.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
int id;
string sid = context.Request.QueryString["id"];
if (int.TryParse(sid, out id))
{
Stream strm = getImage(id);
byte[] buffer = new byte[4096];
int i = strm.Read(buffer, 0, 4096);
while (i > 0)
{
context.Response.OutputStream.Write(buffer, 0, 4096);
i = strm.Read(buffer, 0, 4096);
}
}
else
{
//
}
}
}
public Stream getImage(int id)
{
using (DummyDBEntities cntx = new DummyDBEntities())
{
var db = from c in cntx.Images
where c.imageId == id
select c.imageData;
MemoryStream ms = new MemoryStream();
byte[] byteArray = new byte[db.ToArray().Length];
ms.Write(byteArray, 0, db.ToArray().Length);
return new MemoryStream(byteArray);
}
}
And a button control in Default.aspx page when I click, redirects to handler1.ashx. Gets the id of image from database and supposed to Show it in Default.aspx asp:image control
protected void btnGetID_Click(object sender, EventArgs e)
{
int id=Convert.ToInt32(txtGetID.Text);
Response.Redirect("Handler2.ashx?id="+id);
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
}
How do i supposed to write Eval method and the querystring to pass the image to imageurl?
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
Please help, thanks.
I hope I understood your problem right.
You want to display the image from your handler in the Image1. For that you can just do the following
Image1.ImageUrl = ResolveUrl("~/Handler2.ashx?id=" + id);

How do i maintain the state of my Html Controls on postback with JQuery and JSON?

I have a form with a collection of Html and ASP Server Controls. Im using JSON to preload some drop-down lists.
I want to maintain the states of these drop-down lists on postback. Im quite new to JSON, can anyone help?
If you can use HTML select element instead. Thus, you can get the selected value of select element on the server and register an hidden field to maintain the value. While you are loading the items so you can check the registered hidden field to retrieve the previous selected value.
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script type="text/javascript">
var sv = document.getElementById("SelectedValue");
var v = (sv != null && sv.value != "" ? sv.value : null);
var o = document.getElementById("DropDownList1");
for (var i = 0; i < 10; i++) {
var item = document.createElement("option");
item.innerHTML = "item" + i;
item.setAttribute("value", "item" + i);
if (("item" + i) == v)
item.setAttribute("selected", "selected");
o.appendChild(item);
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
firstly, you should create an HTTPHandler to generate the JSON and get it using getJSON method from jQuery. Lastly, you have to get the selected value on the Load event of the page and maintain the value to a HiddenField for the next time. The following code demonstares it.
public class JsonGenerator : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
JavaScriptSerializer ser = new JavaScriptSerializer();
context.Response.Write(ser.Serialize(new object[]
{
new { Text = "Item1", Value = 1 },
new { Text = "Item2", Value = 2 } ,
new { Text = "Item3", Value = 3 }
}));
}
public bool IsReusable
{
get
{
return false;
}
}
}
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("JsonGenerator.ashx",
null,
function(r) {
var ddl = $("#DropDownList1"), hf = $("#SelectedValue");
$.each(r, function(k, v) {
ddl.append("<option value='" + v.Value + "'>" + v.Text + "</option>");
});
if (hf.length > 0)
ddl.children("[value='" + hf.val() + "']").attr("selected", "selected");
});
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
Don't let the browser do the post, do it yourself with jQuery. On the callback replace a results div with the returned html.
Assuming you've marked your form with class="ajaxform" and your results div with id="results" then something like this (not fully tested)...
// Submit form.ajaxform
// Get the returned html, and get the contents of #results and
// put it into this page into #results
var submit = function() {
$.ajax({
type: "POST",
data: $("form.ajaxform").serialize(),
success: function(data, textStatus) {
$("#results").replaceWith($("#results", $(data)));
}
});
};
$("form.ajaxform input[type=submit]").click(submit);
// I think you'll need this as well to make sure the form doesn't submit via the browser
$("form.ajaxform").submit(function () { return false; });

Resources