SearchRequest and SearchReponse Classes are not present for silverlight application in CRM 2011? - dynamics-crm-2011

i want to search all the available time slots for given resources in CRM 2011. Now CRM 2011 sdk provices a sammple for that in console application which is working fine but i want to do the same thing in silverlight applciation. In my silverlight application i am unable to find the SearchRequest and SearchReponse Classes.
Can any one help me how to do this in silverlight applciation?

First prepare the AppointmentRequest object
private void checkButton_Click(object sender, RoutedEventArgs e)
{
AppointmentRequest appReq = new AppointmentRequest
{
Objectives = new ObservableCollection<ObjectiveRelation>(),
RequiredResources = new ObservableCollection<RequiredResource>(),
AppointmentsToIgnore = new ObservableCollection<AppointmentsToIgnore>(),
Constraints = new ObservableCollection<ConstraintRelation>(),
Sites = new ObservableCollection<Guid>(),
Duration = 60,
Direction = SearchDirection.Forward,
NumberOfResults = 5,
ServiceId = new Guid("DD535FD0-F84B-E111-8F2F-00505688095F"),
SearchWindowStart = DateTime.UtcNow,
SearchWindowEnd = DateTime.UtcNow.AddDays(7.0),
AnchorOffset = 300
};
OrganizationRequest req = new OrganizationRequest() { RequestName = "Search" };
req["AppointmentRequest"] = appReq;
IOrganizationService service = SilverlightUtility.GetSoapService();
service.BeginExecute(req, new AsyncCallback(GetAppReqResult), service);
}
Following is the Asynchromus callback function
private void GetAppReqResult(IAsyncResult res)
{
try
{
OrganizationResponse resp =
((IOrganizationService)res.AsyncState).EndExecute(res);
SearchResults results = (SearchResults)resp["SearchResults"];
this.Dispatcher.BeginInvoke(() => ProcessAppointments(results));
}
catch (Exception)
{
MessageBox.Show("Error Occurred");
}
}
results object will contains the all possible time slots for an appointment request object passed.
Hope this help to the people like me

Related

Add document sharepoint using web service Microsoft Dynamics CRM

I have an account entity in my Microsoft Dynamics CRM and the every account I have folder in Sharepoint which contains documents of this account I want to create app on c# using Web Services CRM IOrganizationService to Add Documents in SharePoint.
it's possible ?
Please any links to do that.
I need to help.
thanks in advance
from your Question what is understood is that you have setup SharePoint in CRM Document Management System. You must have enabled Document Location for Accounts in the Document Management Settings. Now you want to Create/Upload documents to the Sharepoint Library. You can use Sharepoint: Client Side Object Model(CSOM) to do that. I have a piece of code that creates documents in sharepoint:
//Main Section Code
string sharePointUrl = GetDefaultSPSiteUrlFromCRMSiteCollectionEntity();
SharePointMethods sharePointMethods = new SharePointMethods(sharePointUrl, spUsername, spPassword, spDomain);
ClientContext context = sharePointMethods._clientContext;
Web web = sharePointMethods._clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(newTempCRFDocumentFile);
newFile.Url = sharePointFolder.ServerRelativeUrl+ CRFfileGeneratedName;
newFile.Overwrite = true;
List docs = web.Lists.GetByTitle("Account");
Microsoft.SharePoint.Client.File uploadFile = sharePointFolder.Files.Add(newFile);
context.ExecuteQuery();
Helper Functions:
internal string GetDefaultSPSiteUrlFromCRMSiteCollectionEntity()
{
try
{
ConditionExpression c = new ConditionExpression("isdefault", ConditionOperator.Equal, true);
FilterExpression f = new FilterExpression(LogicalOperator.And);
f.Conditions.Add(c);
QueryExpression q = new QueryExpression("sharepointsite");
q.Criteria = f;
q.ColumnSet = new ColumnSet("sharepointsiteid", "name", "absoluteurl", "relativeurl", "isdefault", "parentsite");
EntityCollection crmSites = GRID.CRM.Common.Common.RetrieveMultiple(q);
if (crmSites.Entities.Count > 0)
{
Entity defaultSharePointSite = crmSites.Entities[0];
if (defaultSharePointSite.Attributes.Contains("parentsite") && defaultSharePointSite.Attributes.Contains("relativeurl"))
{
Entity parentSiteOfDefaultSite = GRID.CRM.Common.Common.RetrieveSingle("sharepointsite", ((EntityReference)defaultSharePointSite["parentsite"]).Id);
return (string)parentSiteOfDefaultSite["absoluteurl"] + "/" + defaultSharePointSite.GetAttributeValue<string>("relativeurl");
}
else
{
return defaultSharePointSite.GetAttributeValue<string>("absoluteurl");
}
}
// no SharePoint Sites defined in CRM
throw new Exception("CRM does not have any default SharePoint Sites");
}
catch (Exception ex)
{
throw new Exception("CrmMethods -> GetDefaultSPSite (" + ex.Message + ")");
}
}
internal class SharePointMethods
{
string _siteUrl;
public ClientContext _clientContext;
internal SharePointMethods(string spSiteUrl, string spUsername, string spPassword, string spDomain)
{
try
{
_siteUrl = spSiteUrl;
_clientContext = new ClientContext(_siteUrl);
_clientContext.Credentials = new System.Net.NetworkCredential
(spUsername, spPassword, spDomain);
}
catch (Exception ex)
{
throw new Exception("SharePointMethods.Constructor --> [" + ex.Message + "]");
}
}
}

