Jquery ajax Split and save json response into variable - asp.net

Here my Code, on sucess i need to split (data.d) and stored in variable, but it not working, any idea where am wrong ?
$("#ckAddrow").click(function () {
var abcStr = null;
var taskName = $("#ctl00_ContentPlaceHolder1_txttaskname_").val();
var sdate = $("#ctl00_ContentPlaceHolder1_txtsdate_").val();
var edate = $("#ctl00_ContentPlaceHolder1_txtedate_").val();
var hdfieldid = $("#ctl00_ContentPlaceHolder1_hdid").val();
var dataString = 'taskname=' + taskName + '&sdate=' + sdate + '&edate=' + edate + '&hfid=' + hdfieldid;
// alert(dataString);
$.ajax({
type: "POST",
url: "AutoComWebservices.asmx/insertTasksRecord",
data: "{ 'prefix': '" + dataString + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
async: true,
success: function (data) {
abcStr = data.d;
alert(abcStr);
BuildTable(data.d);
// var valSplit = abcStr.split('-');
// var taskname = valSplit[0];
// var startdate = valSplit[1];
// var enddate = valSplit[2];
// var pf = valSplit[3];
// var myscopeid = valSplit[4];
// alert(taskname + " - - - " + myscopeid);
// alert(data.d)
// var getId = myscopeid;
// var abc = "<tr id='" + getId + "' class='edit_tr'><td class='edit_td'><span ID='taskName_''" + getId + "' class='lblclass'>'" + taskName + "'</span><input id='taskName_txt_''" + getId + "' class='editbox' type='text' value='" + taskName + "' /></td><td class='edit_td'><span ID='startDate_''" + getId + "' class='lblclass'>'" + sdate + "'</span><input id='startDate_txt_''" + getId + "' class='editbox sdatedp' type='text' value='" + sdate + "' /></td><td class='edit_td'><span ID='endDate_''" + getId + "' class='lblclass'>'" + edate + "'</span><input id='endDate_txt_''" + getId + "' class='editbox edatedp' type='text' value='" + edate + "' /></td></tr>";
//"<tr id=9 class=\"edit_tr"><td class="edit_td"><span ID="taskName_9" class="lblclass">dummy</span><input id="taskName_txt_9" class="editbox" type="text" value=dummy /></td><td class="edit_td"><span ID="startDate_9" class="lblclass">03/14/2013</span><input id="startDate_txt_9" class="editbox sdatedp" type="text" value=03/14/2013 /></td><td class="edit_td"><span ID="endDate_9" class="lblclass">03/30/2013</span><input id="endDate_txt_9" class="editbox edatedp" type="text" value=03/30/2013 /></td></tr>"
}
});
});
On alert(abcStr);
is shows heloo-03/19/2013-03/20/2013-138-52
further i need to split('-') and save in variables;
My webmethod code:
[WebMethod]
public string[] insertTasksRecord(string prefix)
{ List<string> d = new List<string>();
string taskname, startdate, enddate,pf;
string datastr = prefix;
string myvalue = "";
string[] val = datastr.Split('&');
string[] tname = val[0].Split('=');
taskname = tname[1];
string[] sdate = val[1].Split('=');
startdate = sdate[1];
string[] edate= val[2].Split('=');
enddate = edate[1];
string[] planid = val[3].Split('=');
pf = planid[1];
DateTime mysdate = Convert.ToDateTime(startdate);
DateTime myedate = Convert.ToDateTime(enddate);
SqlCommand cmd = new SqlCommand(myQuery, connloc);
connloc.Open();
string myscopeid = cmd.ExecuteScalar().ToString();
connloc.Close();
d.Add(string.Format("{0}-{1}-{2}-{3}-{4}",taskname, startdate, enddate,pf,myscopeid));
return d.ToArray();
}

Related

Unable to convert string to date (dd/MMM,YYYY) format ASP.NET

var LR_No_Of_Days = "";
$("#DateRange").jqxDateTimeInput({ width: 250, height: 25, selectionMode: 'range' }); $("#DateRange").on('change', function (event) {
var selection = $("#DateRange").jqxDateTimeInput('getRange');
if (selection.from != null) {
$("#selection").html("<div>From: " + selection.from.toLocaleDateString() + " <br/>To: " + selection.to.toLocaleDateString() + "</div>");
}
var LR_Request_Date_From = selection.from.toLocaleDateString();
var LR_Request_Date_To = selection.to.toLocaleDateString();
$('#LR_Request_Date_From').val(LR_Request_Date_From);
$('#LR_Request_Date_To').val(LR_Request_Date_To);
NoOfdays();
function NoOfdays() {
var LR_No_Of_Days = Math.floor((Date.parse(LR_Request_Date_To) - Date.parse(LR_Request_Date_From)) / 86400000); if (LR_No_Of_Days == '0') {LR_No_Of_Days = 1;} else { LR_No_Of_Days-1; }; alert(LR_Request_Date_From + " &&& " + LR_Request_Date_To + " No of days:" + LR_No_Of_Days);
$("#LR_No_Of_Days").val(LR_No_Of_Days);}});
I'm unable to convert the string variable(LR_Request_Date_From and LR_Request_Date_To) to date format. I receive error converting string to date.
You have to use MM instead of mm and CultureInfo.InvariantCulture as second parameter
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

