I have a problem that I can't understand:
My ajax sends information to my controller
function guardar_stag() {
$.ajax({
url: '/Staging/guardar_stag_bd',
data: "{'po':'" + po + "','estilo':'" + estilo + "','size':'" + size + "','quantity':'" + quantity + "','employee':'" + employee + "','fabric_percent':'" + fabric_percent + "','country':'" + country + "','color':'" + color + "','comentario':'" + comentarios + "'}",
contentType: 'application/json',
dataType: 'json',
type: 'post',
success: function (result) {
//IT DOESN'T GET HERE
}
});
}
Then I handle the information in my controller, it takes all the values
[HttpPost]
public JsonResult guardar_stag_bd(string po, string estilo, string size, string quantity, string employee, string fabric_percent, string country, string color, string comentario)
{
string[] tallas = size.Split('*'), cantidades = quantity.Split('*'), empleados = employee.Split('*'), porcentajes = fabric_percent.Split('*'), paises = country.Split('*'), colores = color.Split('*');
int total = 0, id_size, id_color, id_pais, id_percent;
int summary = ds.buscar_id_summary(po, estilo);
for (int i = 1; i < cantidades.Length; i++)+= Convert.ToInt32(cantidades[i]);
}
int id_empleado;
ds.guardar_stag_bd(po, estilo, total, Convert.ToInt32(Session["id_usuario"]), summary, comentario);
int id_stag = ds.obtener_ultimo_stag();
for (int i = 1; i < cantidades.Length; i++){
id_empleado = stag.obtener_id_empleado(empleados[i]);
id_size = consultas.buscar_talla(tallas[i]);
id_color = consultas.buscar_color(colores[i]);
id_pais = consultas.buscar_id_pais(paises[i]);
id_percent = consultas.buscar_percent(porcentajes[i]);
stag.guardar_yarn(id_stag.ToString(), id_stag.ToString());
}
//FOR ENDS BUT NEVER GO TO THE NEXT LINE
Session["id_staging"] = id_stag;
return Json("0", JsonRequestBehavior.AllowGet);
}
I have to insert information into my DB with guardar_yarn but even after I go line by line in the model, it doesn't show any error nor does it insert, after the Dispose() it just ends and does not return to return Json line
public void guardar_yarn(string staging, string talla)
{
Conexion con = new Conexion();
try
{
SqlCommand com = new SqlCommand();
com.Connection = con.AbrirConexion();
com.CommandText = "INSERT INTO yarn(yarn) values('"+ staging+"') ";
com.ExecuteNonQuery();
}
finally { con.CerrarConexion(); con.Dispose(); }
//it stops after this line and goes to the html page
}
Sorry for my poor explanation, English is not my first language. Thanks
Related
On button click I want the user to redirect to payumoney gateway and if payment has been done successfully, the data of user to be store in database and redirect user to success page vice a versa..
Currently I am saving data using AJAX call and redirect user on ajax success:function.
AJAX
$('#payNowButton').on("click", function () {
var total = $('#main_total_s5').html();
console.log("Total : " + total);
$.ajax({
url: '/Home/Demo?total=' + total, //Demo method in Home Controller is for payumoney payment gateway.
type: "POST",
data: total,
async: false,
success: function (result) {
window.location.href = result;
if (result > 0) {
PlaceOrder(); //after successful payment, it will call this function to save data in database.
window.location.href = '#Url.Action("Sucess", "Home")';
}
else {
alert("Some error occurred." + result);
}
},
error: function (result) {
window.location.href = '#Url.Action("Failure", "Home")';
}
});
});
Controller
[HttpPost]
public void Demo(OrderCustom orderCustom)
{
string firstName = "";
string amount = "";
string productInfo = "";
string email = "";
string phone = "";
string surl;
string furl;
RemotePost myremotepost = new RemotePost();
string key = "";
string salt = "";
//posting all the parameters required for integration.
myremotepost.Url = "https://secure.payu.in/_payment";
myremotepost.Add("key", "");
string txnid = Generatetxnid();
myremotepost.Add("txnid", txnid);
myremotepost.Add("amount", amount);
myremotepost.Add("productinfo", productInfo);
myremotepost.Add("firstname", firstName);
myremotepost.Add("phone", phone);
myremotepost.Add("email", email);
myremotepost.Add("surl", "http://localhost:/Home/Sucess");//Change the success url here depending upon the port number of your local system.
myremotepost.Add("furl", "http://localhost:/Home/Failure");//Change the failure url here depending upon the port number of your local system.
myremotepost.Add("service_provider", "payu_paisa");
string hashString = key + "|" + txnid + "|" + amount + "|" + productInfo + "|" + firstName + "|" + email + "|||||||||||" + salt;
string hash = Generatehash512(hashString);
myremotepost.Add("hash", hash);
myremotepost.Post();
}
public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head>");
System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
for (int i = 0; i < Inputs.Keys.Count; i++)
{
System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
System.Web.HttpContext.Current.Response.End();
}
}
When I click on button it shows this error :
Error Image
I have faced the same problem yesterday. What I did i, I removed myremotepost.Add("service_provider", "payu_paisa"); and It worked!.
Also check the URL once, if you are doing it on test server then the URL would be https://test.payu.in/_payment
"Key" and "SALT" value cannot be blank, these values will be shared to you by payumoney itself.
string key = "";
string salt = "";
myremotepost.Add("service_provider", "payu_paisa");
This is Mandatory Field, Recently I am contacting with help desk they are asking for some customization. Then it will work
I use this query to populate my gallery:
function GalleryCatPopulate(url, listname, target) {
var eng = false;
if ((window.location.href.indexOf("lang=en") > 0)) {
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,English",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryCat(data, target, eng);
},
error: function (data) {
failureGalleryCat(data, target);
}
});
}
function completeGalleryCat(data, target, eng) {
var items = data.d.results;
var prefix = "";
var sufix = "<div class='clear'></div>";
//if (eng)
// prefix = "<div class='filter selected' data-category='cat-all'>All</div>";
//else
// prefix = "<div class='filter selected' data-category='cat-all'>Todas</div>";
var menu = "";
var cat = "";
var title = "Transporte de Materiales";
console.log(title.replace(/\s/g, "_").replace(/[^\w\s]/gi, ''));
for (var item in items) {
if (eng)
cat = items[item].English;
else
cat = items[item].Title;
menu += "<div class='filter' data-category='" + cat.replace(/\s/g, "_").replace(/[^\w\s]/gi, '') +"'>"+ cat +"</div>";
}
$(target).html(prefix + menu + sufix);
}
function failureGalleryCat(data, target) {
$(target).text("Ocurrió un error en la carga las categorias. Por favor revise la consola para más información");
}
function GalleryContentPopulate(url, listname, target) {
var eng = false;
var queryGallery = "$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categoria/Title$SortField=Title&SortDir=Desc";
if ((window.location.href.indexOf("lang=en") > 0)) {
queryGallery = "$select=TitleEnglish,DescriptionEnglish,Enlace,EncodedAbsUrl,Categoria/English&$expand=Categoria/English";
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$top=1000&" + queryGallery,
//url: url + "/_api/web/lists/getbycategory('Office'),
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryContent(data, target, eng);
},
error: function (data) {
failureGalleryContent(data, target);
}
});
}
function completeGalleryContent(data, target, eng) {
var items = data.d.results;
//console.log(items);
var menu = "";
var cat = "";
for (var item in items) {
if(items[item].DescriptionEnglish==null)
items[item].DescriptionEnglish="";
if(items[item].Description==null)
items[item].Description="";
if(items[item].Categoria.results!= null && items[item].Categoria.results!= undefined && items[item].Categoria.results.length > 0){
cat =setCategories(eng,items[item].Categoria.results);
}
if (eng){
//menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class=' ' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div></div>";
menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><a class=' ' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div></div>";
}else{
//menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
}
}
$(target).html(menu);
var api = $(target).megafoliopro(
{
filterChangeAnimation: "pagebottom", // fade, rotate, scale, rotatescale, pagetop, pagebottom,pagemiddle
filterChangeSpeed: 400, // Speed of Transition
filterChangeRotate: 99, // If you ue scalerotate or rotate you can set the rotation (99 = random !!)
filterChangeScale: 0.6, // Scale Animation Endparameter
delay: 20,
defaultWidth: 980,
paddingHorizontal: 10,
paddingVertical: 10,
layoutarray: [9, 11, 5, 3, 7, 12, 4, 6, 13] // Defines the Layout Types which can be used in the Gallery. 2-9 or "random". You can define more than one, like {5,2,6,4} where the first items will be orderd in layout 5, the next comming items in layout 2, the next comming items in layout 6 etc... You can use also simple {9} then all item ordered in Layout 9 type.
});
//console.log("entra");
// FANCY BOX ( LIVE BOX) WITH MEDIA SUPPORT
//console.log("sale");
// THE FILTER FUNCTION
$('.filter').click(function () {
$('.filter').each(function () { jQuery(this).removeClass("selected") });
api.megafilter(jQuery(this).data('category'));
$(this).addClass("selected");
});
var categorySelected = getParameterByName("Category");
// $('[data-category="Office"],[data-category="Oficinas"]').click();
// Aquí agarramos la primera categoria
$(".filter").eq(0).trigger("click");
$("div[data-category='"+categorySelected +"']").click();
jQuery(".fancybox").fancybox();
}
function failureGalleryContent(data, target) {
// console.log(data);
$(target).text("Ocurrió un error en la carga la sección parallax. Por favor revise la consola para más información");
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function setCategories(boolLang, objResult){
var cat ="";
for(var item in objResult){
if(boolLang)
cat += replaceAll(" ", "_",objResult[item].English.replace(/[^\w\s]/gi, '')) + ' ';
else
cat += replaceAll(" ", "_",objResult[item].Title.replace(/[^\w\s]/gi, '')) + ' ';
}
return cat;
}
function replaceAll( find, replace,string) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
The problem is that I don´t know why first take one image of each category and after that get all images of one categorie, for example
I have this categories
Services, Home, Office
In my first row of images I get:
firstimageServices
firstimageHome
firstimageOffice
secondimageOffice
thirdimageOffice
etc...
But I want to group all by categorie, so it will be:
firstimageServices
secondimageServices
thirdimageServices
fourimageServices
etc...
firstimageHome
secondimageHome
thirdimageHome
fourimageHome
etc...
firstimageOffice
secondimageOffice
thirdimageOffice
fourimageOffice
etc..
How can I do in my query to group it? Regards!
Note: I look something of interest in these link msdn but how can I apply it in my query to sort by "Title"
So In first fields I get something like that:
When it pass first rows of categories I get that I want like these:
I finally do it just change query for:
"$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categoria/Title&$orderby=Title asc";
With the code below I am able to save files to folder.
My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.
if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
int filesize = AnnualReport.PostedFile.ContentLength;
int filesizeP = ProjectReports.PostedFile.ContentLength;
int filesizePub = Publications.PostedFile.ContentLength;
int filesizeOther = Other.PostedFile.ContentLength;
int filesizeReg = RegistDoc.PostedFile.ContentLength;
if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
} else {
const string ReportDirectory = "REPORTS/";
//Other Document
string OtherPath = ReportDirectory + Other.FileName;
string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
int iterationOther = 1;
while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
iterationOther++;
}
//Registration Document
string RigisDocPath = ReportDirectory + RegistDoc.FileName;
string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
int iterationRE = 1;
while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
iterationRE++;
}
//Annual Reports
string ReportPath = ReportDirectory + AnnualReport.FileName;
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
iteration++;
}
//Project Report
string ProjecttPath = ReportDirectory + ProjectReports.FileName;
string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
int iterationP = 1;
while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
iterationP++;
}
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iterationPub = 1;
while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
iterationPub++;
}
ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
AnnualReport.SaveAs(Server.MapPath(ReportPath));
Publications.SaveAs(Server.MapPath(publicationPath));
RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
Other.SaveAs(Server.MapPath(OtherPath));
The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.
Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)
You can just check if the required documents are present. (looking at your exising code, present means document name object is not null)
If not, throw an error.
If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.
ie.
if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
I did beak down the code into diferent methods like #irreal suggested, like below;
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else
{
int filesizeP = Publications.PostedFile.ContentLength;
if (filesizeP > 2097152)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Publication is 2.0 MB');", true);
}
else
{
const string ReportDirectory = "REPORTS/";
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
{
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
iteration++;
}
Publications.SaveAs(Server.MapPath(publicationPath));
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
}
}
I then called it o the click event
try{
PublicationReporting();
}
catch (Exception ex)
{
pgError.Text = "Publication Exception Message: " + ex.Message;
}
finally
{
csoW_connection.Close();
}
From here it was pretty easy to figure out the problem.
I just needed to dispose the content in the upload field if no file was selected like this
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else{
//program continues}
I have a project wherein fileupload controls are generating dynamically. Using Json, I'm trying to save file in a directory asynchronously. I want to save files with filename using handler template in asp.net 4.0.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: Sitepath + "Handler/FileUploader.ashx?filename="+strfiles,
secureuri: false,
fileElementClass: "multi",
dataType: "json",
async: false
});
I've added HTTPPostedFile's logic outside FileUploader class as it was throwing error in that.
public class FileUploader : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string rt = "";
HttpContext.Current.Response.ContentType = "text/HTML";
string urlresponse = HttpContext.Current.Request.Url.ToString();
string tempfiles = "";
string filenames = "";
int convert = urlresponse.IndexOf(",");
urlresponse = urlresponse.Substring(convert + 1);
string[] filesArray = urlresponse.Split(',');
for (int i = 0; i < filesArray.Length; i++)
{
tempfiles = filesArray[i].ToString();
int lstIndex=tempfiles.LastIndexOf("\\");
filenames = filenames + "," + tempfiles.Substring(lstIndex + 1);
}
filenames = filenames.Substring(filenames.IndexOf(',') + 1);
HttpFileCollection uploads = HttpContext.Current.Request.Files;
string b = HttpContext.Current.Request.Url.ToString();
Hashtable hashtable = new Hashtable();
// Declare variable
string OrderFileName = String.Empty;
string OrderIDs =String.Empty;
string TempFolder = String.Empty;
if (HttpContext.Current.Session["OrderID"] != null)
{
OrderIDs = HttpContext.Current.Session["OrderID"].ToString();
string mapPath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["DocPath"].ToString());
string mapPathUserId = mapPath + "\\" + HttpContext.Current.Session["UserID"];
///
var g = filenames.Split(',');
for (int t = 0; t < g.Length;t++ )
{
var h = g[t];
rt = filesArray[t].ToString();
if (Directory.Exists(mapPathUserId) == false)
{
Directory.CreateDirectory(mapPathUserId);
}
string mapPathCount = mapPathUserId + "/" + OrderIDs;
if (Directory.Exists(mapPathCount) == false)
{
//--------------Begin(Create Directory)----------------------------------------------------------------------------------//
Directory.CreateDirectory(mapPathCount);
//--------------End(Create Directory)----------------------------------------------------------------------------------//
}
TempFolder = mapPathUserId + "/" + "Temp";
if (Directory.Exists(TempFolder) == false)
{
//--------------Begin(Create Directory for temp folder)----------------------------------------------------------------------------------//
Directory.CreateDirectory(TempFolder);
//--------------End(Create Directoryfor temp folder)----------------------------------------------------------------------------------//
}
OrderFileName = h;
hashtable.Add(t.ToString(), OrderFileName);
var see = HttpContext.Current.Server.MapPath(TempFolder + "/" + OrderFileName);
}
Now, path is being created successfully, but file is not getting saved in specified directory. My code to save the file:
for (int i = 0; i < uploads.Count; i++)
{
HttpPostedFile upload = uploads[i];
if (Directory.Exists(mapPathUserId) == false)
{
Directory.CreateDirectory(mapPathUserId);
}
string mapPathCount = mapPathUserId + "/" + OrderIDs;
if (Directory.Exists(mapPathCount) == false)
{
//--------------Begin(Create Directory)----------------------------------------------------------------------------------//
Directory.CreateDirectory(mapPathCount);
//--------------End(Create Directory)----------------------------------------------------------------------------------//
}
/// Create Path for Temp Folder
TempFolder = mapPathUserId + "/" + "Temp";
if (Directory.Exists(TempFolder) == false)
{
//--------------Begin(Create Directory for temp folder)----------------------------------------------------------------------------------//
Directory.CreateDirectory(TempFolder);
//--------------End(Create Directoryfor temp folder)----------------------------------------------------------------------------------//
}
if (upload.ContentLength > 0)
{
if (upload.FileName.Contains(" "))
{
OrderFileName = upload.FileName.Replace(" ", "_");
}
else
{
OrderFileName = upload.FileName;
}
hashtable.Add(i.ToString(), OrderFileName);
upload.SaveAs(TempFolder + "/" + OrderFileName);
}
}
Please help.
You have to make sure you pass a right path, in the server. I would try mapping the path with the MapPath() function:
upload.SaveAs(Server.MapPath(TempFolder + "/" + OrderFileName));
NOW SOLVED
Hi I am calling a c# web method via Ajax.
I want to handle a returned value of true and false in Ajax but I cannot seem to find a way of interrogating my returned data.
Sorry if this is a easy question, I am quite the novice.
My code is
$.ajax({
url: "Subscriptions.aspx/AddSub",
data: "{ 'strReportPath': '" + Path +
"' , strEmail: '" + $('#EmailAddress').val() +
"' , strDayofWeek: '" + daysSelected +
"' , strInterval: '" + intervalSelected +
"' , intTimeofDay: '" + timeofDay +
"' , strDayofMonth: '" + dayofMonth +
"'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data[0] == true) {
alert("Subscription added");
} else {
alert("There has been a error");
}
// Enable button again
$(".AddSub").removeAttr("disabled");
},
error: function (xhr, status, err) {
alert("Error adding subscription: " + err);
// Enable button again
$(".AddSub").removeAttr("disabled");
},
async: false
});
and the web method is
[WebMethod]
public static bool AddSub(string strReportPath, string strEmail, string strDayofWeek, string strInterval, int intTimeofDay, int strDayofMonth)
{
// Create webservice object
ReportService2005.ReportingService2005 rs = new ReportingService2005();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
// Make sure their is a semi colon at the end of the email
if (strEmail.EndsWith(";"))
{
// Do nothing
}
else
{
strEmail = strEmail + ";";
}
string _reportName = strReportPath;
DateTime topDatetime = DateTime.Now;
ExtensionSettings extensionSettings = new ExtensionSettings();
List<ParameterValue> extParameters = new List<ParameterValue>();
List<ParameterValue> parameters = new List<ParameterValue>();
string description = "Email: " + strEmail;
string eventType = "TimedSubscription";
extensionSettings.Extension = "Report Server Email";
// If report is monthly default its run time to 7am
if (strInterval == "Monthly")
{
intTimeofDay = 7;
}
string scheduleXml = "<ScheduleDefinition><StartDateTime>" + topDatetime.ToString("yyyy-MM-dd") + "-" + (intTimeofDay-1) +":00" + "</StartDateTime>";
// Set up the timing of the report.
switch(strInterval)
{
case "Daily":
scheduleXml += "<WeeklyRecurrence>" +
"<WeeksInterval> 1 </WeeksInterval>" +
"<DaysOfWeek>" + "<Monday>true</Monday>" +
"<Tuesday>true</Tuesday>" +
"<Wednesday>true</Wednesday>" +
"<Thursday>true</Thursday>" +
"<Friday>true</Friday>" + "</DaysOfWeek>" +
"</WeeklyRecurrence>";
break;
case "Weekly":
scheduleXml += "<WeeklyRecurrence>" +
"<WeeksInterval> 1 </WeeksInterval>" +
"<DaysOfWeek>" + strDayofWeek + "</DaysOfWeek>" +
"</WeeklyRecurrence>";
break;
case "Monthly":
scheduleXml += "<MonthlyRecurrence>" +
"<Days>" + strDayofMonth + "</Days>" +
"<MonthsOfYear>" +
"<January>true</January>" +
"<February>true</February>" +
"<March>true</March>" +
"<April>true</April>" +
"<May>true</May>" +
"<June>true</June>" +
"<July>true</July>" +
"<August>true</August>" +
"<September>true</September>" +
"<October>true</October>" +
"<November>true</November>" +
"<December>true</December>" +
"</MonthsOfYear>" +
"</MonthlyRecurrence>";
break;
}
scheduleXml += "</ScheduleDefinition>";
extParameters.Add(new ParameterValue() { Name = "RenderFormat", Value = "EXCELOPENXML" });
extParameters.Add(new ParameterValue() { Name = "TO", Value = strEmail });
extParameters.Add(new ParameterValue() { Name = "IncludeReport", Value = "True" });
extParameters.Add(new ParameterValue() { Name = "Subject", Value = "subject - " + " (" + strReportPath + ")" });
extensionSettings.ParameterValues = extParameters.ToArray();
//Create the subscription
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
// Success
return true;
}
catch(SoapException e)
{
// Failure
return false;
}
}
Thank you
ANSWER
Ah solved it!!!
I now return the data as a string variable in the web method
//Create the subscription
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
string bob = "true";
// Success
return bob;
}
catch(SoapException e)
{
string bob = "false";
// Failure
return bob;
}
Then in ajax use the name followed by the .d suffix.
success: function (bob) {
if (bob.d == "true") {
alert("Subscription added");
} else {
alert("There has been a error");
}
Thanks stackoverflow