how to download excel file for client machine? - javascript

1.Input type button show to client-side and click on this button, call the javascript method.
<input type="button" id="btnImportExcel" name="btnImportExcel" value="Export to Excel" class="btn btn-default" onclick="Export_Excel();" style="width: 10%" />
This javascript method retrieves the following parameters value and passes to the code behind web method.
function Export_Excel() {
debugger;
var Showdata = {};
Showdata.startdate = $("[id*=txtbegindate]").val();
Showdata.enddate = $("[id*=txtenddate]").val();
if ($('input[id*=RadioButton1]').is(":checked")) {
Showdata.radio = 1;
}
else if ($('input[id*=RadioButton2]').is(":checked")) {
Showdata.radio = 2;
}
$('#divProgress').show();
$.ajax({
type: "POST",
url: "Agent_HomePage.aspx/efgh",
data: '{xyz: ' + JSON.stringify(Showdata) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert("Error");
}
});
$('#divProgress').hide();
$('div#OuterShowImageEdu').on('dialogclose', function (event) {
alert('closed');
});
}
we create a web method and using the class object retrieve all parameters values and call the WCF service and pass parameters value.
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static string efgh(Showdata xyz)
{
string result = "";
DataTable dt;
DataSet ds = new DataSet();
string filename = string.Empty;
try
{
string Sdate = string.Format("{0:dd-MMM-yyyy}", xyz.startdate);
string Edate = string.Format("{0:dd-MMM-yyyy}", xyz.enddate);
List<object> listfinal = new List<object>();
HelloServiceClient client = new HelloServiceClient();
string date = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
var path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
if (xyz.radio == "1")
{
dt = client.OracleConert_Excel(Convert.ToDateTime(Sdate), Convert.ToDateTime(Edate), dec_cod, 1);
filename = path + "\\Carrier_House_Manifest" + "_" + date + ".xls";
ExporttoExcel(dt, filename);
}
else { }
}
catch (Exception ex)
{ result = ex.Message; }
return result;
}
After WCF services execute successfully and return the result then result convert to excel file.
private static void ExporttoExcel(DataTable dt, string fileName)
{
int i = 0;
int j = 0;
string data = null;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i1 = 0; i1 < dt.Columns.Count; i1++)
{
xlWorkSheet.Cells[1, i1 + 1] = dt.Columns[i1].ColumnName;
xlWorkSheet.get_Range("A1", "AA1").Font.Bold = true;
xlWorkSheet.get_Range("A1", "AA1").ColumnWidth = "22";
xlWorkSheet.get_Range("A1", "AA1").Borders.Weight = 4d;
//xlWorkSheet.get_Range("A1", "AA1").Interior.Color = Excel.XlRgbColor.rgbLightSteelBlue;
}
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
int s = i + 1;
for (j = 0; j <= dt.Columns.Count - 1; j++)
{
data = dt.Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[s + 1, j + 1] = data;
}
}
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Issue :
I am getting problem file download a client machine.I am trying to file download in client machine but file download on the server.Also, the same code is proper working in my local environment.

You can use SheetJS js-xlsx
Use generateAndDownloadXLSX to download excel file in your page.

Related

How to import csv file and display the data on html table then save on sql database in asp .net core

