Call SSIS Package from c# Console Application For Each Loop - c#-4.0

I have a Console Application which is invoking SSIS Package.Below is the code which is working Fine.
public static void ExecuteSSIS_Staging()
{
DataAccessLayer objDAL = new DataAccessLayer();
LogManager_SSIS objlogM = new LogManager_SSIS();
String strDestinationFilePath = System.Configuration.ConfigurationManager.AppSettings.Get("FileDownloaded");
try
{
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
string staging_pkgLocation = System.Configuration.ConfigurationManager.AppSettings.Get("SSIS_Staging_Filepath").ToString();
app = new Application();
pkg = app.LoadPackage(staging_pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
if (pkgResults == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success)
{
Console.WriteLine("Success");
}
else if (pkgResults == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
string err = "";
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in pkg.Errors)
{
string error = local_DtsError.Description.ToString();
err = err + error;
}
throw new Exception("Error Occurred while executing the SSIS Staging package:" + err);
}
}
catch (Exception ex)
{
throw new Exception("SSIS Package Execution Failed:" + ex.Message.ToString());
}
}
Now I am in a position to Invoke this Package inside Foreach Loop.
static void Main(string[] args)
{
try
{
foreach (DateTime FileDate in SortedDates)
{
ExecuteSSIS_Staging(FileDate);
}
}
Catch(Exception ex)
{
}
}
I am getting Many Issues like
Could not load file or assembly 'Microsoft.SqlServer.ManagedDTS
and few other DLL reference error.
Can anyone suggest me, how can i invoke SSIS Package Inside Foreach loop. The main thing is, In my Local machine it is working obsolutely file. But When i deploy it in server, it is not.

The actuall issue is i have added
Microsoft.SQLServer.ManagedDTS.dll version 9.0
in one machine. When i tried to open it in other machine, some how DLL is refernced to
Microsoft.SQLServer.ManagedDTS.dll version 10.0 version.
I changed it again & executed. Now Working Fine.

Related

Testing for file upload in Spring MVC

Project setup:
<java.version>1.8</java.version>
<spring.version>4.3.9.RELEASE</spring.version>
<spring.boot.version>1.4.3.RELEASE</spring.boot.version>
We have a REST controller that has a method to upload file like this:
#PostMapping("/spreadsheet/upload")
public ResponseEntity<?> uploadSpreadsheet(#RequestBody MultipartFile file) {
if (null == file || file.isEmpty()) {
return new ResponseEntity<>("please select a file!", HttpStatus.NO_CONTENT);
} else if (blueCostService.isDuplicateSpreadsheetUploaded(file.getOriginalFilename())) {
return new ResponseEntity<>("Duplicate Spreadsheet. Please select a different file to upload",
HttpStatus.CONFLICT);
} else {
try {
saveUploadedFiles(Arrays.asList(file));
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded - " + file.getOriginalFilename(), new HttpHeaders(),
HttpStatus.OK);
}
}
UPDATE:
I've tried this approach from an old example I found, but it doesn't compile cleanly, the MockMvcRequestBuilders.multipart method is not defined....
#Test
public void testUploadSpreadsheet_Empty() throws Exception {
String fileName = "EmptySpreadsheet.xls";
String content = "";
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"emptyFile",
fileName,
"text/plain",
content.getBytes());
System.out.println("emptyFile content is '" + mockMultipartFile.toString() + "'.");
mockMvc.perform(MockMvcRequestBuilders.multipart("/bluecost/spreadsheet/upload")
.file("file", mockMultipartFile.getBytes())
.characterEncoding("UTF-8"))
.andExpect(status().isOk());
}
I believe MockMvcRequestBuilders.multipart() is only available since Spring 5. What you want is MockMvcRequestBuilders.fileUpload() that is available in Spring 4.

Start test body after jar file loading (from JAVA) is finished

