How do I set a dynamic datasource for ORM? - orm

ORM settings in Coldfusion application.cfc run before anything else runs (onapplicationstart, etc). So how do you set a dynamic datasource (code before the ORM init) in application.cfc? we can set it after and it re-points the ORM to a dynamic datasource, but that requires that the hardcoded datasource must be valid as well. This is tenuous at best.
Here is an example:
<cfscript>
this.name = "someapp_#hash(cgi.http_host)#";
this.ormenabled = "true";
this.ormsettings = { cfclocation = "config/definitions", eventhandling = "true",datasource="STATICDATASOURCE" };
</cfscript>
If it's not specified in application.cfc scope then you get errors like "ORM is not configured for the current application."
We need to be able to get the datasource from a text file on the server.

this.datasource="YourDatasourceName";
Well, if you wanted to store a file, for this example we'll call it "datasource.xml" consisting of:
<dataSourceName>Name goes here</dataSourceName>
You can read it in with:
dataFile = fileRead("pathToFile/datasource.xml");
data = xmlParse(dataFile);
dataSourceName = data.dataSourceName.xmlText;
this.datasource=dataSourceName;

ORM datasource just uses the default datasource if not defined.
Having said that, if you want to add / remove datasource dynamically, see Administrator API at: http://help.adobe.com/en_US/ColdFusion/9.0/Admin/WSc3ff6d0ea77859461172e0811cbf364104-7fcf.html (available since CF8)
I'm not sure if you can re-set the this.ormsettings.datasource to something else at runtime (i.e. onApplicationStart()? or onServerStart()?), but many of the settings can be set again. You may want to try it out.

Related

Change AR session config after fragment created

I want to re-configure AR session after session has been running. I want to change Augmented Images database.
I don't seem to find a way to set the reset the session configuration.
getSessionConfiguration(Session session)
This function only seems to be called once at the beginning.
Is there a way to re-configure? Should I not be using the fragment?
I make changes to my config on the fly. You can accomplish this by extending ARFragment and having access to the config or simply be accessing the ARFragment from your xml within your activity. Here is an example.
arSceneView.session?.apply {
val changedConfig = config
changedConfig.planeFindingMode = Config.PlaneFindingMode.HORIZONTAL_AND_VERTICAL
configure(changedConfig)
}
That's it, just call configure(myNewConfig) and it will update it for you.
Of course in this example, I get the current config, modify it and put it back, but you could replace it if preferred.

How to access files stored in SQL Server's FileTable?

As I know SQL Server since version 2012 has a new feature, FileTable. It allows us to store files in the file system and to use them from T-SQL.
I am trying to use this feature and I have no idea how to do it properly.
Generally, I don't know how to access files stored in the file table. Let's suppose I have asp.net MVC app and there are a lot of images which I show on web pages in img tags. I would like to store these images in Filetable and access them as files from the filesystem. But I don't know where these files are stored and how to use them as files. Now my images are stored in web application directory in folder images and I write something like this:
<img src='/images/mypicture.png' />
And if I move my images to file table what I should write in src?
<img src='path-toimage-in-filetable' />
I don't think you still need this, anyways I'll post my answer for anyone else interested.
First, a filetable still being a table, so, if you want to access to data from it you need to use a Select SQL statement. So you'd need something like:
select name, file_stream from filetable_name
where
name = 'file_name',
file_type = 'file_extension'
just execute an statement like this in your asp.net app, then fetch the results and use the file_stream column to get the binary data of the stored file. If you want to retrieve the file from HTML, first you need to create an action in your controller, which will return the retrieved file:
public ActionResult GetFile(){
..
return File(file.file_stream,file.file_type);
}
After this, put in you HTML tag something like:
<img src="/controller/GetFile" />
hope this could help!
If you want to know the schema of a filetable see
here
I assume by FileTable you actually mean FileStream. A couple notes about that:
This feature is best used if your files are actually files
The files should be, on average, greater than 1mb - although there can be exceptions to this rule, if they're smaller than 1mb on average, you may be better off using a VARBINARY(MAX) or XML data type as appropriate. If your images are very small on average (only a few KB), consider using a VARBINARY(MAX) column.
Accessing these files will require an open transaction and that the database is properly configured for FILESTREAM
You can get some significant advantages bypassing the normal SQL engine/database file method of data access by telling SQL Server that you want to access the file directly, however it's not meant for directly accessing the file on the file system and attempting to do so can break SQL's management of these files (transactional consistency, tracking, locking, etc.).
It's pretty likely that your use case here would be better served by using a CDN and storing image URLs in the table if you really need SQL for this. You can use FILESTREAM to do this (see code sample below for one implementation), but you'll be hammering your SQL server for every request unless you store the images somewhere else anyway that the browser can properly cache (my example doesn't do that) - and if you store them somewhere else for rendering int he browser you might as well store them there to begin with (you won't have transactional consistency for those images once they're copied to some other drive/disk/location anyway).
With all that said, here's an example of how you'd access the FILESTREAM data using ADO.NET:
public static string connectionString = ...; // get your connection string from encrypted config
// assumes your FILESTREAM data column is called Img in a table called ImageTable
const string sql = #"
SELECT
Img.PathName(),
GET_FILESTREAM_TRANSACTION_CONTEXT()
FROM ImageTagble
WHERE ImageId = #id";
public string RetreiveImage(int id)
{
string serverPath;
byte[] txnToken;
string base64ImageData = null;
using (var ts = new TransactionScope())
{
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
serverPath = rdr.GetSqlString(0).Value;
txnToken = rdr.GetSqlBinary(1).Value;
}
}
using (var sfs = new SqlFileStream(serverPath, txnToken, FileAccess.Read))
{
// sfs will now work basically like a FileStream. You can either copy it locally or return it as a base64 encoded string
using (var ms = new MemoryStream())
{
sfs.CopyTo(ms);
base64ImageData = Convert.ToBase64String(ms.ToArray());
}
}
}
ts.Complete();
// assume this is PNG image data, replace PNG with JPG etc. as appropraite. Might store in table if it will vary...
return "data:img/png;base64," + base64ImageData;
}
}
Obviously, if you have lots of images to handle like this this is not an ideal method - don't try to make an instance of SQL server into what you should be using a CDN for.... However, if you have other really good reasons, you should try to grab as many images as possible in a single request/transaction (e.g. if you know you're displaying 50 images on a page, get all 50 with a single transaction scope, don't use 50 transaction scopes - this code won't handle that).