OrganizationServiceProxy: No authentication error when wrong password is setup

I'm creating Organization service proxy object using following way:
[ThreadStatic]
public static OrganizationServiceProxy OrgServiceProxy;
// ...
sLog.DebugFormat("Get AuthenticationProviderType...");
AuthenticationProviderType _crmAuthType = this.GetServerType(parameters.DiscoveryUri);
sLog.DebugFormat("Get AuthenticationProviderType - DONE!");
// ...
sLog.Info("Perform metadata download (ServiceConfigurationFactory.CreateConfiguration)...");
IServiceConfiguration<IOrganizationService> _crmServiceConfiguration = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(parameters.OrgServiceUri);
sLog.Info("Perform metadata download (ServiceConfigurationFactory.CreateConfiguration) - DONE");
// ...
// enable proxy types
var behavior = new ProxyTypesBehavior() as IEndpointBehavior;
behavior.ApplyClientBehavior(_crmServiceConfiguration.CurrentServiceEndpoint, null);
// ...
public OrganizationServiceProxy GetServiceProxy(ICRMConnectionParameters parameters)
{
// ...
ClientCredentials clientCreds = new ClientCredentials();
clientCreds.Windows.ClientCredential.UserName = parameters.UserName;
clientCreds.Windows.ClientCredential.Password = parameters.Password;
clientCreds.Windows.ClientCredential.Domain = parameters.Domain;
sLog.DebugFormat("Setup client proxy...");
OrgServiceProxy = new OrganizationServiceProxy(_crmServiceConfiguration, clientCreds);
sLog.DebugFormat("Setup client proxy - DONE.");
return OrgServiceProxy;
}
Just note here that AuthenticationProviderType and IServiceConfiguration are statically cached. This code above is part of class named CRMConnection.
I have one more abstract class (ProxyUser) which contains following property:
private CRMConnection conn;
// ...
protected OrganizationServiceProxy OrgServiceProxy
{
get
{
//return orgService;
return this.Conn.GetServiceProxy();
}
}
protected CRMConnection Conn
{
get
{
conn = conn ?? new CRMConnection();
return conn;
}
}
In another class that inherits ProxyUser I have method with following code:
ColumnSet columnSet = new ColumnSet();
ConditionExpression condition1 = new ConditionExpression("new_id", ConditionOperator.NotNull);
FilterExpression filter = new FilterExpression(LogicalOperator.And);
filter.AddCondition(condition1);
QueryExpression query = new QueryExpression()
{
EntityName = new_brand.EntityLogicalName,
ColumnSet = columnSet,
Criteria = filter,
NoLock = true
};
EntityCollection res = OrgServiceProxy.RetrieveMultiple(query);
And now we come to the point :)
If I setup correct parameters - organization service url, discovery service url, username, password and domain, everything works as expected. BUT, in case when wrong password is set, in line below, service is simply unresponsive. It doesn't happen anything.
EntityCollection res = OrgServiceProxy.RetrieveMultiple(query);
Of course, I'm expecting authentication failed error. Any suggestions what I'm missing here?
Thanks in advance!
I solved this problem with adding line below in GetServiceProxy method - when ClientCredentials are created:
clientCreds.SupportInteractive = false;
I figured this out after I moved whole logic in console app. When wrong password is set and app is in debug mode, I'm getting windows login prompt. Then I found this answer.

MediaCapture.CapturePhotoToStreamAsync() and MediaCapture.CapturePhotoToStorageFileAsync() throw Argument exception

