Why function call twice in ASP.NET Web app - c#

I have a master and content page and I have created an eventhandler on a master page that runs through the content page. And it calls twice. Why i dont understand so please help. even i have handled proper postback
When i call function sendmail() it is calling multiple time. please help where i am going to wrong
Master Page Code
namespace Report_Server
{
public partial class ssrs : System.Web.UI.MasterPage
{
public delegate string NoArgEventHandler(string mailid);
public static event NoArgEventHandler sendMail ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
mailLabel.Visible = false;
mailaddress.Visible = true;
btnSendMail.Enabled = true;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mailModal", "$('#mailModal').modal();", true);
//upModal.Update();
}
protected void btnSendMail_Click(object sender, EventArgs e)
{
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mailModal", "$('#mailModal').modal('hide');", true);
mailLabel.Visible = true;
mailaddress.Visible = false;
btnSendMail.Enabled = false;
mailLabel.Text = "Sending, Please Wait";
string message = sendMail(mailaddress.Text);
mailLabel.Text = message;
//Type cstype = this.GetType();
//// Get a ClientScriptManager reference from the Page class.
//ClientScriptManager cs = Page.ClientScript;
//// Check to see if the startup script is already registered.
//if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
//{
// String cstext = string.Format("alert('{0}');",message);
// cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
//}
//string display = "Message Pop-up!";
//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
}
}
}
Content Page code
namespace Report_Server.Reports.Vouchers.Pages
{
public partial class Sales_Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ssrs.sendMail += new ssrs.NoArgEventHandler(sendmail);
ReportViewer ReportViewer1 = (ReportViewer)this.Master.FindControl("ReportViewer1");
ReportViewer1.LocalReport.ReportPath = "Reports/Vouchers/Reports/Sale_Invoice_2.rdlc";
var dc = new dsserp.reportlib.Vouchers();
var mst = new dsserp.reportlib.Masters();
TextBox mailaddress = (TextBox)Page.Master.FindControl("mailaddress");
getParams();
try
{
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.DataSources.Clear();
requestparam.bill = dc.getSalesInvoice(requestparam.sdt, requestparam.edt, requestparam.dist_id, requestparam.acc_code, requestparam.from_no, requestparam.to_no, requestparam.page_no, requestparam.so_code);
if (mailaddress != null)
mailaddress.Text = requestparam.bill[0].d_email;
requestparam.branch = mst.getBranch();
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = requestparam.bill;
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportDataSource rd2 = new ReportDataSource();
rd2.Name = "DataSet2";
rd2.Value = requestparam.branch;
ReportViewer1.LocalReport.DataSources.Add(rd2);
ReportParameter[] p = new ReportParameter[13];
p[0] = new ReportParameter("firm_id", requestparam.firm_id.ToString());
p[1] = new ReportParameter("branch_id", requestparam.branch_id);
p[2] = new ReportParameter("div_id", requestparam.div_id);
p[3] = new ReportParameter("sdt", requestparam.sdt.ToShortDateString());
p[4] = new ReportParameter("edt", requestparam.edt.ToShortDateString());
p[5] = new ReportParameter("dist_id", requestparam.dist_id == null ? "null" : requestparam.dist_id.ToString());
p[6] = new ReportParameter("acc_code", requestparam.acc_code == null ? "null" : requestparam.acc_code.ToString());
p[7] = new ReportParameter("from_no", string.IsNullOrEmpty(requestparam.from_no) ? "null" : requestparam.from_no);
p[8] = new ReportParameter("to_no", string.IsNullOrEmpty(requestparam.to_no) ? "null" : requestparam.to_no);
p[9] = new ReportParameter("page", requestparam.page_no == null ? "-1" : requestparam.page_no.ToString());
p[10] = new ReportParameter("ismail", "2");
p[11] = new ReportParameter("UserId", requestparam.UserId);
p[12] = new ReportParameter("so_code", requestparam.so_code == null ? "null" : requestparam.so_code.ToString());
ReportViewer1.LocalReport.SetParameters(p);
ReportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.InnerException);
}
}
}
protected string sendmail(string mailid)
{
if (requestparam.mailSent == false)
{
string message = "Somthing Went Wrong";
var mailViewer1 = new ReportViewer();
mailViewer1.LocalReport.ReportPath = "Reports\\Vouchers\\Reports\\Sale_Invoice_2.rdlc";
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = requestparam.bill;
mailViewer1.LocalReport.DataSources.Add(rds);
ReportDataSource rd2 = new ReportDataSource();
rd2.Name = "DataSet2";
rd2.Value = requestparam.branch;
mailViewer1.LocalReport.DataSources.Add(rd2);
ReportParameter[] p = new ReportParameter[13];
p[0] = new ReportParameter("firm_id", requestparam.firm_id.ToString());
p[1] = new ReportParameter("branch_id", requestparam.branch_id);
p[2] = new ReportParameter("div_id", requestparam.div_id);
p[3] = new ReportParameter("sdt", requestparam.sdt.ToShortDateString());
p[4] = new ReportParameter("edt", requestparam.edt.ToShortDateString());
p[5] = new ReportParameter("dist_id", requestparam.dist_id == null ? "null" : requestparam.dist_id.ToString());
p[6] = new ReportParameter("acc_code", requestparam.acc_code == null ? "null" : requestparam.acc_code.ToString());
p[7] = new ReportParameter("from_no", string.IsNullOrEmpty(requestparam.from_no) ? "null" : requestparam.from_no);
p[8] = new ReportParameter("to_no", string.IsNullOrEmpty(requestparam.to_no) ? "null" : requestparam.to_no);
p[9] = new ReportParameter("page", "1");
p[10] = new ReportParameter("ismail", "1");
p[11] = new ReportParameter("UserId", requestparam.UserId);
p[12] = new ReportParameter("so_code", requestparam.so_code == null ? "null" : requestparam.so_code.ToString());
//TextBox mailaddress = (TextBox)Page.Master.FindControl("mailaddress");
//Label mailLabel = (Label)Page.Master.FindControl("mailLabel");
message = "Something Went Wrong";
bool smtpFound = false;
var mst = new dsserp.reportlib.Masters();
var Branch = requestparam.branch[0];
smptuser user = new smptuser();
try
{
user.displayName = Branch.smtp_displyname;
user.hostName = Branch.smtp_host;
user.userId = Branch.smtp_UserId;
user.Password = password.DecryptPass(Branch.smtp_Password);
user.mailAddress = Branch.smtp_mailAddress;
user.Port = Convert.ToInt32(Branch.smtp_port);
if (user.Port > 0)
smtpFound = true;
if (smtpFound)
{
var emailFound = string.IsNullOrEmpty(mailid) == false;
if (emailFound)
{
string filename = requestparam.from_no;
if (requestparam.from_no != requestparam.to_no)
{
filename = filename + "-" + requestparam.to_no;
}
string body = "Dear Sir/Maa'm" + "\r\n" + "\r\n" + "A copy of the invoice " + filename + " has been attached for your reference.";
var _file = Path.Combine(Path.GetTempPath(), filename + ".pdf");
export export = new export();
mailViewer1.LocalReport.SetParameters(p);
export.toFile(mailViewer1.LocalReport, _file);
message = mail.send(_file, mailid, "Invoice No:" + filename, body, user); //"Success:sent"
}
else
message = " Email Address Not Found, Please try again";
}
else
message = "No SMTP Server Found";
}
catch (Exception ex)
{
message = "No SMTP Server Found";
}
if (message == "sent")
message = "Successfuly mail sent";
requestparam.response= message;
}
return requestparam.response;
}
public void getParams()
{
string conn = ConfigurationManager.ConnectionStrings["ReportServerEntities"].ConnectionString;
requestparam.firm_id = Convert.ToInt32(Request.QueryString["firm_id"]);
requestparam.branch_id = Request.QueryString["branch_id"];
requestparam.div_id = Request.QueryString["div_id"];
requestparam.sdt = Convert.ToDateTime(Request.QueryString["sdt"]);
requestparam.edt = Convert.ToDateTime(Request.QueryString["edt"]);
requestparam.dist_id = null;
if (!string.IsNullOrEmpty(Request.QueryString["dist_id"]))
requestparam.dist_id = Convert.ToInt32(Request.QueryString["dist_id"]);
requestparam.acc_code = null;
if (!string.IsNullOrEmpty(Request.QueryString["acc_code"]))
requestparam.acc_code = Convert.ToInt32(Request.QueryString["acc_code"]);
requestparam.from_no = Request.QueryString["from_no"];
requestparam.to_no = Request.QueryString["to_no"];
requestparam.UserId = Request.QueryString["User"];
requestparam.page_no = null;
if (!string.IsNullOrEmpty(Request.QueryString["page_no"]))
requestparam.page_no = Convert.ToInt32(Request.QueryString["page_no"]);
requestparam.so_code = null;
if (!string.IsNullOrEmpty(Request.QueryString["so_code"]))
requestparam.so_code = Convert.ToInt32(Request.QueryString["so_code"]);
properties.connectionstring = conn;
properties.firm_id = requestparam.firm_id;
properties.branch_id = requestparam.branch_id;
properties.div_id = requestparam.div_id;
}
public static class requestparam
{
public static int firm_id { get; set; }
public static string branch_id { get; set; }
public static string div_id { get; set; }
public static string from_no { get; set; }
public static string to_no { get; set; }
public static string UserId { get; set; }
public static DateTime sdt { get; set; }
public static DateTime edt { get; set; }
public static int? dist_id { get; set; }
public static int? acc_code { get; set; }
public static int? page_no { get; set; }
public static int? so_code { get; set; }
public static int? ismail { get; set; }
public static List<Voucher.salesInvoice> bill { get; set; }
public static List<Master.Branch> branch { get; set; }
public static bool mailSent { get; set; }
public static string response { get; set; }
}
}
}