Fetching Publishing Pages from Pages Library in SharePoint 2010 ECMAScript OM

i want to fetch all the pages in a specific Publishing Web using JavaScript and Client Object Model, it keeps giving
The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Here's the code,
var selectedDoc;
var ctx = new SP.ClientContext.get_current();
var site = ctx.get_site();
//('created ctx');
//loading the Library
var pagesLib = site.openWeb('/Ar/News').get_lists().getByTitle('Pages');
if (missionType == 'All') {
var query = new SP.CamlQuery();
query.set_viewXml("<View><RowLimit>10</RowLimit></View>");
selectedDoc = pagesLib.getItems(query);
ctx.load(selectedDoc,'Include(Title)');
ctx.executeQueryAsync(getAllNewsWithQuerySuccess(this,this.onListLoadSuccess), getAllNewsWithQueryFailure(this,this.onQueryFailed));
You might be missing a load call. Try this right after you assign pagesLib:
ctx.load(pagesLib);
I'm guessing the error is due to pagesLib not having been populated before you execute the CAML query against it.
You might be missing a load call. Try this right after you assign pagesLib:
ctx.load(pagesLib);
I'm guessing the error is due to pagesLib not having been populated before you execute the CAML query against it.

Applying SSIS Package Configuration to multiple packages

I have about 85 SSIS packages that are using the same connection manager.
I understand that each package has its own connection manager.
I am trying to decide what would be the best configurations approach to simply set the connectionstring of the connection manager based on the server the packages are residing on.
I have visited all kinds of suggestions online, but cannot find anywhere the practice where I can simply copy the configuration from one package to the rest of the packages.
There are obviously many approaches such as XML file, SQL Server, Environment Variable, etc.
All the articles out there are pointing to use an Indirect method by using XML or SQL approach. Why would using an environment variable for just holding a connection string is such a bad approach?
Any suggestions are highly appreciated.
Thanks!
Why would using an environment variable for just holding a connection string is such a bad approach?
I find the environment variable or registry key configuration approach to be severely limited by the fact that it can only configure one item at a time. For a connection string, you'd need to define an environment variable for each catalog on a given server. Maybe it's only 2 or 3 and that's manageable. We had a good 30+ per database instance and we had multi-instanced machines so you can see how quickly this problem explodes into a maintenance nightmare. Contrast that with a table or xml based approach which can hold multiple configuration items for a given configuration key.
...best configurations approach to simply set the connectionstring of the connection manager based on the server the packages are residing on.
If you go this route, I'd propose creating a variable, ConnectionString and using it to configure the property. It's an extra step but again I find it's easier to debug a complex expression on a variable versus a complex expression on a property. With a variable, you can always pop a breakpoint on the package and look at the locals window to see the current value.
After creating a variable named ConnectionString, I right click on it, select Properties and set EvaluateAsExpression equal to True and the Expression property to something like "Data Source="+ #[System::MachineName] +"\\DEV2012;Initial Catalog=FOO;Provider=SQLNCLI11.1;Integrated Security=SSPI;"
When that is evaluated, it'd fill in the current machine's name (DEVSQLA) and I'd have a valid OLE DB connection string that connects to a named instance DEV2012.
Data Source=DEVSQLA\DEV2012;Initial Catalog=FOO;Provider=SQLNCLI11.1;Integrated Security=SSPI;
If you have more complex configuration needs than just the one variable, then I could see you using this to configure a connection manager to a sql table that holds the full repository of all the configuration keys and values.
...cannot find anywhere the practice where I can simply copy the configuration from one package to the rest of the packages
I'd go about modifying all 80something packages through a programmatic route. We received a passel of packages from a third party and they had not followed our procedures for configuration and logging. The code wasn't terribly hard and if you describe exactly the types of changes you'd make to solve your need, I'd be happy to toss some code onto this answer. It could be as simple as the following. After calling the function, it will modify a package by adding a sql server configuration on the SSISDB ole connection manager to a table called dbo.sysdtsconfig for a filter named Default.2008.Sales.
string currentPackage = #"C:\Src\Package1.dtsx"
public static void CleanUpPackages(string currentPackage)
{
p = new Package();
p.app.LoadPackage(currentPackage, null);
Configuration c = null;
// Apply configuration Default.2008.Sales
// ConfigurationString => "SSISDB";"[dbo].[sysdtsconfig]";"Default.2008.Sales"
// Name => MyConfiguration
c = p.Configurations.Add();
c.Name = "SalesConfiguration";
c.ConfigurationType = DTSConfigurationType.SqlServer;
c.ConfigurationString = #"""SSISDB"";""[dbo].[sysdtsconfig]"";""Default.2008.Sales""";
app.SaveToXml(sourcePackage, p, null);
}
Adding a variable in to the packages would not take much more code. Inside the cleanup proc, add code like this to add a new variable into your package that has an expression like the above.
string variableName = string.Empty;
bool readOnly = false;
string nameSpace = "User";
string variableValue = string.Empty;
string literalExpression = string.Empty;
variableName = "ConnectionString";
literalExpression = #"""Data Source=""+ #[System::MachineName] +""\\DEV2012;Initial Catalog=FOO;Provider=SQLNCLI11.1;Integrated Security=SSPI;""";
p.Variables.Add(variableName, readOnly, nameSpace, variableValue);
p.Variables[variableName].EvaluateAsExpression = true;
p.Variables[variableName].Expression = literalExpression;
Let me know if I missed anything or you'd like clarification on any points.

Using System.Reflection and resources in Phalanger

I need to embed some resource in a pure compiled dll written in php using phalanger.
These are txt files tha I set in visual studio as "Embedded Resource".
My problem is that I cannot use the Assembly class to get the resource using GetManifestResourceStream.
I tried code like this:
use System\Reflection\Assembly
$asm = Assembly::GetExecutingAssembly(); //this gives me mscorlib instead of my dll
$str = $asm->GetManifestResourceStream("name");
My question is: how do I get access to embedded resources in phalanger?
Many thanks
I'm not sure, why Assembly::GetExecutingAssembly() returns an incorrect value. Anyway to workaround the $asm value, use following code:
$MyType = CLRTypeOf MyProgram;
$asm = $MyType->Assembly;
Then you can access embedded resources as you posted
$asm->GetManifestResourceStream("TextFile1.txt");
or you can include standard resource file (.resx) into your project, and use \System\Resources\ResourceManager
$this->manager = new \System\Resources\ResourceManager("",$asm);
$this->manager->GetObject("String1",null);
Just note, currently there can be just one .resx within Phalanger project
This question is old, but the part of the Phalanger code (Php.Core.Emit.AddResourceFile() method) responsible for this hasn't changed since this was asked. I faced the same problem and solved it in (almost) non-hacky way. You have to provide alternative name (/res:/path/to/filename,alternative-name) for this to work though.
$asm = clr_typeof('self')->Assembly;
$resourceStream = $asm->GetManifestResourceStream("filename");
$reader = new \System\Resources\ResourceReader($resourceStream);
$type = $data = null;
$reader->GetResourceData("alternative-name", $type, $data);
// and still there are 4 excess bytes
// representing the length of the resource
$data = \substr($data, 4);
$stream = new IO\MemoryStream($data);
// after this $stream is usable as you would expect
Straightforward GetManifestResourceStream() (as suggested by Jakub) does not work because Phalanger does not use System.Reflection.Emit.ModuleBuilder.DefineManifestResource() (like I think it should when supplied with unrecognized file format). It uses ModuleBuilder.DefineResource() which returns ResourceWriter instead, that only really suited for .resources files. And this is what dictates the requirement to use ResourceReader when you need to read your resource.
Note: This answer applies to Phalanger master branch at the time of writing and prior versions since circa 2011. Noted because it looks like a bug (especially the need to use both original and alternative names).