SharePoint - Timeout Error - Copying Folder To Another Folder - sharepoint-online

When I call this method enough times, I think I'm getting throttled because I'm seeing a connection timeout (instead of a 429).
I have a large set of files in a folder that I'm looking to copy to another folder, and looking for suggestions.
Thanks!
public void AddNewFileAndCheckIn(string sharepointFolderRelativeURL, string localFilePath, string indexName)
{
try
{
// Get the Folder
//Folder fileFolder = Web.GetFolderByServerRelativeUrl(this.GetFolderRelativeUrl(sharepointFolderPath));
var initTimeout = ClientContext.RequestTimeout;
var timespans = new List<TimeSpan>();
timespans.Add(TimeSpan.FromSeconds(300));
timespans.Add(TimeSpan.FromSeconds(300));
Polly.Retry.RetryPolicy policy = Polly.Policy.Handle<Exception>().WaitAndRetry(timespans);
policy.Execute(() => {
using (var reader = new System.IO.StreamReader(localFilePath))
{
Folder fileFolder = Web.GetFolderByServerRelativeUrl(sharepointFolderRelativeURL);
// Add the File
FileCreationInformation fci = new FileCreationInformation();
fci.ContentStream = reader.BaseStream; // System.IO.File.ReadAllBytes(localFilePath);
fci.Url = System.IO.Path.GetFileName(localFilePath);
fileFolder.Files.Add(fci);
ClientContext.Load(fileFolder);
ClientContext.RequestTimeout = initTimeout * 10;
ClientContext.ExecuteQuery();
// Get the newly checked in (added) SP File
File fileToCheck = Web.GetFileByServerRelativeUrl(System.IO.Path.Combine(fileFolder.ServerRelativeUrl, fci.Url));
ClientContext.Load(fileToCheck, item => item, item => item.ListItemAllFields["Created"], item => item.ListItemAllFields["Modified"]);
ClientContext.ExecuteQuery();
// Update Metadata
fileToCheck.ListItemAllFields["Created"] = new System.IO.FileInfo(localFilePath).CreationTime;
fileToCheck.ListItemAllFields["Modified"] = new System.IO.FileInfo(localFilePath).LastWriteTime;
fileToCheck.ListItemAllFields["Index"] = indexName;
fileToCheck.ListItemAllFields.Update();
ClientContext.ExecuteQuery();
}
});
}
catch (WebException wex)
{
throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), wex);
}
catch (Exception ex)
{
// Catch and Rethrow with Details
//throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderPath, localFilePath, indexName), ex);
throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), ex);
}
}

Related

Xamarin.iOS Cannot display photo in Push Notification

