Data extraction from XML
Microsoft JS Grid task insertion snippets – template management
...
document.write('<div id="panel" style="display: none;">\
<div id="dialog" title="Выбор договоров">\
<p id="dialog_info"></p>\
<p>\
<select id="contract_selection" multiple="multiple"></select></p>\
</div>\
<div id="template_dialog" title="Выбор шаблона">\
<p id="template_dialog_info"></p>\
<p>\
<select id="template_selection" multiple="multiple"></select></p>\
</div>\
</div>');
$(function() {
if ((getURLParameter("projuid") == null) || (getURLParameter("projuid") == "null")) return;
$("#dialog").dialog({
autoOpen: false
});
$("#template_dialog").dialog({
autoOpen: false
});
$("button").button();
});
…….
var afterInsertRecordFunction = null;
function insertAndFixRecord(afterInsertCall) {
if (afterInsertRecordFunction != null) PJAlert("Вставка новой задачи возможна только после завершения процесса вставки", "Вставка новой задачи");
afterInsertRecordFunction = function(recordKey) {
afterInsertCall(recordKey);
afterInsertRecordFunction = null;
};;
if (_grid.IsEntryRecordKey(_grid.GetFocusedItem().recordKey)) {
_satellite.SetTaskModeAuto();
//trigger updates
_grid.SelectRowRange(_grid.GetTopRowIndex(), _grid.GetTopRowIndex(), false);
} else
_satellite.NewTask();
}
function checkODataExists() {
if (window.OData == null) {
PJAlert("Не загружена библиотека работы с OData");
return false;
};
return true;
};
function getContracts(retFunc) {
if (!checkODataExists()) return;
OData.read(CONTRACTS_SYSTEM_URL + "/ContractsSystemData.svc/contracts?$filter=((project_uid ne null) and (project_uid eq guid'" + PROJECT_UID + "'))", retFunc, ODataErrHandler);
}
function selectContracts(cellText) {
$("#contract_selection").empty();
$("#contract_selection").css("width", "420");
$("#contract_selection").css("height", "350");
$("#dialog").dialog("option", "modal", true);
$("#dialog_info").text("Загрузка списка договоров проекта...");
$("#dialog").dialog({
width: 450,
height: "auto",
buttons: [{
text: "OK",
click: function() {
contractsSelected();
}
}]
});
$("#dialog").dialog("open");
getContracts(function(data) {
data.results.sort(function(a, b) {
return (a.contract_number > b.contract_number) ? 1 : -1;
});
$.each(data.results, function(l, d) {
$("#contract_selection option:selected")
$("#contract_selection").append($('<option value="' + d.id_contract + '"" ' +
((cellText == null) ? '' :
((cellText.indexOf('(' + d.id_contract + ')') >= 0) ? 'selected' : '')) +
'>' + d.contract_number + '</option>'));
});
$("#dialog_info").text("Для связи работы с договорами выберите договоры");
}, function(err) {
PJAlert(err.message, "Ошибка обращения к системе договоров");
});
}….
function contractsSelected() {
_tableCache.GetRecordsByKey([current_grid_action_context.recordKey], function(keys, data) {
var newVal;
$("#contract_selection option:selected").each(function(k, d) {
newVal = appendValueToContractsString(d.value, d.text, newVal);
});
setContractValue(data[0], newVal);
});
};
function setContractValue(record, newVal) {
if (!_grid.IsCellEditable(record, CONTRACT_FIELD_UID))
return;
var propUpdates = [];
propUpdates.push(SP.JsGrid.CreateUnvalidatedPropertyUpdate(record.recordKey, CONTRACT_FIELD_UID, newVal, false));
_grid.UpdateProperties(propUpdates);
}
…
propUpdates.push(SP.JsGrid.CreateUnvalidatedPropertyUpdate(rc, "TASK_DUR", parseFloat(d.TaskDuration) * 60 * 10, false));
propUpdates.push(SP.JsGrid.CreateUnvalidatedPropertyUpdate(rc, TASK_TYPE_FIELD_UID, d["Тип_задачи"], false));
propUpdates.push(SP.JsGrid.CreateUnvalidatedPropertyUpdate(rc, STAGES_TASK_FIELD_UID, d["Этапы_реализации"], false));
propUpdates.push(SP.JsGrid.CreateUnvalidatedPropertyUpdate(rc, "TASK_IS_MILESTONE", d.TaskIsMilestone, false));…
try {
_grid.UpdateProperties(propUpdates);
finishInsertTemplate();
} catch (err) {
PJAlert("Произошла ошибка при обновлении одного из полей: веха, тип задачи, длительность задачи, предшественники:" + err,
"Вставка блока работ шаблона",
false,
closeTemplateInsertDiaog
);
};
…
function finishInsertTemplate() {
_satellite.DeleteTasks([RecordKeyToDeleteAfterInsert]);
_grid.FinalizeEditing(function() {
_satellite.Schedule();
currentTemplateInfo.insertToRecord = null;
_grid.ScrollCellIntoView(_tableCache.KeyToRecordIdx(_grid.GetFocusedItem().recordKey), 1);
closeTemplateInsertDiaog();
}, function() {
PJAlert('Ошибка завершениия изменений', 'Вставка шаблона');
closeTemplateInsertDiaog();
})
}…
function ODataErrHandler(err) {
var errStr;
try {
errStr = JSON.parse(err.response.body)["odata.error"].message.value;
} catch (err_parse) {
errStr = err.response.body;
}
PJAlert(errStr, "Ошибка обращения к системе договоров");
}
function getProjectTasks(retFunc, projectUID) {
if (!checkODataExists()) return;
OData.read(CONTRACTS_SYSTEM_URL + "/ContractsSystemData.svc/MSP_EpmTask_UserViewAlls?$filter=((ProjectUID ne null) and (ProjectUID eq guid'" + projectUID + "'))",
retFunc,
ODataErrHandler
);
}
function getTemplates(retFunc) {
if (!checkODataExists()) return;
OData.read(CONTRACTS_SYSTEM_URL + "/ContractsSystemData.svc/MSP_EpmProject_UserViews?$filter=((EnterpriseProjectTypeUID ne null) and (EnterpriseProjectTypeUID eq guid'" + EPT_TEMPLATE_UID + "'))", retFunc,
ODataErrHandler);
}
ProjectCenterExtension.prototype.selectTemplate = function() {
_diffTracker = _grid.GetDiffTracker();
_diffs = _diffTracker.GetUniquePropertyChanges();
if (_grid.GetFocusedItem() == null) {
PJAlert("Для вставки шаблона выберите место для ставки", "Вставка шаблона");
return;
}
if (!(_grid.IsCellEditable(cur_rec, "TASK_NAME") || _grid.IsEntryRecordKey(_grid.GetFocusedItem().recordKey))) {
PJAlert("Для вставки шаблона откройте проект в режиме редактирования", "Вставка шаблона");
return;
}
$("#template_selection").empty();
$("#template_selection").css("width", "820");
$("#template_selection").css("height", "350");
…
$("#template_selection").dblclick(function() {
handleInsertTemplateAfterSelection();
});
$("#template_dialog").dialog("option", "modal", true);
$("#template_dialog_info").text("Загрузка списка шаблонов...");
$("#template_dialog").dialog({
width: 880,
height: "auto",
closeText: "Отменить",
buttons: [{
text: "OK",
click: handleInsertTemplateAfterSelection
}]
});
$("#template_dialog").dialog("open");
getTemplates(function(data) {
data.results.sort(function(a, b) {
return (a.ProjectName > b.ProjectName) ? 1 : -1;
});
$.each(data.results, function(l, d) {
$("#template_selection").append($('<option value="' + d.ProjectUID + '"" ' +
' ' + (l == 0 ? 'selected' : '') + '>' + d.ProjectName + '</option>'));
});
$("#template_dialog_info").text("Для вставки блока работ выберите шаблон");
});
}
…
prevDelegate = _grid.GetDelegate(SP.JsGrid.DelegateType.GetRecordEditMode);
_grid.SetDelegate(SP.JsGrid.DelegateType.GetRecordEditMode, SetRecordEditMode);
existingValidationFunc = PJ.RemoteTextConv.GetPostprocessor(PJ.ConversionType.StartDate);
PJ.RemoteTextConv.RegisterPostprocessor(PJ.ConversionType.StartDate, CustomPostProcessor);
_grid.AttachEvent(SP.JsGrid.EventType.OnRowFocusChanged, RowChanged);
_grid.AttachEvent(SP.JsGrid.EventType.OnCellEditCompleted, CellEditCompleted);
_grid.AttachEvent(SP.JsGrid.EventType.OnPropertyChanged, PropertyChanged);
_grid.AttachEvent(SP.JsGrid.EventType.OnRightClick, RightClick);
_grid.AttachEvent(SP.JsGrid.EventType.OnDoubleClick, DoubleClick);
_grid.AttachEvent(SP.JsGrid.EventType.OnCellEditBegin, CellEditBegin);
_grid.AttachEvent(SP.JsGrid.EventType.OnCellFocusChanged, CellFocusChanged);
_grid.AttachEvent(SP.JsGrid.EventType.OnSingleCellClick, SingleCellClick);
_grid.AttachEvent(SP.JsGrid.EventType.OnRecordInserted, RecordInserted);
...
Project Server Interface (web services) via PowerShell Scripts
#t-sql launch
#xp_cmdshell 'powershell.exe -ExecutionPolicy bypass -Command "& {& ''\\T005\Exchange\publishprojects.ps1''}"'
function AddDeletePublish($descr)
{
$ProjDataSet.Clear();
$projectTasks = $ProjDataSet.Task;
#add task
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("QueueAddToProject $descr ...");
$NewTaskGuid = [System.Guid]::NewGuid()
$NewTaskRow1 = $projectTasks.NewTaskRow();
$NewTaskRow1.PROJ_UID = $projectUid;
$NewTaskRow1.TASK_UID = $NewTaskGuid
$NewTaskRow1.TASK_DUR_FMT = 53;
$NewTaskRow1.TASK_DUR = 4800;
$NewTaskRow1.TASK_NAME = "temp task";
$NewTaskRow1.TASK_START_DATE = [datetime]::Now;
$projectTasks.AddTaskRow($NewTaskRow1);
$NewJobGuid = [system.guid]::NewGuid()
# Add the above dataset to project and publish and check in
$svcPSProxy.QueueAddToProject($NewJobGuid, $SessionGuid, $ProjDataSet, $false);
sleep 1
WaitForJob($NewJobGuid);
# publish project
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("QueuePublish $descr ...");
$NewJobGuid = [system.guid]::NewGuid()
$temp = $svcPSProxy.QueuePublish($NewJobGuid, $projectUid, $true,"");
WaitForJob($NewJobGuid);
};
function PublishWithCFupdates($pwaUrl,[System.Guid]$puid)
{
#http://social.msdn.microsoft.com/Forums/en-US/5c9dc24a-62d3-4ce4-a575-4abf918da610/how-to-create-task-in-pwa-with-powershell?forum=project2010custprog
cls
$t = get-date
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
write-host -ForegroundColor green "connecting to services.."
$PSvcUrl = $pwaUrl + "/_vti_bin/PSI/Project.asmx?wsdl"
$svcPSProxy = New-WebServiceProxy -uri $PSvcUrl -useDefaultCredential;
#Queue web service
$QSvcUrl = $pwaUrl + "/_vti_bin/PSI/QueueSystem.asmx?wsdl"
$QSvcProxy = New-WebServiceProxy -uri $QSvcUrl -useDefaultCredential; #-credential $Credential
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("read projects");
$EPMTYGUID = [system.guid]::empty
$ProjectList = $svcPSProxy.ReadProjectStatus("$EPMTYGUID","WorkingStore","", "0").Project | format-table proj_uid -hidetableheaders | out-string -stream
if($puid){$projectList = @($puid)}
$projects_left_to_process = $ProjectList.Count;
foreach ($projectUid in $ProjectList)
{
Write-Host -ForegroundColor green ("projects to process left $projects_left_to_process");
$projects_left_to_process = $projects_left_to_process - 1;
if ($projectUid -eq ""){continue;}
Write-Host -ForegroundColor green ("processing project $projectUid");
$projectUid=[System.Guid]$projectUid;
$SessionGuid = [System.Guid]::NewGuid() ;
$SessionDescr = "refresh calculations" ;
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("force checkin project...");
$NewJobGuid = [system.guid]::NewGuid();
$temp = $svcPSProxy.QueueCheckInProject($NewJobGuid, $projectUid, $true, $SessionGuid, $SessionDescr);
sleep 1
WaitForJob($NewJobGuid);
$G = [System.Guid]::NewGuid()
$temp = $svcPSProxy.CheckOutProject($projectUid, $SessionGuid, $SessionDescr);
sleep 1
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("ReadProject...");
$ProjDataSet = $svcPSProxy.ReadProjectEntities($projectUid,2,0);
AddDeletePublish("1");
AddDeletePublish("2");
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("ReadProject...");
$ProjDataSet = $svcPSProxy.ReadProjectEntities($projectUid,2,0);
$tr = @();
foreach($task in $ProjDataSet.Task)
{
if($task.TASK_NAME -eq "temp task")
{
$tr+=$task.TASK_UID;
};
};
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("QueueDeleteFromProject $descr ...");
$NewJobGuid = [system.guid]::NewGuid()
$svcPSProxy.QueueDeleteFromProject($NewJobGuid, $SessionGuid, $projectUid,$tr);
sleep 1
WaitForJob($NewJobGuid);
# publish project
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("QueuePublish after del ...");
$NewJobGuid = [system.guid]::NewGuid()
$temp = $svcPSProxy.QueuePublish($NewJobGuid, $projectUid, $true,"");
WaitForJob($NewJobGuid);
# check in project
sleep 1
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("QueueCheckInProject ...");
$NewJobGuid = [system.guid]::NewGuid()
$temp = $svcPSProxy.QueueCheckInProject($NewJobGuid, $projectUid, $false, $SessionGuid, $SessionDescr);
WaitForJob($NewJobGuid);
}
write-host -ForegroundColor green "$((New-TimeSpan $t $(Get-Date)).TotalSeconds) sec";$t = get-date;
Write-Host -ForegroundColor green ("done. thank you." );
}
function WaitForJob([System.Guid]$jobId)
{
$QUEUE_WAIT_TIME = 2; # two seconds
$jobDone = $false;
$xmlError = [string]::Empty;
$wait = 0;
# Wait for the project to get through the queue.
# Get the estimated wait time in seconds.
# $wait = $QSvcProxy.GetJobWaitTime($jobId);
# Wait for it.
sleep $wait;
# Wait until it is finished.
do
{
# Get the job state.
$jobState = $QSvcProxy.GetJobCompletionState($jobId,[ref]$xmlError);
Write-Host -ForegroundColor green ("job state: $jobState");
if ($jobState -eq "Success")
{
$jobDone = $true;
}
else
{
if (($jobState -eq "Unknown") -or ($jobState -eq "Failed")-or ($jobState -eq "FailedNotBlocking")-or ($jobState -eq "CorrelationBlocked")-or ($jobState -eq "Canceled"))
{
# If the job failed, error out.
Write-Host -ForegroundColor red ("failed");
break;
# Console.WriteLine("Queue request failed \"" + jobState + "\" Job ID: " + jobId + ".");
# throw new Exception("Queue request failed \"" + jobState + "\" Job ID: " + jobId + ".");
}
else
{
#Console.WriteLine("Job State: " + jobState + " Job ID: " + jobId);
$cvt = $QUEUE_WAIT_TIME;
Write-Host -ForegroundColor green ("waiting $cvt ..." );
sleep $cvt ;
}
}
}
while ($jobDone -eq $false);
}
PublishWithCFupdates "http://project.contoso.com/pwa" $args[0]
#PublishWithCFupdates("http://project.contoso.com/pwa")