I want to write UNIT test with SOAP webservices. Webservices work in other jar file, which I try to load Runtime.getRuntime().exec(// java - jar ...). Loading jar file takes 2 min. When loading is in new Thread the test ends before loading jar file will be finished. If loading is in main thread, test is not finished. I try to listen HTTP response with while cycle, but when cycle is working, the jar file is not loading.
#Before
public void setUp() throws Exception {
// Get path of jar file
thread = new Thread() {
public void run() {
try {
Process process = Runtime.getRuntime().exec(path-to-java.exe -jar webservices.jar);
process.waitFor();
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
int responseCode;
do {
responseCode = getResponseCodeHTTP("http://localhost:8080/services");
} while (responseCode < 200 || responseCode >= 400);
System.out.println("Web services have loaded");
}
public int getResponseCodeHTTP(String urlToRead) throws IOException {
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int result;
try {
conn.connect();
result = conn.getResponseCode();
} catch (ConnectException e){
return 500;
}
return result;
}
OK. I want to write test, which will start the webservices from jar file (loading process takes 1.5 min) and then execute test. To start web services I use Runtime.getRuntime().exec and to understand that them started I use HTTP response code. When the code [200-400) , it means the ws started OK.
I tried to debug code inside new Thread and added code with InputStreamReader and while cycle.
String line;
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
while ((line = reader.readLine()) != null)
System.out.println("[Stdout] " + line);
And test successfully executed. The when I removed the while cycle with readline, the problem had repeated.
I have not understand yet why it worked.

cannot access the file because it is using by another program Error

I have been fighting with this issue since last week.still not able to solve.
i am sending file to client machine once i get in server automatically.but so many time when i handle file it throw an error that Cannot access the file because it is using by another program.
below my code
private static string SaveFileStream(string filePath, Stream stream, string Filename1)
{
string localresponse;
try
{
//this.SaveFileStream(System.Configuration.ConfigurationSettings.AppSettings[fileToPush.FileType].ToString() + "\\" + fileToPush.FileName, new MemoryStream(fileToPush.Content));
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Dispose();
}
FileInfo info = new FileInfo(filePath);
ExtractFile(info);
localresponse = "Successful";
}
catch (Exception ex)
{
localresponse = ex.Message;
}
return localresponse;
}

Android 6 get path to downloaded file

I our app (Xamarin C#) we download files from a server. At the end of a succeful download we get the URI to the newly-downloaded file and from the URI we get the file path:
Android.Net.Uri uri = downloadManager.GetUriForDownloadedFile(entry.Value);
path = u.EncodedPath;
In Android 4.4.2 and in Android 5 the uri and path look like this:
uri="file:///storage/emulated/0/Download/2.zip"
path = u.EncodedPath ="/storage/emulated/0/Download/2.zip"
We then use path to process the file.
The problem is that in Android 6 (on a real Nexus phone) we get a completely different uri and path:
uri="content://downloads/my_downloads/2802"
path="/my_downloads/2802"
This breaks my code by throwing a FileNotFound exception. Note that the downloaded file exists and is in the Downloads folder.
How can I use the URI I get from Android 6 to get the proper file path so I can to the file and process it?
Thank you,
donescamillo#gmail.com
I didn't get your actual requirement but it looks like you want to process file content. If so it can be done by reading the file content by using file descriptor of downloaded file. Code snippet as
ParcelFileDescriptor parcelFd = null;
try {
parcelFd = mDownloadManager.openDownloadedFile(downloadId);
FileInputStream fileInputStream = new FileInputStream(parcelFd.getFileDescriptor());
} catch (FileNotFoundException e) {
Log.w(TAG, "Error in opening file: " + e.getMessage(), e);
} finally {
if(parcelFd != null) {
try {
parcelFd.close();
} catch (IOException e) {
}
}
}
But I am also looking to move or delete that file after processing.
May you an build your URI with the download folder :
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toURI();
It's work. #2016.6.24
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals( action)) {
DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = downloadManager.query(query);
if(c != null) {
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String downloadFileUrl = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
startInstall(context, Uri.parse(downloadFileUrl));
}
}
c.close();
}
}
}
private boolean startInstall(Context context, Uri uri) {
if(!new File( uri.getPath()).exists()) {
System.out.println( " local file has been deleted! ");
return false;
}
Intent intent = new Intent();
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction( Intent.ACTION_VIEW);
intent.setDataAndType( uri, "application/vnd.android.package-archive");
context.startActivity( intent);
return true;
}

Calling Console Application (.exe) in Event Receiver and Getting Error

I am using SharePoint foundation. I have a console application that is used to run some OCR process. I am calling the exe of the console application from windows service and it is working fine. I am trying to call the same exe from an event receiver but unable to call the exe and getting some error. The Event receiver is working fine but unable to call exe. I have tried to call the other exes like notepad.exe but getting same error. The details are below:
Code:
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
base.ItemAdded(properties);
Log("Event Occured.");
string OCRedText = string.Empty;
string Listname = properties.ListTitle;
string itemName = Convert.ToString(properties.ListItem["Name"]);
string itemTitle = Convert.ToString(properties.ListItem["Title"]);
callService(); // Here is the method to call Process
SPListItem item = properties.ListItem;
if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(100)))
{
if (Convert.ToString(item["OCRed"]) == "False")
{
item["OCRed"] = "True";
Thread.Sleep(10000);
item.SystemUpdate();
Log("Item Added and Updated.");
}
else
{
Log("Can not update the Item.");
}
}
Log("Event End."+"\r\n");
}
catch (Exception ex)
{
Log("Error in Item Added Event Receiver.");
Log(ex.ToString());
}
}
public void callService()
{
Log("Calling Service is not easy.");
try
{
ProcessStartInfo pinfoService = new ProcessStartInfo();
pinfoService.FileName = #"D:\Khan\khan.exe";
//pinfoService.FileName = #"C:\Windows\System32\notepad.exe";
pinfoService.UseShellExecute = false;
pinfoService.RedirectStandardError = true;
pinfoService.RedirectStandardInput = true;
pinfoService.RedirectStandardOutput = true;
pinfoService.CreateNoWindow = true;
pinfoService.WindowStyle = ProcessWindowStyle.Hidden;
Log("FileName: " + pinfoService.FileName);
Log("Arguments for callService : "+pinfoService.Arguments);
Process pService = new Process();
pService.StartInfo = pinfoService;
Log("Process Before Start.");
Thread.Sleep(5000);
pService.Start();
Thread.Sleep(2000);
Log("Process Before wait for exit.");
pService.WaitForExit();
Log("Process Completed.");
}
catch (Exception ex)
{
Log("Error in callService(). Please contact your Administrator.");
Log(ex.ToString());
}
}
and below is the error I am getting on pService.Start();
=========================================
Info : Process Before Start.
Info : Error in callService(). Please contact your Administrator.
Info : System.ComponentModel.Win32Exception: Not enough quota is available to process this command
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at OCRonUploadDoc.EventReceiver1.EventReceiver1.callService()
=========================================
I am unable to figure out the issue. Please help me...!!!
Thanks in Advance.
Khan Abubakar
I think that the asp.net account under which the application pool runs does not have permissions to start the exe file. You can check this out http://www.daniweb.com/web-development/aspnet/threads/386380/cannot-run-exe-files-in-asp.net-application
However if your system will be used by more users you can run into problems really quickly, because every change of a document will spawn a new process. The server will run out of ram and the farm will not be unavailable.

Resources