Path Manipulation while creating shortcut in C# - c#-4.0

Using below code i am creating a shortcut.When i do run HP fortify tool i am getting path manipulation issues for the highlighted code.I am new to this.Can anyone please tell me how to correct it.I mean what path manipulation is happening.
string fileName = new data().getdata(object_id, Cid, id_pluf).Tables[0].Rows[0]["Name"] + "url";
**var fs = new System.IO.FileStream(start + fileName, System.IO.FileMode.Create);**
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
private static void DeleteShortcut(string start, string fileName)
{
**if (System.IO.File.Exists(start+ fileName))**
{
**System.IO.File.Delete(start+ fileName);**
}
}

Always use :
Path.Combine(start, fileName)
instead of :
start+ fileName

Related

Upload BASE64 binary file to SharePoint document library

I have been looking for ways to upload BASE64 binary files days and I am stuck.
First of all a do not know how to convert BASE64 binary file to array buffer, blob, ... Everything is about BASE64 string but I have BASE64 binary file.
Do you have any solution?
You need to convert this Base64 string to byte array. C# Programming provide several approaches to do this without trouble. Following Upload large files sample SharePoint Add-in and Convert.FromBase64String(String) Method, both at Microsoft Docs, the final code that meet your requirements will be like this:
//This approach is useful for short files, less than 2Mb:
public void UploadFileContentFromBase64(ClientContext ctx, string libraryName, string fileName, string base64Str)
{
Web web = ctx.Web;
// Ensure that target library exists. Create if it is missing.
if (!LibraryExists(ctx, web, libraryName))
{
CreateLibrary(ctx, web, libraryName);
}
FileCreationInformation newFile = new FileCreationInformation();
// The next line of code causes an exception to be thrown for files larger than 2 MB.
newFile.Content = Convert.FromBase64String(base64Str);
newFile.Url = fileName;
// Get instances to the given library.
List docs = web.Lists.GetByTitle(libraryName);
// Add file to the library.
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
//This other approach provides you to Upload large files, more than 2Mb:
public void UploadDocumentContentStreamFromBase64(ClientContext ctx, string libraryName, string fileName, string base64Str)
{
Web web = ctx.Web;
// Ensure that the target library exists. Create it if it is missing.
if (!LibraryExists(ctx, web, libraryName))
{
CreateLibrary(ctx, web, libraryName);
}
byte[] fileContent = Convert.FromBase64String(base64Str);
using (MemoryStream memStream = new MemoryStream(fileContent))
{
FileCreationInformation flciNewFile = new FileCreationInformation();
// This is the key difference for the first case - using ContentStream property
flciNewFile.ContentStream = memStream;
flciNewFile.Url = fileName;
flciNewFile.Overwrite = true;
List docs = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
}

Excel File Upload with Kendo UI

while I was trying to upload an excel file with kendo ui I found a code on the internet. It is using a keyword named "Constants" but this keyword does not recognize the ".xls" file extension. I am stuck at this and did some research but have no answer to solve this. Here is my code:
public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
{
if(files!= null)
{
string fileName;
string filePath;
string fileExtension;
foreach(var f in files)
{
//Set file details
SetFileDetails(f, out fileName, out filePath, out fileExtension);
if(fileExtension == Constants.xls || fileExtension == Constants.xlsx)
{
//Save the uploaded file to app folder
string savedExcelFiles = Constants.UploadedFolder + fileName;
f.SaveAs(Server.MapPath(savedExcelFiles));
ReadDataFromExcelFiles(savedExcelFiles);
}
else
{
//file not supported send alert
}
}
}
return RedirectToActionPermanent("Index","Connect");
}
private static void SetFileDetails(HttpPostedFileBase f,out string fileName,out string filePath,out string fileExtension)
{
fileName=Path.GetFileName(f.FileName);
fileExtension=Path.GetExtension(f.FileName);
filePath = Path.GetFullPath(f.FileName);
}
private void ReadDataFromExcelFiles(string savedExcelFiles)
{
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;",Server.MapPath(savedExcelFiles));
//fill the DataSet by the sheets
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",connectionString);
var ds = new DataSet();
List<UploadExcel> uploadExl = new List<UploadExcel>();
adapter.Fill(ds,"Subscriber");
DataTable data=ds.Tables["Subscriber"];
GetSetUploadExcelData(uploadExl,data);
}
private static void GetSetUploadExcelData (List<UploadExcel> uploadExl,DataTable data)
{
for(int i=0;i<data.Rows.Count-1;i++)
{
UploadExcel NewUpload = new UploadExcel();
NewUpload.ID = Convert.ToInt16(data.Rows[i]["ID"]);
NewUpload.CostCenter = Convert.ToString(data.Rows[i]["CostCenter"]);
NewUpload.FirstName = Convert.ToString(data.Rows[i]["FirstName"]);
NewUpload.LastName = Convert.ToString(data.Rows[i]["LastName"]);
NewUpload.MobileNo = Convert.ToString(data.Rows[i]["MobileNo"]);
NewUpload.EmailID = Convert.ToString(data.Rows[i]["EmailID"]);
NewUpload.Services = Convert.ToString(data.Rows[i]["Services"]);
NewUpload.UsageType = Convert.ToString(data.Rows[i]["UsageType"]);
NewUpload.Network = Convert.ToString(data.Rows[i]["Network"]);
NewUpload.UsageIncluded = Convert.ToInt16(data.Rows[i]["UsageIncluded"]);
NewUpload.Unit = Convert.ToString(data.Rows[i]["Unit"]);
uploadExl.Add(NewUpload);
}
}
}
I suspect that the Constants.xls relates to a static class or enum that the original code author is using to hold the .xls/.xlsx extensions.
If you create a constants class something like:
public static class Constants
{
public static string xls = "xls";
public static string xlsx = "xlsx";
}
This would then should help.
If you need any more assistance then please let me know.
edit: Just reviewing the code it seems they are also putting in constant mapping for the uploadfolder location as well so I suspect this is just a static class rather than an enum with application specific details. in a way a bit like using the appSettings within webconfig

Emgu CV C# Exception creating tesseract object

I can access all emgu libraries. VS finds the libraries and using Emgu.CV.OCR returns no errors.
When I try to create a Tesseract object, Program.cs throws a FileLoadException. in System.Windows.Forms.dll.
Removing the line of code that creates a tesseract lets the program run fine.
I have tried copying tessdata to my debug file and that also has not worked.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}
I fiddled with the same problem for a while; now I got it.
First, make sure you have the following using directives (you might need to download Emgu.CV via NuGet):
using Emgu.CV;
using Emgu.CV.OCR;
using System.Reflection;
using System.IO;
using System.Drawing;
Then, make sure you have the most up-to-date tessdata on board. If not, navigate to github and download it (click "Clone or Download" and select "Download ZIP File"). You should then unzip the file and rename the folder "tessdata-master" to "tessdata." Copy this folder to the place where your binary lives (the assembly location).
Lastly, assign the correct path, and you're ready to do OCR!
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
var _ocr = new Tesseract(path, "eng", OcrEngineMode.Default);
_ocr.SetImage(yourImage);
_ocr.Recognize();
var result = _ocr.GetCharacters();
First you need to check your project References . Is there "Emgu.CV.OCR" library if not kindly add it first. Then try the following code may it will work for you.
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"C:\Emgu\emgucv-windows-universal-cuda 2.9.0.1922\Emgu.CV.OCR\tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);//first Parameter set your path ..complete path like i did
_ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopkrstuvwxyz");
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}

