Creating Internal Accounts in SAS Metadata Server by programm on SAS Base - sas

I'm trying to create Internal Accounts programmaticaly by using proc metadata.
The code section below creates person with External Login.
put"<Person Name=%str(%')&&PersonName&i.%str(%')>";
put"<Logins>";
put"<Login Name=%str(%')Login.&&PersonName&i.%str(%') Password=%str(%')&&word&i.%str(%')/>";
put"</Logins>";
put"</Person>";
To create ExternalLogin we can set attribute Password, and in SAS Metadata it will be encrypted automaticaly.
But to create InternalLogin type of object it is necessary to make the hash value of the password and the salt. I know that the standard sas002 encryption method, but in the case of using proc pwencode how to obtain the value of salt?
Is it possible create InternalLogin by using SAS Base?
Thanx.

So on. I found an article that can tell us how to create Stored Process for this problem. My answer is addition to the article.
The approach is base on execute java methods from sas programm.
1. Prerare setPasswd.java class
I've modified class from article. Separate code to connect to metadata server and create InternalLogin
import java.rmi.RemoteException;
import com.sas.metadata.remote.AssociationList;
import com.sas.metadata.remote.CMetadata;
import com.sas.metadata.remote.Person;
import com.sas.metadata.remote.MdException;
import com.sas.metadata.remote.MdFactory;
import com.sas.metadata.remote.MdFactoryImpl;
import com.sas.metadata.remote.MdOMIUtil;
import com.sas.metadata.remote.MdOMRConnection;
import com.sas.metadata.remote.MdObjectStore;
import com.sas.metadata.remote.MetadataObjects;
import com.sas.metadata.remote.PrimaryType;
import com.sas.metadata.remote.Tree;
import com.sas.meta.SASOMI.ISecurity_1_1;
import com.sas.iom.SASIOMDefs.VariableArray2dOfStringHolder;
public class setPasswd {
String serverName = null;
String serverPort = null;
String serverUser = null;
String serverPass = null;
MdOMRConnection connection = null;
MdFactoryImpl _factory = null;
ISecurity_1_1 iSecurity = null;
MdObjectStore objectStore = null;
Person person = null;
public int connectToMetadata(String name, String port, String user, String pass){
try {
serverName = name;
serverPort = port;
serverUser = user;
serverPass = pass;
_factory = new MdFactoryImpl(false);
connection = _factory.getConnection();
connection.makeOMRConnection(serverName, serverPort, serverUser, serverPass);
iSecurity = connection.MakeISecurityConnection();
return 0;
}catch(Exception e){
return 1;
}
}
public setPasswd(){};
public int changePasswd(String IdentityName, String IdentityPassword) {
try
{
//
// This block obtains the person metadata ID that is needed to change the password
//
// Defines the GetIdentityInfo 'ReturnUnrestrictedSource' option.
final String[][] options ={{"ReturnUnrestrictedSource",""}};
// Defines a stringholder for the info output parameter.
VariableArray2dOfStringHolder info = new VariableArray2dOfStringHolder();
// Issues the GetInfo method for the provided iSecurity connection user.
iSecurity.GetInfo("GetIdentityInfo","Person:"+IdentityName, options, info);
String[][] returnArray = info.value;
String personMetaID = new String();
for (int i=0; i< returnArray.length; i++ )
{
System.out.println(returnArray[i][0] + "=" + returnArray[i][1]);
if (returnArray[i][0].compareTo("IdentityObjectID") == 0) {
personMetaID = returnArray[i][1];
}
}
objectStore = _factory.createObjectStore();
person = (Person) _factory.createComplexMetadataObject(objectStore, IdentityName, MetadataObjects.PERSON, personMetaID);
iSecurity.SetInternalPassword(IdentityName, IdentityPassword);
person.updateMetadataAll();
System.out.println("Password has been changed.");
return 0; // success
}
catch (MdException e)
{
Throwable t = e.getCause();
if (t != null)
{
String ErrorType = e.getSASMessageSeverity();
String ErrorMsg = e.getSASMessage();
if (ErrorType == null)
{
// If there is no SAS server message, write a Java/CORBA message.
}
else
{
// If there is a message from the server:
System.out.println(ErrorType + ": " + ErrorMsg);
}
if (t instanceof org.omg.CORBA.COMM_FAILURE)
{
// If there is an invalid port number or host name:
System.out.println(e.getLocalizedMessage());
}
else if (t instanceof org.omg.CORBA.NO_PERMISSION)
{
// If there is an invalid user ID or password:
System.out.println(e.getLocalizedMessage());
}
}
else
{
// If we cannot find a nested exception, get message and print.
System.out.println(e.getLocalizedMessage());
}
// If there is an error, print the entire stack trace.
e.printStackTrace();
}
catch (RemoteException e)
{
// Unknown exception.
e.printStackTrace();
}
catch (Exception e)
{
// Unknown exception.
e.printStackTrace();
}
System.out.println("Failure: Password has NOT been changed.");
return 1; // failure
}
}
2. Resolve depends
Pay attention to imports in class. To enable execute the code below necessary set CLASSPATH enironment variable.
On linux you can add the next command in %SASConfig%/Lev1/level_env_usermods.sh:
export CLASSPATH=$CLASSPATH:%pathToJar%
On Windows you can add/change environment variable by Advanced system settings
So where should you search jar files? They are in folder:
%SASHome%/SASVersionedJarRepository/eclipse/plugins/
Which files i should include in path?
I've include all that used in OMI(Open Metadata Interface).Also I've added log4j.jar (not working without this jar. Your promts will be helpful):
sas.oma.joma.jar
sas.oma.joma.rmt.jar
sas.oma.omi.jar
sas.svc.connection.jar
sas.core.jar
sas.entities.jar
sas.security.sspi.jar
log4j.jar
setPasswd.jar (YOUR JAR FROM THE NEXT STEP!)
Choose files from nearest release. Example:
Here I'm set file from v940m3f (fix release).
Other ways is here.
3. Compile setPasswd.jar
I'm tried use internal javac.exe into SAS, but it's not worked properly. So ou need to download JDK to compile jars. I've create Bat-file:
"C:\Program Files\Java\jdk1.8.0_121\bin\javac.exe" -source 1.7 -target 1.7 setPasswd.java
"C:\Program Files\Java\jdk1.8.0_121\bin\jar" -cf setPasswd.jar setPasswd.class
Paramethers -source and -target will helpful if your version of JDK is upper, that usses in SAS. Version of "sas"-java you can see by:
PROC javainfo all;
run;
Search the next string in log:
java.vm.specification.version = 1.7
4. Finally. SAS Base call
Now we can call Java code by this method (All methods available here):
data test;
dcl javaobj j ("setPasswd");
j.callIntMethod("connectToMetadata", "%SERVER%", "%PORT%", "%ADMIN%", "%{SAS002}HASHPASSORPASS%", rc1);
j.callIntMethod("changePasswd", "testPassLogin", "pass1", rc2);
j.delete();
run;
In log:
UserClass=Normal
AuthenticatedUserid=Unknown
IdentityName=testPass
IdentityType=Person
IdentityObjectID=A56RQPC2.AP00000I
Password has been changed.
Now time to test. Create new user with no passwords.
Execute code:
data test;
dcl javaobj j ("setPasswd");
j.callIntMethod("connectToMetadata", "&server.", "&port.", "&adm", "&pass", rc1);
j.callIntMethod("changePasswd", "TestUserForStack", "Overflow", rc2);
j.delete();
run;
Now our user has InternalLogin object.
Thanx.

