I'm using .NET Core 3.1 but I encountered a weird problem!
the problem is any uploaded image the size of it is 0KB
when I restart the IIS and trying again will upload it without any problem but after that, the problem returns back.
I tried this solution by making my code async but with no luck
I changed my system file to be accessible by my Application pool user but with no luck
Here is my code :
public Document shareWithUsers([FromForm] CreateDocumentDto documentDto)
{
List<CreateUserType1DocumentsDto> listOfCreateUserType1Documents = new List<CreateUserType1DocumentsDto>();
List<CreateHDDocumentsDto> listOfCreateHDDocuments = new List<CreateHDDocumentsDto>();
if (documentDto.listOfUserType1Documents != null)
{
foreach (var item in documentDto.listOfUserType1Documents)
{
listOfCreateUserType1Documents.Add(JsonConvert.DeserializeObject<CreateUserType1DocumentsDto>(item));
}
}
else if (documentDto.listOfHDDocuments != null)
{
foreach (var item in documentDto.listOfHDDocuments)
{
listOfCreateHDDocuments.Add(JsonConvert.DeserializeObject<CreateHDDocumentsDto>(item));
}
}
if (documentDto.sharedText == null)
{
if (documentDto.document != null) //that mean user upload file
{
if (documentDto.document.Length > 0)
{
var UploadedFilesPath = Path.Combine(hosting.WebRootPath/*wwwroot path*/, "UploadedFiles" /*folder name in wwwroot path*/);
var filePath = Path.Combine(UploadedFilesPath, documentDto.document.FileName);
//documentDto.docUrl = filePath;
var documentObject = new Document();
using (var stream = new FileStream(filePath, FileMode.Create))
{
documentDto.document.CopyToAsync(stream);// Use stream
}
if (documentDto.listOfUserType1Documents != null)
{
documentObject.listOfUserType1Documents = ObjectMapper.Map<List<UserType1Documents>>(listOfCreateUserType1Documents);
}
else if (documentDto.listOfHDDocuments != null)
{
documentObject.listOfHDDocuments = ObjectMapper.Map<List<HDDocuments>>(listOfCreateHDDocuments);
}
documentObject.docTtitle = documentDto.docTtitle;
documentObject.docName = documentDto.docName;
documentObject.docUrl = filePath;
return _repository.Insert(documentObject);
}
}
}
else
{ //that mean user upload text
var documentObject = new Document();
if (documentDto.listOfUserType1Documents != null)
{
documentObject.listOfUserType1Documents = ObjectMapper.Map<List<UserType1Documents>>(listOfCreateUserType1Documents);
}
else if (documentDto.listOfHDDocuments != null)
{
documentObject.listOfHDDocuments = ObjectMapper.Map<List<HDDocuments>>(listOfCreateHDDocuments);
}
documentObject.sharedText = documentDto.sharedText;
return _repository.Insert(documentObject);
}
return null;
}
My code works only if I change both of them (CopyTo and Insert ) to Async with await
await CopyToAsync()
await InsertAsync()
Related
I created AWS Lambda ASP.NET Core 5 project using VS AWS Toolkit.
I am using default dockerfile that is created together with the project.
FROM public.ecr.aws/lambda/dotnet:5.0
WORKDIR /var/task
# This COPY command copies the .NET Lambda project's build artifacts from the host machine into the image.
# The source of the COPY should match where the .NET Lambda project publishes its build artifacts. If the Lambda function is being built
# with the AWS .NET Lambda Tooling, the `--docker-host-build-output-dir` switch controls where the .NET Lambda project
# will be built. The .NET Lambda project templates default to having `--docker-host-build-output-dir`
# set in the aws-lambda-tools-defaults.json file to "bin/Release/net5.0/linux-x64/publish".
#
# Alternatively Docker multi-stage build could be used to build the .NET Lambda project inside the image.
# For more information on this approach checkout the project's README.md file.
COPY "bin/Release/net5.0/linux-x64/publish" .
I created an endpoint that is used to upload excel file that should be parsed and some logic should be executed.
I tried few libs and the result is always the same: it is working on my local Win10 machine but it crashes when it is executed as AWS Lambda function.
Anyone has some idea what I should do with the dockerfile/AWS Lambda configuration to have to working in AWS Lambda?
https://github.com/ClosedXML/ClosedXML
Internal server error: System.IO.FileFormatException: File contains corrupted data.
at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(Stream stream, Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(Stream stream, Boolean isEditable, OpenSettings openSettings)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(Stream stream, Boolean isEditable)
at ClosedXML.Excel.XLWorkbook.LoadSheets(Stream stream)
at ClosedXML.Excel.XLWorkbook.Load(Stream stream)
at ClosedXML.Excel.XLWorkbook..ctor(Stream stream, XLEventTracking eventTracking)
at ClosedXML.Excel.XLWorkbook..ctor(Stream stream)
at BasicAWSLambdaProject.Controllers.UploadController.UploadClosedXML() in D:\GitHub\kicaj29\aws-netcore-sample-system\BasicAWSLambdaProject\BasicAWSLambdaProject\Controllers\UploadController.cs:line 160
https://github.com/ExcelDataReader/ExcelDataReader
Internal server error: System.IO.InvalidDataException: Offset to Central Directory cannot be held in an Int64.
at System.IO.Compression.ZipArchive.ReadEndOfCentralDirectory()
at System.IO.Compression.ZipArchive..ctor(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding)
at System.IO.Compression.ZipArchive..ctor(Stream stream)
at ExcelDataReader.Core.ZipWorker..ctor(Stream fileStream)
at ExcelDataReader.ExcelOpenXmlReader..ctor(Stream stream)
at ExcelDataReader.ExcelReaderFactory.CreateReader(Stream fileStream, ExcelReaderConfiguration configuration)
at BasicAWSLambdaProject.Controllers.UploadController.UploadExcelExcelDataReader() in D:\GitHub\kicaj29\aws-netcore-sample-system\BasicAWSLambdaProject\BasicAWSLambdaProject\Controllers\UploadController.cs:line 123
https://github.com/JanKallman/EPPlus
Internal server error: OfficeOpenXml.Packaging.Ionic.Zip.BadReadException: Could not read block - no data! (position 0x0001718A)
at OfficeOpenXml.Packaging.Ionic.Zip.SharedUtilities._ReadFourBytes(Stream s, String message)
at OfficeOpenXml.Packaging.Ionic.Zip.SharedUtilities.ReadInt(Stream s)
at OfficeOpenXml.Packaging.Ionic.Zip.ZipEntry.HandleUnexpectedDataDescriptor(ZipEntry entry)
at OfficeOpenXml.Packaging.Ionic.Zip.ZipEntry.ReadEntry(ZipContainer zc, Boolean first)
at Ionic.Zip.ZipInputStream.GetNextEntry()
at OfficeOpenXml.Packaging.ZipPackage..ctor(Stream stream)
at OfficeOpenXml.ExcelPackage.Load(Stream input, Stream output, String Password)
at OfficeOpenXml.ExcelPackage.Load(Stream input)
at OfficeOpenXml.ExcelPackage..ctor(Stream newStream)
at BasicAWSLambdaProject.Controllers.UploadController.UploadExcelEPPlus() in D:\GitHub\kicaj29\aws-netcore-sample-system\BasicAWSLambdaProject\BasicAWSLambdaProject\Controllers\UploadController.cs:line 90
https://github.com/nissl-lab/npoi
Internal server error: System.IO.IOException: ZIP entry size is too large
at NPOI.OpenXml4Net.Util.ZipInputStreamZipEntrySource.FakeZipEntry..ctor(ZipEntry entry, ZipInputStream inp)
at NPOI.OpenXml4Net.Util.ZipInputStreamZipEntrySource..ctor(ZipInputStream inp)
at NPOI.OpenXml4Net.OPC.ZipPackage..ctor(Stream in1, PackageAccess access)
at NPOI.OpenXml4Net.OPC.OPCPackage.Open(Stream in1)
at NPOI.Util.PackageHelper.Open(Stream is1)
at NPOI.XSSF.UserModel.XSSFWorkbook..ctor(Stream is1)
at BasicAWSLambdaProject.Controllers.UploadController.UploadExcelNPOI() in D:\GitHub\kicaj29\aws-netcore-sample-system\BasicAWSLambdaProject\BasicAWSLambdaProject\Controllers\UploadController.cs:line 59
And this is the Controller code (when it is run always only one method is uncommented and other are commented out)
[Route("api/[controller]")]
public class UploadController: Controller
{
[HttpPost]
public IActionResult UploadExcelNPOI()
{
try
{
var file = Request.Form.Files[0];
var receivedContent = "";
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
using (var s = file.OpenReadStream())
{
var xssWorkbook = new XSSFWorkbook(s);
var sheet = xssWorkbook.GetSheetAt(0);
var row = sheet.GetRow(0);
var cell = row.GetCell(0);
receivedContent = cell.StringCellValue;
}
return Ok(new { receivedContent });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
[HttpPost]
public IActionResult UploadExcelEPPlus()
{
try
{
var file = Request.Form.Files[0];
var receivedContent = "";
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
using (var s = file.OpenReadStream())
{
using (ExcelPackage package = new ExcelPackage(s))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
receivedContent = worksheet.Cells[1, 1].Value.ToString();
}
}
return Ok(new { receivedContent });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
[HttpPost]
public IActionResult UploadExcelExcelDataReader()
{
try
{
var file = Request.Form.Files[0];
var receivedContent = "";
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
using (var s = file.OpenReadStream())
{
using (var reader = ExcelReaderFactory.CreateReader(s))
{
do
{
while (reader.Read())
{
receivedContent = reader.GetString(0);
}
} while (reader.NextResult());
}
}
return Ok(new { receivedContent });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
[HttpPost]
public IActionResult UploadClosedXML()
{
try
{
var file = Request.Form.Files[0];
var receivedContent = "";
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
using (var s = file.OpenReadStream())
{
using (var excel = new XLWorkbook(s))
{
var worksheet = excel.Worksheets.Worksheet(1);
receivedContent = worksheet.Cell(1, 1).Value.ToString();
}
}
return Ok(new { receivedContent });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
}
And the file is uploaded using Angular app - I am using exactly the same file in case when it is run locally on my Win10 and when it is hosted by AWS Lambda so because of this I think the file is ok. I can also open it in the excel.
I tried to use also IFormFile interface so instead od this
[HttpPost]
public IActionResult UploadExcelNPOI()
{
try
{
var file = Request.Form.Files[0];
var receivedContent = "";
if (file.Length > 0)
...
}
I do:
[HttpPost]
public IActionResult UploadExcelNPOI(IFormFile file)
{
try
{
var receivedContent = "";
if (file.Length > 0)
...
}
but I still crashes when it is run as lambda.
This is angular code for uploading the file:
public uploadFile = (files) => {
if (files.length === 0) {
return;
}
let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this.httpClient.post(`${environment.apiUrl}api/upload`, formData, {reportProgress: true, observe: 'events'})
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
this.UploadProgress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response) {
this.UploadMessage = 'Upload success.';
}
});
}
-Jacek
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");
}
});
}
I've got an ASP.NET core application that uploads images to Azure. I am attempting to resize an image using Magick.NET before uploading said image to Azure Blob container. So far, I've managed to save the image to a folder in a local hard drive. Is this the correct way of writing this?
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product products)
{
var files = products.UploudThumbnail;
List<string> image = new List<string>();
List<string> names = new List<string>();
if (files != null)
{
foreach (var file in files)
{
if (ModelState.IsValid)
{
if (file.ContentType == "image/jpeg" || file.ContentType == "image/jpg")
{
if (file.Length < 1 * 1000 * 1000)
{
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName.Trim('"');
names.Add(fileName);
fileName = Guid.NewGuid().ToString() + "-" + fileName;
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
cloudBlockBlob.Properties.ContentType = file.ContentType;
await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());
image.Add(cloudBlockBlob.Uri.AbsoluteUri);
const int size = 20;
const int quality = 75;
using (var image = new MagickImage(file.OpenReadStream()))
{
image.Resize(size, size);
image.Strip();
image.Quality = quality;
//how to save it into azure?
image.Write(fileName);
}
}
else
{
ModelState.AddModelError("UploudThumbnail", "Max size not accepted");
}
}
else
{
ModelState.AddModelError("UploudThumbnail", "jpeg & jpg are accepted");
}
}
}
}
_context.Add(products);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Just write the image to a memory stream and upload it using the UploadFromStreamAsync method.
Example (pseudo):
using (var memStream = new MemoryStream())
{
image.Write(memStream);
memStream.Seek(0, SeekOrigin.Begin);
await cloudBlockBlob.UploadFromStreamAsync(memStream);
}
I found out how to determine the object type from URL for SharePoint on prem:
https://blogs.msdn.microsoft.com/sanjaynarang/2009/04/06/find-sharepoint-object-type-from-url/
But I didn't find anything for SharePoint Online (CSOM).
Is it possible for SharePoint online?
For the most scenarios such as:
folder url, e.g. https://contoso.sharepoint.com//Documents/Forms/AllItems.aspx?RootFolder=%2FDocuments%2FArchive
list item url, e.g. https://contoso.sharepoint.com/Lists/ShoppingCart/DispForm.aspx?ID=9
list/library url, e.g. https://contoso.sharepoint.com/Lists/Announcements
page url, e.g. https://contoso.sharepoint.com/Lists/Announcements/Newsletter.aspx
the following example demonstrates how to determine client object type:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web;
using Microsoft.SharePoint.Client;
namespace O365Console
{
static class ClientObjectExtensions
{
public static ClientObject ResolveClientObjectFromUrl(string resourceUrl, ICredentials credentials)
{
ClientObject targetObject = null;
var resourceUri = new Uri(resourceUrl);
using (var rootCtx = new ClientContext(resourceUri.Scheme + Uri.SchemeDelimiter + resourceUri.Host))
{
rootCtx.Credentials = credentials;
var webUrl = Web.WebUrlFromPageUrlDirect(rootCtx, resourceUri);
using (var ctx = new ClientContext(webUrl.ToString()))
{
ctx.Credentials = credentials;
var queryBag = System.Web.HttpUtility.ParseQueryString(resourceUri.Query);
if (queryBag["Id"] != null)
{
var listUrl = string.Join(string.Empty,
resourceUri.Segments.Take(resourceUri.Segments.Length - 1));
var list = ctx.Web.GetList(listUrl);
targetObject = TryRetrieve(() => list.GetItemById(Convert.ToInt32(queryBag["Id"])));
}
else if (queryBag["RootFolder"] != null)
{
var folderUrl = HttpUtility.UrlDecode(queryBag["RootFolder"]);
targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(folderUrl));
}
else if (queryBag.Count > 0)
{
throw new Exception("Unsupported query string parameter found");
}
else
{
targetObject = TryRetrieve(() => ctx.Web.GetFileByServerRelativeUrl(resourceUri.AbsolutePath));
if (targetObject == null)
{
targetObject = TryRetrieve(() => ctx.Web.GetList(resourceUri.AbsolutePath),list => list.RootFolder);
if (targetObject == null || ((List)targetObject).RootFolder.ServerRelativeUrl != resourceUri.AbsolutePath)
targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(resourceUri.AbsolutePath));
}
}
}
}
return targetObject;
}
private static T TryRetrieve<T>(Func<T> loadMethod, params Expression<Func<T,object>>[] retrievals) where T : ClientObject
{
try
{
var targetObject = loadMethod();
targetObject.Context.Load(targetObject, retrievals);
targetObject.Context.ExecuteQuery();
return targetObject;
}
catch
{
}
return default(T);
}
}
}
Usage
var credentials = GetCredentials(userName, password);
var clientObj = ClientObjectExtensions.ResolveClientObjectFromUrl("https://contoso.sharepoint.com/Lists/Announcements", credentials);
Console.WriteLine(clientObj.GetType().Name);
where
static ICredentials GetCredentials(string userName,string password)
{
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
return new SharePointOnlineCredentials(userName, securePassword);
}
I am looking to do this step: 'Creating a New FTP Site by Editing the IIS 7.0 Configuration Files' with a batch file and was wondering if anybody has done this already?
http://learn.iis.net/page.aspx/301/creating-a-new-ftp-site/
Try this. You need to reference the COM component "AppHostAdminLibrary"
using AppHostAdminLibrary;
...
public void AddFtp7Site(String siteName, String siteId, String siteRoot) {
String configPath;
String configSectionName;
var fNewSite = false;
var fNewApplication = false;
var fNewVDir = false;
//
// First setup the sites section
//
configPath = "MACHINE/WEBROOT/APPHOST";
configSectionName = "system.applicationHost/sites";
var adminManager = new AppHostAdminLibrary.AppHostWritableAdminManager();
adminManager.CommitPath = configPath;
try {
var sitesElement = adminManager.GetAdminSection(configSectionName, configPath);
IAppHostElement newSiteElement = null;
//
// check if site already exists
//
for (var i = 0; i < sitesElement.Collection.Count; i++) {
var siteElement = sitesElement.Collection[i];
if (siteElement.Properties["name"].Value.Equals(siteName) &&
siteElement.Properties["id"].Value.Equals(siteId)) {
newSiteElement = siteElement;
break;
}
}
if (newSiteElement == null) {
//
// Site doesn't exist yet. Add new site node
//
newSiteElement = sitesElement.Collection.CreateNewElement("");
newSiteElement.Properties["id"].Value = siteId;
newSiteElement.Properties["name"].Value = siteName;
fNewSite = true;
}
// setup bindings for the new site
var ftpBindingString = "*:21:";
var Bindings = newSiteElement.GetElementByName("bindings");
var BindingElement = Bindings.Collection.CreateNewElement("");
BindingElement.Properties["protocol"].Value = "ftp";
BindingElement.Properties["bindingInformation"].Value = ftpBindingString;
try {
Bindings.Collection.AddElement(BindingElement, 0);
}
catch (Exception ex) {
if (ex.Message != "") // ERROR_ALREADY_EXISTS ?
{
throw;
}
}
IAppHostElement newApplication = null;
//
// check if root application already exists
//
for (var i = 0; i < newSiteElement.Collection.Count; i++) {
var applicationElement = newSiteElement.Collection[i];
if (applicationElement.Properties["path"].Value.Equals("/")) {
newApplication = applicationElement;
break;
}
}
if (newApplication == null) {
newApplication = newSiteElement.Collection.CreateNewElement("application");
newApplication.Properties["path"].Value = "/";
fNewApplication = true;
}
IAppHostElement newVirtualDirectory = null;
//
// search for the root vdir
//
for (var i = 0; i < newApplication.Collection.Count; i++) {
var vdirElement = newApplication.Collection[i];
if (vdirElement.Properties["path"].Value.Equals("/")) {
newVirtualDirectory = vdirElement;
break;
}
}
if (newVirtualDirectory == null) {
newVirtualDirectory = newApplication.Collection.CreateNewElement("");
newVirtualDirectory.Properties["path"].Value = "/";
fNewVDir = true;
}
newVirtualDirectory.Properties["physicalPath"].Value = siteRoot;
if (fNewVDir) {
newApplication.Collection.AddElement(newVirtualDirectory, 0);
}
if (fNewApplication) {
newSiteElement.Collection.AddElement(newApplication, 0);
}
var ftpSiteSettings = newSiteElement.GetElementByName("ftpServer").GetElementByName("security").GetElementByName("authentication");
Console.WriteLine("Enable anonymous authentication");
var anonAuthSettings = ftpSiteSettings.GetElementByName("anonymousAuthentication");
anonAuthSettings.Properties["enabled"].Value = "true";
Console.WriteLine("Disable basic authentication");
var basicAuthSettings = ftpSiteSettings.GetElementByName("basicAuthentication");
basicAuthSettings.Properties["enabled"].Value = "false";
BindingElement.Properties["bindingInformation"].Value = "*:21:";
//
// Time to add new site element and commit changes
//
if (fNewSite) {
sitesElement.Collection.AddElement(newSiteElement, 0);
}
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured in AddDefaultFtpSite: " + ex.Message);
}
//
// Add <authorization> section to allow everyone Read
//
Console.WriteLine("Enable everyone Read access");
try {
configPath = "MACHINE/WEBROOT/APPHOST/" + siteName;
configSectionName = "system.ftpServer/security/authorization";
var azSection = adminManager.GetAdminSection(configSectionName, configPath);
azSection.Collection.Clear();
var newAzElement = azSection.Collection.CreateNewElement("");
newAzElement.Properties["accessType"].Value = "Allow";
newAzElement.Properties["users"].Value = "*";
newAzElement.Properties["permissions"].Value = "Read";
azSection.Collection.AddElement(newAzElement, 0);
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured while adding authorization section: " + ex.Message);
}
}
Does this help?:
http://blogs.iis.net/jaroslad/archive/2007/06/13/how-to-programatically-create-an-ftp7-site.aspx