Add document sharepoint using web service Microsoft Dynamics CRM - dynamics-crm-2011

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 + "]");
}
}
}

Related

Is there a way to make a comment in TFS when adding an AD user to a TFS group?

I was wondering if I can make a comment somewhere in Team Foundation Server when I add an AD user to a TFS group or change the group of the user, for auditing purpose.
I have created a PowerShell script to record day2day changes to TFS user databases and query the AD to find out who approved this change.
Now we have a self made db.
For what it's worth - I wrote a C# method to pull the list of all members from every TFS group. Hope that helps!
EDIT: "This is posted as an answer because "xidada" was going to write a script to pull the information and since I already had the code to get the information that needed, I thought the code would be a guide to help him/her with the script"
private void btn_GetNow_Click()
{
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("http://server/collection"));
tfs.EnsureAuthenticated();
TfsConfigurationServer srv = tfs.ConfigurationServer;
CatalogNode configurationServerNode = srv.CatalogNode;
// Query the children of the configuration server node for all of the team project collection nodes
ReadOnlyCollection<CatalogNode> tpcNodes = configurationServerNode.QueryChildren(
new Guid[] { CatalogResourceTypes.ProjectCollection },
false,
CatalogQueryOptions.None
);
Guid tpcId = new Guid(tpcNodes[0].Resource.Properties["InstanceId"]);
TfsTeamProjectCollection tpc = srv.GetTeamProjectCollection(tpcId);
// get a reference to the work item tracking service
var workItemStore = tpc.GetService<WorkItemStore>();
List<Identity> result = new List<Identity>();
// iterate over the projects
foreach (Project project in workItemStore.Projects)
{
Console.WriteLine("\tProject: {0}", project.Name);
try
{
VersionControlServer versionControl = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));
TeamProject teamProject = versionControl.GetTeamProject(project.Name);
IGroupSecurityService gss = (IGroupSecurityService)tpc.GetService<IGroupSecurityService>();
Identity[] appGroups = gss.ListApplicationGroups(teamProject.ArtifactUri.AbsoluteUri);
foreach (Identity group in appGroups)
{
rtb_Users.AppendText(group.DisplayName + "\n");
Identity[] groupMembers = gss.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
foreach (Identity member in groupMembers)
{
if (member.Members != null)
{
foreach (string memberSid in member.Members)
{
Identity memberInfo = gss.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);
if (memberInfo.Type == IdentityType.WindowsUser)
{
if (!result.Contains(memberInfo))
{
result.Add(memberInfo);
rtb_Users.AppendText("\t\t" + memberInfo.AccountName + " - " + memberInfo.DisplayName + " - " + memberInfo.Domain + "\n");
}
else
{
Console.WriteLine("\t\tUser already available " + memberInfo.AccountName);
}
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("\tThe Project: '{0}' throws an exception: {1} and will be ignored.", project.Name, ex.Message);
}
}
}
This method is pulled out from my application AS IS and would need to be customized for your needs.

SharePoint copying images from document library of a Web site to a document library in another Web site

I am moving image files from document library of a Web site to a document library in another Web site. I get the following error # line SPListItem oListItemDest = oFileDest.Item;
error:
[Microsoft.SharePoint.SPException] = {"The object specified does not belong to a list."}
Code:
try
{
using (SPSite oSiteCollectionSrc = new SPSite("http://dev:32223/"))
{
SPWeb oWebsiteSrc = oSiteCollectionSrc.AllWebs["en/people"];
SPList oListSrc = oWebsiteSrc.Lists["Images"];
SPListItemCollection collListItemsSrc = oListSrc.Items;
foreach (SPListItem oListItemSrc in collListItemsSrc)
{
SPFile oFileSrc = oListItemSrc.File;
Stream srcStream = oFileSrc.OpenBinaryStream();
using (SPSite oSiteCollectionDest = new SPSite("http://www.devmysites.com/"))
{
SPWeb oWebsiteDest = oSiteCollectionDest.OpenWeb("en/people");
SPList oListDest = oWebsiteDest.Lists["Images"];
SPFileCollection collFilesDest = oListDest.RootFolder.Files;
try
{
SPFile oFileDest = collFilesDest.Add(oListDest + #"/" + oFileSrc.Name, srcStream, true);
SPListItem oListItemDest = oFileDest.Item;
oListItemDest["Created"] = oFileDest.TimeCreated;
oListItemDest["Modified"] = oFileDest.TimeLastModified;
oListItemDest.Update();
}
catch(Exception es1)
{
Console.WriteLine("# Exception:#");
Console.WriteLine(es1.Message);
}
oWebsiteDest.Dispose();
}
}
oWebsiteSrc.Dispose();
}
}
catch (Exception es)
{
Console.WriteLine("# Exception:#");
Console.WriteLine(es.Message);
}
I have also had to copy documents between sharepoint lists, the code that I used to do it is in the answer to this question: SharePoint 2010: Copy documents between lists

Add/Create new document in SharePoint document Library programmatically

I have created a new Document Library and set up custom content type with MS Word Document Template. When i click on Create new template it works fine. but i need to be able to add some logic on a button event where it will go into that library and create a new document, so that when i go into that library i will see a new document that has been created by that button event.
i tried doing it as i would do a regular list item, but i got the following error on item.update:
To add an item to a document library, use SPFileCollection.Add()
Now i did some research but everywhere i see the code for uploading a file to the document library but no where i can find how to add a new document using my template that is associated in that doc library.
please help and thanks.
public static void colFileMtod()
{
using (SPSite objsite = new SPSite("http://smi-dev.na.sysco.net/SyscoFinance/FSR/"))
{
using (SPWeb objWeb = objsite.OpenWeb())
{
SPFileCollection collFiles = objWeb.GetFolder("BPCPublishRecord").Files;
SPList lst = objWeb.Lists["BPCPublishRecordCopy"];
if (lst != null)
{
if (objWeb.Lists.Cast<SPList>().Any(list => list.Title.Equals("BPCPublishRecordCopy", StringComparison.OrdinalIgnoreCase)))
{
foreach (SPFile file in collFiles)
{
string strDestUrl = collFiles.Folder.Url + "/" + file.Name;
byte[] binFile = file.OpenBinary();
SPUser oUserAuthor = file.Author;
SPUser oUserModified = file.ModifiedBy;
System.DateTime dtCreated = file.TimeCreated;
System.DateTime dtModified = file.TimeLastModified;
SPFile oFileNew = collFiles.Add(strDestUrl, binFile, oUserAuthor, oUserModified, dtCreated, dtModified);
SPListItem oListItem = lst.AddItem();
oListItem = oFileNew.Item;
oListItem["Created"] = dtCreated;
oListItem["Modified"] = dtModified;
oListItem.Update();
objWeb.AllowUnsafeUpdates = true;
}
}
}
}
}
}

Return newly created TFS work item ID using TFS API?

Using the TFS API, I am able to create a TFS item, no problem.
What would be the best way for me to know what the Item ID is for the newly created Item?
Thank you,
George
try
{
// Authenticate User Account
NetworkCredential account = new NetworkCredential(USERNAME, PASSWORD, DOMAIN);
// for user stories from the team project where the user story will be created.
Uri collectionUri = new Uri(tfsURI);
//TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri);
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri, account);
WorkItemStore workItemStore = tpc.GetService<WorkItemStore>();
Project teamProject = workItemStore.Projects[info.TFSProjectName];
WorkItemType workItemType = teamProject.WorkItemTypes[info.ItemType];
// Create the work item.
WorkItem userStory = new WorkItem(workItemType);
userStory.Title = info.Title;
userStory.Description = info.Description;
userStory.AreaPath = info.AreaPath;
userStory.IterationPath = info.IterationPath;
userStory.Fields["Assigned To"].Value = info.AssignedTo;
if (info.ItemType == "Task")
{
userStory.Fields["Discipline"].Value = info.Discipline;
}
else if (info.ItemType == "Bug")
{
userStory.Fields["Symptom"].Value = info.Symptom;
userStory.Fields["Steps To Reproduce"].Value = info.StepsToReproduce;
}
else if (info.ItemType == "Change Request")
{
userStory.Fields["Justification"].Value = info.Justification;
}
// Save the new user story.
userStory.Save();
return true;
}
catch (Exception ex)
{
log.Error("Error Creating TFS Task.", ex);
return false;
}
finally
{
}
}
As soon as you save userStory, the ID field will be populated. You should be able to just return userStory.Id.