Related

checking database from webservice netbeans

sorry if my question confusing cause this is the first time i make a question. if there is something that i can do to make it clearer, just tell me so i can improve the way i'm asking.
currently i'm trying to make web service from netbeans that can check some data from database. Because i'm newbie so i followed tutorial from
http://programmerguru.com/webservice-tutorial/how-to-create-java-webservice-in-netbeans/ to make the web service.
but when i trying to check the database with my usual way with mybattis, it keep in give me java.lang.nulpointerexception. when i try to debug it, it give me "variable information not available, source compiled without -g option" and throw me to InvocationTargetException.java
public InvocationTargetException(Throwable target) {
super((Throwable)null); // Disallow initCause
this.target = target;
}
here is the code for the web service
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bismillah.berkah;
import com.bismillah.berkah.dao.DummyDao;
import com.bismillah.berkah.daoImpl.DummyDaoImpl;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
/**
*
* #author Ari
*/
#WebService(serviceName = "Check4Update")
public class Check4Update {
public DummyDaoImpl ddi;
/**
* This is a sample web service operation
*
* #param InTerminalNumber
* #return
*/
#WebMethod(operationName = "CheckUpdate")
public String hello(#WebParam(name = "InTerminalNumber") String InTerminalNumber) {
String OutError = "";
String OutMessage = "";
if (InTerminalNumber == null) {
return "InTerminalNumber can't be null";
} else {
Map mapdao = new HashMap<String, Object>();
Map map = new HashMap<String, Object>();
map.put("InTerminalNumber", InTerminalNumber);
mapdao = ddi.check4UpdatePatch(map);
OutError = (String) mapdao.get("OutError");
OutMessage = (String) mapdao.get("OutMessage");
return "Error : " + OutError + ", with message : " + OutMessage;
}
}
public void setDdi(DummyDaoImpl ddi) {
this.ddi = ddi;
}
}
and here is the code mybattis impl
package com.bismillah.berkah.daoImpl;
import com.bismillah.berkah.Check4Update;
import com.bismillah.berkah.config.MyBatisConnectionFactory;
import com.bismillah.berkah.dao.*;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
*
* #author Ari
*/
public class DummyDaoImpl
{
private SqlSessionFactory sqlSessionFactory;
public DummyDaoImpl()
{
sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
}
public Map check4UpdatePatch(Map map)
{
Check4Update c4u = new Check4Update();
c4u.setDdi(this);
SqlSession session = sqlSessionFactory.openSession();
try
{
session.selectOne("dummy.check4UpdatePatch", map);
} catch (Exception ex)
{
ex.toString();
} finally
{
session.close();
}
return map;
}
}
could you tell me how to fix it? so i can get the data? by the way i always get thrown at my web service, here exactly
mapdao = ddi.check4UpdatePatch(map);
once again sorry if my question confusing cause this is the first time i make a question. if there is something that i can do to make it clearer, just tell me so i can improve the way i'm asking.
sorry already found the problem, it is cause wrong configuration on mybatis.
i haven't change my string resource on MyBatisConnectionFactory, also the one at xml file.
maybe that's why i always get java lang nul.
actually when i trying to fix this, i make some interface class too, but still not working until i find my problem. if anyone have some problem like me maybe you can fix it with adding some interface so the impl will override the interface.

