I just try to create one of WCF to get all client details. When I try to run that WCF which get data from SP its show this error:
Caught exception:
And also when put break point that time I see the ID is coming but still error showing same.
Class code:
public class CommanCall
{
string Connection = "Data Source=USER-PC\\SQLEXPRESS;Initial Catalog=BlueEyeNewDatabase;Integrated Security=True";
public List<Client> SelectAllClient(int id)
{
List<Client> ClientList = new List<Client>();
using (var Context = new EmpSystemContext(Connection))
{
var DbResult = Context.SelectClientDetails(id);
if (DbResult != null)
{
foreach (var Row in DbResult)
{
Client clist = new Client
{
ClientName = Row.ClientName,
ClientAddress = Row.ClientAddress,
PreferredCurrency = Row.PreferredCurrency,
FirstName = Row.FirstName,
LastName = Row.LastName,
City = Row.City,
State = Row.State,
Country = Row.Country,
PostalCode = Row.PostalCode,
ContactName = Row.ContactName,
ContactNumber = Row.ContactNumber,
Email = Row.Email,
ContactEmail = Row.ContactEmail
};
ClientList.Add(clist);
}
}
}
return ClientList;
}
}
Service.svc.cs
public class Service1 : IService1
{
public static EmpSystem.Domain.CommanCall Comman;
public ListResponce<Client> GetAllClientDetailsById(int id)
{
ListResponce<Client> lstclientResp = new ListResponce<Client>();
lstclientResp.Message = "Taru kai na thai ek record find na thayo";
lstclientResp.Success = false;
int id1 = id;
List<Client> lstclient = Comman.SelectAllClient(id);
lstclientResp.Result = lstclient;
if(lstclient!=null)
{
lstclientResp.Message = "Congo hahahhah Record Find thaya";
lstclientResp.Success = true;
}
return new ListResponce<Client>
{
Message = lstclientResp.Message,
Success = lstclientResp.Success,
Result = lstclientResp.Result
};
}
}
IService file
public interface IService1
{
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
ListResponce<Client> GetAllClientDetailsById(int id);
}
From the code you posted I can suggest you forgot to create an instance of CommanCall. Field Comman is reference type which is by default initialized with null. So NullReferenceException thrown when you trying to call member of null. Create an instance for Comman, for example:
public static EmpSystem.Domain.CommanCall Comman = new EmpSystem.Domain.CommanCall();
If field Comman initialized somewhere else, please, show stack trace of exception you caught.
Related
I want to pass to external web service some values of an entity (Case/incident) while new record is going to be created.
I have a model for preparing data which have to be sent to web service as below:
public class TicketViewModel
{
public string CaseID { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public string CreateTime { get; set; }
public string Owner { get; set; }
public string States { get; set; }
public string Assigned { get; set; }
}
Here is my code inside Execute() method:
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
try
{
var entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "incident") // The logical name for Case entity
return;
Guid recordID = entity.Id;
var ticket = new CaseViewModel
{
// Retrieving Intended Fields Value
};
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Name = "HttpBinding_Service";
httpBinding.Security.Mode = BasicHttpSecurityMode.None;
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
httpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
httpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress epa = new EndpointAddress(#"webservice/url/address");
CallChamberPortalSoapClient tcClient = new CallChamberPortalSoapClient(httpBinding, epa);
var res = tcClient.addTicket(//Passing Intended Fields Value);
entity["X"] = res.ToString();
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Failed to register ticket by this error: " + ex.Message);
}
My first question is how to retrieve intended fields value on Create new record? I have used entity["X"] to get value of "X" field but nothing returned.
My second question is how to set value of a field on Update a record? Using same expression ( entity["X"] = "NewValue" ) not worked for me.
Note: sample static data has sent to web service successfully and it returned true as result.
EDIT:
I tried to get values as below but have error in CRM create record event.
ColumnSet cs = new ColumnSet(new string[] {
"ticketnumber", "title", "description", "createdon", "customerid", "new_peygiriii", "createdby" });
Entity wholeCase = service.Retrieve("incident", recordID, cs);
Owner = wholeCase.GetAttributeValue<EntityReference>("customerid").ToString();
Error:
Unable to cast object of type Microsoft.Xrm.Sdk.OptionSetValue to type
Microsoft.Xrm.Sdk.EntityReference
Thanks.
First, You should register your plugin in Dynamics as Post operation (create). Reason once the record is created in System, you will get it's Guid and so on. This is best way and in addition make your plugin Asynchronous (syn only if it is a real must for your use case).
Now when you create a recrod in crm plugin will get it's context as you are doing.
var entity = (Entity)context.InputParameters["Target"];
now you can get particualr fileds value, you do something like below
if(entity.contains("field name")){
var recordName=entity.GetAttributeValue<string>("field name");
}
if you want optionset values you do something like below
if(entity.contains("optionset field name")){
int selectedTopic = entity.GetAttributeValue<OptionSetValue>("optionset field name").Value
String text = entity.FormattedValues["optionset field name"].ToString();
}
To set up? what type of data you want to set up, assuming you want to set up optionset value
entity["X"] = new OptionSetValue(INDEX)
The INDEX is an int you can look up in your optionset editor (default values are several digit long).
I am writing a C# app in a Xamarin.Forms project that displays a contact name, and street address. I am having trouble pulling the address from the CNContact and assigning the contacts address to a string.
Its going to be something obvious, but i'm stuck!
public List<Contact> GetContacts()
{
contactList = new List<Contact>();
var store = new Contacts.CNContactStore();
var ContainerId = new CNContactStore().DefaultContainerIdentifier;
var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId);
var fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.Birthday, CNContactKey.PostalAddresses, CNContactKey.ImageData };
NSError error;
var IPhoneContacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
foreach(var c in IPhoneContacts)
{
var contact = new Contact();
contact.FirstName = c.GivenName;
contact.FamilyName = c.FamilyName;
if(c.PostalAddresses.Length !=0)
{
contact.StreetAddress = CNPostalAddressFormatter.GetStringFrom(c.PostalAddresses, CNPostalAddressFormatterStyle.MailingAddress);
};
contactList.Add(contact);
}
return contactList;
}
The problem is that CNPostalAddressFormatter.GetStringFrom() method expects a single CNPostalAddress object as a parameter but you're passing all addresses of a single contact since the PostalAddresses property is an array of CNLabeledValue<ValueType> objects.
What you should do is iterate over all addresses, or perhaps just take the first one by default. Really depends on what you want to achieve.
For example, this would get the first CNPostalAddress:
contact.StreetAddress = CNPostalAddressFormatter.GetStringFrom(c.PostalAddresses[0].Value, CNPostalAddressFormatterStyle.MailingAddress);
Also, if you want to know the label of the address (Home, Work etc), you can get it like this:
c.PostalAddresses[0].Label
Then the actual CNPostalAddress object is again this:
c.PostalAddresses[0].Value
Fetching Existing Contacts in iOS :
First , you need to add follow permission in Info.plist :
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
Second , you can create a model contains of needs contact info as follow :
public class ContactModel
{
public IList PhoneNumbers { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
}
Third , create a func to fetch info :
public List<ContactModel> ReadContacts()
{
var response = new List<ContactModel>();
try
{
//We can specify the properties that we need to fetch from contacts
var keysToFetch = new[] {
CNContactKey.PhoneNumbers, CNContactKey.GivenName, CNContactKey.FamilyName,CNContactKey.PostalAddresses,CNContactKey.PhoneNumbers
};
//Get the collections of containers
var containerId = new CNContactStore().DefaultContainerIdentifier;
//Fetch the contacts from containers
using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
{
CNContact[] contactList;
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysToFetch, out
var error);
}
//Assign the contact details to our view model objects
response.AddRange(from item in contactList
where item?.EmailAddresses != null
select new ContactModel
{
PhoneNumbers = item.PhoneNumbers,
PostalAddresses = CNPostalAddressFormatter.GetStringFrom(item.PostalAddresses[0].Value, CNPostalAddressFormatterStyle.MailingAddress),
GivenName = item.GivenName,
FamilyName = item.FamilyName
});
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return response;
}
Fourth , invoke func :
List<ContactModel> contacts = ReadContacts();
ContactModel contactVm;
for (int i = 0; i < contacts.Count; i++)
{
contactVm = contacts[i];
Console.WriteLine("Contact is : " + contactVm.FamilyName);
Console.WriteLine("Contact is : " + contactVm.GivenName);
Console.WriteLine("Contact is : " + contactVm.PostalAddresses);
}
...
Contact is : Taylor
Contact is : David
Contact is : 1747 Steuart Street
Tiburon CA 94920
USA
Fifth , the screenshot as follow :
===================================Udate=====================================
Your code should be modified as follow :
public List<Contact> GetContacts()
{
contactList = new List<Contact>();
var store = new Contacts.CNContactStore();
var ContainerId = new CNContactStore().DefaultContainerIdentifier;
var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId);
var fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.Birthday, CNContactKey.PostalAddresses, CNContactKey.ImageData };
NSError error;
var IPhoneContacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
foreach(var c in IPhoneContacts)
{
var contact = new Contact();
contact.FirstName = c.GivenName;
contact.FamilyName = c.FamilyName;
if(c.PostalAddresses.Length !=0)
{
contact.StreetAddress = CNPostalAddressFormatter.GetStringFrom(c.PostalAddresses[0].Value, CNPostalAddressFormatterStyle.MailingAddress);
};
contactList.Add(contact);
}
return contactList;
}
The property postalAddress of Method CNPostalAddressFormatter.GetStringFrom
is a type of object(Contacts.CNPostalAddress) , however c.PostalAddresses is a type of Array.
public static string GetStringFrom (Contacts.CNPostalAddress postalAddress, Contacts.CNPostalAddressFormatterStyle style);
I have created the class at the bottom in c#. This class is referenced by webservices to determine user accesses, like this:
[WebMethod]
public List<FAFSA> getFAFSA(string pageID)
{
formValues fv = new formValues();
string personID = fv.personID;
List<FAFSA> lf = new List<FAFSA>();
if (fv.secBlur == "no_secBlur")
{
FAFSA f = new FAFSA();
f.fafsaCheck = "0";
lf.Add(f);
}
...
}
I'm trying to add the two variables fafsa and staff. The method getSecBlur() is returning all three values from my database for secBlur, fafsa, and staff. So how do I set up this class, so that the SecBlur method is only called once but populates all three of my variables so that they can be used in webservice calls? It will not work the way it is now because it says fafsa and staff need to be static, but if I make them static, then in the webservices it says that the members must be accessed with an instance reference.
Sorry if this isn't worded to well, but I'm new to this and still trying to learn...
public class formValues : System.Web.Services.WebService
{
public string userName = getUserName();
public string firstName = getFirstName();
public string personID = getPersonID();
public int fafsa = 0;
public int staff = 0;
public string secBlur = getSecBlur();
private static string getUserDataString(int ix)
{
string retValue = "";
if (HttpContext.Current.Request.IsAuthenticated)
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
if (ticket != null)
{
string[] userData = { "" };
char[] delimiterChar = { '|' };
userData = ticket.UserData.Split(delimiterChar);
if (userData.Length > 1)
retValue = userData[ix];
else
{
FormsAuthentication.SignOut();
string redirUrl = "/DMC/loginNotFound.html";
HttpContext.Current.Response.Redirect(redirUrl, false);
}
}
}
}
return retValue;
}
private static string getUserName()
{
//This retrieves the person logged into windows/active directory
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
//string[] fullUsername = wp.Identity.Name.Split('\\');
string fullUsername = wp.Identity.Name;
return fullUsername;
}
private static string getFirstName()
{
string firstName = getUserDataString(1);
return firstName;
}
private static string getPersonID()
{
string personID = getUserDataString(0);
return personID;
}
private static string getSecBlur()
{
string secBlur = "no_secBlur";
string mySQL = "exec get_UserAdminStatus #personID";
string cf = System.Configuration.ConfigurationManager.ConnectionStrings["DistrictAssessmentDWConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(cf);
SqlCommand command = new SqlCommand(mySQL, connection);
command.Parameters.AddWithValue("#personID", getUserDataString(0));
connection.Open();
SqlDataReader dr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
connection.Close();
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["secBlur"].ToString() == "1")
secBlur = "secBlur";
fafsa = Convert.ToInt32(dt.Rows[0]["fafsa"]);
staff = Convert.ToInt32(dt.Rows[0]["staff"]);
}
return secBlur;
}
}
If you give any class static, public values the so called "Static" (or type) Constructor will be called to do the initialization work before any access is done: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Another common way to do initlizsation or define default values, is to use the Factory Pattern. Afaik the Graphics Class in XNA has to adapt depending if you run ona X-Box or PC, so it uses the Factory Pattern.
Of coruse with Web(anything) there is the whole issue with variable Scope, even for Statics. Much less local variables.
I have Implemented services using web service in our application and now we are modifying those services to WCF and I declared all service methods in IService.cs using contracts and implemented them in Service.svc but while building the service it is showing an error
The name 'context' does not exist in the current context.
I have tried adding <service.webmodels> in web.config file and
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
in Service.svc and response format:json in both nothing works.. please if anyone have tried or gone through this error. Please do share...
Here is my code in ICandidateService.cs:
[ServiceContract]
public interface ICandidateService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
void getcandidates(int candidate_id, string whereclause, string hotlist_ind);
}
and CandidateService.svc:
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class CandidateService : ICandidateService
{
[Dependency]
public ICandidateDB candidateDb { get; set; }
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public void getcandidates(int candidate_id, string whereclause, string hotlist_ind)
{
List<Candidatedetails> canddetails = new List<Candidatedetails>();
DataSet ds = candidateDb.GetCandidates(candidate_id, whereclause, hotlist_ind);
foreach (DataRow dtrow in ds.Tables[0].Rows)
{
Candidatedetails cand = new Candidatedetails();
//cand.code = "";// dtrow["code"].ToString();
//cand.avalability = dtrow["avalability"].ToString();
//if(dtrow["available_date"].ToString()==""){
// cand.available_date = "";
//}
//else
//cand.available_date = Convert.ToDateTime(dtrow["available_date"]).ToString("MM/dd/yyyy");
// cand.exptd_loaded_cost = dtrow["exptd_loaded_cost"].ToString();
cand.candidate_ID = dtrow["candidate_ID"].ToString();
cand.Display_Name = dtrow["display_name"].ToString();
cand.Mobile = dtrow["mobile"].ToString();
cand.Email = dtrow["email1"].ToString();
cand.qualification = dtrow["qualification"].ToString();
cand.skills = dtrow["skills"].ToString();
cand.experience = dtrow["experience"].ToString();
cand.Salary = dtrow["expectedSalary"].ToString();
cand.category = dtrow["category"].ToString();
//cand.subcategory = dtrow["subCategory"].ToString();
cand.attachmentFlag = dtrow["attachmentFlag"].ToString();
cand.city = dtrow["city"].ToString();
cand.State = dtrow["State"].ToString();
cand.country = dtrow["country"].ToString();
cand.currentEmployer = dtrow["currentEmployer"].ToString();
cand.dateOfBirth = dtrow["dateOfBirth"].ToString();
canddetails.Add(cand);
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string _jsonReturn = jSearializer.Serialize(canddetails);
_jsonReturn = "{\"aaData\":" + _jsonReturn + "}";
Context.Response.Write(_jsonReturn);
//return _jsonReturn;
// return details.ToArray();
//ResponseFormat.Json(_jsonReturn);
}
A quick one:
If you want to return just a json serialized string, at the end of your method just
return _jsonReturn;
instead of
Context.Response.Write(_jsonReturn);
do not forget to change your return value of getcandidates() from void to string.
Sorry if the title does not reflect what I actually want.
I'm creating a generic class for selecting, updating, inserting and deleting dates from and to a database.
Basically, I want a function that gives me back an ObservableCollection<"can be anything"> ==> Where anything is a class and not strings. I would like to know if it is possible to do this, if yes, please,help me how I can achieve this.
this is my starting point:
//class a
public static ObservableCollection<ContactPerson> contactPersons = new ObservableCollection<ContactPerson>();
public static ObservableCollection<ContactPerson> getContactPerson()
{
contactPersons = (ObservableCollection<ContactPerson>)DBConnection.GetDataOutDatabase(typeof(ContactPerson), "Contactpersoon");
return contactPersons;
}
//class b
public static Object GetDataOutDatabase(Type myType,String table)
{
ObservableCollection<Object> objecten = new ObservableCollection<Object>();
string sql = "SELECT * FROM " + table;
DbDataReader reader = Database.GetData(sql);
while (reader.Read())
{
objecten.Add(Create(myType, reader));
}
return objecten;
}
private static Object Create(Type myType, IDataRecord record)
{
PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < myPropertyInfo.Length; i++)
{
PropertyInfo myPropInfo = (PropertyInfo)myPropertyInfo[i];
String name = myPropInfo.Name;
Type type = myPropInfo.PropertyType;
}
return null;
}
And this is what I ultimately want to get. Is this possible?
//ContactPerson cp = new ContactPerson();
//cp.ID = (record["ID"].ToString());
//cp.Name = record["Name"].ToString();
//cp.Company = record["Company"].ToString();
//cp.JobTitle = new ContactPersonTitle()
//{
// Name = record["JobTitle"].ToString(),
//};
//cp.JobRole = new ContactPersonType()
//{
// Name = record["JobRole"].ToString(),
//};
//cp.City = record["City"].ToString();
//cp.Email = record["Email"].ToString();
//cp.Phone = record["Phone"].ToString();
//cp.Cellphone = record["Cellphone"].ToString();
Many thanks!
You can actually do this with reflection in generic methods.
public class DBConnection
{
public static ObservableCollection<T> GetDataOutDatabase<T>(string table)
{
var objecten = new ObservableCollection<T>();
string sql = "SELECT * FROM " + table;
DbDataReader reader = Database.GetData(sql);
while (reader.Read())
{
objecten.Add(Create<T>(reader));
}
return objecten;
}
public static T Create<T>(IDataRecord record)
{
var properties = typeof(T).GetProperties();
var returnVal = Activator.CreateInstance(typeof(T));
properties.ToList().ForEach(item =>
{
try
{
if (item.PropertyType.IsPrimitive)
{
item.SetValue(returnVal, Convert.ChangeType(record[item.Name].ToString(), item.PropertyType),null);
}
else
{
object[] parameters = {record};
var value =
typeof(DBConnection).GetMethod("Create").MakeGenericMethod(item.PropertyType).Invoke(null, parameters);
item.SetValue(returnVal,value,null);
}
}
catch
{
Write("Property Not Found");
}
});
return (T)returnVal;
}
}
The example above does assume that all properties names match the column names you are retrieving from your database communication. For instance in the ContactPersonTitle above rather than Name you would need to have JobTitle as the property name.
Not as you are currently doing it. You should look into the entity framework which allows translation of database tables datacollections.
have a look at:
http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B