Uploading Image/File via CSOM from ASP web app to SharePoint Online - asp.net

Novice developer here with an issue I would appreciate some assistance with :-)
I am developing an ASP web application (a simple bulletin board, which allows users to create buy and sale adverts). All of my data is being stored/retrieved from an MSSQL database. However, I wish to store/retrieve images for the adverts using a SharePoint Online library.
I am struggling at the first hurdle, which is uploading the image to the library. I've debugged and debugged some more but I am still hitting a brick wall. After many hours of trying, I now have the code below, which is no longer returning any errors although the image never appears in the destination library.
Given all the above, I would sincerely appreciate any assistance from any experts out there!
The following code fires when the "create advert" button is pressed.
string currentUserName =
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
SqlConnection conn2;
SqlCommand comm2;
SqlDataReader reader;
string connectionString2 =
ConfigurationManager.ConnectionStrings["CCString"].ConnectionString;
conn2 = new SqlConnection(connectionString2);
comm2 = new SqlCommand("SELECT TOP 1 * FROM Threads WHERE ([AdvertiserName] = '" + currentUserName + "') ORDER BY PostCreationDateTime DESC", conn2);
conn2.Open();
reader = comm2.ExecuteReader();
reader.Read();
Guid imageID;
string imageIDConfirmed = "";
string fileExtension = "";
if (reader["UniqueImageID"].GetType().Name != "DBNull")
{
imageID = (Guid)reader["UniqueImageID"];
imageIDConfirmed = imageID.ToString().Replace(":", "-");
string myFile = jpgFileUpload.FileName;
fileExtension = myFile.Substring(myFile.Length - 4, 4);
}
reader.Close();
conn2.Close();
string username = "username#emailaddress.com";
string password = "password";
System.Security.SecureString securePass = new
System.Security.SecureString();
foreach (char ch in password.ToCharArray()) securePass.AppendChar(ch);
SharePointOnlineCredentials credentials = new
SharePointOnlineCredentials(username, securePass);
using (ClientContext client = new
ClientContext("https://company.sharepoint.com/sites/SiteName/"))
{
var formLib = client.Web.Lists.GetByTitle("Documents");
client.Credentials = credentials;
client.Load(formLib.RootFolder);
client.ExecuteQuery();
string fileName = #"C:\Temp\" + jpgFileUpload.FileName;
jpgFileUpload.SaveAs(fileName);
var fileUrl = "";
int fileLen;
fileLen = jpgFileUpload.PostedFile.ContentLength;
byte[] input = new byte[fileLen - 1];
input = jpgFileUpload.FileBytes;
UploadDocument(#"https://company.sharepoint.com/sites/SiteName/", "Documents", "https://company.sharepoint.com/sites/SiteName/Shared%20Documents/", "testDocument", input);
using (var fs = new FileStream(fileName, FileMode.Open))
{
var fi = new FileInfo(imageIDConfirmed + fileExtension);
fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
client.ExecuteQuery();
}
var libFields = formLib.Fields;
client.Load(libFields);
client.ExecuteQuery();
Microsoft.SharePoint.Client.File newFile =
client.Web.GetFileByServerRelativeUrl(fileUrl);
Microsoft.SharePoint.Client.ListItem item = newFile.ListItemAllFields;
item["Title"] = "Any Title";
item["File Name"] = "Any File Name";
item.Update();
client.Credentials = credentials;
client.ExecuteQuery();

which is no longer returning any errors although the image never appears in the destination library
Is it possible that the files are there but are in some unchecked-in state?
As a site collection admin, go to Documents -> Settings -> "Permissions and Management" section -> Manage files which have no checked in version.
If there are files with no checked in version, this could indicate the need to provide check-in logic in your code, or there might be an issue with required fields.

Related

System.Net.WebClient.DownloadStringTaskAsync method when webpage contains ™ or other special characters

I am using the System.Net.WebClient.DownloadStringTaskAsync async method to upload a web page content and process it or just save it on my local folder. Everything is fine but when the web page contains some special characters like ™ or ®, they are not getting downloaded. Am I missing something here?
String contentToScrapeURL = "https://www.naylornetwork.com/aaho-advertorial/newsletter.asp?issueID=89542";
Boolean success = true;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}
Found it, or remembered it.
I did set the System.Net.WebClient.Encoding to Encoding.UTF8
So this below is the updated code
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Encoding = Encoding.UTF8;
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}

Spire.xls - return a File from a stream for client download