I have a Notification Service Extension and an AppGroup. I save a photo from camera in the PCL project and copy it to the App Group Container (shared folder).
In the Notification Service Extension I try to download the photo from the App Group container and attach it to the notification but it just does not display in the notification.
I also cannot debug the Service Extension to see what is going. As far as I know that is not possible currently still in Xamarin unless someone can correct me on that please.
Here is the code:
1.in my PCL I save the photo to the AppGroup when a save button is pressed:
private void ButtonSavePhoto_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(photoFilePath))
{
Preferences.Set(AppConstants.CUSTOM_PICTURE_FILE_PATH, photoFilePath);
Preferences.Set(AppConstants.CUSTOM_PHOTO_SET_KEY, true);
if (Device.RuntimePlatform == Device.iOS)
{
bool copiedSuccessfully = DependencyService.Get<IPhotoService>().CopiedFileToAppGroupContainer(photoFilePath);
if (copiedSuccessfully)
{
var customPhotoDestPath = DependencyService.Get<IPhotoService>().GetAppContainerCustomPhotoFilePath();
// save the path of the custom photo in the AppGroup container to pass to Notif Extension Service
DependencyService.Get<IGroupUserPrefs>().SetStringValueForKey("imageAbsoluteString", customPhotoDestPath);
// condition whether to use custom photo in push notification
DependencyService.Get<IGroupUserPrefs>().SetBoolValueForKey("isCustomPhotoSet", true);
}
}
buttonSavePhoto.IsEnabled = false;
}
}
2.in my iOS project, Dependency injection calls this method when pressing save button:
public bool CopiedFileToAppGroupContainer(string filePath)
{
bool success = false;
string suiteName = "group.com.company.appName";
var appGroupContainerUrl = NSFileManager.DefaultManager.GetContainerUrl(suiteName);
var appGroupContainerPath = appGroupContainerUrl.Path;
var directoryNameInAppGroupContainer = Path.Combine(appGroupContainerPath, "Pictures");
var filenameDestPath = Path.Combine(directoryNameInAppGroupContainer, AppConstants.CUSTOM_PHOTO_FILENAME);
try
{
Directory.CreateDirectory(directoryNameInAppGroupContainer);
if (File.Exists(filenameDestPath))
{
File.Delete(filenameDestPath);
}
File.Copy(filePath, filenameDestPath);
success = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return success;
}
Now the path for the photo in the App Group container is:
/private/var/mobile/Containers/Shared/AppGroup/12F209B9-05E9-470C-9C9F-AA959D940302/Pictures/customphoto.jpg
3.Finally in the Notification Service Extension I try to attach the photo to the push notification:
public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
ContentHandler = contentHandler;
BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();
string imgPath;
NSUrl imgUrl;
string notificationBody = BestAttemptContent.Body;
string notifBodyInfo = "unknown";
string suiteName = "group.com.company.appname";
NSUserDefaults groupUserDefaults = new NSUserDefaults(suiteName, NSUserDefaultsType.SuiteName);
string pref1_value = groupUserDefaults.StringForKey("user_preference1");
string[] notificationBodySplitAtDelimiterArray = notificationBody.Split(',');
userPrefRegion = notificationBodySplitAtDelimiterArray[0];
bool isCustomAlertSet = groupUserDefaults.BoolForKey("isCustomAlert");
bool isCustomPhotoSet = groupUserDefaults.BoolForKey("isCustomPhotoSet");
string alarmPath = isCustomAlertSet == true ? "customalert.wav" : "default_alert.m4a";
if (isCustomPhotoSet)
{
// this is the App Group url of the custom photo saved in PCL
imgPath = groupUserDefaults.StringForKey("imageAbsoluteString");
}
else
{
imgPath = null;
}
if (imgPath != null )
{
imgUrl = NSUrl.FromString(imgPath);
}
else
{
imgUrl = null;
}
if (!string.IsNullOrEmpty(pref1_value))
{
if (BestAttemptContent.Body.Contains(pref1_value))
{
if (imgUrl != null)
{
// download the image from the AppGroup Container
var task = NSUrlSession.SharedSession.CreateDownloadTask(imgUrl, (tempFile, response, error) =>
{
if (error != null)
{
ContentHandler(BestAttemptContent);
return;
}
if (tempFile == null)
{
ContentHandler(BestAttemptContent);
return;
}
var cache = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true);
var cachesFolder = cache[0];
var guid = NSProcessInfo.ProcessInfo.GloballyUniqueString;
var fileName = guid + "customphoto.jpg";
var cacheFile = cachesFolder + fileName;
var attachmentUrl = NSUrl.CreateFileUrl(cacheFile, false, null);
NSError err = null;
NSFileManager.DefaultManager.Copy(tempFile, attachmentUrl, out err);
if (err != null)
{
ContentHandler(BestAttemptContent);
return;
}
UNNotificationAttachmentOptions options = null;
var attachment = UNNotificationAttachment.FromIdentifier("image", attachmentUrl, options, out err);
if (attachment != null)
{
BestAttemptContent.Attachments = new UNNotificationAttachment[] { attachment };
}
});
task.Resume();
}
BestAttemptContent.Title = "My Custom Title";
BestAttemptContent.Subtitle = "My Custom Subtitle";
BestAttemptContent.Body = "Notification Body";
BestAttemptContent.Sound = UNNotificationSound.GetSound(alarmPath);
}
}
else
{
pref1_value = "error getting extracting user pref";
}
// finally display customized notification
ContentHandler(BestAttemptContent);
}
/private/var/mobile/Containers/Shared/AppGroup/12F209B9-05E9-470C-9C9F-AA959D940302/Pictures/customphoto.jpg
From shared code, when image getting from AppGroup .You can check the file path whether work in this project.
imgPath = groupUserDefaults.StringForKey("imageAbsoluteString");
If not getting file from this path. You can get Url from AppGroup directly.Here is a sample as follow:
var FileManager = new NSFileManager();
var appGroupContainer = FileManager.GetContainerUrl("group.com.company.appName");
NSUrl fileURL = appGroupContainer.Append("customphoto.jpg", false);
And if fileURL can not be directly used, also can convert to NSData and save to local file system. This also can be a try.
Here is a sample below that grabs from local file system:
public static void Sendlocalnotification()
{
var localURL = "...";
NSUrl url = NSUrl.FromString(localURL) ;
var attachmentID = "image";
var options = new UNNotificationAttachmentOptions();
NSError error;
var attachment = UNNotificationAttachment.FromIdentifier(attachmentID, url, options,out error);
var content = new UNMutableNotificationContent();
content.Attachments = new UNNotificationAttachment[] { attachment };
content.Title = "Good Morning ~";
content.Subtitle = "Pull this notification ";
content.Body = "reply some message-BY Ann";
content.CategoryIdentifier = "message";
var trigger1 = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);
var requestID = "messageRequest";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger1);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
Console.Write("Notification Error");
}
});
}

