使用C#调用P6 Primavera WebService(自建服务IntegrationAPI)

发布于:2022-11-09 ⋅ 阅读:(10) ⋅ 点赞:(0) ⋅ 评论:(0)

目录

Step 1. 自建定制P6 WebService服务

Step 2. C#调用P6定制 WebService服务 


近日应一个朋友的邀请提供c#调用p6 webservice的案例,无奈自己已很多年没碰过C#,上一个与此有关的项目还发生在中国人民抗日战争暨世界反法西斯战争胜利70周年,想想还是翻出了自己多年前用VisualStudio写的demo,由此整理出本文。

本文内容比较简单且核心内容也已包含,结合自己的理解只要简单修改即可运行 ...

PS:我当时使用的P6版本是 Primavera P6 EPPM R15.1, 非常经典的一个发行版

在使用C#调用P6 WebService前,你需要了解P6本身的一些特征

  • 从开发语言来讲, Primavera 以Java为主的Web开发体系.
  • Web Service遵守标准规范, 可以跨开发语言调用: net/Java/Pythson etc
  • Primavera用到一些Java技术体系中的开源的库/组件/框架

因为P6本身Webservicef帆布的方法及用户的特殊需求,不得不使用原生功能重新发布了定制版的服务,所以以下开发的流程或有许些不同

Step 1. 自建定制P6 WebService服务

