How to add required attendees in appoitment in microsoft crm - dynamics-crm-4

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

Related

Iterating through json when new tab is created

I want to iterate through a json and send info to html each time a new tab opens. However, the chrome.tabs.onCreated.addListener isn't working. Any ideas?
Thank you!
var x;
chrome.tabs.onCreated.addListener(function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
console.log(xmlhttp.responseText)
myObj = JSON.parse(xmlhttp.responseText);
title = myObj[x].Title;
date = myObj[x].Date;
artist = myObj[x].Artist;
var obj = document.getElementById('main_image');
obj.style.background = 'url("'+myObj[x].Image+'")';
document.getElementById("title").innerHTML = title;
document.getElementById("date").innerHTML = date;
document.getElementById("artist").innerHTML = artist;
document.getElementById("help").innerHTML =
xmlhttp.responseText;
}
if (x < myObj.length + 1) {
x = x + 1;
}
else {
x = 0;
}
}
xmlhttp.open("GET", chrome.extension.getURL("config.json"), true);
xmlhttp.send();
});
Could you try with a parameter in the ramada function?
chrome.tabs.onCreated.addListener(function(tab) {
And check if the tab.id is properly retriving.
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/onCreated#Syntax

Downloading Attachment from Exchange Server using SSIS package deployed on another Server

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

Retrieve from sql data, adobe air

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

how to insert record to multiple tables with multiple file with linq2sql

I have web application in asp.net 3.5. I just want to add record to 3 tables and one table contains multiple file details that I associated with table primary key value.
For more info I include this code:
protected void submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
int user_id = 0;
var query = from u in db.Users
where u.Username == (String)Session["Username"]
select new
{
Id = u.Id
};
foreach (var item in query)
{
if (item != null)
{
user_id = int.Parse(item.Id.ToString());
break;
}
}
Post myPost = new Post();
myPost.Title = txt_ComName.Text.Trim();
myPost.Category_id = int.Parse(DDL_Categorynames.SelectedItem
.Value.ToString());
myPost.Description = txt_ComName1.Text.Trim();
myPost.User_id = user_id;
myPost.ToUser_id = user_id;
if(file_upload.HasFile)
{
myPost.IsFileAttached = true;
}
else
{
myPost.IsFileAttached = false;
}
db.Posts.InsertOnSubmit(myPost);
db.SubmitChanges();
int newId = myPost.Id;
Flag myFlag = new Flag();
myFlag.IsRead = false;
myFlag.IsImportant = false;
myFlag.IsRemoved = false;
myFlag.User_id = user_id;
myFlag.Post_History_id = newId;
db.Flags.InsertOnSubmit(myFlag);
db.SubmitChanges();
File myFile = new File();
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
string fileName = Path.GetFileName(uploadfile.FileName);
string fileType = System.IO.Path.GetExtension(fileName)
.ToString().ToLower();
myFile.Post_History_id = newId;
myFile.File_name = fileName;
myFile.File_ext = fileType;
myFile.File_Size = uploadfile.ContentLength.ToString();
if (uploadfile.ContentLength > 0)
{
uploadfile.SaveAs(Server.MapPath("~/PostFiles/")
+ fileName);
db.Files.InsertOnSubmit(myFile);
db.SubmitChanges();
}
}
Panel_AddNew.Visible = false;
Panel_ViewPostList.Visible = true;
this.FillGrid();
}
}
}
However, with this scenario first file that was selected that was inserted and after that second file iterated then error occurred like:
Cannot add an entity that already exists.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Cannot add an entity that already exists.
Source Error:
Line 248: {
Line 249: uploadfile.SaveAs(Server.MapPath("~/PostFiles/") + FileName);
Line 250: db.Files.InsertOnSubmit(myFile);
Line 251: db.SubmitChanges();
Line 252: }
Source File: f:\EasyWeb\EndUser\Post_History.aspx.cs Line: 250
please help me...
Create a new File in each iteration of the foreach loop:
for (int i = 0; i < fileCollection.Count; i++)
{
File myFile = new File();
HttpPostedFile uploadfile = fileCollection[i];
...

Cannot implicitly convert type 'System.Data.DataSet' to 'System.Collections.Generic.List<CalendarEvent>''

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