Related

C# and ajax call

//Javascript function
function SaveAndUpdateProjectMaster() {
var CompanyCode = '';
var ProjectName = '';
var ProjectDescription = '';
var ProjectType = '';
var LocationSite = '';
var Client = '';
var Latitude = '';
var Longitude = '';
var Status = '';
var FirstLevelApprover = '';
var SecondLevelApprover = '';
var ThirdLevelApprover = '';
var userComment = '';
var CrudType = '';
var Id = '';
//$('#ddlDivision').val();
//$('#ddlRegionPrm').val();
//$('#ddlCountryPrm').val();
Id = $('#HdxtProjectId').val();
CompanyCode = $('#ddlCompanyPrm').val();
ProjectName = $('#txtProjectnamePrm').val();
ProjectDescription = $('#txtProjectDescriptionPrm').val();
ProjectType = $('#ddlProjecttypePrm').val();
LocationSite = $('#TxtLocationPrm').val();
Client = $('#TxtClientPrm').val();
Latitude = $('#TxtLatitudePrm').val();
Longitude = $('#TxtLongitudePrm').val();
Status = $('#hdnPMStatus').val();
FirstLevelApprover = $('#TxtFirstLevelPrm').val();
SecondLevelApprover = $('#TxtSecondLevelPrm').val();
ThirdLevelApprover = $('#TxtThirdlevel').val();
userComment = $('#txtUserComment').val();
CrudType=$('#hdnBtnType').val();
var obj = {};
obj.Id = Id;
obj.CompanyCode = CompanyCode;
obj.ProjectName = ProjectName;
obj.ProjectDescription = ProjectDescription;
obj.ProjectType = ProjectType;
obj.LocationSite = LocationSite;
obj.Client = Client;
obj.Latitude = Latitude;
obj.Longitude = Longitude;
obj.Status = Status;
obj.FirstLevelApprover = FirstLevelApprover;
obj.SecondLevelApprover = SecondLevelApprover;
obj.ThirdLevelApprover = ThirdLevelApprover;
obj.userComment = userComment;
obj.CrudType = CrudType;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ProjectMaster.aspx/SaveAndUpdateProject",
//data: JSON.stringify({ Id:Id,CompanyCode: CompanyCode, ProjectName: ProjectName, ProjectDescription: ProjectDescription, ProjectType: ProjectType, LocationSite: LocationSite, Client: Client, Latitude: Latitude, Longitude: Longitude, Status: Status, FirstLevelApprover: FirstLevelApprover, SecondLevelApprover: SecondLevelApprover, ThirdLevelApprover: ThirdLevelApprover, userComment: userComment, CrudType: CrudType }),
data: JSON.stringify({ Id: Id, CompanyCode: CompanyCode, ProjectName: ProjectName, ProjectDescription: ProjectDescription, ProjectType: ProjectType, LocationSite: LocationSite, Client: Client, Latitude: Latitude, Longitude: Longitude, Status: Status, FirstLevelApprover: FirstLevelApprover, SecondLevelApprover: SecondLevelApprover, ThirdLevelApprover: ThirdLevelApprover, userComment: userComment, CrudType: CrudType }),
dataType: "json",
success: function (data) {
if (data != '') {
debugger;
data = $.parseJSON(data.d);
data = $.parseJSON(data.d);
$('#ProjectMasterModal').hide();
var divison = $('#ddlDivision').val();
var country = $('#ddlCountryPrm').val();
var company = $('#ddlCompanyPrm').val();
var project = $('#ddlProjMaster').val();
//var masterVal = $('#hdnPMStatus').val();
GetRecord(divison,country,company,project,1);
alert(data.Msg);
CancelWarningCategory();
}
}
});
}
//C# WebMethod
[WebMethod]
public static string SaveAndUpdateProject(string Id,string CompanyCode, string ProjectName, string ProjectDescription, string ProjectType,string LocationSite, string Client, string Latitude, string Longitude, string Status, string FirstLevelApprover, string SecondLevelApprover,string ThirdLevelApprover,string userComment,string CrudType)
//public static string SaveAndUpdateProject(string Id)
{
//string CompanyCode=string.Empty;
//string ProjectName=string.Empty;
//string ProjectDescription=string.Empty;
//string ProjectType=string.Empty;
//string LocationSite=string.Empty;
//string Client=string.Empty;
//string Latitude=string.Empty;
//string Longitude=string.Empty;
//string Status=string.Empty;
//string FirstLevelApprover=string.Empty;
//string SecondLevelApprover=string.Empty;
//string ThirdLevelApprover=string.Empty;
//string userComment=string.Empty;
//string CrudType=string.Empty;
string res = string.Empty;
UserMsg obj = new UserMsg();
try
{
String Result = string.Empty;
BLL_ManageProject BLLProject = new BLL_ManageProject();
//if (btnProjectsave.Text == "Add New")
//{
if (CrudType == "Add New")
{
SqlParameter[] paramSaveProject = new SqlParameter[19];
paramSaveProject[0] = new SqlParameter("#CompanyCode", CompanyCode);
paramSaveProject[1] = new SqlParameter("#ProjectName", Convert.ToString(ProjectName));
paramSaveProject[2] = new SqlParameter("#ProjectDescription", Convert.ToString(ProjectDescription));
paramSaveProject[3] = new SqlParameter("#ProjectType", ProjectType);
paramSaveProject[4] = new SqlParameter("#LocationSite", Convert.ToString(LocationSite));
paramSaveProject[5] = new SqlParameter("#Client", Convert.ToString(Client));
paramSaveProject[6] = new SqlParameter("#Latitude", Convert.ToString(Latitude == "" ? "0.00" : Latitude));
paramSaveProject[7] = new SqlParameter("#Longitude", Convert.ToString(Longitude == "" ? "0.00" : Longitude));
paramSaveProject[8] = new SqlParameter("#IsActive", Convert.ToInt32(Status));
paramSaveProject[9] = new SqlParameter("#FirstLevelApprover", Convert.ToString(FirstLevelApprover));
paramSaveProject[10] = new SqlParameter("#SecondLevelApprover", Convert.ToString(SecondLevelApprover));
paramSaveProject[11] = new SqlParameter("#ThirdLevelApprover", Convert.ToString(ThirdLevelApprover));
paramSaveProject[12] = new SqlParameter("#PageName", HttpContext.Current.Request.Url.Segments.Last());
paramSaveProject[13] = new SqlParameter("#Title", "Insert Project Master");
paramSaveProject[14] = new SqlParameter("#UserComment", userComment);
paramSaveProject[15] = new SqlParameter("#SystemComment", "");
paramSaveProject[16] = new SqlParameter("#Revision", 0);
paramSaveProject[17] = new SqlParameter("#CreatedBy", (!string.IsNullOrEmpty(HttpContext.Current.Session["WindowsID"].ToString())) ? HttpContext.Current.Session["WindowsID"].ToString() : null);
paramSaveProject[18] = new SqlParameter("#CreatedDate", System.DateTime.Now);
Result = BLLProject.SaveProjectMaster(paramSaveProject);
if (Result == "1")
{
obj.Code = "1";
obj.Msg = GlobalConst.strInsertSuccess;
}
else if (Result == "2")
{
obj.Code = "2";
obj.Msg = GlobalConst.strRecordExists;
}
else
{
obj.Code = "0";
obj.Msg = GlobalConst.strInsertFaliure;
}
}
else if (CrudType == "Update")
{
SqlParameter[] paramSaveProject = new SqlParameter[20];
paramSaveProject[0] = new SqlParameter("#CompanyCode",CompanyCode);
paramSaveProject[1] = new SqlParameter("#ProjectName", Convert.ToString(ProjectName));
paramSaveProject[2] = new SqlParameter("#ProjectDescription", Convert.ToString(ProjectDescription));
paramSaveProject[3] = new SqlParameter("#ProjectType", ProjectType);
paramSaveProject[4] = new SqlParameter("#LocationSite", Convert.ToString(LocationSite));
paramSaveProject[5] = new SqlParameter("#Client", Convert.ToString(Client));
paramSaveProject[6] = new SqlParameter("#Latitude", Convert.ToString(Latitude == "" ? "0.00" : Latitude));
paramSaveProject[7] = new SqlParameter("#Longitude", Convert.ToString(Longitude == "" ? "0.00" :Longitude));
paramSaveProject[8] = new SqlParameter("#IsActive", Convert.ToInt32(Status));
paramSaveProject[9] = new SqlParameter("#FirstLevelApprover", Convert.ToString(FirstLevelApprover));
paramSaveProject[10] = new SqlParameter("#SecondLevelApprover", Convert.ToString(SecondLevelApprover));
paramSaveProject[11] = new SqlParameter("#ThirdLevelApprover", Convert.ToString(ThirdLevelApprover));
paramSaveProject[12] = new SqlParameter("#ProjectId", Id);
paramSaveProject[13] = new SqlParameter("#PageName",HttpContext.Current.Request.Url.Segments.Last());
paramSaveProject[14] = new SqlParameter("#Title", "Update Project Master");
paramSaveProject[15] = new SqlParameter("#UserComment", userComment);
paramSaveProject[16] = new SqlParameter("#SystemComment", "");
paramSaveProject[17] = new SqlParameter("#Revision", 0);
paramSaveProject[18] = new SqlParameter("#CreatedBy", (!string.IsNullOrEmpty(HttpContext.Current.Session["WindowsID"].ToString())) ? HttpContext.Current.Session["WindowsID"].ToString() : null);
paramSaveProject[19] = new SqlParameter("#CreatedDate", System.DateTime.Now);
Result = BLLProject.UpdateProjectMaster(paramSaveProject);
if (Result == "1")
{
obj.Code = "1";
obj.Msg = GlobalConst.strUpdateSuccess;
//BindProjectGrid(ddlDivision.SelectedItem.Value, ddlCountryPrm.SelectedItem.Value, ddlCompanyPrm.SelectedItem.Value, ddlProjMaster.SelectedValue.ToString());
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strUpdateSuccess + "');", true);
//btnCancelProject_Click(sender, e);
}
else if (Result == "2")
{
obj.Code = "2";
obj.Msg = GlobalConst.strUpdateSuccess;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strRecordExists + "');", true);
//btnCancelProject_Click(sender, e);
}
else
{
obj.Code = "0";
obj.Msg = GlobalConst.strUpdateFaliure;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strUpdateFaliure + "');", true);
//btnCancelProject_Click(sender, e);
}
}
}
catch (Exception ex)
{
var myActualType = typeof(ProjectMaster);
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Popup", "ShowPopup('" + GlobalConst.strErrorMessge + "');", true);
SecurLog.ErrorLogInfoSave(DateTime.Now, Convert.ToString(HttpContext.Current.Session["WuserCode"]), ex.Source, myActualType.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, "1", ex.Message, ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')), "1", HttpContext.Current.Request.Url.AbsoluteUri, "SECUR", Convert.ToString(HttpContext.Current.Session["ServiceCo"]));
SecurLog.SendErrorMail(DateTime.Now, Convert.ToString(HttpContext.Current.Session["WuserCode"]), ex.Source, myActualType.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, "1", ex.Message, ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')), "1", HttpContext.Current.Request.Url.AbsoluteUri, "SECUR", Convert.ToString(HttpContext.Current.Session["ServiceCo"]));
obj.Code = "0";
obj.Msg = ex.Message;
}
return JsonConvert.SerializeObject(obj);
}
In the above code a mentioned javascript function and C# webmethod the ajax call is not working, not showing any errors and not hitting the break point. please help me thanks in advance!!!!!!!!!!!!!
But the above is working with 5 parameters but not working and not showing any errors where more than 10 parameters is passed to ajax call
please help me..........
Thanks in advance
Can you please add model for the query string params
public class ProjectModel
{
public int Id { get; set; }
public string CompanyCode { get; set; }
public string ProjectName { get; set; }
public string ProjectDescription { get; set; }
public string ProjectType { get; set; }
public string LocationSite { get; set; }
public string Client { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string Status { get; set; }
public string FirstLevelApprover { get; set; }
public string SecondLevelApprover { get; set; }
public string ThirdLevelApprover { get; set; }
public string userComment { get; set; }
public string CrudType { get; set; }
}
and pass model in action method
[WebMethod]
public static string SaveAndUpdateProject(ProjectModel model)
{
// your business logic
// you can access model properties by model.Id, model.CompanyCode
}
Also, in ajax method, you need to change your obj object
var model= new Object();
model.Id = $('#HdxtProjectId').val();
model.CompanyCode = $('#ddlCompanyPrm').val();
model.ProjectName = $('#txtProjectnamePrm').val();
// rest of the properties
And in Ajax method, update data to :
data: JSON.stringify(model),

RecyclerView check CheckBox and store in database

Hello someone could help me please, I am making an application in Xamarin android as a project at school, but I have doubts with a checkbox and RecyclerView, what happens is that it assumes that the user can select one or more item within the RecyclerView and when push a poton that btnagregar save all the item name having the Checked property to true in a mysql database
MenuItemA.cs
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecycleAdapter mAdapter;
List<ItemAli> alilist;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
new I18N.West.CP1250();
new I18N.CJK.CP50220();
int idC = Convert.ToInt32(Intent.GetStringExtra("idc") ?? "Data not available");
SetContentView(Resource.Layout.RecyclerItem);
alilist = new List<ItemAli>();
try
{
string connsqlstring = "";
MySqlConnection sqlconn = new MySqlConnection(connsqlstring);
sqlconn.Open();
DataSet ds = new DataSet();
string queryString = "SELECT `IdAli`, `NombreA`, `Precio`, `Imagen`, `Tiempo` FROM `alimentos` as Item WHERE `IdCategoria` = " + idC;
MySqlDataAdapter adapter = new MySqlDataAdapter(queryString, sqlconn);
adapter.Fill(ds, "Item");
foreach (DataRow row in ds.Tables["Item"].Rows)
{
alilist.Add(new ItemAli { AliID = (row[0]).ToString(), Name = row[1].ToString(), Quantity = 0, Price = Convert.ToDecimal(row[2]), ImageId = row[3].ToString(), Time = row[4].ToString(), AddToOrder = false});
}
sqlconn.Close();
}
catch
{
Toast.MakeText(this, "La categoria esta vacia", ToastLength.Short).Show();
}
Button btnagregar = FindViewById<Button>(Resource.Id.btanadir);
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rvitem);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.SetLayoutManager(mLayoutManager);
mAdapter = new RecycleAdapter(this,alilist);
mAdapter.ItemClick += OnItemClick;
mAdapter.SpinnerItemSelectionChanged += SpinnerItemSelectionChangedEvent;
mRecyclerView.SetAdapter(mAdapter);
btnagregar.Click += delegate
{
};
}
void OnItemClick(object sender, string IdAlimento)
{
var a = new Intent(this, typeof(ActividadDetAli));
a.PutExtra("idA", IdAlimento);
StartActivity(a);
}
void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32 (spinner.Tag);
var currentquantity = alilist[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32( spinner.GetItemAtPosition (e.Position).ToString());
if (currentquantity != selectedQuantity) {
alilist [itemPosition].Quantity = selectedQuantity;
mAdapter.NotifyItemChanged (itemPosition);
}
}
}
RecycleAdapter.cs
public class VegeViewHolder: RecyclerView.ViewHolder
{
public ImageView Image { get; set; }
public TextView Name { get; set; }
public Spinner Quantity { get; set; }
public TextView Price { get; set; }
public TextView TotalAmount { get; set; }
public CheckBox cbx { get; set; }
public string idA { get; set; }
public VegeViewHolder(View itemView, Action<string> itemlistner, Action<object,AdapterView.ItemSelectedEventArgs> spinnerItemSelected )
:base(itemView)
{
Image = itemView.FindViewById<ImageView> (Resource.Id.list_image);
Name = itemView.FindViewById<TextView> (Resource.Id.Name);
Price = itemView.FindViewById<TextView> (Resource.Id.Price);
Quantity = itemView.FindViewById<Spinner> (Resource.Id.spinner1);
TotalAmount = itemView.FindViewById<TextView> (Resource.Id.total);
cbx = itemView.FindViewById<CheckBox>(Resource.Id.cbc);
itemView.Click += (sender, e) => itemlistner (idA);
Quantity.ItemSelected+= new EventHandler<AdapterView.ItemSelectedEventArgs> (spinnerItemSelected);
}
}
public class RecycleAdapter:RecyclerView.Adapter
{
public event EventHandler<string> ItemClick;
public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public List<ItemAli> Items;
Activity Context;
List<string> _quantity = new List<string> ();
public RecycleAdapter (Activity context, List<ItemAli> list)
{
this.Items = list;
this.Context = context;
PopulateSpinnerDropDownValues ();
}
void PopulateSpinnerDropDownValues()
{
_quantity.Add ("0");
_quantity.Add ("1");
_quantity.Add ("2");
_quantity.Add ("3");
_quantity.Add ("4");
_quantity.Add ("5");
_quantity.Add ("6");
_quantity.Add ("7");
_quantity.Add ("8");
_quantity.Add ("9");
_quantity.Add("10");
_quantity.Add("11");
_quantity.Add("12");
_quantity.Add("13");
_quantity.Add("14");
_quantity.Add("15");
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.list_items, parent, false);
VegeViewHolder vh = new VegeViewHolder(itemView, OnClick,spinner_ItemSelected);
return vh;
}
public override int ItemCount
{
get { return Items != null ? Items.Count : 0; }
}
void OnClick(string IdAlimento)
{
if (ItemClick != null)
ItemClick (this, IdAlimento);
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
if (SpinnerItemSelectionChanged != null)
SpinnerItemSelectionChanged (sender, e);
}
public Bitmap GetBitmapFromUrl(string url)
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(url);
if (bytes != null && bytes.Length > 0)
{
return BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
}
}
return null;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var item = Items[position];
var vh = viewHolder as VegeViewHolder;
var spinnerPos = 0;
var adapter =new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Precio: ${0}",item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0) {
spinnerPos = adapter.GetPosition (item.Quantity.ToString ());
vh.TotalAmount.Text = string.Format ("${0}", item.Price * item.Quantity);
} else {
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position;
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
Bitmap bitmap = GetBitmapFromUrl(item.ImageId);
vh.Image.SetImageBitmap(bitmap);
vh.idA = item.AliID +"°"+ item.ImageId + "°" + item.Name + "°" + item.Price + "°" + item.Time;
vh.cbx.Checked = item.AddToOrder;
}
}
}