I'm struggling with importing csv file in my project.
I want to upload a csv file and display the data before saving to sql database.
I'm using asp .net core razor pages.
Here is my C# method for Importing:
public ActionResult OnPostImport()
{
IFormFile file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
StringBuilder sb = new StringBuilder();
if (!Directory.Exists(newPath))
Directory.CreateDirectory(newPath);
if (file.Length > 0)
{
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
ISheet sheet;
string fullPath = Path.Combine(newPath, file.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
stream.Position = 0;
if (sFileExtension == ".xls")//This will read the Excel 97-2000 formats
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream);
sheet = hssfwb.GetSheetAt(0);
}
else //This will read 2007 Excel format
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream);
sheet = hssfwb.GetSheetAt(0);
}
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
// Start creating the html which would be displayed in tabular format on the screen
sb.Append("<table class='table'><tr>");
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
sb.Append("<th>" + cell.ToString() + "</th>");
}
sb.Append("</tr>");
sb.AppendLine("<tr>");
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
}
sb.Append("</table>");
}
}
return this.Content(sb.ToString());
}
Here is my frontend code:
<h2>Import</h2>
<br />
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<input type="file" id="fUpload" name="files" class="form-control" />
</div>
<div class="col-md-8">
<input type="button" id="btnUpload" value="Upload" />
</div>
</div>
<br />
<div id="dvData"></div>
</form>
Javascript code:
#Html.AntiForgeryToken()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$('#btnUpload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fUpload').val();
if (filename.length === 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) === -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fUpload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Home/ImportCSVFile?handler=ImportFromExcel",
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length === 0)
alert('Some error occured while uploading');
else {
$('#dvData').html(response);
}
},
error: function (e) {
$('#dvData').html(e.responseText);
}
});
});
});
</script>
they ajax call doesnt reach the c# method. Please help I'm not sure what is it I'm missing out on this code above.And also pleaae advise how i can get to save the data to sql after importing the csv file.
1.You can try to change public ActionResult OnPostImport() to public ActionResult OnPostImportFromExcel().Becasue your ajax url is /Home/ImportCSVFile?handler=ImportFromExcel.
2.Or you can change ajax url to /Home/ImportCSVFile?handler=Import.
result:
And about saving data to db,you can refer to this.

I want to print to pdf file in javascript, where outputstream and pdfwriter

