Friday, November 28, 2014

Wordpress add custom field to Add New User Page

Unfortunally i could not find a plugin for this purpose and could not write a new one because there is not a hook or filter method in Wordpress.  Altough you can easily write a new one for personel options update and user profile update as shown below:

add_action ( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action ( 'edit_user_profile_update', 'my_save_extra_profile_fields' );

Finally, to be able to add a new field to Add New User  page, i decided to modify user-new.php file.

Before table end tag on line 428  i added the code below

 <tr class="form-field form-required">  
  <th scope="row"><label for="foundation"><?php _e('Kurum'); ?> <span class="description"><?php _e('(required)'); ?></span></label></th>  
  <td>  
   <select id="organizationSelection" name="organizationSelection">  
   <?php  
   $organizations = $wpdb->get_results("SELECT id, organization_name FROM organization ORDER BY organization_name ASC");  
   foreach ($organizations as &$organization) {?>  
    <option value="<?php echo $organization->id;?>"><?php echo $organization->organization_name;?></option>  
   <?php }  
   ?>  
   </select>  
  </td>  
  </tr>  

Then i changed the code as the following on line 94

 elseif ( isset($_REQUEST['action']) && 'createuser' == $_REQUEST['action'] ) {  
  check_admin_referer( 'create-user', '_wpnonce_create-user' );  
  if ( ! current_user_can('create_users') )  
  wp_die(__('Cheatin&#8217; uh?'));  
  if ( ! is_multisite() ) {  
  $user_id = edit_user();  
   if ( is_wp_error( $user_id ) ) {  
   $add_user_errors = $user_id;  
  } else {  
   if ( current_user_can( 'list_users' ) ){  
   //@info following line added by ozayd  
   update_user_meta($user_id, 'organization_id', $_POST['organizationSelection']);  
   $redirect = 'users.php?update=add&id=' . $user_id;}  
   else{  
   //@info following line added by ozayd  
   update_user_meta($user_id, 'organization_id', $_POST['organizationSelection']);  
   $redirect = add_query_arg( 'update', 'add', 'user-new.php' );  
   }  
   wp_redirect( $redirect );  
   die();  
  }  
  } else {  
..


Saturday, May 3, 2014

EJB 3 Web Service Implementation with HTTP Basic Authentication & Authhorization

Before run this sample you have to make neccasery realm configution in your EJB 3.0 compatible application server.


  1. First create a Stateless bean  as shown below:

@Stateless (mappedName = "TestSecureWebService")
@WebService (targetNamespace = "http://webservice.duman.ozay.com/", serviceName = "TestSecureWebService")
public class TestSecureWebService implements TestSecureWebServiceRemote {
@Resource
private WebServiceContext webServiceContext;


@Override
@RolesAllowed({"CallServiceAccessRight"})
@WebMethod(operationName = "sampleSecureServiceSorgula")
@WebResult(name = "TestSecureService")
public String secureServiceMethod(String name) {
 MessageContext messageContext = webServiceContext.getMessageContext();
 javax.servlet.http.HttpServletRequest httpRequest = (javax.servlet.http.HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST);
 String userName = httpRequest.getRemoteUser();


 return "http basic auth. web service method called by " + userName;
}

}
You can access httpRequest information (client ip, remoteuser etc.) by injecting WebServiceContext resource.

To test this service you can simply use SOAP UI passing the service credentials or write a web service client as  follows:

public class WSClientMain {

 public static void main(String[] args) {
 TestSecureWebService  service =new TestSecureWebService();
 TestSecureWebServicePort  port = service.getTestSecureWebServiceservicePort();
 Map<String, Object> rc = ((BindingProvider) port).getRequestContext();
 
 rc.put(BindingProvider.USERNAME_PROPERTY, "user1");
 rc.put(BindingProvider.PASSWORD_PROPERTY, "testuser");
 
 String result= port.secureServiceMethod("abc");
 
 System.err.println(result);
 
 }

}



Friday, April 4, 2014

Proxy Authentication Required Problem When Proxy Class Genarating Using wsdl.exe


Problem: Proxy Authentication Required Problem When Proxy class genarating using wsdl.exe

Solution 1:
wsdl.exe  /proxyusername:username /proxypassword:password /proxydomain:domain /language:CS /namespace:testservice /out:D:\VISIUAL_STD_WSDL_ARTIFACTS/ClassName.cs /protocol:SOAP http://.......:80/TestService?wsdl

Solution 2:
download wsdl and relating schema files to a local folder (D:\TestServiceProxyClasses\) and update the preceding command as shown below:

wsdl.exe   /language:CS /namespace:testservice /out:D:\VISIUAL_STD_WSDL_ARTIFACTS/ClassName.cs /protocol:SOAP D:\TestServiceProxyClasses\TestService?wsdl

Saturday, July 20, 2013

How To prevent browser swf caching when your flex/flash application changes

Actually browser caching mechanism is very useful but sometimes   it might be chaotic especially when new version of applications is avaliable. Cached artifacts likes swf should automatically cleared on the client machines when new version of the application avaliable. The way i solve this problem may not be the best but it works. So here i share it. If you have other solutions please share,
When you get new realese, you should add build number where swf object embedded in your html pages. It will be cached until you assign a new realese number.
You can automatize this in your  continuous integration environment defining a ant job that assigns a realese where swf objects embedded.

In Adobe Flex applications,mxml compiler  (mxml) uses index.template.html file shown below to produce swf and to embed it to application's main html file.  So if you add a query string parameter after  ${swf}.swf  in this javascript prevents swf caching.
To check if this works, write "about:cache?device=disk" in address bar of your firefox browser you will see your swf object with a new query string that means it has forced the browser to  make request for the this swf object .


<script type="text/javascript">
<!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
var swfVersionStr = "${version_major}.${version_minor}.${version_revision}";
<!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
var xiSwfUrlStr = "${expressInstallSwf}";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "${bgcolor}";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "${application}";
attributes.name = "${application}";
attributes.align = "middle";
swfobject.embedSWF(
"${swf}.swf?v=@@@", "flashContent",
"${width}", "${height}",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
<!-- JavaScript enabled so display the flashContent div in case it is not replaced with a swf object. -->
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>

Friday, February 1, 2013

Access Methods to Server Resources



Access methods to server resources through JNDI
·If you are in a managed enviroment such as J2EE ‘s EJB container,  then you can simply access the jndi object by injecting it via the annotations as follows:
EJB Container  makes the resource jou’ve injected ready in a managed pool. When you need one, it pulls the session bean or resource from the pool.
@EJB
Private MyRemoteInterface  myRemoteInterface;
If it is a resource like timer then you should use @Resource annotation
     
·@Resouce
private EJBContext context;
public void myRemoteMethod(){
  MyLocalBean myBean=(MyLocalBean) context.lookup(“com.ozay.MyLocalBean”);
  myBean..
}
·If your object is not managed that means can not inject server resource directly(it does not have @Stateless, @Statefull etc. bean annotation like your domain class),  this time you can access the object via the jndi lookup as follows:

Context context = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,    "weblogic.jndi.WLIni  tialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
ht.put(Context.SECURITY_PRINCIPAL, pUsername);
ht.put(Context.SECURITY_CREDENTIALS, pPassword);
try {
 context = new InitialContext(ht);
 MyLocalBean myBean=(MyLocalBean) context.lookup(“com.ozay.MyLocalBean”);
 myBean.callMethod()
}catch (NamingException e) {
    // an exception occurred
}finally {
  try { context.close();}
  catch (Exception e) {
      // an exception occurred
  }
 }
And if your class running on a different jvm and it wants to access a resource that is kept securely, you must pass credantials.
If your server  environment is a managed server or cluster architecture as shown in the figure below then you can make resource lookup via environment object without specifying credantials:


 
 
 
//MACHINE-B wants to access MACHINE-C
Environment env = new Environment();
env.setProviderURL("t3://machine-c:7001");
Context ctx = env.getInitialContext()



Thursday, November 29, 2012

Continuous Inspection



How can you ensure the quality of your code continuously?
Some measures comes to my mind are as follows:
  • Your bug rate
  • compliance of coding rules
  •   complexity
  • duplications
  • comments
  • coupling and cohesion level
  • code coverage
  • automated acceptance test
  •  performance &stress test

Using continuous inspection tools like Sonar you run pre-defined rules and if not enough for you, plus your custom rules against your source files. Then it collects violations of the rules, quality metrics and then lists them on the dashboard historically. Measuring these while time goes on you actually measure your team’s experience as well.  These results also give you a chance to focus on the risky components and may suggest some action plans to solve them. 
Some rules’ priority should be higher than others for your project. You can change rules threshold as blocker, critical, major, minor, info etc whenever you want.
Here is a screen shot from my test project:

                                                                                                 Figure-1
Here you can assign a violation to someone via the assing button, or you can ignore it by marking False-positive, or you can take action by selecting a plan you've defined. If you use Jira issue tracking system then you can make it viewable to jira by using a sonar jira plugin as well. One of the most important thing, you can    make rules active or inactive anytime you want and you can also change severity of them.

Figure-2


Wednesday, November 14, 2012

Eclipse editor for liquibase database change management



             To use eclipse magic auto-complete feature for liquibase change log file editing i defined a xtext grammer and generated a plugin. [ Xtext, an open-source framework for development of programming langauges and domain-specific languages.]

You will see below my xtext grammer for liquibase which just defines some part of its language and also a template of this language to suggest keywords and phrases smartly when using auto complete feature of the Eclipse environment:

Grammer Part:

grammar org.xtext.example.mydsl.Liquibase with org.eclipse.xtext.common.Terminals
generate LiquibaseEditor "http://www.xtext.org/example/mydsl/LiquibaseEditor"
Model:
      (xlists+=Xlist)*;
Xlist:
   '<?xml version="1.0" encoding="UTF-8"?>'
   '<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"'
      'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
      'xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog'
      'http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">'(include+=INCLUDEFILE)*(changeset+=CHANGESET)*'</databaseChangeLog>';
CHANGESET:'<changeSet' 'id='id=STRING 'author='author=STRING(ra=RUNALWAYS)?(roc=RUNONCHANGE)?'>'(pre+=PRECONDITION)?(comment=COMMENT)?((sql+=SQL)|(createProcedure+=CREATEPROCEDURE)|(rb+=ROOLBACK))*'</changeSet>';
 
SQL returns MSQL:
 a=MSQL
;
terminal MSQL:'<sql>'->'</sql>';
MSQLs:'<sql>'=>'</sql>';
INCLUDEFILE:'<include file='fileLocation=STRING'/>';
//SQLFILE:'<sqlFile path='fileLocation=STRING'/>';
RUNALWAYS:'runAlways='ra=BOOLEAN;
RUNONCHANGE:'runOnChange='roc=BOOLEAN;
ROOLBACK returns MROOLBACK:mr=MROOLBACK;
terminal MROOLBACK:'<roolback>'->'</roolback>';
ENDDELIMITER:'endDelimiter='ed=STRING;
STRIPCOMMENTS:'stripComments='sc=BOOLEAN;
SPLITSTATEMENTS:'splitStatements='sps=BOOLEAN;
PRECONDITION:'<preConditions'prect=PRECONDITIONTYPE'>'(sqlCheck+=SQLCHECK)'</preConditions>';
SQLCHECK returns MSQLCHECK:
 b=MSQLCHECK
;
//SQLCHECK:'<sqlCheck expectedResult='EXPECTEDRESULT'>'(sqlStatement+=STRING)'</sqlCheck>';
 
terminal MSQLCHECK:'<sqlCheck expectedResult='STRING'>'->'</sqlCheck>';
//ANDLOGICALEXP:(ab=ENDBTAG)((s+=SQLCHECK)|(ole+=ORLOGICALEXP)|(ale+=ANDLOGICALEXP))*(ae=ENDETAG);
//ORLOGICALEXP:(ob=ORBTAG)((s+=SQLCHECK)|(ole+=ORLOGICALEXP)|(ale+=ANDLOGICALEXP))*(oe=ORETAG);
//ANDLOGIC:'<and>''</and>';
//ORLOGIC:'<or>''</or>';
//ENDBTAG:'<and>';
//ENDETAG:'</and>';
//ORBTAG:'<or>';
//ORETAG:'</or>';
 
PRECONDITIONTYPE:(u=ONUPDATE)|(f=ONFAIL)|(e=ONERROR)|(fm=ONFAILMESSAGE)|(em=ONERRORMESSAGE);
ONUPDATE:'onUpdate='((o='"RUN"')|(o='"FAIL"')|(o='"IGNORE"'));
ONFAIL:'onFail='onFailAttribute=ONFAILERRORTYPEATTRIBUTE;
ONERROR:'onError='onFailAttribute=ONFAILERRORTYPEATTRIBUTE;
ONFAILERRORTYPEATTRIBUTE:(a='"HALT"')|(a='"CONTINUE"')|(a='"MARK_RAN"')|(a='"WARN"');
ONFAILMESSAGE:'onFailMessage='message=STRING;
ONERRORMESSAGE:'onErrorMessage='essage=STRING;
COMMENT:'<comment>'comment=STRING'</comment>';//Comments should go after preCondition. If they are before then liquibase usually gives error.
DROPTABLE:'<dropTable tableName="'tableName=STRING'/>';
 
//~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
//CREATEPROCEDURE:'<createProcedure>'createProcedure=STRING'</createProcedure>';
CREATEPROCEDURE returns MCREATEPROCEDURE:
 b=MCREATEPROCEDURE;
 
terminal MCREATEPROCEDURE:'<createProcedure>'->'</createProcedure>';
/*MERGECOLUMNS:'<mergeColumns tableName="'tableName=STRING
 'column1Name='column1Name=STRING
 'joinString='joinString=STRING
 'column2Name'column2Name=STRING
 'finalColumnName'finalColumnName=STRING
 'finalColumnType'finalColumnType=STRING
;*/
//ADDCOLUMN:'<addColumn tableName='tableName=STRING'>'column=COLUMN'</addColumn>';
//COLUMN:'<column name='columnName=STRING'type='type=STRING'/>';
//Types
BOOLEAN:(t='"true"')|(f='"false"');
//terminal ID:'~~~';
//terminal STRING:!('') (INT |WS | ID)* ;
//terminal mystr:
//(ANY_OTHER | STRING)*;

Template Part:
i exported this file from my eclipse to use it just import from eclipse Preferences>>LiquibaseEditor>>Templates


<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
- <templates>
  <template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.kw_author=" deleted="false" description="" enabled="true" name="author">author="${user}"</template> 
  <template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.kw_author=" deleted="false" description="" enabled="true" name="author">author="ozayd"</template> 
  <template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.CHANGESET" deleted="false" description="" enabled="true" name="changeSet"><changeSet id="BLK-x-${date}-${time}" author="ozayd"> ${cursor} </changeSet></template> 
  <template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.CREATEPROCEDURE" deleted="false" description="" enabled="true" name="CREATEPROCEDURE"><createProcedure> ${cursor} </createProcedure></template> 
  <template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.CREATEPROCEDURE" deleted="false" description="" enabled="true" name="CREATEPROCEDURE"><createProcedure> ${cursor} </createProcedure></template> 
  <template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.Xlist" deleted="false" description="" enabled="true" name="databaseChangeLog"><?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd"> ${cursor} </databaseChangeLog></template> 
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.Xlist" deleted="false" description="" enabled="true" name="databaseChangeLog"><?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd"> ${cursor} </databaseChangeLog></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.INCLUDEFILE" deleted="false" description="" enabled="true" name="includeFile"><include file="${cursor}"/></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.INCLUDEFILE" deleted="false" description="" enabled="true" name="includeFile"><include file="${cursor}"/></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.ROOLBACK" deleted="false" description="" enabled="true" name="ROOLBACK"><roolback> ${cursor} </roolback></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.ROOLBACK" deleted="false" description="" enabled="true" name="ROOLBACK"><roolback> ${cursor} </roolback></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.Xlist" deleted="false" description="" enabled="true" name="sql"><sql> ${cursor} </sql></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.Xlist" deleted="false" description="" enabled="true" name="sql"><sql> ${cursor} </sql></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.SQL" deleted="false" description="" enabled="true" name="SQL"><sql> ${cursor} </sql></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.SQL" deleted="false" description="" enabled="true" name="SQL"><sql> ${cursor} </sql></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.SQLCHECK" deleted="false" description="" enabled="true" name="sqlCheck"><sqlCheck expectedResult="${cursor}expectedResult">"sqlStatement"</sqlCheck></template>
<template autoinsert="true" context="org.xtext.example.mydsl.LiquibaseEditor.SQLCHECK" deleted="false" description="" enabled="true" name="sqlCheck"><sqlCheck expectedResult="${cursor}expectedResult">"sqlStatement"</sqlCheck></template>
</templates>