Call Salesforce API to Add Leads using ASP.net

I am trying to call Salesforce Parnter wsdl to Create Leads to their system through my c# code.
but its giving me error:
Cannot implicitly convert type Contact[]' to 'sforce.sObject'
private string userID = "sasxxasasas#saasforce.in";
private string password = "sadwdasdasdasdsadasdsxzdddw";
private DateTime _nextLoginTime;
private string _sessionId;
string url="valueleads.in/pushleads/websvc/cigna/wsdl.xml";
SforceService binding;
private void getSessionInfo()
{
sforce.SforceService partnerService = new sforce.SforceService();
sforce.LoginResult lr = new sforce.LoginResult();
lr = partnerService.login(userID, password);
_sessionId = lr.sessionId;
Session["_sessionId"] = lr.sessionId;
Session["_serverUrl"] = lr.serverUrl;
Session["_nextLoginTime"] = DateTime.Now;
binding.SessionHeaderValue = new sforce.SessionHeader();
binding.SessionHeaderValue.sessionId = _sessionId;
binding.Url = lr.serverUrl;
}
public bool IsConnected()
{
bool blnResult = false;
if (!string.IsNullOrEmpty(_sessionId) & _sessionId != null)
{
if (DateTime.Now > _nextLoginTime)
blnResult = false;
else
blnResult = true;
}
else
blnResult = false;
return blnResult;
}
public void create()
{
if (!IsConnected())
{
getSessionInfo();
}
binding = new SforceService();
Contact contact=new Contact();
contact.fname="Eric";
contact.lname="Peter";
contact.mobile="9898989889";
Contact[] contacts = { contact };
string result;
sforce.SaveResult[] createResults = binding.create(new sObject[] { contacts });
if (createResults[0].success)
{
result = createResults[0].id;
}
else
{
result = createResults[0].errors[0].message;
}
Response.Write(result);
}
}
public class Contact
{
public String fname { get; set; }
public String lname { get; set; }
public String mobile { get; set; }
}
}
please help, very much new to this salesforce API.
You need to create an array of SObjects, not contacts, so do
sforce.sObject[] contacts = { contact };
string result;
sforce.SaveResult[] createResults = binding.create(contacts);