Downloading bulk files from sharepoint library

I want to download the files from a sharepoint document library through code as there are thousand of files in the document library.
I am thinking of creating console application, which I will run on sharepoint server and download files. Is this approach correct or, there is some other efficient way to do this.
Any help with code will be highly appreciated.
Like SigarDave said, it's perfectly possible to achieve this without writing a single line of code. But if you really want to code the solution for this, it's something like:
static void Main(string[] args)
{
// Change to the URL of your site
using (var site = new SPSite("http://MySite"))
using (var web = site.OpenWeb())
{
var list = web.Lists["MyDocumentLibrary"]; // Get the library
foreach (SPListItem item in list.Items)
{
if (item.File != null)
{
// Concat strings to get the absolute URL
// to pass to an WebClient object.
var fileUrl = string.Format("{0}/{1}", site.Url, item.File.Url);
var result = DownloadFile(fileUrl, "C:\\FilesFromMyLibrary\\", item.File.Name);
Console.WriteLine(result ? "Downloaded \"{0}\"" : "Error on \"{0}\"", item.File.Name);
}
}
}
Console.ReadKey();
}
private static bool DownloadFile(string url, string dest, string fileName)
{
var client = new WebClient();
// Change the credentials to the user that has the necessary permissions on the
// library
client.Credentials = new NetworkCredential("Username", "Password", "Domain");
var bytes = client.DownloadData(url);
try
{
using (var file = File.Create(dest + fileName))
{
file.Write(bytes, 0, bytes.Length); // Write file to disk
return true;
}
}
catch (Exception)
{
return false;
}
}
another way without using any scripts is by opening the document library using IE then in the ribbon you can click on Open in File Explorer where you can then drag and drop the files right on your desktop!

How to zip and unzip folders and its sub folders in Silverlight?

I have a Windows Phone application. I am using SharpZipLib to zip folders and its sub folders. This is zipping only the folder but the data inside the folders is not getting zipped. Can anyone guide me how to do this?
My code:
private void btnZip_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string filename in appStore.GetFileNames(directoryName + "/" + "*.txt"))
{
GetCompressedByteArray(filename);
}
textBlock2.Text = "Created file has Zipped Successfully";
}
}
public byte[] GetCompressedByteArray(string content)
{
byte[] compressedResult;
using (MemoryStream zippedMemoryStream = new MemoryStream())
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer;
using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
buffer = new byte[file.Length];
file.Read(buffer, 0, buffer.Length);
}
ZipEntry entry = new ZipEntry(content);
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.Finish();
}
compressedResult = zippedMemoryStream.ToArray();
}
WriteToIsolatedStorage(compressedResult);
return compressedResult;
}
public void WriteToIsolatedStorage(byte[] compressedBytes)
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
appStore.CreateDirectory(ZipFolder);
using (IsolatedStorageFileStream zipTemplateStream = new IsolatedStorageFileStream(ZipFolder+"/"+directoryName + ".zip", FileMode.OpenOrCreate, appStore))
using (BinaryWriter streamWriter = new BinaryWriter(zipTemplateStream))
{
streamWriter.Write(compressedBytes);
}
}
I think you'll find this guide helpful.
An excerpt from the above link
The ZipFile object provides a method called AddDirectory() that
accepts a parameter directoryName. The problem with this method is
that it doesn't add the files inside the specified directory but
instead just creates a directory inside the zip file. To make this
work, you need to get the files inside that directory by looping thru
all objects in that directory and adding them one at a time. I was
able to accomplish this task by creating a recursive function that
drills through the whole directory structure of the folder you want to
zip. Below is a snippet of the function.
I guess you too are facing the same problem where the folder is added to the zip file, but the contents and sub folders are not zipped.
Hope this helps.
Have a look over here for a code sample on how to use SharpZipLib to zip a root folder including nested folders.

Resources