I am trying to create a PDF from a server-side controller (report) (ireport) with ajax (and so on), and try to return the data to pdfwriter, servletoutputstream, and httpservletresponse. (I do not know exactly what I'm doing, but I'm doing it this way).
The original purpose was to send a server-side pdf file to the client, find the printer and print without a preview window.
Among them, I wrote 'application / pdf' on the server side and 'datetype: text' on the client side ajax (there is an error if I do not use ajax datatype: text)
If you print the results to the console, they will only be listed as unknown code.
Currently I am trying to put it into an iframe frame.
Question!
1. What should I do to use the text string sent to server -> client as pdf or script code?
(I have already asked you two weeks ago)
2. How do I send a pdf to server -> client? I would like to apply it to the screen by expressing it directly in code instead of downloading it. To print out.
ENG)>
// I used ajax only, because I dont know any other way
$.ajax({
url : "url",
data : JSON.stringify(data),
dataType : "text",
type: "POST",
contentType: 'application/json; charset=utf-8',
async : false,
success: function(result){
// I want to view PDF contents and directly print to PDF.
}
})
public Params createIbExItemLabelReport(HttpServletRequest resq, HttpSession session, Params inParams, HttpServletResponse resp) throws Exception{
Params outParams = ParamsFactory.createParams(inParams);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "0");
List<DataRow> list = new ArrayList<DataRow>();
String reportCd = "15";
String fileName = "ibExItemLabel"+reportCd+"Report";
String nullJpgFile = "";
int flag = 0;
int nullCheck = 0;
for(DataRow dr : inParams.getDataTable("dt_data")){
String imgName = "c:\\WMS\\LABEL\\FIAC021_" +reportCd + ".jpg";
File f = new File(imgName);
if (!f.isFile()) {
flag = 1;
if(nullCheck != 0){
nullJpgFile += ", ";
}
nullJpgFile += "FIAC021";
nullCheck++;
continue;
}
String bacodeCd = "FIAC02120180416001";
dr.setParam("imgName", imgName);
dr.setParam("bacodeCd", bacodeCd);
list.add(dr);
}
if(flag == 1){
outParams.setParam("ERROR_FILE", "제품코드 ["+nullJpgFile+"]의 라벨 사이즈" + reportCd + "인 파일이 존재하지않습니다.");
return outParams;
}
String appPath = session.getServletContext().getRealPath("/");
String pdfPath = null;
List<DataRow> list2 = new ArrayList<DataRow>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).getInt("printQty"); j++){
list2.add(list.get(i));
}
}
Report report = new Report();
pdfPath = report.reportToPdf(session, list2, fileName);
outParams.setParam("fileName", pdfPath);
System.out.println("Found! FileName is ' : "+ pdfPath);
pdfPath = appPath + pdfPath;
pdfPath = pdfPath.replace("//", "/");
ServletOutputStream servletOutput = resp.getOutputStream();
PdfWriter pdfWriter = null;
StringBuffer pdfJs = null;
ByteArrayOutputStream pdfOutput = null;
InputStream pdfInput = null;
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfOutput = convertPDFToByteArrayOutputStream(pdfPath);
int printCopy = 1;
if (printCopy == 0) {
printCopy = 1;
}
if (printCopy > 1) {
PdfCopyFields pdfPrintCopy = new PdfCopyFields(pdfOutput);
for (int i = 0; i < printCopy; i++) {
pdfPrintCopy.addDocument(new PdfReader(outputToInputStream(pdfOutput)));
}
pdfPrintCopy.close();
}
pdfInput = outputToInputStream(pdfOutput);
pdfReader = new PdfReader(pdfInput);
pdfStamper = new PdfStamper(pdfReader, servletOutput);
pdfWriter = pdfStamper.getWriter();
String printerNm = "SINDOH D410 Series PCL";
pdfWriter.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
pdfJs = new StringBuffer();
pdfJs.append("var param=this.getPrintParams();\r");
pdfJs.append("param.printerName=\"").append(printerNm).append("\";\r");
pdfJs.append("param.interactive=param.constants.interactionLevel.silent;\r");
pdfJs.append("param.pageHandling=param.constants.handling.shrink;\r");
pdfJs.append("this.print(param);\r");
pdfJs.append("this.closeDoc();");
pdfWriter.addJavaScript(pdfJs.toString(), false);
servletOutput.flush();
Log.debug("servletOutput " );
if (pdfInput != null) {
try {
pdfInput.close();
} catch (Exception e) {
}
pdfInput = null;
}
if (pdfOutput != null) {
try {
pdfOutput.close();
} catch (Exception e) {
}
pdfOutput = null;
}
if (pdfReader != null) {
pdfReader.close();
pdfReader = null;
}
pdfWriter = null;
try {
if (pdfStamper != null) {
pdfStamper.close();
pdfStamper = null;
}
} catch (Exception e) {
}
resp.setHeader("Content-Disposition", "inline; filename="+pdfPath);
resp.setHeader("Content-Type", "application/pdf; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
Log.debug("before outParams " );
return outParams;
}
private InputStream outputToInputStream(ByteArrayOutputStream source) {
return new ByteArrayInputStream(source.toByteArray());
}
private static ByteArrayOutputStream convertPDFToByteArrayOutputStream(String FilePath) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(new File(FilePath));
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
please answer my question

Not able to load the Gridview on Load

I am not able to load the gridview on page load. It keeps giving me
Uncaught TypeError: Cannot read property 'length' of undefined.
I have mnetioned the code and the handler beneath. Please help me solve the issue. The issue happens in the Jquery.
<script type="text/javascript">
$(document).ready(function () {
BindGridView();
});
function BindGridView() {
$.ajax({
type: "POST",
url: "../Pm/uc/G.ashx/GetMailDetail",
contentType: "application/json;charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
$("#grdDemo").append("<tr><th>Username</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#grdDemo").append("<tr><td>" +
data.d[i].Username + "</td> <td>");
}
}
},
error: function (result) {
}
});
}
</script>
<asp:GridView ID="grdDemo" runat="server">
</asp:GridView>
This is in the Handler.( You can replace the query with anything.)
public void ProcessRequest(HttpContext context)
{
//int mailid = int.Parse(context.Request["mid"]);
//var detail = GetMailDetail(mailid);
var detail = GetMailDetail();
if (detail != null)
{
context.Response.ContentType = "application/json";
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(detail);
context.Response.Write(json);
}
else
{
context.Response.StatusCode = 404;
}
}
//protected object GetMailDetail(int mailid)
protected object GetMailDetail()
{
List<DetailsClass> Detail = new List<DetailsClass>();
Connection Con = new Connection();
String Connection = Con.Active_Connection();
SqlConnection con = new SqlConnection(Connection);
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select Sp4_Txt from Sp4", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtGetData = new DataTable();
da.Fill(dtGetData);
foreach (DataRow dtRow in dtGetData.Rows)
{
DetailsClass DataObj = new DetailsClass();
DataObj.Username = dtRow["Sp4_Txt"].ToString();
Detail.Add(DataObj);
}
return Detail.ToArray();
}
public class DetailsClass //Class for binding data
{
public string Username { get; set; }
}
public bool IsReusable
{
get
{
return false;
}
}
}
Cannot read property 'length' of undefined.
This error is coming because you are accessing the data.d without checking data and accessing data.d.length without checking data.d
Do something like this:
if(data){
if(data.d){
if (data.d.length > 0) {
$("#grdDemo").append("<tr><th>Username</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#grdDemo").append("<tr><td>" +
data.d[i].Username + "</td> <td>");
}
}
}
}