How to convert a function into a class to be used from any page

I have the following function which is accessible from one of my asp.net page:
/* QUERY TO RUN FROM ANY FUNCTION */
public void runQuery()
{
strMainSql = #"SELECT
CT.OBJECTID 'Object ID'
FROM HSI.RMOBJECTINSTANCE1224 CT
WHERE CT.ACTIVESTATUS = 0 AND CT.OBJECTID = '" + s + "'";
using (SqlConnection scConn = new SqlConnection(strConn))
{
scConn.Open();
using (SqlCommand scComm = new SqlCommand(strMainSql, scConn))
{
sdrRead = scComm.ExecuteReader();
while (sdrRead.Read())
{
/* CAN BE USED IN OTHER PAGES */
strTaskName = sdrRead[1].ToString();
strTaskDetail = sdrRead[2].ToString();
strTaskStartDate = sdrRead[3].ToString();
strIdentifier = sdrRead[4].ToString();
strStatus = sdrRead[5].ToString();
strDueDate = sdrRead[6].ToString();
strIssueDate = sdrRead[7].ToString();
strCompleted = sdrRead[8].ToString();
strNotes = sdrRead[9].ToString();
strProvider = sdrRead[10].ToString();
strService = sdrRead[11].ToString();
strCheckedDate = sdrRead[12].ToString();
strCheckedStatus = sdrRead[13].ToString();
strCheckedUser = sdrRead[14].ToString();
strClient = sdrRead[15].ToString();
hfMemoID.Value = sdrRead[16].ToString();
hfObjectID.Value = sdrRead[0].ToString();
break;
}
}
}
/* SPECIFIC TO THE PAGE ONLY */
lblUser.Text = strCheckedUser;
lblDateTime.Text = strCheckedDate;
lblTaskName.Text = strTaskName;
lblClient.Text = strClient;
lblID.Text = strIdentifier;
lblSvc.Text = strService;
lblProvider.Text = strProvider;
lblStat.Text = strStatus;
lblDueDate.Text = strDueDate;
lblDetail.Text = strTaskDetail;
lblTaskIssue.Text = strIssueDate;
lblStartDate.Text = strTaskStartDate;
lblCompleted.Text = strCompleted;
}
The question I have is, if I have to use the above function in multiple pages, instead of having a multiple copies of the same function which might lead to issue later on when updating, how do I make it into a class by itself so I can call it from any page and get the value from the SQL query?
What you can do is expose the results from the query as properties and then use the properties in the ASPX page.
using System.Data.SqlClient;
namespace MyNamespace
{
public class Task
{
public string strTaskName { get; set; }
public string strTaskDetail { get; set; }
public string strTaskStartDate { get; set; }
public string strIdentifier { get; set; }
public string strStatus { get; set; }
public string strDueDate { get; set; }
public string strIssueDate { get; set; }
public string strCompleted { get; set; }
public string strNotes { get; set; }
public string strProvider { get; set; }
public string strService { get; set; }
public string strCheckedDate { get; set; }
public string strCheckedStatus { get; set; }
public string strCheckedUser { get; set; }
public string strClient { get; set; }
// you need to define properties for the appropriate datatype on these
//hfMemoID
//hfObjectID
public string strConn { get; set; }
public void Load(string objectid)
{
var strMainSql = #"SELECT
CT.OBJECTID 'Object ID'
FROM HSI.RMOBJECTINSTANCE1224 CT
WHERE CT.ACTIVESTATUS = 0 AND CT.OBJECTID = '" + objectid + "'";
using (SqlConnection scConn = new SqlConnection(strConn))
{
scConn.Open();
using (SqlCommand scComm = new SqlCommand(strMainSql, scConn))
{
var sdrRead = scComm.ExecuteReader();
while (sdrRead.Read())
{
/* CAN BE USED IN OTHER PAGES */
this.strTaskName = sdrRead[1].ToString();
this.strTaskDetail = sdrRead[2].ToString();
this.strTaskStartDate = sdrRead[3].ToString();
this.strIdentifier = sdrRead[4].ToString();
this.strStatus = sdrRead[5].ToString();
this.strDueDate = sdrRead[6].ToString();
this.strIssueDate = sdrRead[7].ToString();
this.strCompleted = sdrRead[8].ToString();
this.strNotes = sdrRead[9].ToString();
this.strProvider = sdrRead[10].ToString();
this.strService = sdrRead[11].ToString();
this.strCheckedDate = sdrRead[12].ToString();
this.strCheckedStatus = sdrRead[13].ToString();
this.strCheckedUser = sdrRead[14].ToString();
this.strClient = sdrRead[15].ToString();
//
//hfMemoID.Value = sdrRead[16].ToString();
//hfObjectID.Value = sdrRead[0].ToString();
break;
}
}
}
}
}
}
In the code behind use the class to load the data and then set the controls using the properties
private MyNamespace.Task Task = new MyNamespace.Task();
protected void Page_Load(object sender, EventArgs e)
{
Task.strConn = "my connection string.";
Task.Load("task id to load");
// set the value into the controls.
lblUser.Text = Task.strCheckedUser;
lblDateTime.Text = Task.strCheckedDate;
lblTaskName.Text = Task.strTaskName;
lblClient.Text = Task.strClient;
lblID.Text = Task.strIdentifier;
lblSvc.Text = Task.strService;
lblProvider.Text = Task.strProvider;
lblStat.Text = Task.strStatus;
lblDueDate.Text = Task.strDueDate;
lblDetail.Text = Task.strTaskDetail;
lblTaskIssue.Text = Task.strIssueDate;
lblStartDate.Text = Task.strTaskStartDate;
lblCompleted.Text = Task.strCompleted;
}