Email Attachments missing on Azure, works locally

I have implemented something similar to the following question and I can get it working locally on my server, but when I deploy to Azure it doesn't work. I don't get any errors: just an email without the attachment.
Sending attachments using Azure blobs
Are there restrictions on what types of files can be sent with SendGrid (file is only 56k)?
Does the Azure App service have to be at a particular level or can it be done on Basic?
The blob URL definitley exists and I am setting the stream to zero as suggested in that previous question.
MailMessage mm = new MailMessage("receiver address", "someone");
mm.From = new MailAddress("myAddress", "My Name");
mm.Subject = content.Subject;
mm.Body = content.Body;
mm.IsBodyHtml = true;
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
var attachmentAsStream = _storageAccessService.GetAssetAsStreamForEmail("myContainer", "fileThatExists.pdf");
var attachment = new Attachment(attachmentAsStream, "File.pdf", MediaTypeNames.Application.Pdf);
mm.Attachments.Add(attachment);
public MemoryStream GetAssetAsStreamForEmail(string containerName, string fileName)
{
// Create the blob client.
CloudBlobClient blobClient = StorageAccountReference().CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
var memoryStream = new MemoryStream();
try
{
using (var stream = new MemoryStream())
{
blob.DownloadToStream(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Failed to download Email Atatchment: "+ ex.Message));
}
memoryStream.Position = 0;
return memoryStream;
}
using (SmtpClient client = new SmtpClient())
{
client.Port = 587;
client.Host = "smtp.sendgrid.net";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("hidden", "hidden");
await client.SendMailAsync(message);
}
Update
Update after Yasir's suggestion below. Downloading the blob from Azure as a Stream only seems to work locally. But if I change to download as a ByteArray then it works everywhere, nonetheless...
public MemoryStream GetAssetAsStreamForEmail(string containerName, string fileName)
{
// Create the blob client.
CloudBlobClient blobClient = StorageAccountReference().CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
try
{
blob.FetchAttributes();
var fileStream = new byte[blob.Properties.Length];
for (int i = 0; i < blob.Properties.Length; i++)
{
fileStream[i] = 0x20;
}
blob.DownloadToByteArray(fileStream, 0) ;
MemoryStream bufferStream = new MemoryStream(fileStream);
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Failed to download Email Atatchment: " + ex.Message));
}
return null;
}
The following code works for me for sending emails using Sendgrid from Azure functions. I attach a CSV file from Blob Storage. It should work for you as well. All you will have to do is ensure that you read the pdf file as a byte[].
public interface IEmailAttachment
{
string Name { get; }
byte[] FileData { get; }
}
public static void Send(MailMessage mailMessage, IEnumerable<IEmailAttachment> attachments)
{
try
{
// Get the configuration data
string server = ConfigReader.EmailServer;
int port = ConfigReader.EmailPort;
string username = ConfigReader.SendGridUserName;
string password = ConfigReader.SendGridPassword;
smtpClient.EnableSsl = false;
smtpClient.Credentials = new NetworkCredential(username, password);
// Create the SMTP Client
SmtpClient smtpClient = new SmtpClient(server, port);
// Prepare the MailMessage
mailMessage.From = new MailAddress(ConfigReader.FromEmail);
var toEmails = ConfigReader.ToEmail.Split(',');
foreach (var toEmail in toEmails)
{
mailMessage.To.Add(toEmail);
}
var ccEmails = ConfigReader.EmailCc.Split(',');
foreach (var ccEmail in ccEmails)
{
mailMessage.CC.Add(ccEmail);
}
// Add attachments
List<MemoryStream> files = new List<MemoryStream>();
if (attachments != null)
{
foreach (IEmailAttachment file in attachments)
{
MemoryStream bufferStream = new MemoryStream(file.FileData);
files.Add(bufferStream);
Attachment attachment = new Attachment(bufferStream, file.Name);
mailMessage.Attachments.Add(attachment);
}
}
mailMessage.IsBodyHtml = true;
// Send the email
smtpClient.Send(mailMessage);
foreach (MemoryStream stream in files)
{
stream.Dispose();
}
}
catch (Exception)
{
throw;
}
}

How to create file in java

File Name = new File("G:/Java/lesson25_1/Name.txt");
if(Name==null){
JOptionPane.showMessageDialog(this, "Details are missing");
}
try{
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
when i do this in a method it dosn't work when i click the button
There is a method for file called exists to check if the given file exist or not.
String path = "G:/Java/lesson25_1/Name.txt";
File file = new File(path);
if(!file.isFile() || !file.canRead()){
JOptionPane.showMessageDialog(this, "Details are missing");
} else {
try {
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
} catch (Exception e){
e.printStackTrace();
}
}

How to return Json response message for http error like 404 in wcf Service?

I have the below function which i am returning employees list. If
there is no list present in DB, I need to return httpstatusErrorcode
with error message
public List<SelectEventsMClass> FetchAllEmployes(int EmployTypeID)
{
try
{
var EventsList = new List<SelectEventsMClass>();
Employ.Data.EmployTableAdapters.EventsMSelectAllTableAdapter Adp = new Data.EmployTableAdapters.EventsMSelectAllTableAdapter();
Employ.Data.Employ.EventsMSelectAllDataTable Dtl = Adp.GetData(intEventTypeID);
if (Dtl.Rows.Count > 0)
{
var EventsList = (from lst in Dtl.AsEnumerable()
select new SelectEventsMClass
{
TransID = lst.Field<Guid>("TransID"),
SchoolTransID = lst.Field<Guid>("SchoolTransID"),
AcadamicTransID = lst.Field<Guid>("AcadamicTransID"),
EventTypeID = lst.Field<int>("EventTypeID"),
EventTitle = lst.Field<string>("EventTitle"),
}).ToList();
}
return EventsList;
}
catch (Exception ex)
{
throw ex;
}
}

SharePoint List Service Recursive not working

I am using the following code to retrieve the documents in a list. Its working fine. However, it only returns documents and folders in root of the doc library. Is there any thing wrong I am doing here? I am looking for files in sub folders with recursive mode.
Service service = new Service();
service.setMaintainSession(true);
call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL("<host>/_vti_bin/lists.asmx") );
call.setOperationName(new QName("http://schemas.microsoft.com/sharepoint/soap/","GetListItems"));
call.setProperty(Call.SOAPACTION_USE_PROPERTY, new Boolean("true"));
call.setProperty(Call.SOAPACTION_URI_PROPERTY,"http://schemas.microsoft.com/sharepoint/soap/GetListItems");
call.addParameter(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/", "listName"),
new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"),
java.lang.String.class,
javax.xml.rpc.ParameterMode.IN);
MessageElement me =
new MessageElement(new QName("QueryOptions"));
me.addChildElement(new MessageElement(new QName(
"IncludeMandatoryColumns"))).addTextNode("true");
me.addChildElement(new MessageElement(new QName(
"ViewAttributes"))).addAttribute(javax.xml.soap.SOAPFactory.newInstance().createName("Scope"), "Recursive");
MessageElement[] me1 = {me};
String strMyString = ""
+ "<Query>"
+ "<OrderBy><FieldRef Name=\"ows_Modified\" Ascending=\"TRUE\" /></OrderBy>"
+ "</Query>";
MessageElement[] meArray = { getMeFromString(strMyString) };// Array
call.addParameter("query",org.apache.axis.Constants.XSD_SCHEMA,
javax.xml.rpc.ParameterMode.IN);
call.addParameter("queryOptions",org.apache.axis.Constants.XSD_SCHEMA,
javax.xml.rpc.ParameterMode.IN);
call.setReturnType(org.apache.axis.Constants.XSD_SCHEMA);
Schema ret = (Schema)call.invoke(new Object[] {"listGUID",meArray, me1 });
public org.apache.axis.message.MessageElement getMeFromString(final String strMyString) {
DocumentBuilder docBuilder = null;
try {
docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (final ParserConfigurationException e) {
e.printStackTrace();
} catch (final FactoryConfigurationError e) {
e.printStackTrace();
}
final StringReader reader = new StringReader(strMyString);
final InputSource inputsource = new InputSource(reader);
Document doc = null;
try {
doc = docBuilder.parse(inputsource);
} catch (final SAXException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
final Element ele = doc.getDocumentElement();
final MessageElement msg = new MessageElement(ele);
return msg;
}
query.ViewAttributes = "Scope='RecursiveAll'"

Resources