使用IntegrationAPI JAVA 编制P6对外发布的WebService服务(PS: 业务Java工程师多年前整的一个,请忽略架构是否先进

以下是几个核心的文件内容

  • 配置config.property 
apiServerIp = 192.168.1.251
apiServerPort = 9099
username = admin
password = admin
  • 配置applicationContext.xml,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd">

	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<bean id="ws" class="com.campin.tmws.server.service.WebServiceImpl" />

	<jaxws:endpoint implementor="#ws" address="/activity">
		<!-- 配置2个服务端soap IN拦截器 -->
		<jaxws:inInterceptors>
			<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
			<bean class="com.cnpec.tmws.server.MyAuthInterceptor" />
		</jaxws:inInterceptors>
		<!-- 配置soap out拦截器 -->
		<!-- <jaxws:outInterceptors></jaxws:outInterceptors> -->
	</jaxws:endpoint>
</beans>
  •  Inteface类就不介绍,重点是重写实现 WebServiceImpl
package com.campin.tmws.server.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jws.WebService;

import org.apache.log4j.Logger;

import com.campin.tmws.server.bean.ActivityDetail;
import com.campin.tmws.server.bean.NewActivity;
import com.campin.tmws.server.bean.NewActivityCodeAssignment;
import com.campin.tmws.server.bean.NewActivityStep;
import com.campin.tmws.server.bean.NewProject;
import com.campin.tmws.server.bean.NewProjectDocument;
import com.campin.tmws.util.ReadConfigFile;
import com.primavera.common.value.ObjectId;
import com.primavera.integration.client.EnterpriseLoadManager;
import com.primavera.integration.client.RMIURL;
import com.primavera.integration.client.Session;
import com.primavera.integration.client.bo.BOIterator;
import com.primavera.integration.client.bo.object.Activity;
import com.primavera.integration.client.bo.object.ActivityCodeAssignment;
import com.primavera.integration.client.bo.object.OBS;
import com.primavera.integration.client.bo.object.Project;
import com.primavera.integration.client.bo.object.ActivityStep;
import com.primavera.integration.client.bo.object.Relationship;
import com.primavera.integration.client.bo.object.User;
import com.primavera.integration.client.bo.object.UserOBS;
import com.primavera.integration.client.bo.object.ProjectDocument;
import com.primavera.integration.common.DatabaseInstance;

/**
 * 
 * @ClassName: WebServiceImpl
 * @Description: TODO
 * @author Raining Campin Chou
 * @date 2015年11月02日
 * 
 */
@WebService(endpointInterface = "com.campin.tmws.server.service.WebServiceInterface", serviceName = "WebServiceImpl", targetNamespace = "http://tmws.campin.com/Primavera/P6/TMWS")
public class WebServiceImpl implements WebServiceInterface {

	private String uname = ""; // 链接 p6 用户名
	private String password = ""; // 链接 p6 密码
	private String apiserverip = ""; // 链接 p6服务器 ip 信息
	private int apiserverport = 0; // 链接 p6api服务端口

	static Logger logger = Logger.getLogger(WebServiceImpl.class);

	public WebServiceImpl() {
		ReadConfigFile rcf = new ReadConfigFile();
		rcf.read();
		this.uname = rcf.getUsername();
		this.password = rcf.getPassword();
		this.apiserverip = rcf.getApiserverip();
		this.apiserverport = rcf.getApiserverport();
	}


	/**
	 * @Title: getActivity 
	 * @Description: TODO
	 * @param @param activityObjectId
	 * @param @return 
	 * @return NewActivity
	 * @throws
	 */
	public NewActivity getActivity(Integer activityObjectId) {
		NewActivity nactv = new NewActivity();

		String sWhereClause = "ObjectId =" + activityObjectId;
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] actvfields = new Activity(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<Activity> actvIter = elm.loadActivities(actvfields, sWhereClause, null);

			if (actvIter.hasNext()) {
				Activity actv = actvIter.next();
				nactv.setProjectId(actv.getProjectId());
				nactv.setProjectName(actv.getProjectName());
				nactv.setWBSCode(actv.getWBSCode());
				nactv.setWBSName(actv.getWBSName());
				nactv.setObjectId(actv.getObjectId().toInteger());
				nactv.setId(actv.getId());
				nactv.setName(actv.getName());

				// 工程公司非实际完成百分比,初定定为工期完成百分比
				nactv.setPercentComplete(new DecimalFormat("######0.000").format((actv.getPhysicalPercentComplete().doubleValue())));

				if (actv.getPlannedStartDate() != null) {
					nactv.setPlannedStartDate(actv.getPlannedStartDate().toString().substring(0, 10));
				}
				if (actv.getPlannedFinishDate() != null) {
					nactv.setPlannedFinishDate(actv.getPlannedFinishDate().toString().substring(0, 10));
				}
				if (actv.getActualStartDate() != null) {
					nactv.setActualStartDate(actv.getActualStartDate().toString().substring(0, 10));
				}
				if (actv.getActualFinishDate() != null) {
					nactv.setActualFinishDate(actv.getActualFinishDate().toString().substring(0, 10));
				}
				if (actv.getRemainingEarlyStartDate() != null && actv.getRemainingEarlyFinishDate() != null) {
					nactv.setRemainDay((int) ((actv.getRemainingEarlyFinishDate().getTime() - actv.getRemainingEarlyStartDate().getTime()) / (1000 * 24 * 60 * 60)) + 1);
				} else {
					nactv.setRemainDay(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return nactv;
	}

	/**
	 * @Title: getAllActivities 
	 * @Description: TODO
	 * @param @param username
	 * @param @param key
	 * @param @param projid
	 * @param @return 
	 * @return List<NewActivity>
	 * @throws
	 */
	@SuppressWarnings("static-access")
	public List<NewActivity> getAllActivities(String username, String key, Integer projid) {
		List<NewActivity> list = new ArrayList<NewActivity>();
		/**
		 * 分多种情况组合筛选条件 1 初始化过滤作业状态和作业类型 2 过滤项目 / 项目分组 , 一次性只能过滤查看一个项目 3
		 * 过滤关键字,包括作业名称和作业代码
		 */
		String sWhereClause = "Status = 'In Progress'";
		sWhereClause += " AND Type in('Task Dependent','Resource Dependent','Start Milestone','Finish Milestone')";
		if (projid > 0) {
			sWhereClause += " AND ProjectObjectId =" + projid + " AND Status = 'In Progress'";
		} else {
			sWhereClause += " AND ProjectObjectId in(" + getProIds(username) + ")";
		}
		if (key != null) {
			if (key.length() > 0) {
				sWhereClause += " AND ( Name LIKE '%" + key + "%' OR Id LIKE '%" + key + "%')";
			}
		}
		// System.out.println("************* sWhereClause: "+sWhereClause);

		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] actvfields = new Activity(session).getAllFields();

			String sOrderBy = "ProjectName Asc and PlannedStartDate Asc";
			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<Activity> actvIter = elm.loadActivities(actvfields, sWhereClause, sOrderBy);

			while (actvIter.hasNext()) {
				NewActivity nactv = new NewActivity();
				Activity actv = actvIter.next();
				nactv.setProjectId(actv.getProjectId());
				nactv.setProjectName(actv.getProjectName());
				nactv.setWBSCode(actv.getWBSCode());
				nactv.setWBSName(actv.getWBSName());
				nactv.setObjectId(actv.getObjectId().toInteger());
				nactv.setId(actv.getId());
				nactv.setName(actv.getName());

				// 工程公司非实际完成百分比,初定定为工期完成百分比
				nactv.setPercentComplete(new DecimalFormat("######0.000").format(actv.getPercentComplete().doubleValue()));

				// nactv.setActualFinishDate(actv.getPercentComplete().doubleValue());

				if (actv.getPlannedStartDate() != null) {
					nactv.setPlannedStartDate(actv.getPlannedStartDate().toString().substring(0, 10));
				}
				if (actv.getPlannedFinishDate() != null) {
					nactv.setPlannedFinishDate(actv.getPlannedFinishDate().toString().substring(0, 10));
				}
				if (actv.getActualStartDate() != null) {
					nactv.setActualStartDate(actv.getActualStartDate().toString().substring(0, 10));
				}
				if (actv.getActualFinishDate() != null) {
					nactv.setActualFinishDate(actv.getActualFinishDate().toString().substring(0, 10));
				}
				if (actv.getRemainingEarlyStartDate() != null && actv.getRemainingEarlyFinishDate() != null) {
					nactv.setRemainDay((int) ((actv.getRemainingEarlyFinishDate().getTime() - actv.getRemainingEarlyStartDate().getTime()) / (1000 * 24 * 60 * 60)) + 1);
				} else {
					nactv.setRemainDay(0);
				}

				list.add(nactv);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return list;
	}


	/**
	 * @Title: getAllActivitySizeByFilter 
	 * @Description: TODO
	 * @param @param username
	 * @param @param key
	 * @param @param projid
	 * @param @return 
	 * @return int
	 * @throws
	 */
	// 仅限过滤查询时判断总数目用
	private int getAllActivitySizeByFilter(String username, String key, Integer projid) {
		int actvlen = 0;
		String sWhereClause = "Status = 'In Progress'";
		sWhereClause += " AND Type in('Task Dependent','Resource Dependent','Start Milestone','Finish Milestone')";
		if (projid > 0) {
			sWhereClause += " AND ProjectObjectId =" + projid;
		} else {
			sWhereClause += " AND ProjectObjectId in(" + getProIds(username) + ")";
		}
		if (key != null) {
			if (key.length() > 0) {
				sWhereClause += " AND ( Name LIKE '%" + key + "%' OR Id LIKE '%" + key + "%')";
			}
		}
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] actvfields = new Activity(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<Activity> actvIter = elm.loadActivities(actvfields, sWhereClause, null);

			actvlen = actvIter.getAll().length;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return actvlen;
	}

	/**
	 * (Not Javadoc) 
	 * <p>Title: getActivitySize</p> 
	 * <p>Description: </p> 
	 * @param username
	 * @return 
	 * @see com.campin.tmws.server.service.WebServiceInterface#getActivitySize(java.lang.String)
	 */
	@Override
	public int getActivitySize(String username) {
		int result = -2;
		String sWhereClause = "Name = '" + username + "'";
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] userfields = new User(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			// 检验P6系统是否存在该帐号
			BOIterator<User> userIter = elm.loadUsers(userfields, sWhereClause, null);

			if (userIter.hasNext()) {
				result = -1;
			}
			if (result == -1) {
				if (getUserOBSIds(username).length() > 0) {
					result = getAllActivitySize(username);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return result;
	}


	/**
	 * <p>Title: getActivities</p> 
	 * <p>Description: </p> 
	 * @param username
	 * @param pageIndex
	 * @param pageSize
	 * @return 
	 * @see com.campin.tmws.server.service.WebServiceInterface#getActivities(java.lang.String, int, int)
	 */
	@Override
	public List<NewActivity> getActivities(String username, int pageIndex, int pageSize) {
		int size = getAllActivitySize(username);
		// 当总页数末尾值大于 实际值时,作业罗列到实际值
		if (size < pageSize * pageIndex) {
			return getAllActivities(username, null, 0).subList(pageSize * (pageIndex - 1), size);
		}
		return getAllActivities(username, null, 0).subList(pageSize * (pageIndex - 1), pageSize * pageIndex);
	}

//	@Override
	public List<NewActivity> getActivitiesByFilter(String username, String key, Integer projid, int pageIndex, int pageSize) {
		int size = getAllActivitySizeByFilter(username, key, projid);
		// 当总页数末尾值大于 实际值时,作业罗列到实际值
		if (size < pageSize * pageIndex) {
			return getAllActivities(username, key, projid).subList(pageSize * (pageIndex - 1), size);
		}
		return getAllActivities(username, key, projid).subList(pageSize * (pageIndex - 1), pageSize * pageIndex);
	}

	/**
	 * (Not Javadoc) 
	 * <p>Title: getActivityDetail</p> 
	 * <p>Description: </p> 
	 * @param activityObjectId
	 * @return 
	 * @see com.campin.tmws.server.service.WebServiceInterface#getActivityDetail(java.lang.Integer)
	 */
	@Override
	public ActivityDetail getActivityDetail(Integer activityObjectId) {
		ActivityDetail ad = new ActivityDetail();
		ad.setActivity(getActivity(activityObjectId));
		ad.setActvCodeAssSize(getActivityCodeAssignment(activityObjectId).size());
		// ad.setActvCodeAss(getActivityCodeAssignment(activityObjectId));

		ad.setDocSize(getActivityDocument(activityObjectId).size());
		// ad.setDocs(getProjectDocument(activityObjectId));

		ad.setStepSize(getActivityStep(activityObjectId).size());
		// ad.setSteps(getActivityStep(activityObjectId));

		ad.setPredecessorsSize(getActivityPredecessors(activityObjectId).size());
		// ad.setPredecessors(getActivityPredecessors(activityObjectId));

		ad.setSuccessorsSize(getActivitySuccessors(activityObjectId).size());
		// ad.setSuccessors(getActivitySuccessors(activityObjectId));
		return ad;
	}

	/**
	 * (Not Javadoc) 
	 * <p>Title: getActivityCodeAssignment</p> 
	 * <p>Description: </p> 
	 * @param activityObjectId
	 * @return 
	 * @see com.campin.tmws.server.service.WebServiceInterface#getActivityCodeAssignment(java.lang.Integer)
	 */
	@Override
	public List<NewActivityCodeAssignment> getActivityCodeAssignment(Integer activityObjectId) {
		List<NewActivityCodeAssignment> list = new ArrayList<NewActivityCodeAssignment>();

		String sWhereClause = "ActivityObjectId = " + activityObjectId;
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] Assfields = new ActivityCodeAssignment(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<ActivityCodeAssignment> assIter = elm.loadActivityCodeAssignments(Assfields, sWhereClause, null);

			while (assIter.hasNext()) {
				NewActivityCodeAssignment nass = new NewActivityCodeAssignment();
				ActivityCodeAssignment ass = assIter.next();
				nass.setActivityObjectId(activityObjectId);
				nass.setActivityCodeTypeName(ass.getActivityName());
				nass.setActivityCodeValue(ass.getActivityCodeValue());
				nass.setActivityCodeTypeName(ass.getActivityCodeTypeName());
				nass.setActivityCodeDescription(ass.getActivityCodeDescription());

				list.add(nass);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return list;
	}

	/**
	 * (Not Javadoc) 
	 * <p>Title: getActivityStep</p> 
	 * <p>Description: </p> 
	 * @param activityObjectId
	 * @return 
	 * @see com.campin.tmws.server.service.WebServiceInterface#getActivityStep(java.lang.Integer)
	 */
	@Override
	public List<NewActivityStep> getActivityStep(Integer activityObjectId) {
		List<NewActivityStep> list = new ArrayList<NewActivityStep>();
		// 传入条件查询参数
		String sWhereClause = "ActivityObjectId = " + activityObjectId;
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] stepfields = new ActivityStep(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<ActivityStep> stepIter = elm.loadActivitySteps(stepfields, sWhereClause, null);

			while (stepIter.hasNext()) {
				NewActivityStep nstep = new NewActivityStep();
				ActivityStep step = stepIter.next();
				nstep.setActivityObjectId(activityObjectId);
				nstep.setActivityName(step.getActivityName());
				nstep.setName(step.getName());
				nstep.setWeight(step.getWeight());
				nstep.setWeightPercent(step.getWeightPercent().doubleValue());
				nstep.setPercentComplete(step.getPercentComplete().doubleValue());

				list.add(nstep);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return list;
	}

	/**
	 * (Not Javadoc) 
	 * <p>Title: getActivityDocument</p> 
	 * <p>Description: </p> 
	 * @param activityObjectId
	 * @return 
	 * @see com.campin.tmws.server.service.WebServiceInterface#getActivityDocument(java.lang.Integer)
	 */
	@Override
	public List<NewProjectDocument> getActivityDocument(Integer activityObjectId) {
		List<NewProjectDocument> list = new ArrayList<NewProjectDocument>();
		String sWhereClause = "ActivityObjectId = " + activityObjectId;
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] docfields = new ProjectDocument(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<ProjectDocument> stepIter = elm.loadProjectDocuments(docfields, sWhereClause, null);

			while (stepIter.hasNext()) {
				NewProjectDocument ndoc = new NewProjectDocument();
				ProjectDocument doc = stepIter.next();
				ndoc.setActivityObjectId(activityObjectId);
				ndoc.setActivityName(doc.getActivityName());
				ndoc.setObjectId(doc.getObjectId().toInteger());
				ndoc.setDocumentTitle(doc.getDocumentTitle());

				list.add(ndoc);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}

		return list;
	}

	/**
	 * @Title: getUserOBSIds 
	 * @Description: TODO
	 * @param @param username
	 * @param @return 
	 * @return String
	 * @throws
	 */
	@SuppressWarnings("static-access")
	private String getUserOBSIds(String username) {
		// 传入条件查询参数
		String sWhereClause = "UserName ='" + username + "' ", ids = "";
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] userOBSfields = new UserOBS(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<UserOBS> userOBSIter = elm.loadUserOBS(userOBSfields, sWhereClause, null);

			while (userOBSIter.hasNext()) {
				UserOBS ub = userOBSIter.next();
				ids += ub.getOBSObjectId() + ",";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}

		if (ids.length() > 0) {
			ids = ids.substring(0, ids.length() - 1);
		}
		return ids;
	}

	/**
	 * @Title: getOBSChirdren 
	 * @Description: TODO
	 * @param @param username
	 * @param @return 
	 * @return String
	 * @throws
	 */
	public String getOBSChirdren(String username) {
		String ids = getUserOBSIds(username);
		String sWhereClause = "ParentObjectId in(" + ids + ")";
		ids += ",";
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] obsfields = new OBS(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<OBS> ot1 = elm.loadOBS(obsfields, sWhereClause, null);
			OBS o1 = null;
			while (ot1.hasNext()) {
				o1 = ot1.next();
				ids += o1.getObjectId() + ",";

				// 第二次子节点
				BOIterator<OBS> ot2 = o1.loadOBSChildren(new String[] { "ObjectId", "Name" }, null, null);
				while (ot2.hasNext()) {
					OBS o2 = ot2.next();
					ids += o2.getObjectId() + ",";

					// 第三次子节点
					BOIterator<OBS> ot3 = o2.loadOBSChildren(obsfields, null, null);
					while (ot3.hasNext()) {
						OBS o3 = ot3.next();
						ids += o3.getObjectId() + ",";

						// 第四次子节点
						BOIterator<OBS> ot4 = o3.loadOBSChildren(obsfields, null, null);
						while (ot4.hasNext()) {
							OBS o4 = ot4.next();
							ids += o4.getObjectId() + ",";

							// 第五次子节点
							BOIterator<OBS> ot5 = o4.loadOBSChildren(obsfields, null, null);
							while (ot5.hasNext()) {
								OBS o5 = ot5.next();
								ids += o5.getObjectId() + ",";

								// 第六次子节点
								BOIterator<OBS> ot6 = o5.loadOBSChildren(obsfields, null, null);
								while (ot6.hasNext()) {
									OBS o6 = ot6.next();
									ids += o6.getObjectId() + ",";

									// 第七次子节点
									BOIterator<OBS> ot7 = o6.loadOBSChildren(obsfields, null, null);
									while (ot7.hasNext()) {
										OBS o7 = ot7.next();
										ids += o7.getObjectId() + ",";
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return ids = ids.substring(0, ids.length() - 1);
	}

	@SuppressWarnings("static-access")
	public String getProIds(String username) {
		// 传入条件查询参数
		String sWhereClause = "OBSObjectId in(" + getOBSChirdren(username) + ")", pids = "";
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] projfields = new Project(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<Project> projIter = elm.loadProjects(projfields, sWhereClause, null);

			while (projIter.hasNext()) {
				pids += projIter.next().getObjectId() + ",";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}

		return pids.substring(0, pids.length() - 1);
	}

	/**
	 * @Title: getProjectList 
	 * @Description: TODO
	 * @param @param username
	 * @param @return 
	 * @return List<NewProject>
	 * @throws
	 */
	public List<NewProject> getProjectList(String username) {
		List<NewProject> list = new ArrayList<NewProject>();
		String sWhereClause = "OBSObjectId in(" + getOBSChirdren(username) + ")";
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] projfields = new Project(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			BOIterator<Project> projIter = elm.loadProjects(projfields, sWhereClause, null);

			while (projIter.hasNext()) {
				Project p = projIter.next();
				NewProject np = new NewProject();
				np.setObjectid(p.getObjectId().toInteger());
				np.setId(p.getId());
				np.setName(p.getName());

				list.add(np);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}

		return list;
	}

	/**
	 * @Title: getActivityPredecessors 
	 * @Description: TODO
	 * @param @param activityObjectId
	 * @param @return 
	 * @return List<NewActivity>
	 * @throws
	 */
	public List<NewActivity> getActivityPredecessors(Integer activityObjectId) {
		List<NewActivity> list = new ArrayList<NewActivity>();
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] rsfields = new Relationship(session).getAllFields();

			BOIterator<Relationship> rsIter = new Activity(session, new ObjectId(activityObjectId)).loadPredecessorRelationships(rsfields,
					null, null);

			while (rsIter.hasNext()) {
				Relationship re = rsIter.next();
				NewActivity nactv = new NewActivity();
				nactv.setObjectId(re.getPredecessorActivityObjectId().toInteger());
				nactv.setId(re.getPredecessorActivityId());
				nactv.setName(re.getPredecessorActivityName());
				nactv.setProjectId(re.getPredecessorProjectId());
				nactv.setWBSName(re.getPredecessorWbsName());

				list.add(nactv);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return list;
	}

	/**
	 * @Title: userValidate 
	 * @Description: TODO
	 * @param @param username
	 * @param @return 
	 * @return int
	 * @throws
	 */
	private int userValidate(String username) {
		int result = -1;
		String sWhereClause = "Name = '" + username + "'";
		Session session = null;
		try {
			DatabaseInstance[] dbInstances = Session.getDatabaseInstances(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip,
					apiserverport));
			session = Session.login(RMIURL.getRmiUrl(RMIURL.STANDARD_RMI_SERVICE, apiserverip, apiserverport),
					dbInstances[0].getDatabaseId(), uname, password);
			String[] userfields = new User(session).getAllFields();

			EnterpriseLoadManager elm = session.getEnterpriseLoadManager();
			// 检验P6系统是否存在该帐号
			BOIterator<User> userIter = elm.loadUsers(userfields, sWhereClause, null);

			while (userIter.hasNext()) {
				result = 0;
			}
			if (result == 0) {
				if (getUserOBSIds(username).length() > 0) {
					result = 1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null)
				session.logout();
		}
		return result;
	}
}

以上完成编程后,最终发布定制服务如下,这里WebService用的是传统的SOAP协议

 

Step 2. C#调用P6定制 WebService服务 

以上定制服务顺利发布之后,后续的操作就简单多了,打开VisualStudio直接新建项目

直接引用接口方法

用C语言输出要显示的内容即可

using wsdemo.P6EPSWBSWebService;
using wsdemo.P6ProjectWebService;
using wsdemo.P6ActivityService;

namespace wsdemo
{
    public partial class epsdemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            // 测试方法1(demo),根据项目代码获取项目名称
            EPSWBSWebService epsService = new EPSWBSWebService();
            Response.Write(epsService.demo("CS-Plan") + "<br/>");
            P6EPSWBSWebService.NewEPS[] epss = epsService.loadEPS("kping");
            for (int i = 0; i < epss.Length; i++)
            {
                Response.Write(" --------------- <br/>");
                Response.Write(" | EPS编号:" + epss[i].objectId);
                Response.Write(" | EPS编码:" + epss[i].id);
                Response.Write(" | EPS名称:" + epss[i].name);
            }

             测试方法2(loadProjectByUser),根据用户登录名查询其所能看到的project
            //ProjectWebService projservice = new ProjectWebService();
            //P6ProjectWebService.NewProject[] projs = projservice.loadProjectByUser("kping");
            //for (int i = 0; i < projs.Length; i++)
            //{
            //    Response.Write(" 项目加载测试--------------- <br/>");
            //    Response.Write(" | 项目编号:" + projs[i].objectId);
            //    Response.Write(" | 项目编码:" + projs[i].id);
            //    Response.Write(" | 项目名称:" + projs[i].name);
            //}

             测试方法3(loadAllActivities),根据查询某项目下所有作业信息
            //ActivityWebService actvservice = new ActivityWebService();
            //NewActivity[] actvs = actvservice.loadAllActivities(null, null, 644, true);
            //for (int i = 0; i < actvs.Length; i++) {
            //    Response.Write(" 项目加载测试--------------- <br/>");
            //    Response.Write(" | 作业编号:" + actvs[i].objectId);
            //    Response.Write(" | 作业编码:" + actvs[i].id);
            //    Response.Write(" | 作业名称:" + actvs[i].name);
            //    Response.Write(" | 作业计划开始:" + actvs[i].plannedStartDate);
            //    Response.Write(" | 作业计划完成:" + actvs[i].plannedFinishDate);
            //    Response.Write(" | 作业WBS编号:" + actvs[i].WBSObjectId);
            //    Response.Write(" | 作业项目编号:" + actvs[i].projectObjectId);
            //}

             测试方法4(updateActivity),修改作业信息
            //NewActivityDetail a1 = actvservice.getActivityDetail(51992, true);
            //a1.activity.name = "ABCDEFGG";
            //a1.activity.plannedStartDate = "2016-03-10";
            //Response.Write("name2: " + a1.activity.name);
            //actvservice.updateActivity(a1.activity);

             测试方法5(addActivityDirect),增加作业信息
            //NewActivity new1 = new NewActivity();
            //new1.objectId = 160322003;;
            //new1.WBSObjectId = 11391;
            //new1.name = "测试号";
            //new1.id = "AX001002004";
            //new1.name = "测试作业名称2";
            //new1.plannedStartDate = "2016-01-01";
            //new1.plannedFinishDate = "2016-01-06";
            //new1.actualStartDate = "2016-01-02";
            //actvservice.addActivityDirect(new1);
        }
    }
}

以上代码运行即可打印出所连接P6的所有项目名称信息

PS:笔者非专职程序员,以上案例项目源码考虑特殊原因无法提供

还是那句话,这个行业的分享不多,希望更多感兴趣的朋友一同参与,探讨或合作 !

本人可提供Oracle 多种产品技术服务,包括产品的部署和维护及培训,欢迎与我取得联系!

如何联系蚕豆哥_蚕豆哥的博客-CSDN博客https://campin.blog.csdn.net/article/details/52950969