Active Directory notifications

I have seen this example documented by microsoft, but cannot get it to work in visual studio 2012, under a console project.
https://msdn.microsoft.com/en-us/library/ms676877(v=vs.85).aspx
Is there something I am missing, ie. is a console application correct.
The Errors I get are:
Error 1 error LNK2019: unresolved external symbol __imp__ldap_openW referenced in function "int __cdecl GetChangeNotifications(wchar_t *)" (?GetChangeNotifications##YAHPA_W#Z) C:\projects\AD_Notifications\AD_Change_Notifications\AD_Change_Notifications\AD_Change_Notifications.obj AD_Change_Notifications
From what I have been reading its a linker error, which is kinda obvious, but it is all in 1 file, so I don't understand what I am suppose to be linking?
The best answer I found in java is quoted below from https://community.oracle.com/thread/1158217
/**
* ldapnotify.java
* December 2004
* Sample JNDI application that uses AD LDAP Notification Control.
*
**/
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.*;
import javax.naming.ldap.*;
import com.sun.jndi.ldap.ctl.*;
import javax.naming.directory.*;
class NotifyControl implements Control {
public byte[] getEncodedValue() {
return new byte[] {};
}
public String getID() {
return "1.2.840.113556.1.4.528";
}
public boolean isCritical() {
return true;
}
}
class ldapnotify {
public static void main(String[] args) {
Hashtable env = new Hashtable();
String adminName = "CN=Administrator,CN=Users,DC=antipodes,DC=com";
String adminPassword = "XXXXXXXX";
String ldapURL = "ldap://mydc.antipodes.com:389";
String searchBase = "DC=antipodes,DC=com";
//For persistent search can only use objectClass=*
String searchFilter = "(objectClass=*)";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
//set security credentials, note using simple cleartext authentication
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,adminName);
env.put(Context.SECURITY_CREDENTIALS,adminPassword);
//connect to my domain controller
env.put(Context.PROVIDER_URL,ldapURL);
try {
//bind to the domain controller
LdapContext ctx = new InitialLdapContext(env,null);
// Create the search controls
SearchControls searchCtls = new SearchControls();
//Specify the attributes to return
String returnedAtts[] = null;
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//Specifiy the search time limit, in this case unlimited
searchCtls.setTimeLimit(0);
//Request the LDAP Persistent Search control
Control[] rqstCtls = new Control[]{new NotifyControl()};
ctx.setRequestControls(rqstCtls);
//Now perform the search
NamingEnumeration answer = ctx.search(searchBase,searchFilter,searchCtls);
SearchResult sr;
Attributes attrs;
//Continue waiting for changes....forever
while(true) {
System.out.println("Waiting for changes..., press Ctrl C to exit");
sr = (SearchResult)answer.next();
System.out.println(">>>" + sr.getName());
//Print out the modified attributes
//instanceType and objectGUID are always returned
attrs = sr.getAttributes();
if (attrs != null) {
try {
for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("Attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll();e.hasMore();System.out.println(" " + e.next().toString()));
}
}
catch (NullPointerException e) {
System.err.println("Problem listing attributes: " + e);
}
}
}
}
catch (NamingException e) {
System.err.println("LDAP Notifications failure. " + e);
}
}
}