How to use and improve wakhtmltopdf performance?

I have my aspx pages , and some logic is written in code behind to bind the data of aspx pages.Now using wkhtmltopdf i am sending these files to convert into pdf files.Its work very well when the data is smaller in size however when the data comes in larger side for that page the wkhtmltopdf stops working and doesnt create any pdf file.
Can you suggest any way to overcome this problem. What i tried was limiting the data.. for example i have repeater control on my page if that controls binds 350 record i am only taking 20 records , but also if size of those 20 records are large it happens the same
the also next option i tried is my giving the parameter inside
Process myProcess = Process.Start(startInfo);
myProcess.WaitForExit(few seconds);
but it still doesnt work
Please suggest
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
This is the answer => what happen is when u start process , and wait for exit () both creates a deadlock somtimes which hammers the performance .. by adding readtoend() method before waitforexit() clears the deadlock and then continues further processing ...
this solves my problem.
The reason i am showing complete solution is that , wkhtmltopdf is very good for creating dynamic pdf files , but this is free tool as well and hence very limited documentation for this ..
private void ProcessHtmlToPdf(List<ExportToPdfCategories> lstExportToPdfCategories)
{
try
{
string pdfExportPath = string.Empty;
string PDFdeletePath = string.Empty;
string deletePath = string.Empty;
string PdfSavePath = string.Empty;
if (lstExportToPdfCategories != null)
{
foreach (var item in lstExportToPdfCategories)
{
path = "";
pdfExportPath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
PDFdeletePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString();
PdfSavePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
htmlpath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
deletePath = Server.MapPath(PDFdeletePath);
string ClearDirectory = Server.MapPath(PdfSavePath);
if (Directory.Exists(deletePath))
{
//Directory.Delete(ClearDirectory, true);
//Directory.Delete(deletePath, true);
}
if (!Directory.Exists(Server.MapPath(pdfExportPath)))
{
Directory.CreateDirectory(Server.MapPath(pdfExportPath));
}
string name =
pdfExportPath = pdfExportPath + "/" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-" + item.HeaderCategory + "_" + (drpYear.SelectedValue != "0" ? Convert.ToString(drpYear.SelectedValue) : System.DateTime.Now.Year.ToString()) + ".pdf";
objpath = Server.MapPath(pdfExportPath);
//this will create html mockup
//item.WebsiteUrl = CreateTemportHtmlFile(item.HeaderCategory, PdfSavePath, item.WebsiteUrl);
if (path == "")
{
path = CreateTemportHtmlFile(PdfSavePath, item.HeaderCategory);
}
HtmlToPdf(item.WebsiteUrl, objpath, path);
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-actusdocs.zip");
Response.ContentType = "application/zip";
objZip.Save(Response.OutputStream);
Response.End();
}
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("ProcessHtmlToPdf method : ", ex.Message + ex.StackTrace, objExpDetails);
}
}
//Method overloading
//this is for testing html pages(not in used during main running)
private string CreateTemportHtmlFile(string categoryName, string htmlMockupSavingPath, string websiteURL)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
htmlMockupSavingPath = Server.MapPath(htmlMockupSavingPath) + "\\" + categoryName + ".html";
StreamWriter sw;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(websiteURL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(htmlMockupSavingPath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(htmlMockupSavingPath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlMockupSavingPath;
}
private string CreateTemportHtmlFile(string PdfSavePath, string categoryName)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
PdfSavePath = Server.MapPath(PdfSavePath) + "\\BindHeader.html";
htmlpath = htmlpath.Substring(1);
htmlpath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + htmlpath + "/BindHeader.html";
string exportedYear = (drpYear.SelectedValue == "0" ? System.DateTime.Now.Year.ToString() : drpYear.SelectedValue);
StreamWriter sw;
if (categoryName == "MidYearAppraisal" || categoryName == "EndYearAppraisal")
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeaderforAppraisal.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
else
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeader.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(PdfSavePath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(PdfSavePath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlpath;
}
private void HtmlToPdf(string website, string destinationFile, string path)
{
try
{
string hrmlPath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + "/user/UserPdfReports/FooterPdfReports.html";
ProcessStartInfo startInfo = new ProcessStartInfo();
string switches = "";
switches += "--header-html " + path + " --footer-html " + hrmlPath;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
startInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
startInfo.Arguments = switches + " " + website + " " + destinationFile;
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("HtmlToPdf : ", ex.Message + ex.StackTrace, objExpDetails);
}
}

Could not parse query

I have tried rewriting this query a few different ways, but with no luck. Help here is much appreciated.
function createWaterBodyDropDown(region) {
var query = "SELECT 'LAKE_NAME' FROM 1IfQgRAeKPbVJwEpAnqqpYlN8sgiPMg1VQ_RyArI WHERE 'REGION'=" + '"' + region + '"';
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//Send query and draw table with data in response
gvizQuery.send(function (response) {
var str;
var numRows = response.getDataTable().getNumberOfRows();
var numCols = response.getDataTable().getNumberOfColumns();
var name = [
'<label style="font-weight:bolder;font-size:16px">Water body: </label>' + '<select id="waterbody_menu" style="font-size:16px;" onchange="select_waterBody(this.options[this.selectedIndex].value);">' + '<option value="">--All--</option>'
];
for (var i = 0; i < numRows; i++) {
var val = response.getDataTable().getValue(i, 0);
name.push("<option value=" + "'" + val + "'" + ">" + val + "</option>");
}
name.push('</select>');
document.getElementById('waterBody_container').innerHTML = name.join('');
});
}
Your column names have no special characters so they don't need to be quoted, though they could be (with single quotes). String values must be quoted with single quotes. See the reference manual for more details.
So:
SELECT LAKE_NAME FROM 1IfQgRAeKPbVJwEpAnqqpYlN8sgiPMg1VQ_RyArI WHERE REGION = 'foobar'

Change date format in js for jquery datatable

I have this date in table: "2013-10-08T00:00:00"
I want to set it in format "dd.MM.yyyy"
in datatable source i changed like this:
{
"bSortable": true,
"mData": "PublishDate",
"bSearchable": true,
"mRender": function (data, type, row) {
if (data) {
debugger;
var re = /-?\d+/;
var m = re.exec(data);
var d = new Date(parseInt(m[0]));
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var formatedDate = curr_date + "/" + curr_month + "/" + curr_year + " " + d.getHours() + ":" + d.getMinutes();
return formatedDate;
}
else
return data
},
},
But it always return 1/1/1970 2:0
have any suggestions?
Try this:
var m = data.split(/[T-]/);
var d = new Date(parseInt(m[0]),parseInt(m[1])-1,parseInt(m[2]));
See: http://jsfiddle.net/vHTWL/

Jquery Ajax JSON data read is not working

I'm trying to retrieve data from SQL server DB and convert it to JSON and try to show the json data using JQuery Ajax function, here is the C# code,
C#
public String GetData()
{
try
{
String strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}
the GetJSONString(dTable) function working fine, here is the JQuery code,
jQuery & HTML
<form id="form1" runat="server">
<div>
<h1>JSON Sample</h1>
<button id="getdata">Get Data</button>
<div id="company"></div>
<%-- <asp:Button ID="aspbutton" runat="server" Text=".Net Call" OnClick="btnOn_Click" />
<asp:GridView runat="server" ID="grdview"></asp:GridView>--%>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#getdata").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "",
url: "Default.aspx/GetData",
dataType: "json",
success: function (data) {
alert(data.d);
$("#company").html(data.d);
}
});
});
});
</script>
</form>
I have included the jQuery file, please let me know if I have made any mistake,
EDITED :GetJSONString added
public static string GetJSONString(DataTable Dt)
{
string[] StrDc = new string[Dt.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < Dt.Columns.Count; i++)
{
StrDc[i] = Dt.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + Dt.TableName + "\" : [");
for (int i = 0; i < Dt.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < Dt.Columns.Count; j++)
{
switch (Dt.Columns[j].DataType.ToString())
{
case "System.DateTime":
DateTime cv = (DateTime)Dt.Rows[i][j];
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", cv.Year + "," + (cv.Month - 1) + "," + cv.Day + "," + cv.Hour + "," + cv.Minute + "," + cv.Second + "," + cv.Millisecond);
break;
case "System.Boolean":
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString().ToLower());
break;
default:
string str = Dt.Rows[i][j].ToString();
str = str.Replace("\n", "\\\\n");
str = str.Replace("\\", "\\\\\\\\");
str = str.Replace("\"", "ppp");
str = str.Replace("'", "\\\'");
str = str.Replace("\r", "\\\\r");
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", str);
break;
}
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
I added error: section in Ajax call, now getting the error "error; [object Object]"
Finally, I found what was the issue, I have to add "[WebMethod()]" declaration just before the asp.net function. For example,
[WebMethod()]
public static string GetData()
{
try
{
string strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}

Resources