Sharepoint 2010 - Create Site from Code using Custom Site Template

I am creating a NEW sharepoint site from a silverlight webpart. I am using the ClientContext Model and it is working great for a team site template (STS#0). I need to create a NEW site from a CUSTOM site template that I have created, but I do not know how to reference this template being to specify a web template it is by name and only able to reference one of the standard templates.
Here is my code:
string siteUrl = App.RootSite;
string siteDescription = project.projectName; // "A new project site.";
int projectLanguage = 1033;
string projectTitle = project.projectName; // "Project Web Site";
string projectUrl = project.projectURL; //"projectwebsite";
bool projectPermissions = false;
string webTemplate = "STS#0"; //TODO: reference custom site template
try
{
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
WebCreationInformation webCreateInfo = new WebCreationInformation();
webCreateInfo.Description = siteDescription;
webCreateInfo.Language = projectLanguage;
webCreateInfo.Title = projectTitle;
webCreateInfo.Url = projectUrl;
webCreateInfo.UseSamePermissionsAsParentSite = projectPermissions;
webCreateInfo.WebTemplate = webTemplate;
oNewWebsite = oWebsite.Webs.Add(webCreateInfo);
clientContext.Load(
oNewWebsite,
website => website.ServerRelativeUrl,
website => website.Created,
website => website.Id);
clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFail);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
Loop through all of your available templates, you will find that the custom template name has the guid in front of it: {A13D0D34-EEC2-4BB5-A563-A926F7F9681A}#ProjectSiteTemplate.
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
WebTemplateCollection templates = oWebsite.GetAvailableWebTemplates(1033, true);
clientContext.Load(templates);
clientContext.ExecuteQueryAsync(onTemplateSucceeded, null);
private void onTemplateSucceeded(object sender, ClientRequestSucceededEventArgs args)
{
UpdateUIMethod updateUI = ShowTemplates;
this.Dispatcher.BeginInvoke(updateUI);
}
private void ShowTemplates()
{
foreach (WebTemplate template in templates)
{
MessageBox.Show(template.Id + " : "
+ template.Name + " : "
+ template.Title);
}
}
example
http://www.learningsharepoint.com/2010/07/25/programatically-create-site-from-site-template-sharepoint-2010/

Resources