I am passing the value of doctype variable from my c# code to javascript.
Now I am unable to find any file based on the inputs.
Does the naming convention has to be exact?
Edit: Added current version with DocType hardcoded in onclick javascript page.
Variable:
DOC_TYPE in ascx.cs
DocType in ascx
AllGroup_UserControl.ascx.cs:
public partial class AllGroup_UserControl : UserControl
{
ProductProvider provider = new ProductProvider();
TBL_USER_PROFILEProvider uprovider = new TBL_USER_PROFILEProvider();
DocumentProvider dprovider = new DocumentProvider();
int DOC_TYPE;
// Document Types
const int G1_DOC_TYPE = 1;
const int G2_DOC_TYPE = 2;
const int G3_DOC_TYPE = 3;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = SPContext.Current.Web.CurrentUser.Name;
TBL_USER_PROFILE p = uprovider.GetUser(userName);
if (p != null)
{
List<string> G1List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 1");
List<string> G2List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 2");
List<string> G3List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 3");
if (G1List.Count != 0)
{
DOC_TYPE = G1_DOC_TYPE;
}
else if (G2List.Count != 0)
{
DOC_TYPE = G2_DOC_TYPE;
}
else if (G3List.Count != 0)
{
DOC_TYPE = G3_DOC_TYPE;
}
else
{
Response.Redirect("/SitePages/AccessDeny.aspx");
}
Page.DataBind();
}
}
}
public int DocType
{
get
{
return DOC_TYPE;
}
}
//rest of the code
AllGroup_UserControl.ascx:
<a href="#" runat="server" onclick="openDialog('/SitePages/FileDownload.aspx?DocType=<%# DocType %>&ItemNo=<%#Eval("StoreItemNo")%>&CustomerID=<%#Eval("CustomerID")%>')">
ADDED:
Working code with docType hardcoded:
Group1_UserControl.ascx.cs: (with doctype hardcoded)
public partial class Group1_UserControl : UserControl
{
ProductProvider provider = new ProductProvider();
TBL_USER_PROFILEProvider uprovider = TBL_USER_PROFILEProvider();
DocumentProvider dprovider = new DocumentProvider();
int docType = 100;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = SPContext.Current.Web.CurrentUser.Name;
TBL_USER_PROFILE p = uprovider.GetUser(userName);
if (p != null)
{
List<string> alist = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 1");
if (alist.Count == 0)
Response.Redirect("/SitePages/AccessDeny.aspx");
}
}
}
}
Group1_UserControl.ascx: (with doctype hardcoded)
<a href="#" onclick="openDialog('/SitePages/FileDownload.aspx?DocType=100&ItemNo=<%#Eval("StoreItemNo")%>&CustomerID=<%#Eval("CustomerID")%>')">
You will have to use AJAX for that. Then you can pass values from backend to JavaScript.
Below is an example,
Client Side Script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/YourFunctionHere",
data: '{name: "' + DocType + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
The Web Method
[System.Web.Services.WebMethod]
public static string YourFunctionHere(string name)
{
return "return value here";
}
Related
I followed the video and I can display a real-time value using SignalR in tag. But I don't know what signalr script code do so when I add a similar code to display 2 real-time values in 2 tags , it just displays one. I really hope someone will know clearly about that SignalR and please tell me something's wrong in my project? Thank you so much!
My code in index.html :
<script type="text/javascript">
$(function () {
//Proxy created on the fly
var cus = $.connection.cusHub;
//Declare a function on the job hub so the server can invoke
cus.client.displayValue = function () {
getData();
getData1();
};
//Start the connection
$.connection.hub.start();
getData();
getData1();
});
function getData() {
var $tbl = $('#tblValue');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
model.Value
);
});
}
});
}
function getData1() {
var $tbl = $('#tblValue1');
$.ajax({
url: $("#Get1").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus1, function (i1, model) {
$tbl.append
(
model.Value
);
});
}
});
}
</script>
Tag h2 with id="tblValue"> runs and has its value but not with id="tblValue1" :
<div class="col-md-6 col-lg-3">
<div class="statistic__item statistic__item--orange">
<h2 id="tblValue" class="number">
</h2>
<span class="desc">MONTHLY COST</span>
<div class="icon">
<i class="zmdi zmdi-money"></i>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="statistic__item statistic__item--blue">
<h2 id="tblValue1" class="number">1,086</h2>
<span class="desc">YEARLY USAGE</span>
<div class="icon">
<i class="zmdi zmdi-time"></i>
</div>
</div>
</div>
My code in Controller ( I just copy paste from function JsonResult Get ) :
public JsonResult Get()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand value1 = new SqlCommand(#"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM1'", connection))
{
value1.Notification = null;
SqlDependency dependency = new SqlDependency(value1);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = value1.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult Get1()
{
using (var connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection1.Open();
using (SqlCommand value1 = new SqlCommand(#"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM2'", connection1))
{
value1.Notification = null;
SqlDependency dependency1 = new SqlDependency(value1);
dependency1.OnChange += new OnChangeEventHandler(dependency_OnChange1);
if (connection1.State == ConnectionState.Closed)
connection1.Open();
SqlDataReader reader1 = value1.ExecuteReader();
var listCus1 = reader1.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus1 = listCus1 }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
private void dependency_OnChange1(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
My code in CusHub.cs :
public class CusHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CusHub>();
context.Clients.All.displayValue();
}
}
I have an ASP.NET Web forms site with C# code behind called from VS2013 running under Win 10 and viewed in Google Chrome. I am trying to call a C# function from Javascript in the Default.aspx markup as shown below
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
<img id="imgPaste" src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
<asp:Button Text="Save" runat="server" OnClick="Save" />
<input id="Text1" type="text" name ="ImageData" hidden="hidden" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('txtPaste').focus();
document.getElementById('txtPaste').onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items));
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
document.getElementById("imgPaste").src = event.target.result;
document.getElementById("Text1").value = event.target.result;
PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
};
reader.readAsDataURL(blob);
}
}
};
function onSuccess(result) {
alert("Success! " + result);
}
function onFailure(result) {
alert("Failed! " + result);
}
</script>
</asp:Content>
The PageMethod is defined in Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Save(object sender, EventArgs e)
{
string str = Request.Form["ImageData"];
SaveImg(str);
}
[WebMethod]
public static bool SaveImg(string str)
{
try
{
string imageData = str.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(imageData);
string filePath = #"C:\Windows\Temp\File.jpg";
if (File.Exists(filePath)) File.Delete(filePath);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
return false;
}
catch (Exception Ex)
{
return true;
}
}
}
When I click in txtPaste and paste an image, the image appears in imgPaste OK and can be downloaded as a file by clicking by the Save button to execute the SaveImg function.
I am trying to create the file only by pasting an image, without clicking the Save button by defining SaveImg as Web Method and calling PageMethods.SaveImg after filling the Image control. The call to SaveImg shows and alert as specified in the OnSuccess function, but SaveImg is not executed - breakpoints set in the function are not hit on the Paste event, although they are if the Save button is clicked. The same behaviour is shown if the web site is viewed in Firefox.
ScriptManager in the Master.aspx file has EnablePageMethods set to True.
I have tried the following to make SaveImg execute on the paste event without success:
1) Commenting out settings.AutoredirectMode in Route.Config made PageMethods.SaveImg return a Fail status.
2) Commenting one or both lines in global.asax:
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
3) Using an AJAX function as shown below. sParam was defined as event.target.result.toString() and the call replaced the PageMethods.SaveImg call
function showDetail(sParam) {
$.ajax({
type: "POST",
url: "Default.aspx/SaveImg",
data: "{'str': '" +sParam +"'}", // passing the parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(retValue) {
// Do something with the return value from.Net method
}
});
Calling a C# function from Javascript in ASP.Net can be done by placing the C# function in the click event of a control and then calling the control's click event from Javascript as shown below for the above scenario:
JavaScript in page markup:
%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="txtPaste" name="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
<img id="imgPaste" src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
<asp:Button Text="Save" runat="server" OnClick="cmdSave_Click" ID="cmdSave" />
<input id="Text1" type="hidden" name ="ImageData" hidden="hidden" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('txtPaste').focus();
document.getElementById('txtPaste').onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items));
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
document.getElementById("imgPaste").src = event.target.result;
document.getElementById("Text1").value = event.target.result;
//PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
document.getElementById("txtPaste").value = "Image Pasted"
document.getElementById("cmdSave").click();
};
reader.readAsDataURL(blob);
}
}
};
</script>
C# code:
protected void cmdSave_Click(object sender, EventArgs e)
{
string str = Request.Form["ImageData"];
SaveImg(str);
}
public bool SaveImg(string str)
{
try
{
string imageData = str.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(imageData);
string filePath = #"C:\Windows\Temp\File.jpg";
if (File.Exists(filePath)) File.Delete(filePath);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
return false;
}
catch (Exception Ex)
{
return true;
}
}
This is my front-end:
ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id
String strApplication1 = Details.CommandArgument.ToString();
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onClick", "SelectRow()");
This is my back-end:
<script type="text/javascript">
function SelectRow() {
var strApplication1 = '<%=strApplication1%>'
if (strApplication1 == "IT Application Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "IT Account Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Change Control Management")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Backup & Restore")
{
window.open('http://.aspx', '_blank');
}
}
</script>
I want to pass String Argument to javascript function, but I got error that strApplication1 doesn't exist in the current context.
You need to make strApplication1 a public property on your page class. Currently, it is just an internal variable.
Something like:
public partial class YourPage : System.Web.UI.Page
{
public string strApplication1 {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
//Your page logic
}
//Looks like you set the variable in an onDatabound or similar.
//So use this where you currently set the variable
strApplication1 = Details.CommandArgument.ToString();
}
I submit a form to take objects from database.
I need to add varbinary(MAX) type (image) column inside json string, and send it via WebMethod to Ajax to display in the page, with the rest of the properties of the object. So in the class its string type instead of byte[] type.
In the encoding part I receive Javascript runtime Error:
Unable to get property 'pingInterval' of undefiened null reference.
<form id="form1" runat="server">
Arrival:
<input type="text" id="txtArrival" />
departure:
<input type="text" id="txtDeparture" />
Nob:
<input type="text" id="txtNob" />
<input type="button" id="btnSubmit" value="Get Rooms" />
</form>
Class:
public int ID { get; set; }
public string RoomType { get; set; }
public string RoomNumber { get; set; }
public string RoomTitle { get; set; }
public decimal Price { get; set; }
public string ServiceName { get; set; }
public string Photo { get; set; }
Ajax:
$(document).ready(function () {
$(function () {
$("#btnSubmit").click(function () {
var arrival = $("#txtArrival").val();
var departure = $("#txtDeparture").val();
var nob = $("#txtNob").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm2.aspx/GetRooms",
data: "{'arrival':'" + arrival + "','departure':'" + departure + "','nob':'" + nob + "'}",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (result) {
alert("Error!");
}
});
});
});
});
WebMethod:
[WebMethod]
public static string GetRooms(string arrival, string departure, string nob)
{
string val = "";
DateTime d1 = Convert.ToDateTime(arrival);
DateTime d2 = Convert.ToDateTime(departure);
int noib=Convert.ToInt32(nob);
var jSerialize = new JavaScriptSerializer();
List<Room> lst = new List<Room>();
using (SqlConnection con = new SqlConnection("Server=.;Database=ResDB;Trusted_Connection=True;"))
{
using (SqlCommand cmd = new SqlCommand("roomsAvailable", con))
{
cmd.Parameters.AddWithValue("#arr", d1);
cmd.Parameters.AddWithValue("#dep", d2);
cmd.Parameters.AddWithValue("#nob", noib);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader sr = cmd.ExecuteReader(); ;
while (sr.Read())
{
Room r = new Room();
r.ID = Convert.ToInt32(sr["ID"]);
//objects..
if (sr["Photo"] != System.DBNull.Value)
{
byte[] p = (byte[])sr["Photo"];
r.Photo = Convert.ToBase64String(p);// error here
}
lst.Add(r);
val = jSerialize.Serialize(lst);
}
con.Close();
}
}
return val;
}
Error is in this statement in WebMethod:
r.Photo = Convert.ToBase64String(p);
After changing JQuery hosted file to newer version,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
Error disappeared!
I am trying to create a demo of Group Chat using reverse ajax in Spring. I am using Spring 3.2.0.RELEASE version.
I am using DeferredResult to perform reverse ajax in my controller. Following is the snippet of my Controller class.
#Autowired
private AsyncRepository asyncRepository;
Map<Integer, List<DeferredResult<String>>> watchers = new ConcurrentHashMap<Integer, List<DeferredResult<String>>>();
#RequestMapping(value="/asyncRequest/getMessages/{id}", method=RequestMethod.GET)
#ResponseBody
public DeferredResult<String> getMessages(final #PathVariable("id") Integer id){
final DeferredResult<String> deferredResult = new DeferredResult<String>(null, Collections.emptyList());
if(watchers.containsKey(id)) {
watchers.get(id).add(deferredResult);
} else {
watchers.put(id, new ArrayList<DeferredResult<String>>());
watchers.get(id).add(deferredResult);
}
deferredResult.onCompletion(new Runnable() {
#Override
public void run() {
watchers.get(id).remove(deferredResult);
}
});
return deferredResult;
}
#RequestMapping(value="/asyncRequest/setMessages/{id}/{message}", method=RequestMethod.GET)
#ResponseBody
public String setMessage(#PathVariable("id") Integer id, #PathVariable("message") String message) {
asyncRepository.setMessage(id, message);
return "";
}
#Scheduled(fixedRate=1000)
public void processQueues() {
for (Map.Entry<Integer, Queue<AsyncDataBean>> entry : asyncRepository.getAsyncBeans().entrySet()) {
while(entry != null && entry.getValue() != null && !entry.getValue().isEmpty()) {
AsyncDataBean asyncDataBean = entry.getValue().poll();
for (DeferredResult<String> deferredResult : watchers.get(asyncDataBean.getId())) {
deferredResult.setResult(asyncDataBean.getMessage());
}
}
}
}
And below is the Repository class which holds the Map of GroupID and its relevant messageQueue. And it also has the functions for getting and setting the messages for relevant group id.
#Repository
public class AsyncRepository {
private Map<Integer, Queue<AsyncDataBean>> asyncBeans = new ConcurrentHashMap<Integer, Queue<AsyncDataBean>>();
public String getMessages(Integer id) {
StringBuilder stringBuilder = new StringBuilder();
while (asyncBeans.get(id) != null && !asyncBeans.get(id).isEmpty()) {
stringBuilder.append(asyncBeans.get(id).poll().getMessage()).append("~");
}
return stringBuilder.toString();
}
public void setMessage(Integer id, String message) {
if(asyncBeans.containsKey(id)) {
asyncBeans.get(id).add(new AsyncDataBean(id, message));
} else {
Queue<AsyncDataBean> messageQueue = new ConcurrentLinkedQueue<AsyncDataBean>();
messageQueue.add(new AsyncDataBean(id, message));
asyncBeans.put(id, messageQueue);
}
}
public Map<Integer, Queue<AsyncDataBean>> getAsyncBeans() {
return asyncBeans;
}
public void setAsyncBeans(Map<Integer, Queue<AsyncDataBean>> asyncBeans) {
this.asyncBeans = asyncBeans;
}
}
And below is the data bean I am using to store each message with its group id.
public class AsyncDataBean {
private Integer id;
private String message;
public AsyncDataBean() {
}
public AsyncDataBean(int id, String message) {
this.setId(id);
this.setMessage(message);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And then comes the jsp page for group chat. which looks like below.
<script type="text/javascript">
var messagesWaiting = false;
function getMessages(){
if(!messagesWaiting){
$.ajax({ url: "${pageContext.servletContext.contextPath}/asyncRequest/getMessages/${id}",
dataType:"text",
success: function(data,textStatus,jqXHR) {
if(textStatus == 'success'){
messagesWaiting = false;
var arr = data.split("~");
for(var i=0; i<arr.length; i++)
{
try
{
if(arr[i] != '') {
$("#txtaMessages").val($("#txtaMessages").val() + "\n\n" + arr[i]);
document.getElementById("txtaMessages").scrollTop = document.getElementById("txtaMessages").scrollHeight;
}
}
catch(e){
alert(e.message);
}
}
}
},
complete: function(j) {
},
error: function(xhr) {
}
});
messagesWaiting = true;
}
}
setInterval(getMessages, 1000);
getMessages();
function sendMessage() {
var xmlhttp1 = new XMLHttpRequest();
xmlhttp1.open("GET", '${pageContext.servletContext.contextPath}/asyncRequest/setMessages/${id}/' + $("#txtMessage").val(), true);
xmlhttp1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp1.send();
$("#txtMessage").val("");
$("#txtMessage").focus();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<table>
<tr>
<td>Messages :: </td>
<td>
<textarea cols="100" rows="10" id="txtaMessages"></textarea>
</td>
</tr>
<tr>
<td>Send Message :: </td>
<td><input type="text" id="txtMessage"/></td>
</tr>
<tr>
<td><input type="button" value="Send" onclick="sendMessage();"/></td>
</tr>
</table>
</body>
</html>
That is what I have coded till now to get this working. And everything is working finw in FF and Chrome. But in IE it is not working as expected. The request is never gets hold on the server and it always gets executed every second as configured in the javascript code. And it always returns the same result as previous. I have tried to use several other methods to send ajax request for IE but its not working. Can anyone get it working for me?
Since everything works fine in FF and Chrome, I suspect the problem is with javascript code to send the request to get messages.
Please help me.
Thanks in advance.
This is very very frustrating.
To get this thing work properly in IE I need to set cache:false attribute in the ajax request I am creating with jquery for getMessages. Otherwise IE will not hold the request in pending status and always returns back with the old response text.
Its a very big issue with IE. I hope no one face the problem again or finds this answer as early as possible.
:)