Here is what I'm trying to accomplish.
I am creating an asp.net MVC application. My restrictions are that I cannot programmatically save anything to the file structure of the server, so I can't save it as a physical file on the host, and then grab it for client download.
I am loading a PDF to a stream, extracting information from the PDF, dynamically building an excel file, and then offering the file for download to the client. My code is below.
// Loads the incoming PDF document to stream
PdfDocument doc = new PdfDocument();
using (var stream = model.BudgetPdfFile.OpenReadStream())
{
doc.LoadFromStream(stream);
}
var pageCount = doc.Pages.Count;
var date = DateTime.Now.ToShortDateString().Replace("/", "-");
// Extracts data from the PDF and separates it by NewLine
SimpleTextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
StringBuilder allText = new StringBuilder();
for (var i = 0; i < pageCount; i++)
{
allText.Append(doc.Pages[i].ExtractText(strategy));
}
var fullDocText = allText.ToString();
List<string> linesList = new List<string>(fullDocText.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList());
// generates a comparison list for output data manipulation from static data
var finalList = linesList.BuildFinalList(budgetItems);
// creates a new Spire.PDF.Workbook for the final output excel file
var result = new Workbook();
// checks for whether the submitted budget is for a case in litigation or not and builds the correct excel workbook
if (model.isTrial)
{
result = ExportExcelBudget.TrialBudgetSheet(model, finalList);
}
else
{
result = ExportExcelBudget.PreTrialBudgetSheet(model, finalList);
}
Absolutely everything up to the last section below works perfectly. However, I cannot figure out how to load the workbook into a new stream and then return the file for download.
// saves the final workbook to a stream and offers it for download to the client
Stream outStream = new MemoryStream();
var fileName = "Budget Report_" + model.ClaimNumber + "_" + date + ".xlsx";
var contentType = "application/vnd.ms-excel";
result.SaveToStream(outStream, Spire.Xls.FileFormat.Version2016);
return File(outStream, contentType, fileName);
I've searched and tried multiple different variations but when the application hits the return File(), it returns a null.
I've stepped through execution and the results seem to be there, but it's not passing anything. Any help on what is wrong here would be greatly appreciated.
Stream outStream = new MemoryStream();
var fileName = "Budget Report_" + model.ClaimNumber + "_" + date + ".xlsx";
var contentType = "application/vnd.ms-excel";
result.SaveToStream(outStream, Spire.Xls.FileFormat.Version2016);
**outStream.Position = 0;**
return File(outStream, contentType, fileName);
Had to reset the stream position to 0. Working perfectly now.

Application is not working when using SQlite databse in windows phone 8