A console application to get a web page resource, using c# (javascript may cause this)

Aim: To download a website source with using a console application. You can find the used class in the program below.
Question: I use the code below to download a data (source) of a web page. Imagine you use chrome; If you enter first this query string, the web page itself redirects you a view HTML page and you see the data.
Entering this URL, to show the results it redirects itself to second page below. I make it by using javascript.
www.xyz.com/aaa.html?search=aaa&id=1
it redirects here: www.xyz.com/ViewResult.html
In an explorer, It works fine . I see 4 HTML tables inside the page when I use google chrome view source option. Bu in my application I see only two tables of the 4 . The two tables inside the web page is missing.(the missing two tables are the second and third.)
How can I overcome to this problem? I want to get the source of the page as I see in chrome.
Bonus informations: There is no iframe.
The particular Code :
string url = "www.xyz.com/aaa.html?search=aaa&id=1";
WebPage pG = ss.RequestPage(url, "", "GET");
pG = ss.RequestPage("www.xyz.com/ViewResult.html");
string source= pG.Html;
public WebPage RequestPage(Uri url, string content, string method, string contentType)
{
string htmlResult;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = null;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] contentData = encoding.GetBytes(content);
request.Proxy = Proxy;
request.Timeout = 60000;
request.Method = method;
request.AllowAutoRedirect = false; // false
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Referer = LastUrl;
request.KeepAlive = true; //false,
request.UserAgent = UserAgent;
request.Headers.Add("Accept-Language", "en-us,en;q=0.5");
//request.Headers.Add("UA-CPU", "x86");
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
String cookieString = "";
foreach (KeyValuePair<String, String> cookiePair in Cookies)
cookieString += cookiePair.Key + "=" + cookiePair.Value + ";";
if (cookieString.Length > 2)
{
String cookie = cookieString.Substring(0, cookieString.Length - 1);
request.Headers.Add("Cookie", cookie);
}
if (method == "POST")
{
request.ContentLength = contentData.Length;
request.ContentType = contentType;
Stream contentWriter = request.GetRequestStream();
contentWriter.Write(contentData, 0, contentData.Length);
contentWriter.Close();
}
int attempts = 0;
while (true)
{
try
{
response = (HttpWebResponse)request.GetResponse();
if (response == null)
throw new WebException();
break;
}
catch (WebException)
{
if (response != null)
response.Close();
if (attempts == PageReattempts)
{
throw;
}
else { }
// Wait three seconds before trying again
Thread.Sleep(3000);
}
attempts += 1;
}
// Tokenize cookies
if (response.Headers["Set-Cookie"] != null)
{
String headers = response.Headers["Set-Cookie"].Replace("path=/,", ";").Replace("HttpOnly,", "");
foreach (String cookie in headers.Split(';'))
{
if (cookie.Contains("="))
{
String[] splitCookie = cookie.Split('=');
String cookieKey = splitCookie[0].Trim();
String cookieValue = splitCookie[1].Trim();
if (Cookies.ContainsKey(cookieKey))
Cookies[cookieKey] = cookieValue;
else
Cookies.Add(cookieKey, cookieValue);
}
else
{
if (Cookies.ContainsKey(cookie))
Cookies[cookie] = "";
else
Cookies.Add(cookie, "");
}
}
}
htmlResult = ReadResponseStream(response);
response.Close();
if (response.Headers["Location"] != null)
{
response.Close();
Thread.Sleep(1500);
String newLocation = response.Headers["Location"];
WebPage result = RequestPage(newLocation);
return new WebPage(result.Html, new WebPage(htmlResult));
}
LastUrl = url.ToString();
return new WebPage(htmlResult);
}
1-WebBrowser :
public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
{
public ExtendedWebBrowser()
{
// Ensure that ScriptErrorsSuppressed is set to false.
this.ScriptErrorsSuppressed = true;
this.ProgressChanged += ExtendedWebBrowser_ProgressChanged;
}
private void ExtendedWebBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
// InjectAlertBlocker();
string alertBlocker = #"window.alert = function () { };
window.print = function () { };
window.open = function () { };
window.onunload = function () { };
window.onbeforeunload = function () { };";
var webBrowser = sender as WebBrowser;
webBrowser?.Document?.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
this.Document?.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
}
public void NavigationWaitToComplete(string url)
{
bool complete = false;
NavigationAsync(url).ContinueWith((t) => complete = true);
while (!complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
public void NavigationWaitToComplete(string url, string targetFrameName, byte[] postData, string additionalHeaders)
{
bool complete = false;
NavigationAsync(url, targetFrameName, postData, additionalHeaders).ContinueWith((t) => complete = true);
while (!complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
public async Task NavigationAsync(string url, string targetFrameName, byte[] postData, string additionalHeaders)
{
TaskCompletionSource<bool> tcsNavigation = new TaskCompletionSource<bool>(); ;
TaskCompletionSource<bool> tcsDocument = new TaskCompletionSource<bool>(); ;
Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
DocumentCompleted += (s, e) =>
{
if (ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
Navigate(url, targetFrameName, postData, additionalHeaders);
await tcsNavigation.Task;
// navigation completed, but the document may still be loading
await tcsDocument.Task;
// the document has been fully loaded, you can access DOM here
}
public async Task NavigationAsync(string url)
{
TaskCompletionSource<bool> tcsNavigation = new TaskCompletionSource<bool>(); ;
TaskCompletionSource<bool> tcsDocument = new TaskCompletionSource<bool>(); ;
Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
DocumentCompleted += (s, e) =>
{
if (ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
Navigate(url);
await tcsNavigation.Task;
// navigation completed, but the document may still be loading
await tcsDocument.Task;
// the document has been fully loaded, you can access DOM here
}
}
Calling:
var browser = new ExtendedWebBrowser();
browser.NavigationWaitToComplete("www.xyz.com/aaa.html?search=aaa&id=1");
var html = browser.Document.Body.OuterHtml();
2-CefSharp.OffScreen
private async Task<string> RequestPageAsync(string url, string cachePath, double zoomLevel)
{
var tcs = new TaskCompletionSource<string>();
var browserSettings = new BrowserSettings();
//Reduce rendering speed to one frame per second so it's easier to take screen shots
browserSettings.WindowlessFrameRate = 1;
var requestContextSettings = new RequestContextSettings { CachePath = cachePath };
// RequestContext can be shared between browser instances and allows for custom settings
// e.g. CachePath
using (var requestContext = new RequestContext(requestContextSettings))
using (var browser = new ChromiumWebBrowser(url, browserSettings, requestContext))
{
if (zoomLevel > 1)
{
browser.FrameLoadStart += (s, argsi) =>
{
var b = (ChromiumWebBrowser)s;
if (argsi.Frame.IsMain)
{
b.SetZoomLevel(zoomLevel);
}
};
}
browser.FrameLoadEnd += (s, argsi) =>
{
var b = (ChromiumWebBrowser)s;
if (argsi.Frame.IsMain)
{
b.GetSourceAsync().ContinueWith(taskHtml =>
{
tcs.TrySetResult(taskHtml.Result);
});
}
};
}
return tcs.Task.Result;
}
Calling :
RequestPageAsync("www.xyz.com/aaa.html?search=aaa&id=1", "cachePath1", 1.0);

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources