I have an application that will validate username and password to give access to a soap webservice and im trying to log the username and method used, so how to log that info into a database (get user and method)?
this is the code i have so far:
<mule-ss:security-manager
xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security">
<mule-ss:delegate-security-provider
name="jdbc-provider" delegate-ref="authenticationManager" />
</mule-ss:security-manager>
<spring:beans>
<spring:bean id="loggingInInterceptor"
class="org.apache.cxf.interceptor.LoggingInInterceptor" />
<spring:bean id="loggingOutInterceptor"
class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
<spring:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<spring:property name="driverClassName" value="org.postgresql.Driver" />
<spring:property name="url" value="jdbc:postgresql://127.0.0.1/anydb" />
<spring:property name="username" value="anyuser" />
<spring:property name="password" value="0123456" />
</spring:bean>
<ss:http xmlns:ss="http://www.springframework.org/schema/security"
auto-config="true" use-expressions="true" request-matcher="regex">
<ss:intercept-url pattern="^/services/any/anyservice"
access="hasRole('ROLE_ANY')" />
</ss:http>
<ss:authentication-manager
xmlns:ss="http://www.springframework.org/schema/security" alias="authenticationManager">
<ss:authentication-provider>
<ss:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select username, password, enabled
from users where username=?"
authorities-by-username-query="
select u.username, ur.authority from users u, authorities ur
where u.id = ur.user_id and u.username =? " />
</ss:authentication-provider>
</ss:authentication-manager>
</spring:beans>
<jdbc:postgresql-data-source name="postgreName"
user="anyuser" password="0123456" url="jdbc:postgresql://127.0.0.1/anyservice"
transactionIsolation="UNSPECIFIED" doc:name="PostgreSQL Data Source">
</jdbc:postgresql-data-source>
<jdbc:connector name="jdbcConnector" dataSource-ref="postgreName"
validateConnections="false" queryTimeout="10" pollingFrequency="10000"
doc:name="Database">
<reconnect frequency="3000" blocking="false" />
<jdbc:query key="anydb" value="insert into inbound_msgs (ip_from, request_size, modified_request_size, timestamp, url)
values (
#[groovy: return message.getInboundProperty('MULE_REMOTE_CLIENT_ADDRESS').toString()],
#[groovy: return message.getInboundProperty('http.request.old').toString().length()],
#[groovy: return message.getInboundProperty('http.request').toString().length()],
now(),
#[groovy: return message.getInboundProperty('http.context.uri').toString()]);">
</jdbc:query>
</jdbc:connector>
<scripting:transformer name="noopLoggingTransformer"
doc:name="Script">
<scripting:script engine="groovy">
def props = [:]
//props['User-Agent'] = message.getProperty('User-Agent', org.mule.api.transport.PropertyScope.INBOUND)
props['MULE_REMOTE_CLIENT_ADDRESS'] =
message.getProperty('MULE_REMOTE_CLIENT_ADDRESS',
org.mule.api.transport.PropertyScope.INBOUND)
props['http.request'] = message.getProperty('http.request',
org.mule.api.transport.PropertyScope.INBOUND)
props['http.context.uri'] = message.getProperty('http.context.uri',
org.mule.api.transport.PropertyScope.INBOUND)
props['http.request.old'] = message.getProperty('http.request',
org.mule.api.transport.PropertyScope.INBOUND)
muleContext.client.dispatch('vm://log-request.in', payload, props)
message
</scripting:script>
</scripting:transformer>
<flow name="log-request" doc:name="log-request">
<vm:inbound-endpoint path="log-request.in"
doc:name="VM" />
<jdbc:outbound-endpoint exchange-pattern="one-way"
queryKey="anydb" responseTimeout="10000" queryTimeout="10"
connector-ref="jdbcConnector" doc:name="Persist raw message">
</jdbc:outbound-endpoint>
</flow>
<pattern:web-service-proxy name="logBypass" doc:name="logBypass">
<inbound-endpoint address="http://localhost/services/logBypass" exchange-pattern="request-response" transformer-refs="noopLoggingTransformer">
<mule-ss:http-security-filter realm="mule-realm"></mule-ss:http-security-filter>
</inbound-endpoint>
<outbound-endpoint address="http://targetServer/logBypass" exchange-pattern="request-response"/>
</pattern:web-service-proxy>
Mule version 3.4.0
After a few days i came with a solution to my problem:
with:
<scripting:transformer name="noopLoggingTransformer"
doc:name="Script">
<scripting:script engine="groovy">
import org.apache.commons.codec.binary.Base64
def props = [:]
//props['User-Agent'] = message.getProperty('User-Agent', org.mule.api.transport.PropertyScope.INBOUND)
props['MULE_REMOTE_CLIENT_ADDRESS'] =
message.getProperty('MULE_REMOTE_CLIENT_ADDRESS',
org.mule.api.transport.PropertyScope.INBOUND)
props['http.request'] = message.getProperty('http.request',
org.mule.api.transport.PropertyScope.INBOUND)
props['http.context.uri'] = message.getProperty('http.context.uri',
org.mule.api.transport.PropertyScope.INBOUND)
props['http.request.old'] = message.getProperty('http.request',
org.mule.api.transport.PropertyScope.INBOUND)
def headerData = message.getProperty('http.headers',org.mule.api.transport.PropertyScope.INBOUND)
def userName = ""
if (headerData["Authorization"] != null) {
def security = headerData["Authorization"].split(" ")
def bytes = security[1].bytes
Base64 coder = new Base64()
def decodedData = coder.decode(bytes)
def userNamePwd = new String(decodedData)
def userNameSplit = userNamePwd.split(":")
userName = userNameSplit[0]
}
props['userName'] = userName
def method = ""
if (headerData["SOAPAction"] != null) {
method = headerData["SOAPAction"]
}
props['method'] = method
muleContext.client.dispatch('vm://log-request.in', payload, props)
message
</scripting:script>
</scripting:transformer>
That and the code from the question will work perfect on Mule 3.4.0
Remember to change the database to adapt to your necessity.
Related
After upgrading from CF11 to CF2018, Update 3, none of my editable cfgrids are working. When I make an edit and then submit the form, the columns seem to get jumbled. I created the simplest cfgrid I could (below) but am still getting the same behavior.
<cfif isDefined("form.submitname")>
<cfdump var="#form#">
<cfelse>
<cfform action="test.cfm" method="post" name="testform" id="testformId">
<cfinput type="Submit" name="submitname" id="submitid">
<cfgrid name="TestGrid" format="html" selectmode="edit">
<cfgridcolumn name="A">
<cfgridcolumn name="B">
<cfgridrow data="john,doe">
<cfgridrow data="steve,anon">
</cfgrid>
</cfform>
</cfif>
The grid displays correctly, but what I change 'john' to 'peter' and submit, I get the following dump:
enter image description here
As you can see, it thinks 'peter' was entered as both the first and last name, and it also thinks that 'peter' was the original first name.
When I modify any of the fields in the second column, I get the following javascript error in the console:
TypeError: _dd.values[_de] is undefined.
The error is thrown by cfgrid.js
If I submit only a change in the second column, the dump is completely empty.
It seems like the cfgrid is mixing up columns or something.
Your thoughts?
Ultimately the solution here is to move away from ColdFusion's implementation of <cfgrid> and roll your own grid-UI or.... wait for a patch from Adobe.
This is definitely a bug in ColdFusion, the error you are seeing is specifically a bug in the function ColdFusion.Grid.Actions.afterEdit()
I spent a little bit of time fiddling around with the JS generated with <cfgrid> and found that they index into the columns incorrectly
You can override ColdFusion's implementation of ColdFusion.Grid.Actions.afterEdit() with your own to create a possible workaround ( I ran on Solaris 11.4 - Apache - ColdFusion 2018 : Update 3 )
<Body>
<cfif isDefined("form.submitname")>
<cfdump var="#form#">
<cfelse>
<cfform action="test.cfm" method="post" name="testform" id="testformId">
<cfinput type="Submit" name="submitname" id="submitid">
<cfgrid name="TestGrid" format="html" selectmode="edit">
<cfgridcolumn name="A">
<cfgridcolumn name="B">
<cfgridrow data="john,doe">
<cfgridrow data="steve,anon">
</cfgrid>
</cfform>
</cfif>
<script>
ColdFusion.Grid.Actions.afterEdit = function(_d8, _d9, _da) {
var _db = _d9.value;
if (_db == this.editOldValue) {
return;
}
if (this.insertInProgress == false && this.onChangeFunction) {
this.onChangeHandler("U", this.selectedRow, _d9);
} else {
if (!this.dynamic) {
rowidx = _d9.rowIdx;
if (!rowidx && rowidx != 0) {
rowidx = _d9.row;
}
var _dc = ColdFusion.Grid.computeActualRow_editField(this.editFieldState, _d9.record.data.CFGRIDROWINDEX);
var _dd = this.editFieldState[_dc - 1];
var _de = _d9.colIdx;
if (!_de && _de != 0) {
_de = _d9.column;
}
_de = _de + 1;
if (_dd) {
if (this.multiRowSelection === true && this.insertInProgress == true) {
_de = _de - 1;
}
//-------------------------------------------------------------------
//Subtracted 1 from column index to correctly index array
//-------------------------------------------------------------------
_dd.values[_de -1][1] = _db;
} else {
var _df = this.grid.getStore().getById(_d9.record.data.CFGRIDROWINDEX);
_dd = ColdFusion.Grid.Actions.initEditState(this, "U", _df, _dc);
var _e0 = this.editOldValue + "";
if (_d9.column.type == "date") {
if (_e0 && typeof _e0 == "string") {
_e0 = new Date(_e0);
}
var _e1 = "F, j Y H:i:s";
if (_d9.column && _d9.column.format) {
_e1 = _d9.column.format;
}
_dd.values[_de][1] = Ext.Date.format(_db, _e1);
_dd.values[_de][0] = _e0 ? Ext.Date.format(_e0, _e1) : _e0;
} else {
//-------------------------------------------------------------------
//Subtracted 1 from column index to correctly index array
//-------------------------------------------------------------------
_dd.values[_de -1][0] = _e0;
_dd.values[_de -1][1] = _db;
}
}
ColdFusion.Grid.Actions.computeEditField(this);
}
}
this.editOldValue = null;
this.fireSelectionChangeEvent();
}
;
</script>
</BODY>
There are definitely a ton of other bugs plaguing this tag ... and its definitely worth noting that Lucee ( opensource ColdFusion engine) DOES NOT support this tag
I'm confused on the signature aspect for a JWT. I believe I have the header and claim set correct as I got past any errors was seeing when originally writing this. My question is mostly around the signature. IS HMac with HMACSHA256 correct? I think I may be confused on where to get the private key for encryption. If anyone has some guidance that would be great.
<cfset JWT_header = structNew()>
<cfset JWT_header['alg'] = 'RS256'>
<cfset JWT_header['typ'] = 'JWT'>
<cfset JWT_header = serializeJSON(JWT_header)>
<cfset JWT_claim_set = structNew()>
<cfset JWT_claim_set['iss'] = 'secret_iss'>
<cfset JWT_claim_set['scope'] = 'my_scope'>
<cfset JWT_claim_set['aud'] = 'https://www.googleapis.com/oauth2/v4/token'>
<cfset JWT_claim_set['exp'] = 'Time_Stamp')>
<cfset JWT_claim_set['iat'] = 'Time_Stamp')>
<cfset JWT_claim_set = serializeJSON(JWT_claim_set)>
<cfset data = ToBase64(JWT_header) & '.' & ToBase64(JWT_claim_set)>
<cfset hashedData = HMac(data, 'my_secret_private_key','HMACSHA256')>
<cfset signature = toBase64(hashedData)>
<cfset JWT = data & '.' & signature>
<cfhttp url="https://www.googleapis.com/oauth2/v4/token" method="post" result="result">
<cfhttpparam name="grant_type" type="formField" value="urn:ietf:params:oauth:grant-type:jwt-bearer" />
<cfhttpparam name="assertion" type="formField" value="#JWT#" />
</cfhttp>
<cfoutput>#result.filecontent#</cfoutput>
This returns:
'{ "error": "invalid_grant", "error_description": "Invalid JWT Signature." }'
For anyone that needs some code in the future to get them on the right path. This code is used for the firebase messaging api for push notification but can be adapted for other google services.
<cfscript>
variables.service_json = deserializeJSON(fileRead(expandPath('./serviceaccountprivatekey.json')));
variables.timestamp = dateDiff("s", CreateDate(1970,1,1), now());
variables.timestampUTC = timestamp + 21600; //add 6 hour to convert to utc
//generate jwt
variables.jwt_header = {
'alg': 'RS256',
'typ': 'JWT'
};
variables.jwt_header = serializeJSON(variables.jwt_header);
variables.jwt_header = toBase64(variables.jwt_header);
variables.jwt_claim = {
'iss': service_json.client_email,
'scope': 'https://www.googleapis.com/auth/firebase.messaging',
'aud': 'https://www.googleapis.com/oauth2/v4/token',
'iat': timestampUTC,
'exp': (timestampUTC + 3600)
};
variables.jwt_claim = serializeJSON(variables.jwt_claim);
variables.jwt_claim = toBase64(variables.jwt_claim);
variables.jwt = variables.jwt_header & '.' & variables.jwt_claim;
//sign jwt
variables.keyText = reReplace( service_json.private_key, "-----(BEGIN|END)[^\r\n]+", "", "all" );
variables.keyText = trim( keyText );
variables.privateKeySpec = createObject( "java", "java.security.spec.PKCS8EncodedKeySpec" )
.init(binaryDecode( variables.keyText, "base64" ));
variables.privateKey = createObject( "java", "java.security.KeyFactory" )
.getInstance( javaCast( "string", "RSA" ) )
.generatePrivate( privateKeySpec );
variables.signer = createObject( "java", "java.security.Signature" )
.getInstance( javaCast( "string", 'SHA256withRSA' ));
variables.signer.initSign( variables.privateKey );
variables.signer.update( charsetDecode( variables.jwt, "utf-8" ) );
variables.signedBytes = signer.sign();
variables.signedBase64 = toBase64(signedBytes);
variables.jwt_signed = variables.jwt & '.' & variables.signedBase64;
</cfscript>
<cfhttp
url="https://www.googleapis.com/oauth2/v4/token"
method="POST"
result="res"
>
<cfhttpparam name="grant_type" type="formField" value="urn:ietf:params:oauth:grant-type:jwt-bearer" />
<cfhttpparam name="assertion" type="formField" value="#variables.jwt_signed#" />
</cfhttp>
<cfset variables.res = deserializeJSON(res.filecontent) />
<cfscript>
variables.body = {
"message": {
"notification": {
"title": "test",
"body": "test test test"
},
"token": "e7blahblahSQ:thisisanexamplefirebasemessengingtokenpleaseputyourownonehere"
}
};
</cfscript>
<cfhttp url="https://fcm.googleapis.com/v1/projects/{project_id}/messages:send" method="post" result="res">
<cfhttpparam type="header" name="Content-type" value="application/json" />
<cfhttpparam type="header" name="Authorization" value="Bearer #variables.res.access_token#" />
<cfhttpparam type="body" value="#serializeJSON(body)#" />
</cfhttp>
<cfdump var="#res.fileContent#">
I got this to work with Ben Nadel's code(https://www.bennadel.com/blog/2941-experimenting-with-rsa-encrypted-signature-generation-and-verification-in-coldfusion.htm), but I had to modify it to work. I commented out anything to do with a public key as I was not using one to interface with google. If I was to enhance it I could create logic to look for the use of public or private key. Next I skipped anything with Pem file formatting since google isn't using that. Now it works.
I have two objects : Profile and Tags. Each profile can contain multiple tags. On my search page I can select multiple tags to search on. Now I want a query that get all profiles that have all the selected tags.
So if I use WhereRestrictionOn().IsIn() I get profiles which contains at least 1 of the tags but I need to return profiles which contains all the tags in the list.
I also tried multiple Where conditions for each selected tag but then I get no results at all.
I have no clue how to do this any help is much appreciated!
Structure:
Profile : Id
ProfileTag : ProfileId, TagId
Tag: Id
Mapping Profile
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Agrolink.Application.Models" assembly="Agrolink.Application">
<class name="Agrolink.Application.Models.Profile" lazy="false" table="Profiles" >
<id name="Id" column="Id" >
<generator class="identity" />
</id>
<bag name="Tags" table="ProfileTags" cascade="all-delete-orphan" inverse="true">
<key column="IdProfile" not-null="true"/>
<one-to-many class="Agrolink.Application.Models.ProfileTag" />
</bag>
</class>
</hibernate-mapping>
Mapping ProfileTag
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Agrolink.Application.Models" assembly="Agrolink.Application">
<class name="Agrolink.Application.Models.ProfileTag" lazy="false" table="ProfileTags" >
<id name="Id" column="Id" >
<generator class="identity" />
</id>
<many-to-one name="Profile" class="Agrolink.Application.Models.Profile" column="IdProfile" cascade="save-update" />
<many-to-one name="Tag" class="Agrolink.Application.Models.Tag" column="IdTag" cascade="none" />
</class>
</hibernate-mapping>
Mapping Tag
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Agrolink.Application.Models" assembly="Agrolink.Application">
<class name="Agrolink.Application.Models.Tag" lazy="false" table="Tags" >
<id name="Id" column="Id" >
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="Type" type="Agrolink.Application.Models.TagType, Agrolink.Application" column="IdType" />
<many-to-one name="Parent" class="Agrolink.Application.Models.Tag" column="IdParent" cascade="none" />
<bag name="Children" table="Tags" cascade="all" inverse="true">
<key column="IdParent" not-null="true"/>
<one-to-many class="Agrolink.Application.Models.Tag" />
</bag>
</class>
</hibernate-mapping>
SubQuery to achieve this (Solution):
Profile p = null;
Account a = null;
Institute i = null;
var q = Session.QueryOver(() => p)
.JoinAlias(x => x.Account, () => a)
.JoinAlias(x => x.Institute, () => i)
.Where(x => x.Type == ProfileType.Expert && x.Status == ProfileStatus.Active);
if(_keywordIds.Any())
foreach (var keywordId in _keywordIds)
{
Tag t = null;
var subQ = QueryOver.Of<ProfileTag>()
.JoinAlias(pt => pt.Tag, () => t)
.Where(() => t.Id == keywordId)
.Select(pt => pt.Profile.Id);
q.WithSubquery.WhereProperty(() => p.Id).In(subQ);
}
if (_institute != null) q.Where(() => i.Id == _institute);
if (!string.IsNullOrEmpty(_name)) q.Where(Restrictions.Disjunction()
.Add(Restrictions.Like("a.FirstName", _name + "%"))
.Add(Restrictions.Like("a.LastName", _name + "%"))
);
return (PagedList<Profile>) q.List<Profile>().ToPagedList(_page, _itemsPerPage);
It is almost it, but we need so called Detached QueryOver, which we will get with construction QueryOver.Of
foreach (var keywordId in _keywordIds)
{
//Tag t = null;
var subQ = QueryOver.Of<ProfileTag>()
//.JoinAlias(pt => pt.Tag, () => t)
//.Where(() => t.Id == keywordId)
.Where(x => x.Tag.Id == keywordId)
//.Select(pt => t.Id);
.Select(pt => pt.Profile.Id);
q.WithSubquery.WhereProperty(() => p.Id).In(subQ);
}
Hey anyone can help me with this problem ?
I have this issue with my code, two files:
1 - test.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin tÃtulo</title>
<script>
var url = "getagentids.php?param=";
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('formality').value = results[0];
document.getElementById('fullname').value = results[1];
document.getElementById('sex').value = results[2];
document.getElementById('id').value = results[3];
document.getElementById('joindate').value = results[4];
document.getElementById('jobtitle').value = results[5];
document.getElementById('city').value = results[6];
document.getElementById('typeofsalary').value = results[7];
document.getElementById('contract_type').value = results[8];
}
}
function getagentids() {
var idValue = document.getElementById("email").value;
var myRandom=parseInt(Math.random()*99999999); // cache buster
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();
</script>
</head>
<body>
<form name="schform">
<table bgcolor="#dddddd">
<tbody>
<?php
echo $param;
include '../../../connect.php';
$db =& JFactory::getDBO();
$query = "SELECT email FROM dbemployeekpw";
$db->setQuery($query);
$result = $db->loadObjectList();
$email = $result[0];
echo " <select size='1' name='email' id='email' onChange='getagentids()' required >
<option value=''> Seleccione </option>";
foreach($result as $email)
{
echo "<option value='".$email->email."'>".$email->email."</option>";
}
echo "</select>"
?>
<tr><td>Formality</td><td><input id="formality" type="text" name="formality"></td></tr>
<tr><td>Fullname</td><td><input id="fullname" type="text" name="fullname"></td></tr>
<tr><td>Sex</td><td><input id="sex" type="text" name="sex"></td></tr>
<tr><td>Id</td><td><input id="id" type="text" name="id"></td></tr>
<tr><td>Joindate</td><td><input id="joindate" type="text" name="joindate"></td></tr>
<tr><td>Jobtitle</td><td><input id="jobtitle" type="text" name="jobtitle"></td></tr>
<tr><td>City</td><td><input id="city" type="text" name="city"></td></tr>
<tr><td>Typesalary</td><td><input id="typeofsalary" type="text" name="typeofsalary"></td></tr>
<tr><td>Contract Type</td><td><input id="contract_type" type="text" name="contract_type"> </td></tr>
<tr><td><input size="60" type="reset" value="Clear"></td><td></td>
</tr>
</tbody></table>
</form>
</body>
</html>
and..
2 - getagentids.php
<?php
//$param = $_GET["param"];
include '../../../connect.php';
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query = "SELECT * FROM dbemployeekpw WHERE email = 'camilo.uribe#kantarworldpanel.com'";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result )
{
$formality = $result->formality;
$fullname = $result->fullname;
$sex = $result->sex;
$id = $result->id;
$joindate = $result->joindate;
$jobtitle = $result->jobtitle;
$city = $result->city;
$typeofsalary = $result->typeofsalary;
$contract_type = $result->contract_type;
$textout = $formality.",".$fullname.",".$sex.",".$id.",".$joindate.",".$jobtitle.",".$city.",".$typeofsalary.",".$contract_type;
}
echo $textout;
?>
But ajax dont works, only works if I put this :
$query = "SELECT * FROM dbemployeekpw WHERE email = 'camilo.uribe#kantarworldpanel.com'";
instead this:
$query = "SELECT * FROM dbemployeekpw WHERE email = '".$param."'";
But I need that the code works with second one :(
Anyone can help me with this problem ?
Thanks !!
SOLVED (works like a charm!!):
I change this:
$jinput = JFactory::getApplication()->input;
$param = $jinput->get('param', 'param', 'filter');
instead this:
$param = $_GET["param"];
and I'm still with:
$query = "SELECT * FROM dbemployeekpw WHERE email = '".$param."'";
because this code don't works for me:
$query->select($db->quoteName('*'))
->from($db->quoteName('dbemployeekpw'))
->where($db->quoteName('email') . ' = '. $db->quote($param));
Many Thanks #lodder
Before anything, lets see if the $param variable is correct and gets the value. Add the following which one the form is processed, will display the value. If the result is NULL then you firstly need to ensure you get the correct value. If you do get the correct value, then carry on reading.
Just on a side note, I would recommend looking at the following link rather than using $_GET:
http://docs.joomla.org/Retrieving_request_data_using_JInput
Lets now use up to date coding standards for you database query:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('*'))
->from($db->quoteName('dbemployeekpw'))
->where($db->quoteName('email') . ' = '. $db->quote($param));
$db->setQuery($query);
$results = $db->loadObjectList();
Hope this helps
I have a List called Registration and the following are the columns of my list.
Column : Type
Employee Name : Person or Group
Manager Name : Person or Group
Practice Name : Single line of text
Program Name : Lookup
Status : Choice
Prerequisite : Multiple lines of text
And now i created a web part which will display all these values as a grid view
here is the code which i have done for webpart.cs
protected void Page_Load(object sender, EventArgs e)
{
gridViewManager.DataSource = GetData();
gridViewManager.DataBind();
}
#region Try2
DataTable GetData()
{
SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWeb = oSiteCollection.OpenWeb();
SPList oSPList = oWeb.Lists["Registration"];
SPListItemCollection oSPListItemCollection = oSPList.Items;
DataTable dt = new DataTable();
try
{
dt.Columns.Add("Employee Name", typeof(String));
dt.Columns.Add("Manager Name", typeof(String));
dt.Columns.Add("Practice Name", typeof(String));
dt.Columns.Add("Program Name", typeof(LookupField));
//dt.Columns.Add("Program Name", typeof(String));
dt.Columns.Add("Status", typeof(String));
dt.Columns.Add("Prerequisite", typeof(String));
DataRow dataRow;
foreach (SPListItem oSplistItem in oSPListItemCollection)
{
dataRow = dt.Rows.Add();
dataRow["Employee Name"] = oSplistItem["Employee Name"].ToString();
dataRow["Manager Name"] = oSplistItem["Manager Name"].ToString();
dataRow["Practice Name"] = oSplistItem["Practice Name"].ToString();
dataRow["Program Name"] = oSplistItem["Program Name"].ToString();
dataRow["Status"] = oSplistItem["Status"].ToString();
dataRow["Prerequisite"] = oSplistItem["Prerequisite"].ToString();
}
return dt;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Managers Approval" + ex.Message.ToString());
return dt;
}
#endregion Try2
}
Here is the code for usercontrol code:
<SharePoint:SPGridView runat="server" ID="gridViewManager" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Employee Name" HeaderText="Employee Name" />
<asp:BoundField DataField="Manager Name" HeaderText="ManagerName" />
<asp:BoundField DataField="Practice Name" HeaderText="Practice Name" />
<asp:BoundField DataField="Program Name" HeaderText="Program Name" />
<asp:BoundField DataField="Status" HeaderText="Current Status" />
<asp:BoundField DataField="Prerequisite" HeaderText="Prerequisite" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Take Action" />
<asp:Button ID="Button1" runat="server" Text="View Details" />
</ItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</SharePoint:SPGridView>
Now i am facing a proble with these two lines of code
dt.Columns.Add("Program Name", typeof(LookupField));
dt.Columns.Add("Prerequisite", typeof(String));
if i don't use this then this webpart works perfectly . but i wanted to display these fields too . how can i do this ?
Did you take a look at having the SharePoint API generate the DataTable for you using SPListItemCollection.GetDataTable()?
The problem you're having is with null values. .ToString() will fail if the object is null. I assume that all of the other fields never have any null values (at least with your queries) but the fields that you are having problems with do. You have a few options. You can just check if the value is null and put in an empty string if it's not, for many of the fields that are already strings you can just cast them, rather than .ToString-ing them. You can use Convert.ToString(object) which handles nulls. I could go on with several other options, but I think you can take it from here.