I developed my first application in windows phone 8.1.It is working fine in my local emulator and device but whenever i upload the app in store it is not working.whenever I open the app it is suddenly come back.I used the SQlite database in my application.When I am not using the Sqlite database it is working fine(I uploaded in beta).Please any one help me solve from this issue.
Thank you in advance
sqlite code:
public async void createdatabase()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
await conn.CreateTableAsync<Operators>();
}
public async void Drop()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
using (var dbConn = new SQLiteConnection(c.DatabasePath))
{
SQLiteCommand cmd = new SQLiteCommand(dbConn);
cmd.CommandText = "DROP TABLE IF EXISTS Operators";
int response = cmd.ExecuteNonQuery();
}
public async void insert()
{
rechargeOperator1.Items.Clear();
rechargeCircles1.Items.Clear();
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
var client = new pavandatabase.JsonWebClient();
var resp1 = await client.DoRequestAsync(Url.weburl + "getRechargeCircleList");
string result1 = resp1.ReadToEnd();
JArray jsonArray = JArray.Parse(result1);
for (int j = 0; j < jsonArray.Count; j++)
{
JObject jobj = (JObject)jsonArray[j];
string id = (string)jobj["CircleID"];
string statename = (string)jobj["CircleName"];
//circles combobox......
rechargeCircles1.Items.Add(statename);
Operators op = new Operators();
op.Operatorid = int.Parse(OperatorID);
op.Operatorname = Operator;
op.servicetypeid = int.Parse(ServiceTypeID);
await conn.InsertAsync(op);
}
Try to put the break points on the first line of your application and keep on pressing f10 and see at which line it com out and post that line.
Hope it will help you to get the solution.
Thanks,

Error SQL data reader

I created Intranet project which connect with AD to retrieve User's
data as Image , Department . I did my code and it works well but I had
the below error a lot of times .
string User = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
var entry = new DirectoryEntry("LDAP://" + "xxxxx", User, Password);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.SearchScope = SearchScope.Subtree;
string UserName = Page.User.Identity.Name;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", UserName.Split('\\')[1]);
SearchResult findUser = searcher.FindOne();
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
//string loginuser = user.Properties["UserName"].Value.ToString();
LoggedUser = user.Properties["displayName"].Value.ToString();
Session.Add("LoggedUser", LoggedUser);
LoggedEmail = user.Properties["mail"].Value.ToString();
Session.Add("LoggedEmail", LoggedEmail);
string Mobile = user.Properties["Mobile"] != null && user.Properties["Mobile"].Value != null ? user.Properties["Mobile"].Value.ToString() : null;
string Login = user.Properties["sAMAccountName"].Value.ToString();
if (user.Properties["Department"].Value != null)
LoggedDepartement = user.Properties["Department"].Value.ToString();
_userDept = user.Properties["Department"].Value != null ? user.Properties["Department"].Value.ToString() : "";
ftier.AddLoggedUser(LoggedUser, LoggedDepartement, title, LoggedEmail, data, DateTime.Now, DateTime.Now, " nnnnn", true);
When I've done this in the past one of the problems was unusual characters in the properties of the user object caused this sort of error.
One approach would be to put error checking on each of the variables you're setting so the code can keep working, or export to a text file all the data and go through it using excel and look for unusual or strange control characters.
If the error always occurs at a certain person you could just look at the properties of that user and hope to find the issue that way.
Our issue was the use of Chinese simplified characters in some fields.
Hope this helps you track down your issue.
Dorje

X509Certificate2 - the system cannot find the path specified

I wish to get the data of Google analytics via service account.
When I launch first time the application, everything works correctly and I have access to the data. But When I launch second time the application I have the following error which appears: " the system cannot find the path specified ". Have you an idea? I thought it can be a lock.
This is my source code:
public static String GetAccessToken(string clientIdEMail, string keyFilePath, String scope)
{
// certificate
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
// header
var header = new { typ = "JWT", alg = "RS256" };
// claimset
var times = GetExpiryAndIssueDate();
var claimset = new
{
iss = clientIdEMail,
scope = scope,
aud = "https://accounts.google.com/o/oauth2/token",
iat = times[0],
exp = times[1],
};
JavaScriptSerializer ser = new JavaScriptSerializer();
// encoded header
var headerSerialized = ser.Serialize(header);
var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
var headerEncoded = Convert.ToBase64String(headerBytes);
// encoded claimset
var claimsetSerialized = ser.Serialize(claimset);
var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
var claimsetEncoded = Convert.ToBase64String(claimsetBytes);
// input
var input = headerEncoded + "." + claimsetEncoded;
var inputBytes = Encoding.UTF8.GetBytes(input);
// signiture
var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
var cspParam = new CspParameters
{
KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2,
Flags = CspProviderFlags.UseMachineKeyStore
};
var aescsp = new RSACryptoServiceProvider(1024,cspParam) { PersistKeyInCsp = false };
var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
var signatureEncoded = Convert.ToBase64String(signatureBytes);
// jwt
var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
var uri = "https://accounts.google.com/o/oauth2/token";
var content = new NameValueCollection();
content["assertion"] = jwt;
content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));
JsonGoogleResponse result = (ser.Deserialize<JsonGoogleResponse>(response));
return result.access_token;
}
And this is the stack:
à System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
à System.Security.Cryptography.SafeProvHandle._FreeCSP(IntPtr pProvCtx)
à System.Security.Cryptography.SafeProvHandle.ReleaseHandle()
à System.Runtime.InteropServices.SafeHandle.InternalFinalize()
à System.Runtime.InteropServices.SafeHandle.Dispose(Boolean disposing)
à System.Runtime.InteropServices.SafeHandle.Finalize()
If you are running in IIS, you need to set "Load User Profile" to True in the application pool's advanced settings to be able to load a cert by filename & password.
So, I just had the exact same problem. I tried to solve it for almost 4 hours.
Problem was in passed path to key. Because I used the code from Google sample console application, where the path was just "key.p12" and the key was in the same directory as the exe file.
And when I wanted to create MVC application, I did not realize, that root of virtual server path can not be called just like "key.p12".
SOLUTION
Double check the path to the key. If it is MVC application (or another ASP web), then add the key file to the root and in code call the key by using Server.MapPath("key.p12").
I just had the same issue, in my case it was a space in the path. I have no idea why, but when I put the p12 file on c:\ root, it's working...

Resources