I am attempting to define a variable conn in my controller.js.
With the code at the bottom, I get lots of horrible UI glitches, so I'm presuming the code below is wrong. If I try:
var conn;
conn.name = 'Fred';
I get what looks like a NullPointer Error "Cannot set property 'name' of undefined" when I attempt to set conn.name.
How do I define my variable?
var addDBConnControllerBase = app.controller('addDBConnControllerBase',
function($scope,$http,serviceFactory,$modal,$location,$log)
{
$scope.saveDBConn = function()
{
var conn = {
name,
driverType,
connectionString,
userID,
password
};
conn.name = $scope.addDBConnController.displayName;
conn.driverType = $scope.addDBConnController.driverType;
conn.connectionString = $scope.addDBConnController.connectionString;
conn.userID = $scope.addDBConnController.userID;
conn.password = $scope.addDBConnController.password;
$log.debug('Saving db conn');
$log.debug(JSON.stringify(conn));
}
});
var newAttrs = {};
newAttrs[nameOfProp] = valueOfProp;
try this!!!
In your case I think this would be
var conn = {};
conn["name"] = 'Fred';
You need to brush up on your javascript pronto! This:
var conn;
is a variable declaration, not definition. conn is still undefined after this statement so you can't go conn.name = .... You have to initialize things before you use them:
var conn = {};
conn.name = ...
or
var conn = {
name: ...
};
You should define variable conn as an array first. Like following.
var conn = [];
conn.name=$scope.addDBConnController.displayName;
Related
I converted the IdPInitiatedController example code for my WebForms project. Although I don't get compiler or runtime error, I still cannot seem to get the manually created claims added to the Saml2AuthnResponse object after setting the claims identity. Is there another way to add attributes to the SAML response? The app uses forms authentication; and the credentials are in a SQL database. That's why I don't have Windows Identity.
' SSO CODE BEHIND
...
Dim binding = New Saml2PostBinding With {
.RelayState = String.Format("RPID={0}", Uri.EscapeDataString(serviceProviderRealm))
}
Dim config = New Saml2Configuration With {
.Issuer = "company.stage.app",
.SingleSignOnDestination = New Uri(ConfigurationManager.AppSettings.Get("appValue")),
.SigningCertificate = CertificateUtil.Load(X509Certificates.StoreName.TrustedPeople, X509Certificates.StoreLocation.LocalMachine, X509Certificates.X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get("ThatKey")),
.SignatureAlgorithm = Saml2SecurityAlgorithms.RsaSha256Signature
}
Dim samlResponse = New Saml2AuthnResponse(config) With {
.Status = Saml2StatusCodes.Success
}
_ssoService.AddAttributes(samlResponse, currentUser)
binding.Bind(samlResponse) ' NO ATTRIBUTES WERE ADDED
Me.SAMLResponse.Value = binding.XmlDocument.InnerXml
Me.RelayState.Value = binding.RelayState
frmSSO.Action = config.SingleSignOnDestination.AbsoluteUri()
frmSSO.Method = "POST"
Public Sub AddAttributes(ByRef samlResponse As Saml2AuthnResponse, ByVal currentUser As CurrentUser)
Dim acctContact As CoveredInsuredDto = _coveragesService.GetAccountPointOfContact(currentUser.getControlNo())
If Not IsNothing(acctContact) Then
' Adding Attributes as claims
Dim claimIdentity = New ClaimsIdentity(Me.BuildClaims(currentUser, acctContact))
samlResponse.NameId = New IdentityModel.Tokens.Saml2NameIdentifier(acctContact.Name)
samlResponse.ClaimsIdentity = claimIdentity
End If
End Sub
Private Function BuildClaims(ByVal currentUser As CurrentUser, ByVal acctContact As CoveredInsuredDto) As IEnumerable(Of Claim)
Dim claims = New List(Of Claim)
If Not IsNothing(acctContact) Then
claims.Add(New Claim("FIRST_NAME", acctContact.FirstName))
claims.Add(New Claim("LAST_NAME", acctContact.LastName))
End If
Return claims.ToList()
End Function
The problem is that you have forgot the var token = response.CreateSecurityToken(appliesToAddress); line which is actually the line creating the token.
The ASP.NET Core IdP Initiated sample code:
public IActionResult Initiate()
{
var serviceProviderRealm = "https://some-domain.com/some-service-provider";
var binding = new Saml2PostBinding();
binding.RelayState = $"RPID={Uri.EscapeDataString(serviceProviderRealm)}";
var config = new Saml2Configuration();
config.Issuer = "http://some-domain.com/this-application";
config.SingleSignOnDestination = new Uri("https://test-adfs.itfoxtec.com/adfs/ls/");
config.SigningCertificate = CertificateUtil.Load(Startup.AppEnvironment.MapToPhysicalFilePath("itfoxtec.identity.saml2.testwebappcore_Certificate.pfx"), "!QAZ2wsx");
config.SignatureAlgorithm = Saml2SecurityAlgorithms.RsaSha256Signature;
var appliesToAddress = "https://test-adfs.itfoxtec.com/adfs/services/trust";
var response = new Saml2AuthnResponse(config);
response.Status = Saml2StatusCodes.Success;
var claimsIdentity = new ClaimsIdentity(CreateClaims());
response.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent);
response.ClaimsIdentity = claimsIdentity;
var token = response.CreateSecurityToken(appliesToAddress);
return binding.Bind(response).ToActionResult();
}
private IEnumerable<Claim> CreateClaims()
{
yield return new Claim(ClaimTypes.NameIdentifier, "some-user-identity");
yield return new Claim(ClaimTypes.Email, "some-user#domain.com");
}
Using the node-mssql library to pull data from SQL. I've been using Sinon for a while now (written about 200 tests with it); having a ton of trouble getting my head around how to stub this library out. The code looks like:
var sql = require('mssql');
var conn = new sql.Connection(sqlConfig); // sqlConfig is connection info, defined elsewhere
conn.connect(function(err) {
var req, selectFromTable;
if (err != null) {
// handle error
}
req = new sql.Request(conn);
selectFromTable = "select * from DW." + table + " where DWCreatedDate >= '" + start + "' and DWCreatedDate <= '" + end + "' ";
logger.debug("Selecting with: ", selectFromTable);
req.input('statement', sql.NVarChar, selectFromTable);
return req.execute('sp_executesql', function(err, results, returnValue, affected) {
if (err != null) {
// etc.
} else {
// data processing
}
});
});
Code works fine. Now I'm trying to write a test for it. I knew this library would be difficult to test so I procrastinated. My closest code:
var conn, reqExecute, sqlReqStub;
sqlReqStub = sinon.stub();
sqlReqStub.execute = sinon.stub();
sinon.stub(sql, 'Request').returns(sqlReqStub);
conn = sinon.stub();
sinon.stub(sql, 'Connection').returns(conn);
conn.connect = sinon.stub().callsArgWith(0, null);
reqExecute = sqlReqStub.execute.withArgs('sp_executesql').onFirstCall().callsArgWith(1, null, {
a: 1
});
Your natural inclination might be to say "well, use createStubInstance" but when I use that I get back connection objects (new sql.Connection(config)) that have TediousRequest (what the library defaults to when it builds out the driver object inside of the connection) in them instead of my stub request. I can't find TediousRequest anywhere in the sql object to stub it out.
I'm stuck here; hoping someone has some code around that does this or can explain what I'm doing wrong.
Well, I did manage to solve it but it feels a little hacky for some reason. Possibly because I never figured out how to stub the new sql.Request(conn) call.
Ideally I'd like to get this working without having to include the sql library in my module.exports. I can do that with the request library but after a few hours knocking away at this library I'm unable to get it working in the same way.
First: export the sql library:
sql = require('mssql')
// much code
module.exports.sqlLib = sql
Second: stub things:
var connection, sqlReqStub, sqlStubLib;
var server = require('./index.js')
sqlStubLib = {};
connection = new EventEmitter();
connection.connected = true;
connection.close = function() {};
connection.connect = sinon.stub().callsArgWith(0, null);
sqlStubLib.Connect = sinon.stub();
sqlStubLib.Connection = function() {
return connection;
};
sqlReqStub = sinon.stub();
sqlReqStub.input = function() {};
sqlReqStub.execute = sinon.stub();
sqlReqStub.execute.withArgs('sp_executesql').onFirstCall().callsArgWith(1, null, [
[
// js object
]
], null, null);
sqlStubLib.Request = function() {
return sqlReqStub;
};
server.sqlLib = sqlStubLib;
Still new and just learning how to use arrays. I am getting the error "Cannot convert Array to Object[][]. (line 46, file "Submit to Record")
Line 46 is
targetSheet.getRange(lastRow+1, 1, 1, arrayOfData.length).setValues(arrayOfData);
I had this error once before, but it was because of an array inside an array issue. Now I don't know what's wrong.
The entire code is
function submitButtonClick() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
Logger.log('sheet.getName(): ' + sheet.getName());
if (sheet.getName() !== "SubmitReceipt") {return;};
var targetSheet = ss.getSheetByName("ReceiptRecord");
var arrayOfData = [];
var week = sheet.getRange(6,9).getValue();
var emplN = sheet.getRange(4,9).getValue();
var purDate = sheet.getRange(9,9).getValue();
var purFrom = sheet.getRange(11,9).getValue();
var custC = sheet.getRange(14,9).getValue();
var deptC = sheet.getRange(16,9).getValue();
var lotC = sheet.getRange(18,9).getValue();
var laborC = sheet.getRange(20,9).getValue();
var itemC = sheet.getRange(22,9).getValue();
var hyperL = sheet.getRange(28,9).getValue();
var notes = sheet.getRange(44,8).getValue();
arrayOfData[0] = week;
arrayOfData[1] = emplN;
arrayOfData[2] = purDate;
arrayOfData[3] = purFrom;
arrayOfData[4] = custC;
arrayOfData[5] = deptC;
arrayOfData[6] = lotC;
arrayOfData[7] = laborC;
arrayOfData[8] = itemC;
arrayOfData[9] = hyperL;
arrayOfData[10] = notes;
Logger.log('arrayOfData '+ arrayOfData)
var lastRow = targetSheet.getLastRow();
Logger.log('lastRow: ' + lastRow);
Logger.log('arraylength ' + arrayOfData.length);
targetSheet.getRange(lastRow+1, 1, 1, arrayOfData.length).setValues(arrayOfData);
sheet.getRange(6,9).clearContent();
sheet.getRange(4,9).clearContent();
sheet.getRange(9,9).clearContent();
sheet.getRange(11,9).clearContent();
sheet.getRange(14,9).clearContent();
sheet.getRange(16,9).clearContent();
sheet.getRange(18,9).clearContent();
sheet.getRange(20,9).clearContent();
sheet.getRange(22,9).clearContent();
sheet.getRange(28,9).clearContent();
sheet.getRange(44,8).clearContent();
}
I know this code is clunky and could be written more efficiently and condensed, but I am writing this way on purpose because I am new to JS and this is an easy way for me to keep my head on straight about what is happening in the code. I hope my sanity efforts are not the cause of my problem. Please help. :)
Serge insas answered the question in the comments. He said:
I guess you should simply write
setValues([arrayOfData])
but I'm just guessing ;-)"
That did indeed fix the problem. Thanks, Serge insas!
I have 7 Arrays to begin with:
private var listArray:Array = new Array();
private var oneArray:Array = new Array();
private var twoArray:Array = new Array();
private var threeArray:Array = new Array();
private var fourArray:Array = new Array();
private var fiveArray:Array = new Array();
private var sixArray:Array = new Array();
listArray contain 6 string element of text file name.
something like:
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
All other array is empty at the moment.
I have wrote a for loop like this:
for (var i:int = 0; i < listArray.length; i++)
{
var urlRequest:URLRequest = new URLRequest(File.documentsDirectory.resolvePath(listArray[i]).url);
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
try
{
urlLoader.load(urlRequest);
}catch (error:Error){
trace("Cannot load : " + error.message);
}
}
if without for loop I know I can do this for only one array of data:
private function completeHandler(e:Event):void
{
oneArray = e.target.data.split(/\r\n/);
}
Here I am trying to get something to work like:
oneArray contain the data from 1.txt
twoArray contain the data from 2.txt
so on...
sixArray contain the data from 6.txt
problem:
I known the completeHandler function only execute after for loop looped six times.
is there anyway I could get the correct data to the correct array.
Thanks
Since you are using AIR to load data from the file-system, you don't have to do it asynchronously. You can load it synchronously like this:
function readTxtList(url:String):Array {
var file:File = File.documentsDirectory.resolvePath(url);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var text:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
fileStream.close();
return text.split("\r\n");
}
Now you can just assign each value directly:
var oneArray:Array = readTxtList("1.txt");
var twoArray:Array = readTxtList("2.txt");
// etc
I recommend you to use Dictionary.
Create new Dictionary:
var dict:Dictionary = new Dictionary();
Bind an instance of the URLLoader class to the file name:
var urlRequest:URLRequest = ...
var urlLoader:URLLoader = new URLLoader();
dict[urlLoader] = listArray[i];
In the completeHandler you can get the file name:
trace(dict[e.currentTarget]);
Add if statements to reach your goal.
if (dict[e.currentTarget] == "1.txt")
oneArray = e.target.data.split(/\r\n/);
else if (dict[e.currentTarget] == "2.txt")
twoArray = e.target.data.split(/\r\n/);
...
I have a functionality as follows:
When Any user logs in I want to connect to a particular DB based on login credentials
.
I tried with
$this->db->close();
and this->db->reconnect();
but it did not help
In your application/config/database.php you can define more than one database connection by doing
$db['database1']['hostname'] = 'localhost';
$db['database1']['username'] = 'db1_root';
$db['database1']['password'] = 'xxxxxx';
$db['database1']['database'] = 'database1_name';
$db['database1']['db_debug'] = false; //Important
$db['database2']['hostname'] = 'localhost';
$db['database2']['username'] = 'db2_root';
$db['database2']['password'] = 'xxxxxx';
$db['database2']['database'] = 'database2_name';
$db['database2']['db_debug'] = false; //Important
Then you can load specific databases by doing
$database1 = $this->load->database('database1', true);
$database2 = $this->load->database('database2', true);
Then rather than doing
$this->db->query();
You will need to do either
$database1->query();
$database2->query();
You can connect using a dynamic config in your controller/model/library/whatever by passing a config array to $this->load->database().
$config['hostname'] = "localhost";
$config['username'] = $user_name;
$config['password'] = $user_password;
$config['database'] = $user_database;
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$user_db = $this->load->database($config, true);
I figured out my answer.. Coded as follows:
in the database.php file i have added a new database config:
$db['db2']=$db['default'];
$db['db2']['database'] = 'new_db2';
and then in all the models constructor function i have put the following code:
$new_db = $this->load->database('db2', TRUE );
$this->db = $new_db;
So in this case i don't need to change all my queries. Hurray!!! :)