I am new here in the forum and I just start to work in a new web application on Visual studio 2013. I need to create an application that copy all the content from one Word Document to another. I had found this plugin that should make the job but I dont know how to put it in my code and make it work. I need to do it in a MVC application, so maybe I am not putting the code in the right place (now it is in the Model). Someone can help me telling me how to make it work? Please see the code that I have:
using Spire.Doc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DocumentApplication.Models
{
public class HomeModel
{
public string Message { get; set; }
}
public class CopyDocument
{
Document sourceDoc = new Document("source.docx");
Document destinationDoc = new Document("target.docx");
foreach (Section sec in sourceDoc.Sections)
{
foreach (DocumentObject obj in sec.Body.ChildObjects)
{
destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
}
}
destinationDoc.SaveToFile("target.docx");
System.Diagnostics.Process.Start("target.docx");
}
public class OpenDocument
{
Document document = new Document(#"C:\Users\daniel\Documents\ElAl-DRP.doc");
}
}
I cannot compile this because I have an error on the "foreach" line that says: "Invalid token 'foreach' in class' struct' or interface member declaration".
Please help me.
Thanks in advance
Okay this is pretty rough but it at least works.
I could not make the example from the Spire work, I had to make some changes.
This example will take an uploaded file, save it in to the "AppData/uploads" folder then it will create a copy of that saved file in the "AppData/copies" folder.
My Changes
the way we create the destination Doc in memory then save later.
Create a new section in the "foreach" loop
Add the cloned sections to the new section
List item
Document Format on the SaveDocument Method (This is a huge
assumption)
Controller
using System.IO;
using System.Web;
using System.Web.Mvc;
using Spire.Doc;
using Spire.Doc.Collections;
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
var outputPath = Path.Combine(Server.MapPath("~/App_Data/copies"), fileName);
var sourceDoc = new Document(path);
var destinationDoc = new Document();
foreach (Section sec in sourceDoc.Sections)
{
var newSection = destinationDoc.AddSection();
foreach (DocumentObject obj in sec.Body.ChildObjects)
{
newSection.Body.ChildObjects.Add(obj.Clone());
}
}
destinationDoc.SaveToFile(outputPath, FileFormat.Docx);
}
return View();
}
}
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file"/>
<button type="submit">Save</button>
}
Related
I have an image gallery where the images are loaded dynamically from a server, and the paths of each image is saved in MySql. Now, I want to have a "Download all images" button, so it generate a .zip with all images in the gallery.
The project is hosted on Linux, and to test the updates I use Github actions.
To create de .zip I found DotNetZip Nugget package.
When I do git push, on my Github Actions I have this error:
The type or namespace name 'Ionic' could not be found (are you missing
a using directive or an assembly reference?)
The ionic namespace is the namespace that allows me to use Zipfile.
I will show you the code...but Visual Studio has no problems.
Html:
#using(Html.BeginForm("DownloadAll", "Home", new { pedido = ViewBag.pedido}, FormMethod.Post))
{
<div>
<input class="btn btn-primary" value="Descargar Todas las Imagenes" type="submit"/>
</div>
}
Back:
public FileResult DownloadAll()
{
string consulta;
List<PedidoViewModel> listaPedidos;
try
{
listaPedidos = new List<PedidoViewModel>();
consulta = "SELECT DISTINCT p.Pedido, p.Entrega, p.Remito, e.Path, e.Fecha from Pedido p INNER JOIN Entrega e ON p.Entrega = e.Entrega WHERE p.Pedido = " + ViewBag.pedido + " GROUP by e.Path";
listaPedidos = SelectConexionMySql(consulta);
using (ZipFile zip = new ZipFile())
{
foreach (var lista in listaPedidos)
{
var archivo_nombre = lista.getPathImagen();
var archivo_arregloBytes = System.IO.File.ReadAllBytes(lista.getPathImagen());
zip.AddEntry(archivo_nombre, archivo_arregloBytes);
}
var nombreZip = "ImagenesPedido" + ViewBag.pedido;
using (MemoryStream output = new MemoryStream())
{
zip.Save(output);
return File(output.ToArray(), "application/zip", nombreZip);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
I use MySql query so I can recover the path of the images. Then, I use a foreach loop so every path I can save the name and a bytes in the zip.
So, the problem is that Github Actions cannot recognize the Ionic namespace, so, how can I create a .zip from a dinamic image gallery? I have to add something more so Github can recognize Ionic?
I try to get the "Last modified" excel file in a folder and load it in SSIS. I found a C# code to get the name of most recent excel sheet in a folder path, and copy that in the Script Task. The code is :
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
namespace ST_2e01f076aa4f46d692cf4b47f5587da9.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
// TODO: Add your code here
var directory = new DirectoryInfo(Dts.Variables["User::VarFolderPath"].Value.ToString());
FileInfo[] files = directory.GetFiles();
DateTime lastModified = DateTime.MinValue;
foreach (FileInfo file in files)
{
if (file.LastWriteTime > lastModified)
{
lastModified = file.LastWriteTime;
Dts.Variables["User::VarFileName"].Value = file.ToString();
}
}
MessageBox.Show(Dts.Variables["User::VarFileName"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
However, when I run the script task to test it, I get the following error:
I used the project name displaying in error in my code, but still does not work. Could you please kindly help me how to fix it as I am new to both SSIS and C#. Thanks
Here is an answer using Linq.
First add these namespaces
using System.Collections.Generic; //This gets you list
using System.Linq; //This allows you linq functions
//Here is your code
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(#"D:\Temp");
List<System.IO.FileInfo> fi = di.EnumerateFiles().ToList();
Dts.Variables["VarFileName"].Value = fi.Where(i=>i.Extension.ToLower()==".xls")
.OrderByDescending(i => i.LastWriteTime)
.Select(i => i.FullName).FirstOrDefault();
I just deployed a new controller to my production environment. For some reason, the controller does not get called. All other controllers on the site work fine. This is the only one that is failing. What I keep getting is the error:
Error rendering controller BlogListing.GetIndex: Could not create
controller: 'BlogListing'. The controller for path '/' was not found
or does not implement IController
I've spent about 3 hours trying to troubleshoot this. I have:
Added debug code into the controller to see if it is in fact being called. My debug statements does not get hit.
Verified the name of the controller is correct
I am using the default MVC routing.
Thinking that it might be a missing dependent dll, I copied all of the dlls from my production environment (where it is not working) to my local environment and it came right up
Checked file system permissions thinking that somehow it couldn't be read.
I did look at other posts regarding similar issues but none of those solutions worked or were not applicable
namespace Portal.Features.Blog.Controllers
{
using Glass.Mapper.Sc;
using Glass.Mapper.Sc.Web.Mvc;
using Sitecore.Data.Items;
using System;
using System.Linq;
using System.Web.Mvc;
using Portal.Foundation.Blog;
using portal.ct.gov.Models;
using Portal.Features.Blog.Models;
using portal.ct.gov.Business;
public class BlogListingController : GlassController
{
public ActionResult GetIndex(string keyword = "", string page = "", string author = "")
{
Sitecore.Diagnostics.Log.Info("Blog Controller found", "portal.ct.gov");
try
{
SitecoreContext scContext = new SitecoreContext();
Item contextItem = scContext.GetCurrentItem<Item>();
Item blogHome = null;
//Get Blog Root
if (contextItem != null)
{
blogHome = contextItem.Axes.SelectSingleItem("ancestor-or-self::*[##templatename = 'Blog Section']");
}
var sKeyword = !string.IsNullOrEmpty(HttpContext.Request.QueryString[Constants.QueryStrings.SearchKeyword]) ? HttpContext.Request.QueryString[Constants.QueryStrings.SearchKeyword] : string.Empty;
var blogAuthor = !string.IsNullOrEmpty(HttpContext.Request.QueryString["author"]) ? HttpContext.Request.QueryString["author"] : string.Empty;
var blogCategory = !string.IsNullOrEmpty(HttpContext.Request.QueryString["category"]) ? HttpContext.Request.QueryString["category"] : string.Empty;
var blogPage = !string.IsNullOrEmpty(HttpContext.Request.QueryString["page"]) ? HttpContext.Request.QueryString["page"] : "1";
var model = GetBlogListing(blogHome, sKeyword, blogCategory, blogAuthor, Convert.ToInt32(blogPage));
return View("/views/blog/BlogResultsMain.cshtml", model);
}
catch(Exception ex)
{
Sitecore.Diagnostics.Log.Error("Error processing bloglisting-->getINdex " + ex.Message, ex, "portal.ct.gov");
return View("/views/blog/BlogResultsMain.cshtml");
}
}
}
Any help is appreciated. Please note that I am using Sitecore CMS.
It is worth checking the cached MVC-ControllerTypeCache.xml file in folder c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\NAMEOFYOURAPP\xxxxx\xxxxxxxx\UserCache\.
If you can't find your controller there, remove the cached xml file and restart your website. More details you can find here
I'd like to use Roslyn to analyze semantic information within the context of a block of C# code inside a Razor View.
Is there any way (within Visual Studio 2015, or even in a unit test) to get the SemanticModel that represents this code?
Razor files contain a C# projection buffer with the generated C# code (including the parts that you don't write yourself). This buffer has full Roslyn services and is exactly what you're looking for.
You need to walk through the TextView's BufferGraph and find the CSharp buffer; you can then get its Document and semantic model.
If you're starting from the cursor location, you need simply need to map that location to a CSharp buffer.
Note that it is perfectly legal for a TextView to contain multiple CSharp buffers. (although the Razor editor will never do that)
If you aren't working in a TextView, you need to do all of this yourself; you need to run the Razor source through the Razor compiler to get the generated C# source, then compile that with Roslyn to get a semantic model.
Extract the code representing the view from the Razor view file using RazorTemplateEngine.GenerateCode and CSharpCodeProvider.GenerateCodeFromCompileUnit (or the VBCodeProvider if you want the intermediate source as VB.NET). You can then use Roslyn to parse the code.
There's an example of using Roslyn with Razor view files here.
Take note that GenerateCode carries a caveat:
This type/member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Just in case anyone else gets stuck on this, I have mini sample app which may help.
I had a CMS class like this:
public partial class CMS
{
public static string SomeKey
{
get { return (string) ResourceProvider.GetResource("some_key"); }
}
// ... and many more ...
}
... and I wanted to find out which of these were used throughout my solution for a report ... Enter Roslyn!
The following app will print out the count for the used and unused references:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Razor;
namespace TranslationSniffer
{
class Program
{
static void Main(string[] args)
{
new Program().Go().Wait();
}
public async Task Go()
{
// Roslyn!
var ws = MSBuildWorkspace.Create();
// Store the translation keys...
List<string> used = new List<string>();
List<string> delete = new List<string>();
string solutionRoot = #"C:\_Code\PathToProject\";
string sln = solutionRoot + "MySolution.sln";
// Load the solution, and find all the cshtml Razor views...
var solution = await ws.OpenSolutionAsync(sln);
var mainProj = solution.Projects.Where(x => x.Name == "ConsumerWeb").Single();
FileInfo[] cshtmls = new DirectoryInfo(solutionRoot).GetFiles("*.cshtml", SearchOption.AllDirectories);
// Go through each Razor View - generate the equivalent CS and add to the project for compilation.
var host = new RazorEngineHost(RazorCodeLanguage.Languages["cshtml"]);
var razor = new RazorTemplateEngine(host);
var cs = new CSharpCodeProvider();
var csOptions = new CodeGeneratorOptions();
foreach (var cshtml in cshtmls)
{
using (StreamReader re = new StreamReader(cshtml.FullName))
{
try
{
// Let Razor do it's thang...
var compileUnit = razor.GenerateCode(re).GeneratedCode;
// Pull the code into a stringbuilder, and append to the main project:
StringBuilder sb = new StringBuilder();
using (StringWriter rw = new StringWriter(sb))
{
cs.GenerateCodeFromCompileUnit(compileUnit, rw, csOptions);
}
// Get the new immutable project
var doc = mainProj.AddDocument(cshtml.Name + ".cs", sb.ToString());
mainProj = doc.Project;
}
catch(Exception ex)
{
Console.WriteLine("Compile fail for: {0}", cshtml.Name);
// throw;
}
continue;
}
}
// We now have a new immutable solution, as we have changed the project instance...
solution = mainProj.Solution;
// Pull out our application translation list (its in a static class called 'CMS'):
var mainCompile = await mainProj.GetCompilationAsync();
var mainModel = mainCompile.GetTypeByMetadataName("Resources.CMS");
var translations = mainModel.GetMembers().Where(x => x.Kind == SymbolKind.Property).ToList();
foreach (var translation in translations)
{
var references = await SymbolFinder.FindReferencesAsync(translation, solution) ;
if (!references.First().Locations.Any())
{
Console.WriteLine("{0} translation is not used!", translation.Name);
delete.Add(translation.Name);
}
else
{
Console.WriteLine("{0} :in: {1}", translation.Name, references.First().Locations.First().Document.Name);
used.Add(translation.Name);
}
}
Console.WriteLine();
Console.WriteLine("Used references {0}. Unused references: {1}", used.Count, delete.Count);
return;
}
}
}
Roslyn only models cshtml files while they are open, but during that time they are similar to every other source file in the Workspace model.
Is there something specific you have tried that isn't working?
In Windows Forms I can create a class file called 'Authentication.cs' with the following code:
public class Authentication
{
public string Name;
internal bool Authenticate()
{
bool i = false;
if (Name == "Jason")
{
i = true;
}
return i;
}
}
In WebMatrix, I can insert a new Class file, called 'Authentication.cs', and insert the above code.
And in my default.cshtml file, I do this:
<body>
#{
Authentication auth = new Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp");</p>
}
}
</body>
But it won't work! It works for the WinForms desktop app, but not in WebMatrix. I don't know why it's not working. The error message is:
"The namespace Authenticate does not
exist. Are you sure you have
referenced assemblies etc?"
So, then at the top of my default.cshtml file I tried this:
#using Authentication.cs;
Which led to the exact same error!
There's no documentation that I can find anywhere that tells you how to "include" a class file into your WebMatrix pages.
Any help is appreciated,
Thank you!
You import a namespace, not a file. So; what namespace is Authentication in? For example:
#using My.Utils.Authentication.cs;
Also - you want to drop the ; in the razor call:
<p>#auth.Authenticated("jasonp")</p>
You can also provide the fully qualified name in the code:
#{
var auth = new My.Utils.Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp")</p>
}
}
(aside: are you intentionally calling the same method twice with the same values?)
Just drop the cs file in you App_Code directory
then do something like this
#{
Authentication auth = new Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp");</p>
}
}
No need to add a using.
Additionally if you wanted to use a .dll then you would need the using
#using NameSpace.Authenication
#{
Authenticated auth = new Authenicated();
}
#if(#auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp")</p>
}
Create a file named linkRef.cs
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class linkRef
{
public linkRef() {
//
// TODO: Add constructor logic here
//
}
}
Put it in a folder App_code then by dot net 2012 publish to bin then upload bin folder