I'm trying to create an app that can use the camera for Windows Phone 8.1, using the Windows RT/XAML development model.
When I try to call either of the capture methods off of the MediaCapture class I get an ArgumentException with the message "The parameter is incorrect." Here is my code
private async Task Initialize()
{
if (!DesignMode.DesignModeEnabled)
{
await _mediaCaptureMgr.InitializeAsync();
ViewFinder.Source = _mediaCaptureMgr;
await _mediaCaptureMgr.StartPreviewAsync();
}
}
private async void ViewFinder_OnTapped(object sender, TappedRoutedEventArgs e)
{
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var stream = new InMemoryRandomAccessStream();
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
_bitmap = new WriteableBitmap((int) ViewFinder.ActualWidth, (int) ViewFinder.ActualHeight);
stream.Seek(0);
await _bitmap.SetSourceAsync(stream);
PreviewImage.Source = _bitmap;
PreviewElements.Visibility = Visibility.Visible;
ViewFinder.Visibility = Visibility.Collapsed;
Buttons.Visibility = Visibility.Visible;
Message.Visibility = Visibility.Collapsed;
stream.Seek(0);
var buffer = new global::Windows.Storage.Streams.Buffer((uint) stream.Size);
stream.ReadAsync(buffer, (uint) stream.Size, InputStreamOptions.None);
DataContext = buffer.ToArray();
if (PhotoCaptured != null)
PhotoCaptured(this, null);
}
The initialize method is called on page load, and the viewfinder_ontapped is called when they tap the CaptureElement I have in the xaml. The error is thrown on
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
What's really bizarre is that I downloaded the latest source for the winrt xaml toolkit http://winrtxamltoolkit.codeplex.com/ and tried their sample camera app, which uses similar code. It throws the same error on MediaCapture.CapturePhotoToStorageFileAsync(). Can anyone help me identify why?

call log function in windows phone 8

I am developing VoIP application (Dialler) in windows phone 8, In that application contain dial pad , contacts, call log , I already create a dial pad and contact list, I need to develop a call log function in that application. I struggle in to create a call log for windows phone 8 any help please
This is a class that creates an XML file which holds the logs of all calls. You didn't specify the question enough or what you want to do, or what have you already tried. So here is an idea of what you should implement:
public class Logger
{
private static string logPath;
public Logger()
{
logPath = "/Logs/log.xml";
}
public void LogData(string contactName, string duration)
{
Object thisLock = new Object();
logPath += DateTime.Now.ToShortDateString().Replace('.', '_') + ".log";
XmlDocument doc = new XmlDocument();
lock (thisLock)
{
try
{
XmlNode root = null;
if (File.Exists(logPath))
{
doc.Load(logPath);
root = doc.SelectSingleNode("/Call");
}
else
{
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
root = doc.AppendChild(doc.CreateElement("Call"));
}
XmlElement call = doc.CreateElement("call");
root.AppendChild(call);
XmlElement xcontactName = doc.CreateElement("contactName");
xcontactName.InnerText = contactName;
call.AppendChild(xcontactName);
XmlElement xdate = doc.CreateElement("date");
xdate.InnerText = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
call.AppendChild(xdate);
XmlElement xduration = doc.CreateElement("duration");
xduration.InnerText = duration;
call.AppendChild(xduration);
doc.Save(logPath);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
}

How to Get Project Type Guid of selected project in the Solution Explorer by using VS Package

I've created the simple VS Package for adding new item in the context menu of solution explorer. In that I need to check Selected Project's Project Type GUID. How can i get this.
For example, One Solution contains the three different type of projects, like WindowFormsApplication, MVC Projects,WebApplication. While select the MVC Projects, we need to get that ProjectType GUID.
I've tried the followings in my Package.cs,
IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection));
monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr);
IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy;
if (hierarchy != null)
{
object prjItemObject;
hierarchy.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out prjItemObject);
string projectTypeGuid;
Project prjItem = prjItemObject as Project;
projectTypeGuid = prjItem.Kind;
}
In that I get GUID as "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC" for all selected Projects.
Could anyone please help me this?
I've found answer for this,
Reference: https://www.mztools.com/articles/2007/MZ2007016.aspx
public string GetProjectTypeGuids(EnvDTE.Project proj)
{
string projectTypeGuids = "";
object service = null;
Microsoft.VisualStudio.Shell.Interop.IVsSolution solution = null;
Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hierarchy = null;
Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject aggregatableProject = null;
int result = 0;
service = GetService(proj.DTE, typeof(Microsoft.VisualStudio.Shell.Interop.IVsSolution));
solution = (Microsoft.VisualStudio.Shell.Interop.IVsSolution)service;
result = solution.GetProjectOfUniqueName(proj.UniqueName, out hierarchy);
if (result == 0)
{
aggregatableProject = (Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject)hierarchy;
result = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids);
}
return projectTypeGuids;
}
public object GetService(object serviceProvider, System.Type type)
{
return GetService(serviceProvider, type.GUID);
}
public object GetService(object serviceProviderObject, System.Guid guid)
{
object service = null;
Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider = null;
IntPtr serviceIntPtr;
int hr = 0;
Guid SIDGuid;
Guid IIDGuid;
SIDGuid = guid;
IIDGuid = SIDGuid;
serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)serviceProviderObject;
hr = serviceProvider.QueryService(ref SIDGuid, ref IIDGuid, out serviceIntPtr);
if (hr != 0)
{
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
}
else if (!serviceIntPtr.Equals(IntPtr.Zero))
{
service = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(serviceIntPtr);
System.Runtime.InteropServices.Marshal.Release(serviceIntPtr);
}
return service;
}
}
Its working fine for my requirement.

Resources