how to create user on windows ec2 using java

I am new to AWS, Can any one please help me how to create users on virtual machine using java code. I have created windows ec2 instance and able to connect using sshClient, but unable to create users. I dont have any idea about how it can be done.
[I am new to stack overflow please forgive me if wrong formatting]
Answering my own question... It may help someone..
You can use execute command to create user on remote windows...
Example:
public boolean executeCommands(String commands, SSHRequestParam param)
throws Exception,IOException {
boolean response = false;
try {
Connection conn = getConnection(param);
Session sess = conn.openSession();
sess.execCommand(commands);
sess.waitForCondition(ChannelCondition.EXIT_SIGNAL, 0);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(
new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
response=true;
System.out.println(line);
}
InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader br1 = new BufferedReader(new InputStreamReader(
stderr));
while (true) {
String line = br1.readLine();
if (line == null)
break;
response=false;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
System.out.println("closing session");
sess.close();
closeConnection(conn);
} catch (IOException e) {
System.out.println("Exception..while executing command.: " + commands);
e.printStackTrace();
}
System.out.println("Command executed : "+response);
return response;
}
public void createUser(String userName, String password,SSHRequestParam param)
throws Exception,IOException {
String command = "net user " +userName+" "+password+" /add" ;
if(executeCommands(command,param))
System.out.println("User created successfully");
else
System.out.println("User didn't create....");
}
In above example param variable stores the parameters to connect to the server i.e. hostname, username, password....

openid4java ConsumerManager request/thread safe?

I am using openid4java in servlets. I have two servlets - one which performs first step (redirects user to login/accept application access) and second, which processes resulting information
In the documentation, there is written, that org.openid4java.consumer.ConsumerManager class must be the same instance in both steps. Can I create singleton for that? Is it thread and request safe?
Thanks for your replies!
In the consumer servlet from official openid4java sample it seems that ConsumerManager is thread safe - they use single ConsumerManager instance for all sessions. I use it this way too and have not noticed any strange behaviour yet. But a javadoc statement about thread-safety from the developers would be great...
//Currently only working with google only
// Try this - this is all ine one..
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.jboss.web.tomcat.security.login.WebAuthentication;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
public class OpenAuth extends javax.servlet.http.HttpServlet {
final static String YAHOO_ENDPOINT = "https://me.yahoo.com";
final static String GOOGLE_ENDPOINT = "https://www.google.com/
accounts/o8/id";
//Updated version of example code from :
https://crisdev.wordpress.com/2011/03/23/openid4java-login-example/
//Add your servlet script path here - so if auth fails or
succeeds it will carry out actions - check below in doGet
public String scr="/servlets/MyServlet";
private ServletContext context;
private ConsumerManager manager;
private ConsumerManager mag;
//Code updated by Vahid Hedayati http://pro.org.uk
//Removed config init - moved post to doGet - since previous code
required it to be a post but also to include identifier as part of
url
//identifier was also the same variable used for Identifier code -
//cleaned up to make different variable and less confusion
//doGet identifer changed to openid_identifier and it also now looks
for openid_username which are the default variables returned from
openid-selector
//http://groups.google.com/group/openid4java/browse_thread/thread/
5e8f24f51f54dc2c
//After reading above post - store the manager in the session object
and failing with Yahoo authentication I changed code for the manager
//manage
public void doPost(HttpServletRequest req,HttpServletResponse
response) throws ServletException,IOException {
doGet(req, response);
}
protected void doGet(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
//New variable
String ouser=(String)req.getParameter("openid_username");
if (ouser==null) { ouser="";}
//Mage is the session value of openid_consumer_manager if it is
null it will generate it once
//And where ever manager is called within code it first returns
managers value by looking up session value
mag=(ConsumerManager)req.getSession().getAttribute("open_id_consumer_manager");
if (mag==null) {
this.manager = new ConsumerManager();
req.getSession().setAttribute("open_id_consumer_manager", manager);
}
String identify=(String)req.getParameter("openid_identifier");
if (identify==null) { identify="";}
if (!identify.equals("")) {
this.authRequest(identify,ouser, req, resp);
}else{
//If they have succeeded it will return them to welcome
//welcome looks up if NEWUSER = yes in the session value below
and if so
//scr now has the ip city/country/postcode so it finalises
user additiion by adding users ip country/city/ip as their sign up
// if not new well they are already logged in from the
relevant session values this code has put in so updats records and
returns they my accoount
//if authentication here failed or they rejected sharing their
email then login page is returned
Identifier identifier = this.verifyResponse(req);
if (identifier != null) {
resp.sendRedirect(scr+"?act=welcome");
} else {
resp.sendRedirect(scr+"?act=login");
}
}
}
// --- placing the authentication request ---
public String authRequest(String userSuppliedString,String Ouser,
HttpServletRequest httpReq, HttpServletResponse httpResp) throws
IOException {
try {
// configure the return_to URL where your application will
receive
// the authentication responses from the OpenID provider
String returnToUrl = httpReq.getRequestURL().toString();
// --- Forward proxy setup (only if needed) ---
// ProxyProperties proxyProps = new ProxyProperties();
// proxyProps.setProxyName("proxy.example.com");
// proxyProps.setProxyPort(8080);
// HttpClientFactory.setProxyProperties(proxyProps);
// perform discovery on the user-supplied identifier
//Modified - Look up manager value from session
manager = (ConsumerManager)
httpReq.getSession().getAttribute("open_id_consumer_manager");
List discoveries = manager.discover(userSuppliedString);
// attempt to associate with the OpenID provider
// and retrieve one service endpoint for authentication
DiscoveryInformation discovered =
manager.associate(discoveries);
// store the discovery information in the user's session
httpReq.getSession().setAttribute("openid-disc", discovered);
// obtain a AuthRequest message to be sent to the OpenID
provider
AuthRequest authReq = manager.authenticate(discovered,
returnToUrl);
FetchRequest fetch = FetchRequest.createFetchRequest();
if (userSuppliedString.startsWith(GOOGLE_ENDPOINT)) {
fetch.addAttribute("email", "http://axschema.org/
contact/email", true);
fetch.addAttribute("firstName", "http://axschema.org/
namePerson/first", true);
fetch.addAttribute("lastName", "http://axschema.org/
namePerson/last", true);
} else if (userSuppliedString.startsWith(YAHOO_ENDPOINT)) {
fetch.addAttribute("email", "http://axschema.org/
contact/email", true);
fetch.addAttribute("fullname", "http://axschema.org/
namePerson", true);
} else {
// works for myOpenID
fetch.addAttribute("fullname", "http://
schema.openid.net/namePerson", true);
fetch.addAttribute("email", "http://schema.openid.net/
contact/email", true);
}
httpReq.getSession().setAttribute("Ouser",Ouser);
// attach the extension to the authentication request
authReq.addExtension(fetch);
httpResp.sendRedirect(authReq.getDestinationUrl(true));
} catch (OpenIDException e) {
// present error to the user
}
return null;
}
// --- processing the authentication response ---
public Identifier verifyResponse(HttpServletRequest httpReq) {
try {
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider)
ParameterList response = new
ParameterList(httpReq.getParameterMap());
// retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation)
httpReq.getSession().getAttribute("openid-disc");
// extract the receiving URL from the HTTP request
StringBuffer receivingURL = httpReq.getRequestURL();
String queryString = httpReq.getQueryString();
if (queryString != null && queryString.length() > 0)
receivingURL.append("?").append(httpReq.getQueryString());
// verify the response; ConsumerManager needs to be the same
// (static) instance used to place the authentication request
//Modified - look up session value before running verification
result
manager = (ConsumerManager)
httpReq.getSession().getAttribute("open_id_consumer_manager");
VerificationResult verification =
manager.verify(receivingURL.toString(), response, discovered);
// examine the verification result and extract the verified
// identifier
Identifier verified = verification.getVerifiedId();
String id=verified.getIdentifier();
if (verified != null) {
AuthSuccess authSuccess = (AuthSuccess)
verification.getAuthResponse();
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse)
authSuccess.getExtension(AxMessage.OPENID_NS_AX);
List emails =
fetchResp.getAttributeValues("email");
String email = (String) emails.get(0);
////////////////////////////////////////////////////////////////////////////////
//Custom bit each person needs to implement to
interact with their application:
//Authenticate the user, send email verify if
user exists on local system
//If it does {
//
httpReq.getSession().setAttribute("USERNAME",usern);
httpReq.getSession().setAttribute("LOGGEDIN", "on");
//}else{
String firstName =
fetchResp.getAttributeValue("firstName");
String lastName =
fetchResp.getAttributeValue("lastName");
String
fullname=fetchResp.getAttributeValue("fullname");
if (fullname==null)
{fullname="";}
if (firstName==null)
{ firstName="";}
if (lastName==null) { lastName="";}
if (!fullname.equals("")) {
if (fullname.indexOf(",")>-1)
{
firstName=fullname.substring(0,fullname.indexOf(","));
lastName=fullname.substring(fullname.indexOf(","),fullname.length());
}else if (fullname.indexOf("
")>-1){
firstName=fullname.substring(0,fullname.indexOf(" "));
lastName=fullname.substring(fullname.indexOf(" "),fullname.length());
}
}
//This is username returned
from the various services that ask for a username - it is returned as
openid_username
//When using openid-selector it uses
openid_identifier and openid_username - which is what this program now
looks for
String
ouser=(String)httpReq.getSession().getValue("Ouser");
if (ouser==null) {ouser="";}
//Adduser -- pass email address and
ouser
//In Adduser class - if ouser is blank
split email from 0 to substring.indexOf("#")
// generate a random number - look up
current user - if exist add random number to end
//and add user with email and new
username
//return bac the newuser and log in
like above.
httpReq.getSession().setAttribute("NEWUSER","YES");
//
httpReq.getSession().setAttribute("USERNAME",usern);
httpReq.getSession().setAttribute("LOGGEDIN", "on");
//}
return verified; // success
}
}
} catch (OpenIDException e) {
// present error to the user
}
return null;
}

Custom webservice in Umbraco 4.5 giving odd error

We've created a custom webservice in Umbraco to add (async) files and upload them. After upload the service is called with node and file-information to add a new node to the content tree.
At first our main problem was that the service was running outside of the Umbraco context, giving strange errors with get_currentuser.
Now, we inherit the umbraco BaseWebService from the umbraco.webservices dll and we've set all acces information in the settings file; we authenticatie before doing anything else using (correct and ugly-hardcoded) administrator.
When we now execute the webservice (from the browser or anything else) we get:
at umbraco.DataLayer.SqlHelper`1.ExecuteReader(String commandText, IParameter[] parameters)
at umbraco.cms.businesslogic.CMSNode.setupNode()
at umbraco.cms.businesslogic.web.Document.setupNode()
at umbraco.cms.businesslogic.CMSNode..ctor(Int32 Id)
at umbraco.cms.businesslogic.Content..ctor(Int32 id)
at umbraco.cms.businesslogic.web.Document..ctor(Int32 id)
at FileUpload.AddDocument(String ProjectID, String NodeID, String FileName)*
Where AddDocument is our method. The node (filename w/o extension) does not exist in the tree (not anywhere, it's a new filename/node). We've cleared the recycle bin, so it's not in there either.
Are we missing something vital, does anyone has a solution?
Below is the source for the webservice;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;
using umbraco.presentation.nodeFactory;
using umbraco.cms.businesslogic.member;
using umbraco.cms;
/// <summary>
/// Summary description for FileUpload
/// </summary>
[WebService(Namespace = "http://umbraco.org/webservices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class FileUpload : umbraco.webservices.BaseWebService //System.Web.Services.WebService
{
private string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public void AddDocument(string ProjectID, string NodeID, string FileName)
{
Authenticate("***", "***");
string MimeType = GetMimeType(FileName); //"application/unknown";
// Create node
int nodeId = 1197;
string fileName = System.IO.Path.GetFileNameWithoutExtension(#"*****\Upload\" + FileName);
string secGroups = "";
//EDIT DUE TO COMMENT: Behavior remains the same though
Document node = umbraco.cms.businesslogic.web.Document.MakeNew(fileName.Replace(".", ""), new DocumentType(1049), umbraco.BusinessLogic.User.GetUser(0), nodeId);
secGroups = "Intern";
StreamWriter sw = null;
try
{
//EXCEPTION IS THROWN SOMEWHERE HERE
Document doc = NodeLevel.CreateNode(fileName, "Bestand", nodeId);
doc.getProperty("bestandsNaam").Value = fileName;
byte[] buffer = System.IO.File.ReadAllBytes(#"****\Upload\" + FileName);
int projectId = 0;
int tempid = nodeId;
//EXCEPTION IS THROWN TO THIS POINT (SEE BELOW)
try
{
Access.ProtectPage(false, doc.Id, 1103, 1103);
Access.AddMembershipRoleToDocument(doc.Id, secGroups);
}
catch (Exception ex)
{
// write to file
}
try
{
doc.Publish(umbraco.BusinessLogic.User.GetUser(0));
umbraco.library.UpdateDocumentCache(doc.Id);
umbraco.content.Instance.RefreshContentFromDatabaseAsync();
}
catch (Exception ex)
{
// write to file
}
System.IO.File.Delete(FileName);
}
catch (Exception ex)
{
// THIS EXCEPTION IS CAUGHT!!
}
}
public override umbraco.webservices.BaseWebService.Services Service
{
get { return umbraco.webservices.BaseWebService.Services.DocumentService; }
}
}
If anyone has a solution, pointer, hint or whatever; help is appreciated!!
TIA,
riffnl
We've rewritten the whole procedure (dumped all code and restart) and we've got it working now.
I think we've been messing around with the old code so much in trying to get it to work we were missing some key issues, because it functions.
Thanks for thinking along anyway!