SSIS (File System Task) - Unable to move file [duplicate] - sql

I've created a connection using Microsoft Office 12.0 Access Database Engine OLE DB Provider as Excel Schema to loop through all the sheets in the Excel file as demonstrated in this question How to loop through Excel files and load them into a database using SSIS package?
And using Foreach ADO.NET Schema Rowset Enumerator to loop through the excel files.
Everything is working fine now, but after importing the data from Excel, I wanted to move that file to Archive folder. And tried using a File System Task, but I get the error as
[File System Task] Error: An error occurred with the following error message: "The process cannot access the file because it is being used by another process.".
And I also tried with script task from this link. But I was getting some error and couldn't solve the error as I've got zero knowledge on C#.
Below is the error I've got when I tried to move the files using a script task.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript().
Update:
Here's my complete code with which I'm trying to move the files.
If I add a breakpoint at enum ScriptResults, I don't get that popup and the task gets completed successfully and the file is also been moved to archive, but if I don't add any breakpoint in the C# code, I get that pop and the file is not moved to archive.
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
#endregion
namespace ST_9fc6ad7db45c4a7bb49f303680f789ef
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
DirectoryInfo di = new DirectoryInfo(Dts.Variables["SplitSkill_FolderPath"].Value.ToString());
FileInfo[] fi = di.GetFiles("*.xlsx");
String filename = fi[0].Name;
string sourceFileName = filename;
string destinationFile = #"D:\Flipkart\Data\Split Skill\Archive\" + sourceFileName;
string sourceFile = #"D:\Flipkart\Data\Split Skill\" + sourceFileName;
if (File.Exists(destinationFile))
File.Delete(destinationFile);
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

As far as I understand, I think you have a task for looping through sheets and another for looping through files. So you probably have 2 tasks inside a foreach loop. Try making a copy of the file inside the foreach loop with a system task
for the executable
c:\windows\system32\cmd.exe
and for the arguments soemthing like
C COPY "C:\xxx\abc\\Destination_template.accdb" "C:\xxx\abc\\Destination_template.accdb"Destination_template - Kopie.accdb"
Then create a file system task which moves that copy to your archive.
This should do the trick (Maybe not the best approach but should work)

Related

NReco.PdfGenerator The pipe has been ended error on the server

I'm using NReco.PdfGenerator for my PDF documents(that component is based on WkHtmlToPdf tool), my code allow me to create a pdf calling a function with the parameters controller, action, model:
public static byte[] GeneratePdfDocument(System.Web.Mvc.Controller controller, string viewName, object model)
{
string result;
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
result = sw.ToString();
}
return (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(result);
}
With this code I can create a PDF easily from my views and it's working great on my development environment but on a server I'm getting this error:
The pipe has been ended.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The pipe has been ended.
[IOException: The pipe has been ended.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +11185413
System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count) +10770013
System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count) +139
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdfInternal(String htmlFilePath, Byte[] inputBytes, String coverHtml, String outputPdfFilePath, Stream outputStream) +2166
[Exception: Cannot generate PDF: The pipe has been ended.]
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdfInternal(String htmlFilePath, Byte[] inputBytes, String coverHtml, String outputPdfFilePath, Stream outputStream) +2734
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdf(String htmlContent, String coverHtml, Stream output) +51
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdf(String htmlContent, String coverHtml) +42
I think that is maybe a problem with permissions or some configuration on my IIS, any idea?
You are probably missing Visual C++ Redistributable Packages for VS2013 (x86). Even if your server is running 64bit Windows, you need to install the x86 C++ Packages.

IsolatedStorageException in Ms Word Addin

