How to determine if a file exists in a SharePoint SPFolder [closed] - sharepoint

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Is there a way other than looping through the Files in a SPFolder to determine if a give filename (string) exists?

You can, if you know the URL also use the SPFile.Exists property as follows:
using (SPSite site = new SPSite("http://server/site"))
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("/site/doclib/folder/filename.ext");
if (file.Exists)
{
...
}
}
One would on first thought assume SPWeb.GetFile throws an exception if the file does not exist. But as you see this is not the case - it will actually return a SPFile object.

But if you are using SP 2010 Client OM, it would actually throw an exception if the file doesn't exist:
using(var clientContext = new ClientContext(site))
{
Web web = clientContext.Web;
Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl("/site/doclib/folder/filename.ext");
bool bExists = false;
try
{
clientContext.Load(file);
clientContext.ExecuteQuery(); //Raises exception if the file doesn't exist
bExists = file.Exists; //may not be needed - here for good measure
}
catch{ }
if (bExists )
{
.
.
}
}

Using a CAML query is the most efficient way (example here)
CAML can be a bit unwieldy, so also worth looking at the Linq to Sharepoint provider, which hides the details of CAML away from you.

Related

Azure search schema migrations [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What's the best way to migrate an Azure search schema in a release pipeline?
In the SQL world, I'd use something like DbUp. Is there anything similar for Azure search?
Or is there a different approach when the schema needs to change?
It depends on whether you are pushing content via the SDK or if you are pulling content from a supported content source using one of the pre-built indexers. Using the SDK you can add new properties to your model as explained in this post: Update Azure search document schema
Note: Changes in your data model may require either an update or a rebuild of the index. For example, adding new properties only requires and update. But, if you change a setting like searchable, filterable or sortable you will need a rebuild. For details, see How to rebuild an index in Azure Cognitive Search
COMPATIBILITY PROBING VIA PUSH
My preferred solution is to use push indexing for everything. To test if the data model in the index is compatible, I create a sample item and submit to the index. If the model used in the index is incompatible, and error is thrown by the Azure Search SDK. I then delete the index and create it from scratch using my new model.
Here is a simplified method to test if any item is compatible with a named index:
public async Task<bool> TestItemAsync<T>(T item, string indexName)
{
var isCompatible = false;
var indexClient = _searchServiceClient.Indexes.GetClient(indexName);
var indexActions = new List<IndexAction<T>> { IndexAction.MergeOrUpload((item)) };
var batch = IndexBatch.New(indexActions);
try
{
var unused = await indexClient.Documents.IndexAsync(batch);
isCompatible = true;
}
catch
{
// ignored
}
return isCompatible;
}
And here is an example of how you might use it to probe your index for compatibility.
var item = new Product();
item.ID = 123;
item.Title = "Sample";
item.MyNewProperty = "Some value"
// ...
var isCompatible = await TestItemAsync(item, indexName);
if (isCompatible)
{
await DeleteItemAsync(item, indexName);
}
else
{
await DeleteIndexAsync<T>(indexName);
await CreateIndexAsync<T>(indexName);
}
To actually verify the compatiblity, make sure you populate your item with some values. In this example I hard-coded some values for the sake of the example. In actual use I use a Mock framework that populates every property of my item with some random sample value, but I did not want to give the impression that a third-party component is required for this use-case.

json find object by name and grab its value (api) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
i am grabbing the steam data and saving it to variable called body
now what i want to do is find total_kills its not necessary that this object is always at body.playerstats.stats[0].value so is there any way to find the body by total_kills and get its value
the complete api reply is given below with beautified form
https://codebeautify.org/jsonviewer/cb2b563d
It seems like body.playerstats.stats is an Array that contains objects. What you could do is go through that array and store all the objects that have name: 'total_kills', something like this could work:
const totalKillsArr = body.playerstats.stats.filter((stat) => {
return stat.name === 'total_kills';
});
Once you have the new array of totalKills you can use reduce to get the sum of all total kills:
const sumTotalKills = totalKills.reduce((sum, el) => {
sum += el.value;
return sum;
}, 0);
If there is only one object in the stats array that has the name of total_kills then just use a simple find function on the main array like this:
const totalKills = body.playerstats.stats.find(stat => {
return stat.name === 'total_kills';
});
This will find you the first object with name property of total_kills. If there is no such object it will return undefined.

Translate the content of a page to other language using Microsoft APIs [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
We have a requirement to translate the content of a page or rather full page to other language for instance from English to Spanish,
I tried to use the variations available OOTB to translate but it doesn't work and only the OOTB options are translated but not the content on the page.
Is there anyway to accomplish the same using Microsoft APIs?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using Microsoft.Office.Client.TranslationServices;
using System.Security;
namespace testTranslate
{
class Program
{
static void Main(string[] args)
{
ClientContext clientContext = new ClientContext("https://xyz.sharepoint.com/sites/abc/");
string username = "abc#xyz.onmicrosoft.com", pssword = "";
var securePassword = new SecureString();
foreach (char c in pssword)
{
securePassword.AppendChar(c);
}
var onlineCredentials = new SharePointOnlineCredentials(username, securePassword);
clientContext.Credentials = onlineCredentials;
string jobID;
string culture = "en";
string name = "translationJob1";
string inputFile = "https://xyz.sharepoint.com/sites/abc/SitePages/testTranslate.aspx";
string outputFile = "https://xyz.sharepoint.com/sites/abc/SitePages/testTranslateEnglish.aspx";
TranslationJob job = new TranslationJob(clientContext, culture);
job.AddFile(inputFile, outputFile);
job.Name = name;
job.Start();
clientContext.Load(job);
clientContext.ExecuteQuery();
//To retrieve the translation job ID.
jobID = job.JobId.ToString();
//IEnumerable<string> supportedLanguages = TranslationJob.EnumerateSupportedLanguages(clientContext);
//clientContext.ExecuteQuery();
//foreach (string item in supportedLanguages)
//{
// Console.Write(item + ", ");
//}
Console.WriteLine("Script completed,press any key to exit");
Console.ReadKey();
}
}
}
Thanks
Paru
SharePoint offers a Machine Translation service at no charge, which is powered by the Microsoft Translator Text API. Learn more in the Microsoft Translator SharePoint webpage at https://www.microsoft.com/en-us/translator/sharepoint.aspx
If you are interested in using the Translator Text API, follow the steps in the Getting Started webpage at https://www.microsoft.com/en-us/translator/getstarted.aspx . You can test the API by subscribing to the free monthly subscription tier.
Not a SharePoint expert, but you probably need to add code to translate the actual document. Here is a link to a full document translation tool using the Microsoft Translator API:
https://github.com/MicrosoftTranslator/DocumentTranslator

Best way to Spell Check a web page [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
When adding text to a webpage best practice would be to use localization resources, or at least copy/paste text out of a program like Word (or any other grammar/spell checker). That being said there are "always" a couple words here and there where a developer just "updates it."
My question, how do other people check for typos on their webpages? I have a solution (Which I will post as a possible answer), but looking for other ideas.
You can add a function in your javascript library to grab all text and put it in a textbox, which on a browser like chrome will then trigger the native spellchecker.
function SpellCheck()
{
var ta=document.createElement('textarea');
var s=document.createAttribute('style');
s.nodeValue='width:100%;height:100em;';
ta.setAttributeNode(s);
ta.appendChild(document.createTextNode(document.body.innerText));
document.body.appendChild(ta);
ta.focus();
for (var i = 1; i <= ta.value.length; i++)
ta.setSelectionRange(i, i);
}
Code from #JohnLBevan blog post (posted on 2011/03/28)
I made the comment above, then I used the idea from the first answer to add this to my dev environment:
function showPageSource()
{
var text = document.body.innerText;
var textarea = document.createElement('TEXTAREA');
textarea.style.position = 'absolute';
textarea.style.opacity = 0.95;
textarea.style.zIndex = 999;
textarea.style.top = '25px';
textarea.style.left = '25px';
textarea.style.width = 'calc(100% - 50px)';
textarea.style.height = '500px';
textarea.value = text;
document.body.appendChild(textarea);
textarea.addEventListener('click', function (e)
{
e.stopPropagation();
}, false);
document.body.addEventListener('click', function (e)
{
textarea.parentNode.removeChild(textarea);
}, false);
}
And then a tag like this to show the sauce:
SHOW PAGE SOURCE
Shows a fair amount of crap from the navigation - but I can live with that.

Unable to Retrieve “two option” values on plugin - CRM 2011 [duplicate]

This question already has answers here:
Retrieving "two option" field value on the plugin in CRM 2011
(4 answers)
Closed 9 years ago.
I'm unable to retrieve "two option" field's selected value on plugin using the following code
bool? update = entity.GetAttributeValue<bool?>("new_updatecontacts");
bool update = entity.GetAttributeValue<bool>("new_updatecontacts");
if (update)
{
..................
}
Is there any other way of retrieving the same? I have already posted the same question, but did not get a definite answer, so am asking again.
By default, a plugin only contains the values for fields that have been added/updated. For other events you get other properties but let's go with that for now.
So if you want to be sure you have a value, you need to run off to CRM to get a copy.
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
var target = context.InputParameters["Target"] as Entity;
if (!target.Contains("new_updatecontacts"))
{
target = service.Retrieve(target.LogicalName, target.Id, new ColumnSet(new [] { "new_updatecontacts", "other_required_fields_here" });
}
//now you know it is present
It is worth checking if it is there first as it saves a server hit.

Resources