String not getting value from string in requete.cs - c#

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.

Related

Why function call twice in ASP.NET Web app

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; }
}
}
}

Create a user node in firebase database Xamarin.Android

I want to create a node in the firebase database like below:
{
"Users" : {
"SktNBDO4pOgS6wNfFIc5lV8p4u73" : {
"Email" : "user#email.com",
"Name" : "Name Surname"
}
}
}
the code I'm using is:
user = auth.CurrentUser;
//Init Firebase
dataBase = FirebaseDatabase.Instance.GetReference("Users").Child(user.Uid).Child("Name");
var postData = new UserListItemViewModel
{
Name = "Name Surname",
Email = "user#email.com",
};
dataBase.SetValue(postData.Name);
what I want to do is to set all the UserListItemViewModel into the database, like:
user = auth.CurrentUser;
//Init Firebase
dataBase = FirebaseDatabase.Instance.GetReference("Users").Child(user.Uid).Child("Name");
Dictionary<string, UserListItemViewModel> userData = new Dictionary<string, UserListItemViewModel>
{
{
user.Uid,
new UserListItemViewModel
{
Name = "Name Surname",
Email = "user#email.com",
}
}
};
dataBase.SetValue(userData);
The problem with the above code is that userData should be Java.Lang.Object.
I came in this solution following a tutorial in Java suggesting
Map<string, UserListItemViewModel> userData = new HashMap(user.Uid, new UserListItemViewModel
{
Name = "Name Surname",
Email = "user#email.com",
})`
Any help please?
I have done similar function with FCM, you can refer to the following code:
private DatabaseReference mMsgDatabaseReference;
//************************************
var taskSnapShot = (UploadTask.TaskSnapshot)snapshot;
Android.Net.Uri downloadUrl = taskSnapShot.DownloadUrl;
FriendlyMessage msg = new FriendlyMessage(null,mUserName,downloadUrl.ToString());
mMsgDatabaseReference.Push().SetValue(FriendlyMessage.MsgModelToMap(msg));
Method MsgModelToMap:
public static HashMap MsgModelToMap(FriendlyMessage msg)
{
HashMap map = new HashMap();
map.Put("text", msg.text);
map.Put("name", msg.name);
map.Put("photoUrl", msg.photoUrl);
map.Put("UId", msg.UId);
return map;
}
FriendlyMessage.cs
class FriendlyMessage : Java.Lang.Object, IParcelable
{
public String text;
public String name;
public String photoUrl;
public String UId;
public void setUid(String Id) {
this.UId = Id;
}
public String getUId() {
return UId;
}
private static readonly MyParcelableCreator<FriendlyMessage> _create = new MyParcelableCreator<FriendlyMessage>(GetMessage);
//[ExportField("CREATOR")]
[ExportField("CREATOR")]
public static MyParcelableCreator<FriendlyMessage> Create()
{
return _create;
}
private static FriendlyMessage GetMessage(Parcel parcel)
{
FriendlyMessage msg = new FriendlyMessage();
msg.text = parcel.ReadString();
msg.name = parcel.ReadString();
msg.photoUrl = parcel.ReadString();
msg.UId = parcel.ReadString();
return msg;
}
public FriendlyMessage()
{
}
public FriendlyMessage(String text, String name, String photoUrl)
{
this.text = text;
this.name = name;
this.photoUrl = photoUrl;
this.UId = Guid.NewGuid().ToString();
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPhotoUrl()
{
return photoUrl;
}
public void setPhotoUrl(String photoUrl)
{
this.photoUrl = photoUrl;
}
public int DescribeContents()
{
throw new NotImplementedException();
}
public void WriteToParcel(Parcel dest, [GeneratedEnum] ParcelableWriteFlags flags)
{
dest.WriteString(text);
dest.WriteString(name);
dest.WriteString(photoUrl);
dest.WriteString(UId);
}
public static HashMap MsgModelToMap(FriendlyMessage msg)
{
HashMap map = new HashMap();
map.Put("text", msg.text);
map.Put("name", msg.name);
map.Put("photoUrl", msg.photoUrl);
map.Put("UId", msg.UId);
return map;
}
public override string ToString()
{
return "name = " + name +" text = " + text + " photoUrl= " + photoUrl+ " UId = " + UId;
}
public static FriendlyMessage MapToMsgModel(DataSnapshot snapShot)
{
FriendlyMessage msg = new FriendlyMessage();
if (snapShot.GetValue(true) == null)
{
return null;
}
msg.UId = snapShot.Key;
msg.text = snapShot.Child("text")?.GetValue(true)?.ToString();
msg.name = snapShot.Child("name")?.GetValue(true)?.ToString();
msg.photoUrl = snapShot.Child("photoUrl")?.GetValue(true)?.ToString();
return msg;
}
public bool Equal_obj(object obj)
{
var message = obj as FriendlyMessage;
return message != null &&
text == message.text &&
name == message.name &&
photoUrl == message.photoUrl &&
UId == message.UId;
}
}

C# Save and repopulate data from array

I am working on a C# program that store the student name, student number, unit number, unit name, mark and attendance in an array. All the data are displayed in a ListView. How can I save the data from the array and then repopulate the array by using a Load Button? Thank you in advance.
public partial class Main : Form
{
public Main()
{
InitializeComponent();
//ListVIEW Properties
listView.View = View.Details;
listView.FullRowSelect = true;
}
private void insert(string StudentNumber, string StudentName, string UnitNumber, string UnitName, string Mark, string combobox)
{
// Array
string[] row = { StudentNumber, StudentName, UnitNumber, UnitName, Mark, combobox };
ListViewItem item = new ListViewItem(row);
listView.Items.Add(item);
}
private void update()
{
//Update
listView.SelectedItems[0].SubItems[0].Text = TXTStudentNumber.Text;
listView.SelectedItems[0].SubItems[1].Text = TXTStudentName.Text;
listView.SelectedItems[0].SubItems[2].Text = TXTUnitNumber.Text;
listView.SelectedItems[0].SubItems[3].Text = TXTUnitName.Text;
listView.SelectedItems[0].SubItems[4].Text = TXTMark.Text;
listView.SelectedItems[0].SubItems[5].Text = comboBox1.Text;
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
private void delete()
{
if (MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
listView.Items.RemoveAt(listView.SelectedIndices[0]);
}
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
//Insert
insert(TXTStudentNumber.Text, TXTStudentName.Text, TXTUnitNumber.Text, TXTUnitName.Text, TXTMark.Text, comboBox1.Text);
// Clear All textBox after Pressing Button
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
//Update Button
private void btnUpdate_Click(object sender, EventArgs e)
{
update();
}
//Delete Button
private void btnDelete_Click(object sender, EventArgs e)
{
delete();
}
//Clear Button
private void btnClear_Click(object sender, EventArgs e)
{
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
// ListView
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
TXTStudentNumber.Text = listView.SelectedItems[0].SubItems[0].Text;
TXTStudentName.Text = listView.SelectedItems[0].SubItems[1].Text;
TXTUnitNumber.Text = listView.SelectedItems[0].SubItems[2].Text;
TXTUnitName.Text = listView.SelectedItems[0].SubItems[3].Text;
TXTMark.Text = listView.SelectedItems[0].SubItems[4].Text;
comboBox1.Text = listView.SelectedItems[0].SubItems[5].Text;
}
array is not suitable in this case. Instead use list.
private List<Student> students = new List<Student>();
private void insert(string StudentNumber, string StudentName, string UnitNumber, string UnitName, string Mark, string combobox)
{
Student s = new Student
{
StudentNumber =StudentNumber,
StudentName =StudentName,
UnitNumber =UnitNumber
UnitName =UnitName,
Mark = Mark
Combobox = combobox
};
students.Add(s);
}
public class Student
{
public string StudentNumber{get; set;}
public string StudentName {get; set;}
public string UnitNumber {get; set;}
public string UnitName {get; set;}
public string Mark {get; set;}
public string Combobox {get;set;}
}
Follow the below steps
Add extension Method to convert your object to and from xml
ExtensionMethods class
public static class ExtensionMethods
{
/// <summary>
/// Converts given class to XML using xml serialization
/// </summary>
/// <typeparam name="T">Type of Class</typeparam>
/// <param name="classObject">Class to be serialized</param>
/// <returns>Xml string</returns>
public static string ToXML<T>(this T classObject) where T : class
{
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = Environment.NewLine;
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Document;
using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
{
xmls.Serialize(writer, classObject);
}
string xml = Encoding.UTF8.GetString(ms.ToArray());
return xml;
}
}
/// <summary>
/// Converts given XML string to class of type T
/// </summary>
/// <typeparam name="T">Type to be converted</typeparam>
/// <param name="XmlData">xml string</param>
/// <returns>class of Type T</returns>
public static T ToClass<T>(this string XmlData)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T newClass;
using (XmlTextReader reader = new XmlTextReader(new StringReader(XmlData)))
{
//reader.Namespaces = false;
newClass = (T)serializer.Deserialize(reader);
}
return newClass;
}
}
create a class to hold student information
student class
public class Student
{
public string StudentNumber{get; set;}
public string StudentName {get; set;}
public string UnitNumber {get; set;}
public string UnitName {get; set;}
public string Mark {get; set;}
public string Combobox {get;set;}
}
In form load check if file exists
Form load
//declare global variable for student list and filepath
List<Student> students = new List<Student>();
string FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName) + ".xml";
private void Form1_Load(object sender, EventArgs e)
{
string XmlData = string.Empty;
if (File.Exists(FilePath))
{
using (StreamReader sr = new StreamReader(FilePath))
{
XmlData = sr.ReadToEnd();
}
students = XmlData.ToClass<List<Student>>();
}
}
In insert,update and delete operations save the xml file to file system
save xml
string XmlData = students.ToXML();
File.WriteAllText(FilePath, XmlData);

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);

Silverlight 4.0 reading complex xml with linq

I'm stuck with following XML problem.
This is my XML file:
<POIs lastUsedId="9000010">
<POI id="9000010" name="München"><Latitude>48.139126</Latitude><Longitude>11.5801863</Longitude>
<Address>muenchen</Address><PhotoDescription>Hofbräuhaus</PhotoDescription>
<Photos directory="_x002F_pics"><PhotoFile>pic4poi_9000010-01.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-02.jpg</PhotoFile><PhotoFile>pic4poi_9000010-03.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-04.jpg</PhotoFile></Photos>
<InformationFile>infos\info4poi_9000010.txt</InformationFile></POI>
</POIs>
And here is my code to read the file:
XDocument doc = XDocument.Load(s);
lastID = Int32.Parse(doc.Root.Attribute("lastUsedId").Value.ToString());
CultureInfo cultureInfo = new CultureInfo("en-GB");
var pois = from res in doc.Descendants("POI")
select new
{
id = Int32.Parse(res.Attribute("id").Value.ToString()),
name = res.Attribute("name").Value.ToString(),
latitude = Double.Parse(res.Element("Latitude").Value, cultureInfo),
longitude = Double.Parse(res.Element("Longitude").Value, cultureInfo),
address = res.Element("Address").Value.ToString(),
photoDesc = res.Element("PhotoDescription").Value.ToString(),
photoDir = XmlConvert.DecodeName(res.Element("Photos").Attribute("directory").Value.ToString()),
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
info = res.Element("InformationFile").Value.ToString()
};
foreach (var poi in pois)
{
IEnumerable<string> pF = (poi.photoFiles as IEnumerable<string>);
List<string> photoFiles = null;
if(pF != null)
photoFiles = pF.ToList<string>();
AddPushpin(poi.id, poi.name, poi.latitude, poi.longitude, poi.address, poi.photoDesc, poi.photoDir, photoFiles, poi.info);
};
I'm unsure about the part with the PhotoFiles because I get an unknown Object error when I try to read the Pushpin.
This what my Pushpin looks like:
public class MyPushpin : Pushpin
{
public int ID { get; set; }
public string Address { get; set; }
public string PhotoDesc { get; set; }
public string PhotoDir { get; set; }
public List<string> PhotoFiles { get; set; }
public MyPushpin() { }
public MyPushpin(int id, string name, double latitude, double longitude, string address, string photoDesc, string photoDir, List<string> photoFiles, string info)
{
Location loc = new Location(latitude, longitude);
this.ID = id;
this.Location = loc;
this.Name = name;
this.Address = address;
this.PhotoDesc = photoDesc;
this.PhotoDir = photoDir;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public void Update(string name , string photoDesc, List<string> photoFiles, string info)
{
this.Name = name;
this.PhotoDesc = photoDesc;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public override string ToString()
{
return String.Format("{0} - {1}", this.ID, this.Location, this.Address, this.PhotoDesc, this.PhotoDir, this.Tag);
}
And that's the code how I would like to use the file info in the custom Pushpin:
public partial class Gallery : ChildWindow
{
List<string> pics = null;
public Gallery(MyPushpin currentPin)
{
InitializeComponent();
pics = currentPin.PhotoFiles;
Loaded += (a, b) => {
LoadImages();
};
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
Close();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
Close();
}
private void LoadImages()
{
List<Picture> coll = new List<Picture>();
pics.ForEach(delegate(String url)
{
coll.Add(AddPicture("url"));
});
//coll.Add(AddPicture("/pics/pic4poi_9000010-01.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-02.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-03.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-04.jpg"));
Preview.Source = new BitmapImage(
new Uri(
"/pics/pic4poi_9000010-01.jpg",
UriKind.Relative));
lbImage.ItemsSource = coll;
}
private Picture AddPicture(string path)
{
return new Picture
{
Href = new BitmapImage(
new Uri(
path,
UriKind.Relative))
};
}
private void lbImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Preview.Source = ((Picture)lbImage.SelectedItem).Href;
}
}
public class Picture
{
public ImageSource Href { get; set; }
THX for your time
Chau
Could you please describe the problem that you are having in more detail. Have you debugged into it, where does it fail, what is the exception? What do you expect it to do.
Off the top of my head, this code looks wrong:
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
Replace doc with res, because you want the child elements of the current element, not of the document. Also you can use Elements here instead of Descendants since they are direct children. Also since there are multiple photo files, try a SelectMany (from a ... from b ...):
photoFiles = from a in res.Elements("Photos")
from b in a.Elements("PhotoFile")
select new
{
photo = b.Value.ToString()
},

Categories