I created a Word add-in project with a ribbon, and when I want to save the document, after several modifications with OpenXml, an exception is raised.
Dim MainXMLDoc As New XmlDocument()
Using WordDoc As WordprocessingDocument = WordprocessingDocument.Open(DocPath, True)
Dim mainPart As MainDocumentPart = WordDoc.MainDocumentPart
If Not mainPart Is Nothing Then
MainXMLDoc.Load(mainPart.GetStream())
EXmlDocument.XMLDoc = Nothing
EXmlDocument.XMLDoc = MainXMLDoc
EXmlDocument.GetWordDocIds()
'..............
end if
'........
Dim stream As IO.Stream
stream = mainPart.GetStream(FileMode.Create, FileAccess.Write)
MainXMLDoc.Save(stream) '-----> exception
And the exception message is:
Interception de System.IO.IsolatedStorage.IsolatedStorageException
Message=Unable to determine the identity of domain. Source=mscorlib
StackTrace:
at System.IO.IsolatedStorage.IsolatedStorage._GetAccountingInfo(Evidence
evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, Object&
oNormalized)
at System.IO.IsolatedStorage.IsolatedStorage.GetAccountingInfo(Evidence
evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, String&
typeName, String& instanceName)
at System.IO.IsolatedStorage.IsolatedStorage._InitStore(IsolatedStorageScope
scope, Evidence domainEv, Type domainEvidenceType, Evidence assemEv,
Type assemblyEvidenceType, Evidence appEv, Type appEvidenceType)
at System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedStorageScope
scope, Type domainEvidenceType, Type assemblyEvidenceType)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope
scope, Type domainEvidenceType, Type assemblyEvidenceType)
at MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder.GetCurrentStore()
at MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder..ctor()
at MS.Internal.IO.Packaging.PackagingUtilities.GetDefaultIsolatedStorageFile()
at MS.Internal.IO.Packaging.PackagingUtilities.CreateUserScopedIsolatedStorageFileStreamWithRandomName(Int32
retryCount, String& fileName)
at MS.Internal.IO.Packaging.SparseMemoryStream.SwitchModeIfNecessary()
at MS.Internal.IO.Packaging.SparseMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.CompressEmulationStream.Write(Byte[] buffer,
Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.CompressStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Write(Byte[]
buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Write(Char value)
at System.Xml.XmlTextWriter.Indent(Boolean beforeEndElement)
at System.Xml.XmlTextWriter.AutoComplete(Token token)
at System.Xml.XmlTextWriter.WriteStartElement(String prefix, String localName, String ns)
at System.Xml.XmlDOMTextWriter.WriteStartElement(String prefix, String localName, String ns)
at System.Xml.XmlElement.WriteStartElement(XmlWriter w)
at System.Xml.XmlElement.WriteElementTo(XmlWriter writer, XmlElement e)
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlDocument.WriteContentTo(XmlWriter xw)
at System.Xml.XmlDocument.WriteTo(XmlWriter w)
at System.Xml.XmlDocument.Save(Stream outStream) InnerException:
This problem appears when the document size is larger than 1 MB.
After several searches, the 'save' action is made with an isolated storage, and the solutions is :
Install with Clickonce
Create new domain
Modify registry.
But for this project, I can't use ClickOnce and I can't modify the registry.
So I made changes to my source code, to create a new domain.
Imports DocumentFormat.OpenXml.Packaging
Imports System.IO
<Serializable()> Public Class ToIsolatedPackageSave
Public Sub Save(ByRef mainPart As MainDocumentPart, ByRef xmlDocument As Xml.XmlDocument)
Dim stream As IO.Stream
stream = mainPart.GetStream(FileMode.Create, FileAccess.Write)
xmlDocument.Save(stream) -----> same exception
End Sub
End Class
And
Dim stream As Stream
Dim isolatedPackageSave As ToIsolatedPackageSave
Dim isolatedAppDomain As AppDomain
Try
Dim isolatedAppDomainSetup As AppDomainSetup = New AppDomainSetup()
isolatedAppDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
Dim isolatedEvidence As Evidence = New Evidence(AppDomain.CurrentDomain.Evidence)
isolatedEvidence.AddAssembly(Reflection.Assembly.GetExecutingAssembly().FullName)
isolatedEvidence.AddHost(New Zone(Security.SecurityZone.MyComputer))
isolatedAppDomain = AppDomain.CreateDomain("TrustIsolatedDomain", isolatedEvidence, isolatedAppDomainSetup)
isolatedPackageSave = isolatedAppDomain.CreateInstanceAndUnwrap(GetType(ToIsolatedPackageSave).Assembly.FullName, GetType(ToIsolatedPackageSave).FullName)
'(IsolatedPackageSave)isolatedAppDomainSetup.CreateInstanceAndUnwrap(GetType(ToIsolatedPackageSave).Assembly.FullName, GetType(ToIsolatedPackageSave).FullName)
isolatedPackageSave.Save(mainPart, MainXMLDoc)
Catch ex As Exception
Finally
AppDomain.Unload(isolatedAppDomain)
End Try
But this code doesn't fix my problem.
I followed Tim Lewis' advice in this post to inject the needed security evidence:
http://rekiwi.blogspot.com/2008/12/unable-to-determine-identity-of-domain.html
public void VerifySecurityEvidenceForIsolatedStorage(Assembly assembly)
{
var isEvidenceFound = true;
var initialAppDomainEvidence = System.Threading.Thread.GetDomain().Evidence;
try
{
// this will fail when the current AppDomain Evidence is instantiated via COM or in PowerShell
using (var usfdAttempt1 = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain())
{
}
}
catch (System.IO.IsolatedStorage.IsolatedStorageException e)
{
isEvidenceFound = false;
}
if (!isEvidenceFound)
{
initialAppDomainEvidence.AddHostEvidence(new Url(assembly.Location));
initialAppDomainEvidence.AddHostEvidence(new Zone(SecurityZone.MyComputer));
var currentAppDomain = Thread.GetDomain();
var securityIdentityField = currentAppDomain.GetType().GetField("_SecurityIdentity", BindingFlags.Instance | BindingFlags.NonPublic);
securityIdentityField.SetValue(currentAppDomain, initialAppDomainEvidence);
var latestAppDomainEvidence = System.Threading.Thread.GetDomain().Evidence; // setting a breakpoint here will let you inspect the current app domain evidence
}
}
Then call the following code at startup:
VerifySecurityEvidenceForIsolatedStorage(this.GetType().Assembly);
I think, you can't use OpenXML inside office addins. If you want to use OpenXML, u have to do it offline (when document is not opened). You can only use COM interops (office object Model calls) from inside addins.

Converter failed to convert value of type 'Windows.Foundation.String' to type 'ImageSource'

This is for my Windows 8 app:
In my object I have a string property that contains the path of the images I want to use.
public String ImagePath
In my XAML I have set up an Image tag with the following binding:
<Image Source="{Binding ImagePath}" Margin="50"/>
When I reference an image that I've included in my project (in the Asset folder) the image displays correctly. The path is: Assets/car2.png
However, when I reference an image that the user selects (using the FilePicker) I get an error (and no image). The path is: C:\Users\Jeff\Pictures\myImage.PNG
Converter failed to convert value of type 'Windows.Foundation.String'
to type 'ImageSource'
Just to add a little more info. When I use the file picker I am converting the file location to a URI:
Uri uriAddress = new Uri(file.Path.ToString());
_VM.vehicleSingle.ImagePath = uriAddress.LocalPath;
Update:
I'm also saving this image path to isolated storage. I think this is where the issue is. I'm able to save the path of the file selected, but when I try to bind to it when I'm reloading the Isolated Storage it doesn't work.
So if I can't use an image outside of the application directory. Is there a way I can save that image and add it to the directory?
I tried creating a BitmapImage property to my model but now I'm getting errors stating that it can't serialize a BitmapImage.
You should Use Converter
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
MemoryStream memStream = new MemoryStream((byte[])value,false);
BitmapImage empImage = new BitmapImage();
empImage.SetSource(memStream);
return empImage;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
You can't use a file path that points outside the app directory. You will need to read in the StorageFile stream that you get from the file picker and assign that stream to an image source - so binding is pretty hard unless you change your model,to have an imagesource property instead.
As mentioned, you cannot use bindings to access the file system directly, even if you grant access via the File Picker. Take a look at the XAML Images Sample at the Dev Center, for a technique you can use.
In a nutshell, you'll use SetSourceAsync to get your file into a BitmapImage and then you can use that as the binding source.
I recently did some work on binding to an ImageSource.
public System.Windows.Media.ImageSource PhotoImageSource
{
get
{
if (Photo != null)
{
System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
image.BeginInit();
image.StreamSource = new MemoryStream(Photo);
image.EndInit();
return image as System.Windows.Media.ImageSource;
}
else
{
return null;
}
}
}
My "Photo" was an image stored in a byte[]. You could either convert your image to a byte[] or maybe try using a FileStream instead (I haven't tested with a FileStream so I can't say if it will work).

Serialization error while publishing the content using DD4T TBB's

We rebuilt the DD4T TBBs from source control and deployed them to tridion using TCMUploadAssembly.exe.
We Created a simple component with a multimedia link field ,a component link field and a text field and populated the values. Then created a CT with [Generate dynamic component, Publish binaries for component ] TBB’s inside it and tried to publish a single DCP.
We are able to run the CT against component in template builder and get the expected output [ i.e well formatted Serialized component XML output]
However when publishing we get a serialization error. (see below) . This error is occurring while the code is trying to serialize any component field (text/multimedia/component link etc)
We are unable to identify the root cause. Tried to remote debug the code , even though all the dynamic.component object properties are correctly set while serializing the component object we are facing this issue. Even tried to restart COM +, publisher services but issue still persists. Any pointers is highly appreciated.
Couldn’t able to find why the code is running correctly in Template builder without serialization errors but failing at publish time with below error.
Here’s the error message:
There was an error generating the XML document.
There was an error generating the XML document.
Object reference not set to an instance of an object.
Component: Templating
Errorcode: 0
User: NORD\DWTMTSUser
StackTrace Information Details:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterField.XSArrayInfo.get_Item(Object a, Int32 i)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterField.Write13_Field(String n, String ns, Object o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterField.Write14_Field(Object o)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o)
at DD4T.ContentModel.SerializableDictionary`3.WriteXml(XmlWriter writer) in D:\DW-Source\Mainline\Src\DD4T\DD4T.ContentModel\SerializableDictionary.cs:line 80
at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write13_Component(String n, String ns, Component o, Boolean isNullable, Boolean needType) in :line 0
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write32_Component(Object o) in :line 0
at Microsoft.Xml.Serialization.GeneratedAssembly.ComponentSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer) in :line 0
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces)
at DD4T.Templates.Base.BaseComponentTemplate.Transform(Engine engine, Package package) in D:\DW-Source\Mainline\Src\DD4T\DD4T.Templates.Base\BaseComponentTemplate.cs:line 88
at Tridion.ContentManager.Templating.Assembly.AssemblyMediator.Transform(Engine engine, Template template, Package package)
at Tridion.ContentManager.Templating.Assembly.CSharpSourceCodeMediator.RunTemplate(Engine engine, Package package, String templateUri, String className)
at Tridion.Templating.CSharpTemplate.CSharpSourceTemplate.Transform(Engine __engine, Package __package)
at Tridion.ContentManager.Templating.Assembly.CSharpSourceCodeMediator.Transform(Engine engine, Template template, Package package)
at Tridion.ContentManager.Templating.Engine.ExecuteTemplate(Template template, Package package)
Did Quirijn's answer help you? https://groups.google.com/d/msg/dynamic-delivery-4-tridion/K0BzzPovUz4/1RvTHFHktukJ
Also, if you have multiple publishers make sure you you add the DD4T.Templates.Base.dll to the GAC of all your publishers. (If you've gone for option 2 of Q's answer)

C# to vb.net conversion

I need to convert this code from C# to VB. I'm not sure of the proper syntax.
C#
[XcoWorkerExtension(Optional = new Type[] { typeof(Subscribe<OnNewsArrived>) })]
private readonly XcoPublisher<OnNewsArrived> publisher = new XcoPublisher<OnNewsArrived>();
This is what I've come up with in VB:
<XcoWorkerExtension([Optional]:=New Type() {GetType(Subscribe(Of OnNewsArrived))})> _
Private ReadOnly publisher As New XcoPublisher(Of OnNewsArrived)()
The C# version runs fine but when I try to run the VB version I'm getting this exception:
System.IO.FileLoadException was unhandled
Message=The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
Source=mscorlib
The exception is generated at the first line of this sub:
internal XcoWorkerExtensionAttribute Get_worker_extension_attribute(FieldInfo field)
{
object[] fieldAttrs = field.GetCustomAttributes(typeof(XcoWorkerExtensionAttribute), false);
object[] classAttrs = field.FieldType.GetCustomAttributes(typeof(XcoWorkerExtensionAttribute), false);
if (fieldAttrs.Length > 0 && classAttrs.Length == 0)
throw new XcoWorkerException("A field can only be marked with the XcoWorkerExtension attribute when its type is also marked with this attribute");
if (fieldAttrs.Length > 0)
return (XcoWorkerExtensionAttribute)fieldAttrs[0];
if (classAttrs.Length > 0)
return (XcoWorkerExtensionAttribute)classAttrs[0];
return null;
}
Sorry for giving a "meta answer".
For small conversions like this, Reflector is a nice tool if you are unsure about syntax and/or results.
Possibilities of use:
Compile in C#, and decompile to VB.Net.
Compile in VB.Net, compare to original
C# to VB Converter
Worked for one of my projects, though I suspect there are a few things that will make it unhappy. And you as well.