String not getting value from string in requete.cs

I am not getting value from a string.
Exemple :
public static void ticket(string ticketName) // ticketName = "testTicket"
{
string abc = ticketName; // result : abc null
}
Can someone help me please I am stuck on it for almost 2 days
Here is real code
namespace FirstOutlookAddIn
{
public partial class lblSubject : Form
{
Outlook._Explorer currentExplorer = null;
private string Conversation_ID;
private string subject;
private string senderName;
private string senderEmail;
private string incident;
private DateTime creationDate;
public lblSubject()
{
InitializeComponent();
Outlook.Application myAPP = new Outlook.Application();
}
private void button3_Click(object sender, EventArgs e)
{
Outlook.Application myAPP = new Outlook.Application();
Outlook.MAPIFolder selectedFolder =
myAPP.Application.ActiveExplorer().CurrentFolder;
String expMessage = "Your current folder is "
+ selectedFolder.Name + ".\n";
String itemMessage = "Item is unknown.";
try
{
if (myAPP.Application.ActiveExplorer().Selection.Count > 0)
{
Object selObject = myAPP.Application.ActiveExplorer().Selection[1];
if (selObject is Outlook.MailItem)
{
Outlook.MailItem mailItem =
(selObject as Outlook.MailItem);
itemMessage = "The item is an e-mail message : Entery ID:"+ mailItem.EntryID+ " Conversation ID" + mailItem.ConversationID;
Conversation_ID = mailItem.ConversationID;
//mailItem.Display(false);
// Grab the Body
//txtBody.Text = mailItem.Body;
rIncident.Text = mailItem.Body;
incident = mailItem.Body;
senderName = mailItem.SenderName;
senderEmail = mailItem.SenderEmailAddress;
creationDate = mailItem.CreationTime;
Conversation_ID = mailItem.ConversationID;
// Sender Name
lblSenderName.Text = mailItem.SenderName;
// Sender Email
lblSenderEmail.Text = mailItem.SenderEmailAddress;
// Creation date
lblCreationdate.Text = mailItem.CreationTime.ToString();
}
}
private void lblSubject_Load(object sender, EventArgs e)
{
cboUsers.DataSource = Requetes.userliste();
cboPriority.DataSource = Requetes.priorityliste();
}
private void btnCreateTicket_Click(object sender, EventArgs e)
{
string userNom = cboUsers.SelectedItem.ToString();
string priorityNom = cboPriority.SelectedItem.ToString();
string convoID = Conversation_ID;
Requetes.saveTicket(userNom, priorityNom, subject,
senderName, senderEmail, incident, convoID, creationDate);
}
}
}
//Requete Class
namespace FirstOutlookAddIn
{
public static class Requetes
{
private static TicketingDBEntities6 ticketDB = new TicketingDBEntities6();
private static DateTime now = DateTime.Now;
//Recover User ID
public static void saveTicket(string userNom2, string priority, string subject,
string senderName, string email, string incident, string conversationID, DateTime mailCreateTime)
{
User u = ticketDB.User.Single(user1 => user1.User_Nom == userNom2);
int userIdenti = u.User_Id;
Priority p = ticketDB.Priority.Single(pr => pr.Priority_Name == priority);
int priorityID = p.Priority_Id;
Ticket t = new Ticket();
t.Ticket_Body = incident;
t.Ticket_ConversationID = conversationID;
t.Ticket_SenderEmail = email;
t.Ticket_SentDate = mailCreateTime;
t.Ticket_Priority = p.Priority_Id;
ObjectSet<Ticket> insert = ticketDB.Ticket;
insert.AddObject(t);
ticketDB.SaveChanges();
// Ticket ticket = ticketDB.Ticket.Single(ti => ti.Ticket_ConversationID == conversationID);
string getConvoID;
string getSenderEmail;
getSenderEmail = email;
DateTime dt = mailCreateTime;
getConvoID = conversationID;
var Users = (from uc in ticketDB.Ticket
where uc.Ticket_ConversationID == getConvoID
select uc
);
int abc = Users.Count();
Ticket_User tu = new Ticket_User();
tu.Ticket_User_Ticket_Id = ticket.Ticket_Id;
tu.Ticket_User_User_id = u.User_Id;
ObjectSet<Ticket_User> insert_Ticket_User = ticketDB.Ticket_User;
insert_Ticket_User.AddObject(tu);
ticketDB.SaveChanges();
}
}
}
THE PROBLEM IS WITH Classrequete
for exemple
if conversationID = "FFF1614651616fssd";t.Ticket_ConversationID = conversationID; // in debuget it shows conversationID is equal to "FF.....ssd" but t.Ticket_ConversationID is null:(((((((
`
Hope someone can help me out. Sorry for too much code code here
I guess you are trying to call ticket() method but you are not passing parameter to ticket("testTicket"), or when you try to call ticket(value) might be your variable is not getting value from source, I am very sure. everything is pretty straight forward.
Try to follow it:
public void SomeEvent()
{
string value = "testTicket";
ticket(value);
}
public static void ticket(string ticketName) // ticketName = "testTicket"
{
string abc = ticketName; // result : abc null
}
Good Luck.

Categories