I am trying to write in C# what this powershell script does ( See image ).
Went halfway but not much luck ( I use these namespaces
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer;
using Microsoft.SqlServer.Management.IntegrationServices;
)
I managed to get my code to work upto the point
SqlConnection ssisConnection = new SqlConnection(#"Data
Source=MHPDW2;Initial Catalog=master;Integrated Security=SSPI;");
IntegrationServices ssisServer = new IntegrationServices(ssisConnection);
foreach ?? ( you continue )
But no luck after that how to iterate through each folder. BTW the powershell script works fine with no issues.
Help! Click link below for powershell script code picture
powerscript code
$sqlConnectionString = "Data Source=MHPAPP2;Initial Catalog=master;Integrated Security=SSPI;"
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString
# Create the Integration Services object
$integrationServices = New-Object $ISNamespace".IntegrationServices" $sqlConnection
if ($integrationServices.Catalogs.Count -gt 0)
{
$catalog = $integrationServices.Catalogs["SSISDB"]
write-host "Enumerating all folders..."
$folders = $catalog.Folders
if ($folders.Count -gt 0)
{
foreach ($folder in $folders)
{
$foldername = $folder.Name
Write-Host "Exporting Folder " $foldername " ..."
# Create a new file folder
mkdir $ProjectFilePath"\"$foldername
# Export all projects
$projects = $folder.Projects
if ($projects.Count -gt 0)
{
foreach($project in $projects)
{
$fullpath = $ProjectFilePath + "\" + $foldername + "\" + $project.Name + ".ispac"
Write-Host "Exporting to " $fullpath " ..."
[System.IO.File]::WriteAllBytes($fullpath, $project.GetProjectBytes())
}
}
}
}
}
Write-Host "All done."
Related
Im trying to implement a local database (sqlite) in an Android/PC game
I am able to load the database from the editor and the standalone pc build of the games but the android version has an error that does not find the tables im trying to query from
This is the code that loads the database into three lists from the streaming assets folders
using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using Mono.Data.Sqlite;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DBAdministrator : MonoBehaviour {
//
//Android sdk > platform-tools > adb logcat MarsGames.ChippyRemix *:E
public List<LevelDP> levelsList;
public List<LevelDP> defaultLevels;
public List<LevelDP> myLevels;
public List<LevelDP> otherLevels;
GameObject playMenu;
public string myName;
public string defaultName = "chippy";
public string debugString;
void Start () {
//myName = PlayerPrefs.GetString("MyName");
playMenu = GameObject.FindWithTag("UI");
//levelsList = new List<LevelDP>();
defaultLevels = new List<LevelDP>();
myLevels = new List<LevelDP>();
otherLevels = new List<LevelDP>();
//Fill the list
FillLists();
//PrintAllLevels();
if(playMenu != null){
playMenu.SendMessage("CreateDisplayLists");
}
}
void FillLists(){
//Path to database
string conn = "";
//Debug.Log(Application.streamingAssetsPath);
#if UNITY_EDITOR_WIN
//Debug.Log("Using unity editor conn");
conn = "URI=file:" + Application.dataPath + "/StreamingAssets/chickdb.db";
#elif UNITY_ANDROID
debugString = "Using andriod";
conn = Application.persistentDataPath + "/chickdb.db";
if(!File.Exists(conn)){
debugString = "DB file does not exist";
//Open Streaming assets and load the db
WWW loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/chickdb.db");
while (!loadDb.isDone) { }
File.WriteAllBytes(conn,loadDb.bytes);
}else{
debugString = "File exists";
//debugString = conn;
}
//Once file is loaded, use the appropiate filepath to access db
conn = "URI=file:" + Application.persistentDataPath + "/chickdb.db";
#elif UNITY_STANDALONE
//debugString = "Using standalone PC";
//string conn = "URI=file:" + System.IO.Path.Combine(Application.streamingAssetsPath, "Database/TMDB.s3db");
//conn = "URI=File:" + System.IO.Path.Combine(Application.streamingAssetsPath,"/StreamingAssets/chickdb.db");
conn = "URI=file:" + Application.streamingAssetsPath + "/chickdb.db";
debugString = conn;
/*
#elif UNITY_IOS
debugString = "Using ios";
// this is the path to your StreamingAssets in iOS
var loadDb = Application.dataPath + "/Raw/chickdb.do";
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
//conn = "URI=file " + Application.persistentDataPath + "/chickdb.db";
*/
#endif
//Debug.Log("ST Connection DB: " + conn);
#if UNITY_ANDROID
debugString = "Connection Attempted";
#endif
IDbConnection dbconn = (IDbConnection) new SqliteConnection(conn);
//Open connection to the database.
dbconn.Open();
#if UNITY_ANDROID
debugString = "Database Open";
#endif
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT * FROM levels";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
#if UNITY_ANDROID
debugString = "Query executed";
#endif
while (reader.Read()){
LevelDP lp = new LevelDP();
lp.SetLevelID(reader.GetInt32(0));
lp.SetLevelName(reader.GetString(1));
lp.SetCreationDate(reader.GetString(2));
lp.SetUserID(reader.GetString(3));
lp.SetBlocks(reader.GetString(4));
lp.SetCompleted(reader.GetInt32(5));
//levelsList.Add(lp);
if(lp.GetUserID().Equals(defaultName)){
defaultLevels.Add(lp);
}else if(lp.GetUserID().Equals(myName)){
myLevels.Add(lp);
}else{
otherLevels.Add(lp);
}
}
//Close the db reader
reader.Close();
reader = null;
//Close the comand executer
dbcmd.Dispose();
dbcmd = null;
//Close the db connection
dbconn.Close();
dbconn = null;
}
void PrintAllLevels(){
Debug.Log("Print all levels");
for(int i = 0; i < defaultLevels.Count; i++){
Debug.Log(defaultLevels[i].ToString());
}
for(int i = 0; i < myLevels.Count; i++){
Debug.Log(myLevels[i].ToString());
}
for(int i = 0; i < otherLevels.Count; i++){
Debug.Log(otherLevels[i].ToString());
}
}
}
From this code i've been able to print ("Database Open") but when the database is supposed to query i get an error (from the adb tool) that states ("Table levels not found") and i dont know where the error is
I do have to add the editor, and pc build work just fine,
Steps i've followed are:
Place the .db file in the Streaming Assets folder Unpack the .apk and check the values present in the .db file via sqlitebrowser
i have a theory that maybe im not loading the db correctly into memory in the #if UNITY_ANDROID conditional statement but almost every other example ive seen works this way
I can't comment, that's why Im writing an answer.
Try to use Debug.Log to see the pathfile when you are testing the game/app.
And then checking if your sq3db file is in the correct folder.
I Have a similar code for streaming the sqlite DB but if I test it on PC the DB should be in Assets folder not in StreamingAssets folder.
Edit 1:
First:
I'll show you a fragment of the code I use when I make games:
if(Application.platform != RuntimePlatform.Android)
_filepath = Application.dataPath + "/" + _DBName;
else
{
_filepath = Application.persistentDataPath + "/" + _DBName;
if (!File.Exists(_filepath))
{
//Debug.Log("Check in");
WWW loadDB = new WWW("jar:file://" + Application.dataPath +
"!/assets/" + _DBName);
while (!loadDB.isDone) { }
File.WriteAllBytes(_filepath, loadDB.bytes);
}
}
_StringConnection = "URI=file:" + _filepath;
Second:
When I test the game on pc (unity editor) I have my Database (.s3db) here:
ProjectName/Assets/Database.s3db
When I run the game on android I have my Database here:
ProjectName/Assets/StreamingAssets/Database.s3db
Something you may notice is that my Database file extension is s3db, I use SQlite3, but it should work anyway.
In Android sqlite db should save in persistent data path. I put my sqlite db in resources with .txt extension and read it as text. then chagne the extension in code and save it in Application.persistentDataPath.
Can someone tell me if there is a way to get each characters location in X,Y coordinates from a PDF.
i appreciate that it may not be XY i just need a way to identify where a text character is on a page.
the characters are not raster, so i don't need to recognise them.
i have started with this.
$Path = "C:\temp\test.pdf"
$reader = New-Object iTextSharp.text.pdf.pdfreader -ArgumentList $Path
for ($page = 1; $page -le $reader.NumberOfPages; $page++)
{
$text = [iTextSharp.text.pdf.parser.PdfTextExtractor]::GetTextFromPage($reader,$page).Split([char]0x000A)
}
$reader.Close()
I'm not familiar at all with PowerShell, but you can do it like this in C#. FYI you will either need iTextSharp 5.5.10 or iText 7.0.1 for .NET to get this to run.
void Run()
{
PdfReader reader = new PdfReader("/path/to/input.pdf");
var s = PdfTextExtractor.GetTextFromPage(reader, 1, new LocationTextExtractionStrategy(new Local()));
}
private class Local : LocationTextExtractionStrategy.ITextChunkLocationStrategy
{
public LocationTextExtractionStrategy.ITextChunkLocation CreateLocation(TextRenderInfo renderInfo, LineSegment baseline)
{
// you need the info per character, so iterate all characters per TextRenderInfo
foreach (TextRenderInfo tr in renderInfo.GetCharacterRenderInfos())
{
LineSegment bl = tr.GetBaseline();
// do something with the info
Console.WriteLine(tr.GetText() + " # (" + bl.GetStartPoint()[Vector.I1] + ", " + bl.GetStartPoint()[Vector.I2] + ")");
}
return new LocationTextExtractionStrategy.TextChunkLocationDefaultImp(baseline.GetStartPoint(), baseline.GetEndPoint(), renderInfo.GetSingleSpaceWidth());
}
}
Based on blagae answer, here is a powershell script that will basically run his C# code. I didn't find an easy way to use LocationTextExtractionStrategy directly in powershell. You will need iTextSharp 5.5.10 as it is the first public version to expose LocationTextExtractionStrategy.
$Source = #"
using System;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
public class PdfHelper
{
public static void Run(string filePath)
{
PdfReader reader = new PdfReader(filePath);
for(var page = 1; page <= reader.NumberOfPages; page++)
{
PdfTextExtractor.GetTextFromPage(reader, page, new LocationTextExtractionStrategy(new Local()));
}
}
}
class Local : LocationTextExtractionStrategy.ITextChunkLocationStrategy
{
public LocationTextExtractionStrategy.ITextChunkLocation CreateLocation(TextRenderInfo renderInfo, LineSegment baseline)
{
// you need the info per character, so iterate all characters per TextRenderInfo
foreach (TextRenderInfo tr in renderInfo.GetCharacterRenderInfos())
{
LineSegment bl = tr.GetBaseline();
// do something with the info
Console.WriteLine(tr.GetText() + " # (" + bl.GetStartPoint()[Vector.I1] + ", " + bl.GetStartPoint()[Vector.I2] + ")");
}
return new LocationTextExtractionStrategy.TextChunkLocationDefaultImp(baseline.GetStartPoint(), baseline.GetEndPoint(), renderInfo.GetSingleSpaceWidth());
}
}
"#
$DLLPath = "$PSScriptRoot\iTextSharp.dll"
Add-Type -Path $DLLPath
Add-Type -ReferencedAssemblies $DLLPath -TypeDefinition $Source -Language CSharp
$Path = "C:\temp\test.pdf"
[PdfHelper]::Run($Path)
I am trying to use ASP.NET to return the total startup RAM on a VM on a Hyper-V server. The function I have is this:
public static double GetRamVM(string vm, string host)
{
string cmdToRun = "get-vmmemory -name " + vm + " -computername " + host + " | select Startup" ;
var shell = PowerShell.Create();
shell.Commands.AddScript(cmdToRun);
var mem = shell.Invoke();
foreach (PSObject obj in mem)
{
var startMem = obj.Members["Startup"].Value;
return (double)startMem;
}
return 9999.9999;
}
However, whenever I return it - it ALWAYS returns as 9999.9999. I know that the command works, as when I run it manually in a powershell window I get the result that I want.
Please help - as I am going out of my mind.
Edit:
The manual run of the script looks like this
PS C:\Users\mark> Get-VMMemory -vmname "test test" -computername "testhost" | select Startup
Startup
-------
536870912
You could try using the -ExpandProperty on the PowerShell Select cmdlet. This will return a number for the account of memory being used and not an PS-object, so you wont have to extract the value in your C code.
public static double GetRamVM(string vm, string host)
{
string cmdToRun = "get-vmmemory -name " + vm + " -computername " + host + " | select -ExpandProperty Startup" ;
var shell = PowerShell.Create();
shell.Commands.AddScript(cmdToRun);
var mem = shell.Invoke();
return (double)mem;
}
I would like to connect DotCMIS.dll to my SharePoint but does not work correct.
I open the script in the SharePoint 2013 Management Shell.
I use my user permissions (This is not a Farm user)
Probably here's the problem with giving the correct link. org.apache.chemistry.dotcmis.binding.atompub.url=?
Have you got any idea where link in sharepoint have to go?
Website of example:
http://chemistry.apache.org/dotnet/powershell-example.html
Error
You cannot call a method on a null-valued expression.
At line:6 char:7
+ $b = $contentStream.Stream.Read($buffer, 0, 4096)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Important part of my Script
$sp["org.apache.chemistry.dotcmis.binding.atompub.url"] = "http://localhost/_layouts/15/start.aspx#/SitePages/WebSite.aspx"
$sp["org.apache.chemistry.dotcmis.user"] = "mylogin"
$sp["org.apache.chemistry.dotcmis.password"] = "mypassword"
All Script
# load DotCMIS DLL
[Reflection.Assembly]::LoadFile("C:\dotCmisServer\DotCMIS.dll")
# -----------------------------------------------------------------
# helper functions
function New-GenericDictionary([type] $keyType, [type] $valueType) {
$base = [System.Collections.Generic.Dictionary``2]
$ct = $base.MakeGenericType(($keyType, $valueType))
New-Object $ct
}
function New-ContentStream([string] $file, [string] $mimetype) {
$fileinfo = ([System.IO.FileInfo]$file)
$contentStream = New-Object "DotCMIS.Data.Impl.ContentStream"
$contentStream.Filename = $fileinfo.Name
$contentStream.Length = $fileinfo.Length
$contentStream.MimeType = $mimetype
$contentStream.Stream = $fileinfo.OpenRead()
$contentStream
}
function Download-ContentStream([DotCMIS.Client.IDocument] $document, [string] $file) {
$contentStream = $document.GetContentStream()
$fileStream = [System.IO.File]::OpenWrite($file)
$buffer = New-Object byte[] 4096
do {
$b = $contentStream.Stream.Read($buffer, 0, 4096)
$fileStream.Write($buffer, 0, $b)
}
while ($b -ne 0)
$fileStream.Close()
$contentStream.Stream.Close()
}
# -----------------------------------------------------------------
# create session
$sp = New-GenericDictionary string string
$sp["org.apache.chemistry.dotcmis.binding.spi.type"] = "atompub"
$sp["org.apache.chemistry.dotcmis.binding.atompub.url"] = "http://localhost/_layouts/15/start.aspx#/SitePages/WebSite.aspx"
$sp["org.apache.chemistry.dotcmis.user"] = "mylogin"
$sp["org.apache.chemistry.dotcmis.password"] = "mypassword"
$factory = [DotCMIS.Client.Impl.SessionFactory]::NewInstance()
$session = $factory.GetRepositories($sp)[0].CreateSession()
# print the repository infos
$session.RepositoryInfo.Id
$session.RepositoryInfo.Name
$session.RepositoryInfo.Vendor
$session.RepositoryInfo.ProductName
$session.RepositoryInfo.ProductVersion
# get root folder
$root = $session.GetRootFolder()
# print root folder children
$children = $root.GetChildren()
foreach ($object in $children) {
$object.Name + " (" + $object.ObjectType.Id + ")"
}
# run a quick query
$queryresult = $session.Query("SELECT * FROM cmis:document", $false)
foreach ($object in $queryresult) {
foreach ($item in $object.Properties) {
$item.QueryName + ": " + $item.FirstValue
}
"----------------------------------"
}
# create a folder
$folderProperties = New-GenericDictionary string object
$folderProperties["cmis:name"] = "myNewFolder"
$folderProperties["cmis:objectTypeId"] = "cmis:folder"
$folder = $root.CreateFolder($folderProperties)
# create a document
$documentProperties = New-GenericDictionary string object
$documentProperties["cmis:name"] = "myNewDocument"
$documentProperties["cmis:objectTypeId"] = "cmis:document"
$source = $home + "\source.txt"
$mimetype = "text/plain"
$contentStream = New-ContentStream $source $mimetype
$doc = $folder.CreateDocument($documentProperties, $contentStream, $null)
# download a document
$target = $home + "\target.txt"
Download-ContentStream $doc $target
# clean up
$doc.Delete($true)
$folder.Delete($true)
Unfortunately in SharePoint Foundation 2013 I have to write own C# software.
SharePoint Foundation 2013 IMPORT\EXPORT dbo.allDocs file\files
string cmd = " $srv = new-object Microsoft.SqlServer.Management.Smo.Server('" + svr + "')" + Environment.NewLine;
cmd += " $srv.Logins | where-object {$_.Name -eq 'DOMAIN\server55' } | select-object 'State'" + Environment.NewLine;
That code is added between the PSSnapin & PSSession code then invoked:
util>string prep = "$hasSnapin = get-pssnapin | Select { $_.Name.toLower().Trim() = 'sqlservercmdletsnapin100' }" + Environment.NewLine;
util>prep += "if ($hasSnapin -eq $null) { Add-Pssnapin SqlServerCmdletSnapin100 }" + Environment.NewLine;
util>cmd = prep;
util>cmd = "$pssessSql = New-PSSession -ComputerName " + svr + Environment.NewLine;
util>cmd += " Invoke-Command -session $pssessSql -ScriptBlock {" + Environment.NewLine;
util>cmd += " " + " sqlps -nologo -noprofile -command {" + Environment.NewLine;
util>cmd += " " + command + " }" + Environment.NewLine;
util>cmd += " }" + Environment.NewLine;
util>cmd += " Remove-PSSession -Session $pssessSql" + Environment.NewLine;
util>cmd += " exit";
util>try {
util>IList<System.Management.Automation.PSObject> results = pipeline.Invoke();
util>runspace.Close();
util>return results;
util>}
If I capture the script going to the Invoke it works by replacing "\r\n" with a newline, why wouldn't it work in C#, I have a other scripts working from the C# so may be missing something obvious, here's the captured code that runs from a ps prompt:
$hasSnapin = get-pssnapin | Select { $_.Name.toLower().Trim() = 'sqlservercmdletsnapin100' }
if ($hasSnapin -eq $null) { Add-Pssnapin SqlServerCmdletSnapin100 }
$pssessSql = New-PSSession -ComputerName Server54
Invoke-Command -session $pssessSql -ScriptBlock {
sqlps -nologo -noprofile -command {
$srv = new-object Microsoft.SqlServer.Management.Smo.Server('Server54')
$srv.Logins | where-object {$_.Name -like 'DOMAIN\Server55$' } | select-object 'State' }
}
Remove-PSSession -Session $pssessSql
exit
Thanks for any clues, I've had trouble with nested quotes but able to get most of those so this is I think from the \r\n's in the code but not sure how to find that out, I can't get the results to return from the app but the whole script does fine via a ps prompt.
Could the problem be the loading of the snapin on the remote end?
You have:
cmd = prep;
cmd = "$pssessSql ...";
which means that the prep code is completely ignored/overwritten by the second assignment.
One alternative is is to unconditionally add the snapin, specifying that you want errors to be ignored.
Add-Pssnapin -ErrorAction SilentlyContinue SqlServerCmdletSnapin100
Found it, the code is fine but I was using formatting, when I commented that out I was able to get my results. Before that it was returning formatting objects but I couldn't get values from them ... glad I tried without:
query += "\r\n" + "$data = $cmdCheckLogin.ExecuteReader()";
query += "\r\n" + "$dt = new-object System.Data.DataTable";
query += "\r\n" + "$dt.Load($data)";
query += "\r\n" + "$dt"; // | format-table -hidetableheaders";
query += "\r\n" + "$conn.Close()";