I'm trying to retrieve data from a list I was able to create using SqlConnection.
I understand how to repopulate my text boxes by selecting an item from the list box (component). But how would I get data by using a separate button, or timeline event, and fill out the text boxes. t_fname t_lname t_phone
var connection:SQLConnection;
openDatabase();
t_phone.restrict = "0-9";
function openDatabase():void
{
var dbFile:File = File.applicationStorageDirectory.resolvePath("database.db");
connection = new SQLConnection();
connection.addEventListener(SQLEvent.OPEN, onOpen);
connection.openAsync(dbFile, SQLMode.CREATE);
}
function onOpen(SQLEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connection;
stat.text = "CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, fname TEXT, lname TEXT, phone INTEGER)";
stat.execute(-1, new Responder(selectItems));
}
function selectItems(SQLEvent):void
{
b_save.enabled = false;
b_delete.enabled = false;
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connection;
stat.text = "SELECT id, fname, lname, phone FROM contacts ORDER BY id";
stat.execute(-1, new Responder(onSelected));
}
function onSelected(evt:SQLResult):void
{
if (evt.data != null)
{
itemList.dataProvider = new DataProvider();
for (var i:int=0; i<evt.data.length; i++)
{
itemList.addItem({label:(evt.data[i].fname + " " + evt.data[i].lname), data:evt.data[i]});
}
}
}
b_new.addEventListener(MouseEvent.CLICK, createNew);
function createNew(MouseEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connection;
stat.text = "INSERT INTO contacts (fname, lname, phone) VALUES (#fname, #lname, #phone)";
stat.parameters["#fname"] = t_fname.text;
stat.parameters["#lname"] = t_lname.text;
stat.parameters["#phone"] = t_phone.text;
stat.execute(-1, new Responder(selectItems));
t_fname.text = t_lname.text = t_phone.text = "";
}
itemList.addEventListener(Event.CHANGE, onChange);
function onChange(evt:Event):void
{
b_save.enabled = true;
b_delete.enabled = true;
t_fname.text = evt.target.selectedItem.data.fname;
t_lname.text = evt.target.selectedItem.data.lname;
t_phone.text = evt.target.selectedItem.data.phone;
}
b_save.addEventListener(MouseEvent.CLICK, saveThis);
function saveThis(MouseEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connection;
stat.text = "UPDATE contacts SET fname=#fname, lname=#lname, phone=#phone WHERE id=" + itemList.selectedItem.data.id;
stat.parameters["#fname"] = t_fname.text;
stat.parameters["#lname"] = t_lname.text;
stat.parameters["#phone"] = t_phone.text;
stat.execute(-1, new Responder(selectItems));
t_fname.text = t_lname.text = t_phone.text = "";
}
b_delete.addEventListener(MouseEvent.CLICK, deleteThis);
function deleteThis(MouseEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connection;
stat.text = "DELETE FROM contacts WHERE id=" + itemList.selectedItem.data.id;
stat.execute(-1, new Responder(selectItems));
t_fname.text = t_lname.text = t_phone.text = "";
}
//// ?how would I do it for this recall button ?
b_recall.addEventListener(MouseEvent.CLICK, recall1);
function recall1(MouseEvent):void
{
t_fname.text = data from the first entry
t_lname.text = data from the first entry
t_phone.text = data from the first entry
}
You have to store the data. It's harder to learn to work around not storing the data. Here's the basic code to add to your code. First line is your existing code, add new below it.
t_phone.restrict = "0-9";
var aItems:Array;
var oItem:Object;
var i:uint;
The first line is another line of your code, add the code below it - sorry that wasn't clear:
itemList.addItem({label:(evt.data[i].fname + " " + evt.data[i].lname), data:evt.data[i]});
// add item to end of aItems array
oItem = new Object();
oItem.t_id = evt.data[i].itemID;
oItem.t_fname = evt.data[i].fname;
oItem.t_fname = evt.data[i].lname;
oItem.t_phone = evt.data[i].phone;
aItems.push(oItem);
Then you can loop through your array and look for matching id or whatever.
// loop through aItems to find match for t_id
for (var i:int = 0; i < aItems.length; i++) {
if(aItems[i].t_id == testID){
trace("f_name: " + aItems[i].t_fname);
}
}
Related
good work
v.b.net I will start a new project on my project and my purpose in this project from the database to extract data from certain tables and I want to save as csv
"##FILE VERSION##","251" "##TABLEDEF START##"
"MESAJ=String,50,""MESAJ"","""",50,Data,"""""
"ID=Integer,0,""ID"","""",10,Data,"""""
"SUBEIND=Integer,0,""SUBEIND"","""",10,Data,"""""
"KASAIND=Integer,0,""KASAIND"","""",10,Data,""""" "##INDEXDEF START##"
"##INDEXDEF END##" "##TABLEDEF END##"
"MESAJ","ID","SUBEIND","KASAIND", "YeniFirma","112","100","101",
"YeniCari","100","100","101", "YeniStok","101","100","101", –
Send your sql dataset result as a parameter to this function. It create csv format for you.
public string ConvertToCSV(DataSet objDataSet)
{
StringBuilder content = new StringBuilder();
if (objDataSet.Tables.Count >= 1)
{
System.Data.DataTable table = objDataSet.Tables[0];
if (table.Rows.Count > 0)
{
DataRow dr1 = (DataRow)table.Rows[0];
int intColumnCount = dr1.Table.Columns.Count;
int index = 1;
foreach (DataColumn item in dr1.Table.Columns)
{
content.Append(String.Format("\"{0}\"", item.ColumnName));
if (index < intColumnCount)
content.Append(",");
else
content.Append("\r\n");
index++;
}
foreach (DataRow currentRow in table.Rows)
{
string strRow = string.Empty;
for (int y = 0; y <= intColumnCount - 1; y++)
{
strRow += "\"" + currentRow[y].ToString() + "\"";
if (y < intColumnCount - 1 && y >= 0)
strRow += ",";
}
content.Append(strRow + "\r\n");
}
}
}
This function send a mail:
public void sendMail(string csv)
{
var sendMailThread = new Thread(() =>
{
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv));
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = DateTime.Now.ToShortDateString() + "Report.csv";
MailMessage ePosta = new MailMessage();
ePosta.From = new MailAddress("xx");
ePosta.To.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.Attachments.Add(attachment);
ePosta.Subject = DateTime.Now + " Subject";
ePosta.Body = DateTime.Now + " body message.";
SmtpClient smtp = new SmtpClient();
smtp.Credentials = new System.Net.NetworkCredential("xxx", "xxx");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
object userState = ePosta;
smtp.SendAsync(ePosta, (object)ePosta);
});
sendMailThread.Start();
}
I have built an SSIS package which reads CSV from certain folder. But now I need to download same csv from exchange server.Also Outlook is not installed on my machine. Will I be able to download CSV from exchange server and how ? Thanks!
I have used some of the code from the link http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html but i have added some new code for removing TCP binding error using ServicePointManager as well as added search filter for retrieving specific emails and this code also takes care of multiple attachment from different emails to be saved on file system.
public void Main()
{
string filePath = "";
string fileName = "";
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
DateTime now = DateTime.Now;
DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
EmailMessage latestEmail = null;
try
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.UseDefaultCredentials = true;
//service.Credentials = new WebCredentials("username", "password");
service.Url = new Uri("");
// 10 mails per page in DESC order
ItemView view = new ItemView(10);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
searchFilterCollection.Add(greaterthanfilter);
SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
searchFilterCollection.Add(lessthanfilter);
SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
//Find mails
FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
foreach (Item item in fir.Items)
{
item.Load(); //Load the entire message with attachment
EmailMessage email = item as EmailMessage;
if (email != null)
{
if (email.HasAttachments == true && email.Attachments.Count == 1)
{
if (email.Subject.StartsWith("Scheduled search") == true)
{
filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
, email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name);
// fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
// email.Attachments[0].Name.ToString();
emailsMap.Add(email, filePath);
}
}
}
}
if (emailsMap.Count > 0) {
foreach (var item in emailsMap) {
//Save attachment
EmailMessage email = item.Key;
filePath = item.Value;
FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
fileAttachment.Load(filePath);
string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name.ToString();
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
}
// Dts.Variables["User::SourceFileName"].Value = fileName;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch(System.Runtime.InteropServices.COMException ex)
{
if (Dts.Variables.Locked == true)
{
Dts.Variables.Unlock();
}
//An error occurred.
Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
I am new to application block.
I am trying to get data from database. Following is the code snap.
JsonResponse.ashx:
public void ProcessRequest(HttpContext context)
{
HttpContext _context = HttpContext.Current;
context.Response.ContentType = "application/json";
int user_id = Convert.ToInt32(HttpContext.Current.Session["userid"]);
DateTime start = new DateTime(1970, 1, 1);
DateTime end = new DateTime(1970, 1, 1);
start = start.AddSeconds(double.Parse(context.Request.QueryString["start"]));
end = end.AddSeconds(double.Parse(context.Request.QueryString["end"]));
String result = String.Empty;
result += "[";
List<int> idList = new List<int>();
foreach (CalendarEvent cevent in EventDAO.getEvents(start, end, user_id))
{
result += convertCalendarEventIntoString(cevent);
idList.Add(cevent.id);
}
if (result.EndsWith(","))
{
result = result.Substring(0, result.Length - 1);
}
result += "]";
//store list of event ids in Session, so that it can be accessed in web methods
context.Session["idList"] = idList;
context.Response.Write(result);
}
private String convertCalendarEventIntoString(CalendarEvent cevent)
{
String allDay = "true";
if (ConvertToTimestamp(cevent.start).ToString().Equals(ConvertToTimestamp(cevent.end).ToString()))
{
if (cevent.start.Hour == 0 && cevent.start.Minute == 0 && cevent.start.Second == 0)
{
allDay = "true";
}
else
{
allDay = "false";
}
}
else
{
if (cevent.start.Hour == 0 && cevent.start.Minute == 0 && cevent.start.Second == 0
&& cevent.end.Hour == 0 && cevent.end.Minute == 0 && cevent.end.Second == 0)
{
allDay = "true";
}
else
{
allDay = "false";
}
}
return "{" +
"id: '" + cevent.id + "'," +
"title: '" + HttpContext.Current.Server.HtmlEncode(cevent.title) + "'," +
"start: " + ConvertToTimestamp(cevent.start).ToString() + "," +
"end: " + ConvertToTimestamp(cevent.end).ToString() + "," +
"allDay:" + allDay + "," +
"user_id:" + cevent.user_id + "," +
"description: '" + HttpContext.Current.Server.HtmlEncode(cevent.description) + "'" +
"},";
}
DA:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
}
sqlhelper:
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 120;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
//return the dataset
return ds;
}
I am getting error:
Cannot implicitly convert type 'System.Data.DataSet' to 'System.Collections.Generic.List'.
I am unable to understand what is the problem.
In getEvents method, you need to iterate through the records in the dataset and fill in the list that you would return in this method.
var dataset = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
foreach (var row in ds.Tables["FooTable"].Rows)
{
events.Add(new CalendarEvent(...));
}
return events;
That's because you try to return a dataset as List, which it isn't.
You need to convert the dataset to a list. A possible solution would be to change the getEvents method to something like this ->
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
var ds = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
return ds.Tables[0].AsEnumerable().Select(datarow => new CalendarEvent{ Title = datarow.Field<string>("Title), /*the rest of your params*/}).ToList();
}
Your problem is this piece of code:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
}
You defined the type of this method as List<CalenderEvent> but you return a DataSet.
I do not know which datatables are contained in your dataset, but I assume there is one which represents your calenderevents.
This means you need to extract the data you want from your dataset and make a list out of it. Assuming there is one table in your dataset your new method would look something like this:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
var data = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
events = ds.Tables[0].AsEnumerable().Select(r => new CalenderEvent
{
//using dummy properties because I dont know
//your class
Property1 = r.Field<string>("Column1"),
Property2 = r.Field<string>("column2"),
//...
}).ToList();
return events;
}
I added a new contact in microsoft dynamics 4.0 from C#. How to required attendees from code? I created a contact like this. now how to add this contact as required attendees for selected appointment ?
CRM.CrmService service = GetService();
var contactResult = new contact
{
emailaddress1 = userContact.Email
};
var requestContact = new RetrieveDuplicatesRequest
{
BusinessEntity = contactResult
,
MatchingEntityName = EntityName.contact.ToString()
,
PagingInfo = new PagingInfo
{
PageNumber = 1,
Count = 1
}
};
bool blnEmailExists = false;
try
{
var response = (RetrieveDuplicatesResponse)
service.Execute(requestContact);
foreach (contact contactItem in response.DuplicateCollection.BusinessEntities)
{
blnEmailExists = true;
contactResult.contactid = new Key();
contactResult.contactid.Value = new Guid(contactItem.contactid.Value.ToString());
contactResult.firstname = userContact.FirstName;
contactResult.lastname = userContact.LastName;
contactResult.fullname = userContact.FullName;
contactResult.mobilephone = userContact.PhoneNumber;
contactResult.description = userContact.Description;
service.Update(contactResult);
}
if (!blnEmailExists)
{
contactResult.firstname = userContact.FirstName;
contactResult.lastname = userContact.LastName;
contactResult.fullname = userContact.FullName;
contactResult.mobilephone = userContact.PhoneNumber;
contactResult.description = userContact.Description;
Guid contactId = service.Create(contactResult);
if (!string.IsNullOrEmpty(userContact.Notes))
AppendToNotesSection(userContact.Notes, contactId, service);
}
}
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new Exception(ex.Message);
}
Thanks
Through activityParty it can be updated, atlast i found it and fixed.
CRM.CrmService service = GetService();
appointment appointment = (appointment)service.Retrieve(EntityName.appointment.ToString(), activityid, new AllColumns());
if(appointment == null)
{
throw new ArgumentNullException("Invalid Appointment");
}
contact contact = RegisterContact(userContact, service);
activityparty[] activityParty = new activityparty[appointment.requiredattendees.Length + 1];
activityParty[0] = new activityparty();
activityParty[0].partyid = new Lookup();
activityParty[0].partyid.Value = contact.contactid.Value;
activityParty[0].partyid.type = "contact";
Int16 index = 1;
foreach (var item in appointment.requiredattendees)
{
//for avoiding duplicates
if (item.partyid.Value != contact.contactid.Value)
{
activityParty[index] = new activityparty();
activityParty[index].partyid = item.partyid;
activityParty[index].partyid.Value = item.partyid.Value;
activityParty[index].partyid.type = item.partyid.type;
index++;
}
}
appointment.requiredattendees = activityParty;
try
{
service.Update(appointment);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(ex.Message + ". " + ex.Detail.InnerText);
}
I load label and icon from mysql database.
and i'd like to create a list with label and icon field.
So I try to do something like that but it doesn't work indeed each line contain label but icon is empty.
var xmllisteFamille:XMLList = XML(event.result).famille;
var xmlListCollFami = new XMLListCollection(xmllisteFamille);
for each (var item:Object in xmlListCollFami){
var vbox:VBox = new VBox;
vbox.label = item.sdfNom;
trace(vbox.label);
vbox.percentHeight=100;
vbox.percentWidth=100;
var xmlItem2:XMLList = item.commDent;
if(xmlItem2.length()>0){
/*
var listAcc:List = new List();
listAcc.percentHeight = 100;
listAcc.percentWidth =100;
listAcc.labelField = "name";
listAcc.dataProvider = xmlItem2;
vbox.addChild(listAcc);
accOnglet1.addChild(vbox); */
var urlImageRoot : urlManager = new urlManager();
var urlRootDental:String = urlImageRoot.urlDental();
trace(urlRootDental);
var list:Array = new Array();
var object:Object;
var xmlListdetail:XMLListCollection = new XMLListCollection(xmlItem2);
for each (var item2:Object in xmlListdetail)
{
object = new Object();
// -- --
object.label = item2.name;
var rootIcon:String= "http://127.0.0.1:10088/Sys/OEMySQL/Dental/"+item2.photo;
trace("rootIcon " + rootIcon);
object.icon = rootIcon;
trace("object.icon " + object.icon);
list.push(object);
}
/* var aNode:XML;
for each (aNode in xmlItem2)
{
object = new Object();
// -- --
object.label = aNode.name;
object.icon = new urlManager().urlDental()+aNode.photo;
list.push(object);
} */
var arrList:ArrayList;
arrList = new ArrayList(list);
var listAcc:List = new List();
listAcc.percentHeight = 100;
listAcc.percentWidth =100;
listAcc.labelField = "label";
listAcc.iconField="icon";
//listAcc.dataProvider = xmlItem2;
listAcc.dataProvider = arrList;
vbox.addChild(listAcc);
accOnglet1.addChild(vbox);
}
}
}
}
I hope that you can help me.
Thanks
it may be crossdomain issue
you need to know if flash player requires crossdomain.xml in this case
use charles proxy to check what exactly you are sending to server (request) and getting back from server (response)
charles proxy website
I found the solution.
I had to create an itemrenderer and add it in as3 to my list.
thanks