I'd like to add an custom field to contacts for permission management in my app.
f.e. Contact => Name, Number, Permission ("allowed"/"denied")
In my App I have a part which can receive commands by SMS.
Now I want to add a "Permission Management".
So that SMS from users, which are not allowed to send commands, not would be processed.
The "Permission Management" I'd like to realize with a custom field in the contactlist.
f.e. Contact => Name, Number, Permission ("allowed"/"denied")
Who can I add (programmatically) a custom filed to a contact?
(look at method "AddFieldtoContact" in ContactHelper.cs)
I found a solution where a custom mime type must be added: How to add new field(s) to the contact?
How can I add a custom mime type to add it in a contact?
-----------------------------------------------------------------------------
File StatusInAppPermission.cs
namespace Appname.Models
{
public class StatusInAppPermission
{
public const string Allowed = "allowed";
public const string Denied = "denied";
public const string NotSet = "notset";
public string Status = "";
public StatusInAppPermission(string sta)
{
switch (sta)
{
case Allowed:
Status = Allowed;
break;
case Denied:
Status = Denied;
break;
case NotSet:
Status = NotSet;
break;
default:
Status = NotSet;
break;
}
}
}
}
-----------------------------------------------------------------------------
File Contact.cs
namespace Appname.Models
{
public class Contact
{
public int Id { get; set; }
public string DisplayName { get; set; }
public string Number { get; set; }
public StatusInAppPermission StatusPermission { get; set; }
}
}
-----------------------------------------------------------------------------
File ContactHelper.cs
using Android.Provider;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Appname.Interfaces;
using Appname.Models;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(Appname.Droid.ContactHelper))]
namespace Appname.Droid
{
class ContactHelper : IContactHelper
{
public async Task<List<Contact>> GetDeviceContactsAsync()
{
Contact selectedContact = new Contact();
List<Contact> contactList = new List<Contact>();
var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
//TODO: Add element for custom field "AppnamePermission"
string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, ContactsContract.CommonDataKinds.Phone.Number /*, custom field "AppnamePermission" */ };
var cursor = Forms.Context.ContentResolver.Query(
uri,
projection,
null,
null,
ContactsContract.ContactsColumns.DisplayName + " ASC");
if (cursor.MoveToFirst())
{
do
{
// Get StatusInAppPermission from contact if saved
string status = "";
try
{
//TODO: Get custom field "AppnamePermission" value if exists
status = cursor.GetString(cursor.GetColumnIndex(projection[3]));
}
catch (Exception ex) { }
// Create new contact-object and add it to a List
contactList.Add(new Contact()
{
Id = cursor.GetInt(cursor.GetColumnIndex(projection[0]))
,DisplayName = cursor.GetString(cursor.GetColumnIndex(projection[1]))
,Number = cursor.GetString(cursor.GetColumnIndex(projection[2])).Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "")
,StatusPermission = new StatusInAppPermission(status)
});
} while (cursor.MoveToNext());
}
return contactList;
}
public async Task<Contact> GetDeviceContactByNumber(string Number)
{
Contact selectedContact = new Contact();
List<Contact> contactList = new List<Contact>();
contactList = await GetDeviceContactsAsync();
foreach (Contact c in contactList)
{
if (c.Number.Equals(Number))
{
selectedContact = c;
}
}
return selectedContact;
}
public void AddFieldtoContact(Contact contact, string fieldname, string fieldvalue)
{
int ContactId = contact.Id;
// f.i. add fieldvalue by ContactId and fieldname
// fieldname => mimetype
// replace "clsContacts.FORMALITY_MIMETYPE" with mimetype
// the following code is adapted from: https://stackoverflow.com/questions/2733589/how-to-add-new-fields-to-the-contact
try
{
ContentValues values = new ContentValues();
int mod = Forms.Context.ContentResolver.Update(
uri
,values
,Data.InterfaceConsts.RawContactId + "=" + ContactId + " AND "
+ Data.InterfaceConsts.Mimetype + "= '"
+ clsContacts.FORMALITY_MIMETYPE + "'", null);
if (mod == 0)
{
values.Put(Data.InterfaceConsts.RawContactId, ContactId);
values.Put(Data.InterfaceConsts.Mimetype, clsContacts.FORMALITY_MIMETYPE);
Forms.Context.ContentResolver.Insert(uri, values);
}
}
catch (Exception e)
{
}
}
public string GetFieldFromContact(Contact contact, string fieldname)
{
int ContactId = contact.Id;
string fieldvalue = "";
// f.i. get fieldvalue by ContactId and fieldname
return fieldvalue;
}
}
}
Related
please I have these entities to be sent to database
MatchingChildtoApplicant
{
[Key]
public int MatchId { get; set; }
public int ChildId {get; set;}
public Child Children { get; set; }
public int ApplyId {get; set;}
public ICollection<Application> Applications { get; set; }
public string MatchingBy { get; set; }
}
this is the post request to send to the database
[HttpPost]
public async Task<ActionResult<MatchingChildtoApplicant>> AddNewMatching( int applyid, int chd, [FromForm]MatchingChildtoApplicant matchingChildtoApplicant)
{
//getting the application to match
var gettheapplicantion = await _unitOfWork.ApplicationRepository.GetApplicantByIdAsync(applyid);
if(gettheapplicantion == null){
return NotFound("The Application to match was not found");
}
var appid = gettheapplicantion.ApplyId;
//getting the child to match with applicant
var childtomatch = await _unitOfWork.ChildRepository.GetChildByIdAsync(chd);
if(childtomatch == null){
return NotFound("The child to match was not found");
}
var childtoid = childtomatch.Cld;
//getting the login user doing the matching
var userdoingmatch = await _userManager.FindByEmailFromClaimsPrinciple(User);
if (userdoingmatch == null)
{
return NotFound("The user doing the matching details is missing");
}
var nameofuser = userdoingmatch.DisplayName;
//declaring new instance of MatchingChildtoApplicant
var newmatching = new MatchingChildtoApplicant
{
ApplyId = appid,
ChildId = childtoid,
MatchingBy = nameofuser,
Comment = matchingChildtoApplicant.Comment,
TheApplicationAcepted = matchingChildtoApplicant.TheApplicationAcepted,
MatchedDate = matchingChildtoApplicant.MatchedDate,
};
This is where I get the error sending to the database
// var result = await _context.MatchingChildtoApplicant.AddAsync(matchingChildtoApplicant);
// var result = await _context.MatchingChildtoApplicant.AddAsync(matchingChildtoApplicant);
// gettheapplicantion.MatchingChildtoApplicants.Children.Add(matchingChildtoApplicant);
await _context.SaveChangesAsync();
return new MatchingChildtoApplicant
{
ApplyId = appid,
ChildId = childtoid,
MatchingBy = nameofuser,
Comment = matchingChildtoApplicant.Comment,
TheApplicationAcepted = matchingChildtoApplicant.TheApplicationAcepted,
MatchedDate = matchingChildtoApplicant.MatchedDate,
};
The error I get is this
The type arguments for method 'ValueTransformerConfigurationExtensions.Add(List, Expression<Func<TValue, TValue>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. [API]
I'm working on a project that keeps track of the hours employees have worked between different crews. The way the app is supposed to work is that an employee submits a Daysheet form that has their clock-in and clock-out time and the id of their Field Manager(FMId). Each Field Manager has a column in the database that should keep track of the DaysheetIds of forms that are submitted with their FMId. The problem is that this column is only saving the first DaysheetId that gets submitted. Once there's a value in that column, the Field Manager doesn't update to add any other DaysheetIds.
To keep my post concise, I'm trying to post only the relevant code, but let me know if I'm missing something that would be important.
Here's the action in my controller where the Field Manager should be updated. I added the var FM just before the return to see what was happening to the Field Manager with the debugger.
public IActionResult Submit(EmployeeDaySheetViewModel employeeDaySheetViewModel)
{
if (ModelState.IsValid)
{
var newDaySheet = new EmployeeDaySheet
{
Id = employeeDaySheetViewModel.DaysheetId,
EmployeeId = employeeDaySheetViewModel.EmployeeId,
EmployeeName = employeeDaySheetViewModel.EmployeeName,
FMId = employeeDaySheetViewModel.FMId,
Date = employeeDaySheetViewModel.Date,
ClockIn = employeeDaySheetViewModel.ClockIn,
ClockOut = employeeDaySheetViewModel.ClockOut,
};
var success = _employeeDaySheetRepository.AddDaySheet(newDaySheet);
if (success)
{
_applicationUserRepository
.AddCrewDaySheetToFieldManager(employeeDaySheetViewModel.FMId,
employeeDaySheetViewModel.DaysheetId);
TempData["UserMessage"] = "Successfully submitted daysheet for " + DateTime.Now.Day.ToString();
}
else
{
TempData["ErrorMessage"] = "Unable to submit daysheet. Please try again in a few minutes.";
}
}
var FM = _applicationUserRepository.GetFieldManagerById(employeeDaySheetViewModel.FMId);
return Redirect("/home/");
Here is the AddCrewDaySheetToFieldManager method in my user repository that's being called in the controller action:
public bool AddCrewDaySheetToFieldManager(string FMId, string DaySheetId)
{
var fieldManager = _applicationDbContext.ApplicationUsers
.FirstOrDefault(u => u.Id == FMId);
if (fieldManager.CrewDaySheetIds != null)
{
var oldCrewIds = fieldManager.CrewDaySheetIds;
// If the user deletes all their crewIds, the database leaves an empty string in their crewIds column.
// Replacing user.crewIds that has "" at index 0 is the same as starting a new list.
if (oldCrewIds[0] == "")
{
var newCrewIds = new List<string> { DaySheetId };
fieldManager.CrewDaySheetIds = newCrewIds;
}
else
{
fieldManager.CrewDaySheetIds.Add(DaySheetId);
}
}
else { fieldManager.CrewDaySheetIds = new List<string> { DaySheetId }; }
_applicationDbContext.SaveChanges();
return true;
This is what my ApplicationUser looks like:
public class ApplicationUser : IdentityUser
{
public string Tier { get; set; }
public bool IsFieldManager { get; set; }
public double HourRate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<string> PayrollObjectIds { get; set; }
public List<string> CrewDaySheetIds { get; set; }
}
In order to convert the lists attributes of this object to strings, I've got this in my DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
var splitStringConverter = new ValueConverter<List<string>, string>(v => string.Join(";", v), v => v.Split(new[] { ';' }).ToList());
builder.Entity<ApplicationUser>().Property(nameof(ApplicationUser.PayrollObjectIds)).HasConversion(splitStringConverter);
builder.Entity<ApplicationUser>().Property(nameof(ApplicationUser.CrewDaySheetIds)).HasConversion(splitStringConverter);
base.OnModelCreating(builder);
//I also seed some data here//
}
What I can't figure out is the point at which the data is not getting saved. When I run the debugger, I can see the fieldManager is getting updated. In the AddCrewDaySheetToFieldManager method, fieldManager.CrewDaySheetIds has the DaysheetId. Then, back in the action, just before return Redirect('/home/')the FM.CrewDaySheetIds still has the DaysheetId. However, when I look at the database or try to access the CrewDaysheetIds on the FM user, only the first DaysheetId is there.
I suspect that there's something going wrong with the splitStringConversion, but I've used the same code in another project and not had this issue, so I'm stuck for what to do.
I didn't understand your question correctly but if you want update or insert some data in your database you can use _applicationDbContext.ApplicationUsers.add(fieldManager); for insert, and _applicationDbContext.Entry(fieldManager).State = EntityState.Modeified; for update. but you didn't use any of them before _applicationDbContext.SaveChanges().
I think you have to write this:
public bool AddCrewDaySheetToFieldManager(string FMId, string DaySheetId)
{
var fieldManager = _applicationDbContext.ApplicationUsers
.FirstOrDefault(u => u.Id == FMId);
if (fieldManager.CrewDaySheetIds != null)
{
var oldCrewIds = fieldManager.CrewDaySheetIds;
// If the user deletes all their crewIds, the database leaves an empty string in their crewIds column.
// Replacing user.crewIds that has "" at index 0 is the same as starting a new list.
if (oldCrewIds[0] == "")
{
var newCrewIds = new List<string> { DaySheetId };
fieldManager.CrewDaySheetIds = newCrewIds;
}
else
{
fieldManager.CrewDaySheetIds.Add(DaySheetId);
}
}
else { fieldManager.CrewDaySheetIds = new List<string> { DaySheetId }; }
_applicationDbContext.entry(fieldManager).State = EntityState.Modified;
_applicationDbContext.SaveChanges();
return true;
I'm implementing an application with Breezesharp. I ran into a issue when insert the entity in the EntityManager. The error is:
There are no KeyProperties yet defined on EntityType: 'TransportReceipt:#Business.DomainModels'
I already faced this error with my first entity type "Customer" and implement a mismatching approach as suggested here. In that case I made the get operation against my WebApi with success. But now I'm creating the TransportReceipt entity inside my application.
Mapping mismatch fix
public static class ExtendMap
{
private static bool? executed;
public static void Execute(MetadataStore metadataStore) {
if (ExtendMap.executed == true)
{
return;
}
var customerBuilder = new EntityTypeBuilder<Customer>(metadataStore);
customerBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
var transportReceiptBuilder = new EntityTypeBuilder<TransportReceipt>(metadataStore);
transportReceiptBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
var transportReceiptAttachmentBuilder = new EntityTypeBuilder<TransportReceiptAttachment>(metadataStore);
transportReceiptAttachmentBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
var uploadedFileBuilder = new EntityTypeBuilder<UploadedFile>(metadataStore);
uploadedFileBuilder.DataProperty(t => t.id).IsPartOfKey().IsAutoIncrementing();
ExtendMap.executed = true;
}
}
My base dataservice core code
public abstract class SimpleBaseDataService
{
public static string Metadata { get; protected set; }
public static MetadataStore MetadataStore { get; protected set; }
public string EntityName { get; protected set; }
public string EntityResourceName { get; protected set; }
public EntityManager EntityManager { get; set; }
public string DefaultTargetMethod { get; protected set; }
static SimpleBaseDataService()
{
try
{
var metadata = GetMetadata();
metadata.Wait();
Metadata = metadata.Result;
MetadataStore = BuildMetadataStore();
}
catch (Exception ex)
{
var b = 0;
}
}
public SimpleBaseDataService(Type entityType, string resourceName, string targetMethod = null)
{
var modelType = typeof(Customer);
Configuration.Instance.ProbeAssemblies(ConstantsFactory.BusinessAssembly);
try
{
this.EntityName = entityType.FullName;
this.EntityResourceName = resourceName;
this.DefaultTargetMethod = (string.IsNullOrWhiteSpace(targetMethod) ? "GetAllMobile" : targetMethod);
var dataService = new DataService($"{ConstantsFactory.Get.BreezeHostUrl}{this.EntityResourceName}", new CustomHttpClient());
dataService.HasServerMetadata = false;
this.EntityManager = new EntityManager(dataService, SimpleBaseDataService.MetadataStore);
this.EntityManager.MetadataStore.AllowedMetadataMismatchTypes = MetadataMismatchTypes.AllAllowable;
// Attach an anonymous handler to the MetadataMismatch event
this.EntityManager.MetadataStore.MetadataMismatch += (s, e) =>
{
// Log the mismatch
var message = string.Format("{0} : Type = {1}, Property = {2}, Allow = {3}",
e.MetadataMismatchType, e.StructuralTypeName, e.PropertyName, e.Allow);
// Disallow missing navigation properties on the TodoItem entity type
if (e.MetadataMismatchType == MetadataMismatchTypes.MissingCLRNavigationProperty &&
e.StructuralTypeName.StartsWith("TodoItem"))
{
e.Allow = false;
}
};
}
catch (Exception ex)
{
var b = 0;
}
}
}
This is who I'm trying to add the new entity
//DataService snippet
public void AttachEntity(T entity)
{
this.EntityManager.AttachEntity(entity, EntityState.Added);
}
//Business
this.TransportReceipt = new TransportReceipt { id = Guid.NewGuid(), date = DateTime.Now, customerId = Customer.id/*, customer = this.Customer*/ };
this.Attachments = new List<TransportReceiptAttachment>();
this.TransportReceipt.attachments = this.Attachments;
TransportReceiptDataService.AttachEntity(this.TransportReceipt);
When I try to add add the entity to the EntityManager, I can see the custom mapping for all my entity classes.
So my question is what I'm doing wrong.
Ok. That was weird.
I changed the mapping for a new fake int property and works. I'll test the entire save flow soon and I'll share the result here.
Update
I moved on and start removing Breezesharp. The Breezesharp project is no up-to-date and doesn't have good integration with Xamarin. I'll appreciate any comment with your experience.
I have hit a problem building a uCommerce site based on top of the demo razor store available http://thesitedoctor.co.uk/portfolio/avenue-clothingcom/
The demo uses servicestack and the ucommerceapi for its basket functions.
I am trying to add a dynamic property to the basket (on an order line) at the point where the user clicks buy. I traced through the productpage.js file and amended the code to add a new property ('message'):
function (data) {
var variant = data.Variant;
$.uCommerce.addToBasket(
{
sku: variant.Sku,
variantSku: variant.VariantSku,
quantity: qty,
message: $('#personalisedMessage').val()
},
function () {
updateCartTotals(addToCartButton);
}
);
});
using firebug, i checked the data that is being posted
addToExistingLine: true
message: "this is a message"
quantity:"1"
sku: "Product (options: none)"
variantSku:""
Posting this does not cause an error, but I cannot tell if it has worked either - I cannot find it in the database, assuming that it would be stored in OrderProperty table. In this scenario, I am 'buying' a product with no variations.
Any help is greatly appreciated with this.
Out of the box you can't add order/line item properties via the API like that. The API payload that you've added to is specified although valid JSON won't get interpreted/used by the API.
Instead what you'll need to do is add your own method to the API. To do this you'll need to implement a service from IUCommerceApiService and then you can do what you need. I've created an example (untested) below and will get it added to the demo store as I think it's a useful bit of functionality to have.
public class AddOrderLineProperty
{
public int? OrderLineId { get; set; }
public string Sku { get; set; }
public string VariantSku { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
public class AddOrderLinePropertyResponse : IHasResponseStatus
{
public AddOrderLinePropertyResponse() { }
public AddOrderLinePropertyResponse(UCommerce.EntitiesV2.OrderLine line)
{
if (line == null)
{
UpdatedLine = new LineItem();
return;
}
var currency = SiteContext.Current.CatalogContext.CurrentCatalog.PriceGroup.Currency;
var lineTotal = new Money(line.Total.Value, currency);
UpdatedLine = new LineItem()
{
OrderLineId = line.OrderLineId,
Quantity = line.Quantity,
Sku = line.Sku,
VariantSku = line.VariantSku,
Price = line.Price,
ProductName = line.ProductName,
Total = line.Total,
FormattedTotal = lineTotal.ToString(),
UnitDiscount = line.UnitDiscount,
VAT = line.VAT,
VATRate = line.VATRate
};
}
public ResponseStatus ResponseStatus { get; set; }
public LineItem UpdatedLine { get; set; }
}
public class AddOrderLinePropertyService : ServiceBase<AddOrderLineProperty>, IUCommerceApiService
{
protected override object Run(AddOrderLineProperty request)
{
var orderLineId = request.OrderLineId;
var sku = request.Sku;
var variantSku = request.VariantSku;
var orderLine = findOrderLine(orderLineId, sku, variantSku);
addPropertyToOrderLine(orderLine, request.Key, request.Value);
TransactionLibrary.ExecuteBasketPipeline();
var newLine = findOrderLine(orderLineId, sku, variantSku);
return new AddOrderLinePropertyResponse(newLine);
}
private void addPropertyToOrderLine(OrderLine orderLine, string key, string value)
{
if (orderLine == null)
return;
orderLine[key] = value;
orderLine.Save();
}
private static OrderLine findOrderLine(int? orderLineId, string sku, string variantSku)
{
return orderLineId.HasValue
? getOrderLineByOrderLineId(orderLineId)
: getOrderLineBySku(sku, variantSku);
}
private static OrderLine getOrderLineBySku(string sku, string variantSku)
{
return String.IsNullOrWhiteSpace(variantSku)
? getOrderLines().FirstOrDefault(l => (l.Sku == sku))
: getOrderLines().FirstOrDefault(l => (l.Sku == sku && l.VariantSku == variantSku));
}
private static OrderLine getOrderLineByOrderLineId(int? orderLineId)
{
return getOrderLines().FirstOrDefault(l => l.OrderLineId == orderLineId);
}
private static ICollection<OrderLine> getOrderLines()
{
return TransactionLibrary.GetBasket().PurchaseOrder.OrderLines;
}
}
You'll need to add the new method to uCommerce.jQuery.js as well something like this:
addOrderLineProperty: function (options, onSuccess, onError) {
var defaults = {
orderLineId: 0
};
var extendedOptions = $.extend(defaults, options);
callServiceStack({ AddOrderLineProperty: extendedOptions }, onSuccess, onError);
}
Let me know if you have any issues using it.
Tim
I have been given the painful task of writing a C# application to sync up employee time entries in a separate database with Quickbooks. Since I'm brand new to QB programming, I'm trying to peform basic tasks, such as getting a list of customers, then jobs for each customer, then employees. I've been reading the SDK documentation, but I'm still a little fuzzy on the details because the examples I'm finding are a little too advanced for me at the moment :-P
To keep things simple, I would like to ask for a code snippet that gives me the list of customers for starters. Here's the code I've got:
QBSessionManager SessionManager = new QBSessionManager();
IMsgSetRequest customerSet = SessionManager.CreateMsgSetRequest("US", 8, 0);
//
// Code to get list of customers here.
//
SessionManager.OpenConnection2("", "New App", ENConnectionType.ctLocalQBD);
SessionManager.BeginSession(string.Empty, ENOpenMode.omDontCare);
IMsgSetResponse Resp = SessionManager.DoRequests(customerSet);
MessageBox.Show(Resp.ToXMLString());
SessionManager.EndSession();
SessionManager.CloseConnection();
Can anyone fill in the "code to get list of customers here" for me? Thank you very much in advance!
Victor
customers.IncludeRetElementList.Add("IsActive");
customers.IncludeRetElementList.Add("ListID");
customers.IncludeRetElementList.Add("EditSequence");
customers.IncludeRetElementList.Add("Name");
customers.IncludeRetElementList.Add("ParentRef");
Only the fields specified in the above list will be returned from QuickBooks - it is very important to use the correct strings in the correct case - no error messages will result if something is wrong. You cannot specify sub-fields (eg, City within an Address block; you must get the entire Address block). For custom fields, you also must specify the OwnerID (use 0 for custom fields that are not private to an application)
customers.IncludeRetElementList.Add("DataExtRet"); //will return non-private and/or private data extension fields depending on the OwnerIDList, below
customers.OwnerIDList.Add("0"); // required for non-private data extn fields
customers.OwnerIDList.Add("Your Appln GUID"); // Use this to get private data extns for the Appln identified by the GUID
Ok, seems like I found the missing piece:
ICustomerQuery customers = customerSet.AppendCustomerQueryRq();
This produces all the data related to each customer, which is a step forward. Parsing the XML for customers should be pretty straightforward, but parsing the individual tasks/jobs for each customer will be laborious, because there are no subnodes for each task - basically you get repeating chunks of XML with all the basic customer info (address, billing address, shipping address, etc.), then this one property called "FullName" which appends a colon to the customer name, followed by the task title (which itself can be followed by another colon with a subtask title, etc.). I'm wondering if there's something clever I can do with the request query to get a better xml response (for instance, specify what properties I want returned, and maybe enforce the creation of subnodes for each task for a given customer)...comments are appreciated.
Adding to Victors, Chili and Hassan's answer. Glad to have stumbled on this question as I myself was struggling with the QBFC examples.
Here is a full set of code that might just help someone down the road. If in the meantime someone could just point me in the direction of some useful documentation...that would be great.
Getting the Employee data to an XML string
public static string EmployeeListXML()
{
QBSessionManager SessionManager = new QBSessionManager();
IMsgSetRequest msgSetReq = SessionManager.CreateMsgSetRequest("US", 8, 0);
IEmployeeQuery employee = msgSetReq.AppendEmployeeQueryRq();
employee.IncludeRetElementList.Add("IsActive");
employee.IncludeRetElementList.Add("ListID");
employee.IncludeRetElementList.Add("EditSequence");
employee.IncludeRetElementList.Add("FirstName");
employee.IncludeRetElementList.Add("LastName");
employee.IncludeRetElementList.Add("SSN");
//employee.IncludeRetElementList.Add("ParentRef");
//employee.IncludeRetElementList.Add("DataExtRet"); //will return non-private and/or private data extension fields depending on the OwnerIDList, below
employee.OwnerIDList.Add("0"); // required for non-private data extn fields
//customers.OwnerIDList.Add("Your Appln GUID"); // Use this to get private data extns for the Appln identified by the GUID
SessionManager.OpenConnection2("", Application.ProductName, ENConnectionType.ctLocalQBD);
//SessionManager.BeginSession(string.Empty, ENOpenMode.omDontCare);
SessionManager.BeginSession(frmMain.QBFileName, ENOpenMode.omDontCare); // I have the filename on frmMain
IMsgSetResponse Resp = SessionManager.DoRequests(msgSetReq);
SessionManager.EndSession();
SessionManager.CloseConnection();
//MessageBox.Show(Resp.ToXMLString());
return Resp.ToXMLString();
}
Putting the XML string into a List of Emplpoyee Objects
public static List<Employee> EmployeeXMLtoList()
{
string sXML = EmployeeListXML();
List<Employee> lstEmp = new List<Employee>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sXML);
XmlNodeList parentNode = xmlDoc.GetElementsByTagName("EmployeeRet");
foreach (XmlNode childNode in parentNode)
{
Employee oEmp = new Employee();
oEmp.ListID = childNode.SelectSingleNode("ListID").InnerText;
oEmp.EditSequence = childNode.SelectSingleNode("EditSequence").InnerText;
oEmp.Active = childNode.SelectSingleNode("IsActive").InnerText;
oEmp.FirstName = childNode.SelectSingleNode("FirstName").InnerText;
oEmp.LastName = childNode.SelectSingleNode("LastName").InnerText;
oEmp.SSN = childNode.SelectSingleNode("SSN").InnerText;
lstEmp.Add(oEmp);
}
return lstEmp;
}
Function that return an Employee Object using Linq
public static Employee GetEmployeeObject(string sSSN)
{
Employee oReturn = null;
List<Employee> lstEmployee = EmployeeXMLtoList();
IEnumerable<Employee> lstEmps = from oEmp in lstEmployee
where oEmp.SSN == sSSN
select oEmp;
foreach (var oEmp in lstEmps)
{
oReturn = oEmp;
}
return oReturn;
}
Example of Code
Employee oEmployee = QB.GetEmployeeObject("112-35-8560");
Employee Class
public class Employee
{
private string sEmployeeID;
private string sSSN;
private string sLastName;
private string sFirstName;
private string sAddress1;
private string sAddress2;
private string sCity;
private string sState;
private string sZipCode;
private string sGender;
private string sEthnicity;
private DateTime dDOB;
private string sMaritalStatus;
private int iDependants;
private string sUScitizen;
private decimal iPayRate;
private string sPhone;
private DateTime dHireDate;
private string sEmail;
public Employee() { }
public string EmployeeID
{
get { return sEmployeeID; }
set { sEmployeeID = value; }
}
public string ListID
{
get; set;
}
public string EditSequence
{
get; set;
}
public string Active
{
get; set;
}
public string SSN
{
get { return sSSN; }
set { sSSN = value; }
}
public string LastName
{
get { return sLastName; }
set { sLastName = value; }
}
public string FirstName
{
get { return sFirstName; }
set { sFirstName = value; }
}
public string FullName
{
get { return FirstName + " " + LastName; }
set { }
}
public string Address1
{
get { return sAddress1; }
set { sAddress1 = value; }
}
public string Address2
{
get { return sAddress2; }
set { sAddress2 = value; }
}
public string State
{
get { return sState; }
set { sState = value; }
}
public string City
{
get { return sCity; }
set { sCity = value; }
}
public string ZipCode
{
get { return sZipCode; }
set { sZipCode = value; }
}
public string Gender
{
get { return sGender; }
set { sGender = value; }
}
public string Ethnicity
{
get { return sEthnicity; }
set { sEthnicity = value; }
}
public DateTime DOB
{
get { return dDOB; }
set { dDOB = value; }
}
public string MaritalStatus
{
get { return sMaritalStatus; }
set { sMaritalStatus = value; }
}
public int Dependants
{
get { return iDependants; }
set { iDependants = value; }
}
public string UScitizen
{
get { return sUScitizen; }
set { sUScitizen = value; }
}
public decimal PayRate
{
get { return iPayRate; }
set { iPayRate = value; }
}
public DateTime HireDate
{
get { return dHireDate; }
set { dHireDate = value; }
}
public string Phone
{
get { return sPhone; }
set { sPhone = value; }
}
public string Email
{
get { return sEmail; }
set { sEmail = value; }
}
}