Project Server 2013 : How to Change Project owner Using PSI - ms-project

I need to update the project owner using PSI, since i need to make it an automatic process.
I have the following sets of codes for changing the project owner but both of them have not worked.
Following is the first way which i have already tried
private static bool UpdateProjectOwner()
{
bool projUpdated = false;
try
{
User newOwner = projContext.Web.SiteUsers.GetByLoginName(Username);
Guid ProjectGuid = ProjectUID;
//Console.Write("\nUpdating owner to {1} on project: {0} ...," ProjectGuid, Username);
DraftProject draftProjectToUpdate = projContext.Projects.GetByGuid(ProjectGuid).CheckOut();
draftProjectToUpdate.Owner = newOwner;
QueueJob qJob = draftProjectToUpdate.Update();
projContext.Load(qJob);
projContext.ExecuteQuery();
JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds);
QueueJob qJob2 = draftProjectToUpdate.CheckIn(false);
projContext.Load(qJob2);
projContext.ExecuteQuery();
JobState jobState2 = projContext.WaitForQueue(qJob2, timeoutSeconds);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
return projUpdated;
}
Following is the second way which i have already tried
String projectOwnerIDstrNew = Convert.ToString(dr["ProjectOwnerUID"]);
String projectOwnerIDstrOriginal = Convert.ToString(project_Ds.Project[0].ProjectOwnerID);
if (!projectOwnerIDstrNew.Equals(projectOwnerIDstrOriginal))
{
Guid ownerID = new Guid(projectOwnerIDstrNew);
project_Ds.Project[0].ProjectOwnerID = ownerID;
project_Ds.AcceptChanges();
bool managerChanged = true;
}
Is there any mistake in these above functions ?
If Not, then is there any other way of updating the project owner with help of PSI.

Following is the first way which i have already tried
private static bool UpdateProjectOwner()
{
bool projUpdated = false;
try
{
User newOwner = projContext.Web.SiteUsers.GetByLoginName(Username);
Guid ProjectGuid = ProjectUID;
//Console.Write("\nUpdating owner to {1} on project: {0} ...," ProjectGuid, Username);
DraftProject draftProjectToUpdate = projContext.Projects.GetByGuid(ProjectGuid).CheckOut();
draftProjectToUpdate.Owner = newOwner;
QueueJob qJob = draftProjectToUpdate.Update();
projContext.Load(qJob);
projContext.ExecuteQuery();
JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds);
QueueJob qJob2 = draftProjectToUpdate.CheckIn(false);
projContext.Load(qJob2);
projContext.ExecuteQuery();
JobState jobState2 = projContext.WaitForQueue(qJob2, timeoutSeconds);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
return projUpdated;
}
Following is the second way which i have already tried
String projectOwnerIDstrNew = Convert.ToString(dr["ProjectOwnerUID"]);
String projectOwnerIDstrOriginal = Convert.ToString(project_Ds.Project[0].ProjectOwnerID);
if (!projectOwnerIDstrNew.Equals(projectOwnerIDstrOriginal))
{
Guid ownerID = new Guid(projectOwnerIDstrNew);
project_Ds.Project[0].ProjectOwnerID = ownerID;
project_Ds.AcceptChanges();
bool managerChanged = true;
}

Related

Insert data in Value Object Table

Inserting Data By POSTMAN, but some error occurred.
My Code is given below:
public async Task<BusinessProfile> Save(string ID,bool Status,string Logo,string TaxNumber,string StateRegisterNumber,string StreetName,string Number
,string Complement,string PostalCode,string Neighborhood,string City,string State,string AreaCode,string Department
,string PhoneNo,string Type,string Website,string EDepartment,string EmailAddress)
{
try
{
int EnumPhoneNumber = 0;
string[] values = Enum.GetNames(typeof(PhoneNumberEnum.PhoneNumber));
if (values[0] == Type)
{
EnumPhoneNumber = (int)PhoneNumber.FixedPhone;
}
else if (values[1] == Type)
{
EnumPhoneNumber = (int)PhoneNumber.MobilePhone;
}
var businessProfile = new BusinessProfile() { ID = ID, Status = Status, Logo = Logo, TaxNumber = TaxNumber, StateRegisterNumber = StateRegisterNumber, Website = Website };
businessProfile.AssignAddress(new Address(StreetName, Number, Complement, PostalCode, Neighborhood, City, State));
businessProfile.AssignPhones(new Phones(Convert.ToString(EnumPhoneNumber), AreaCode, PhoneNo, Department));
businessProfile.AssignEmail(new Emails(EmailAddress, EDepartment));
//_db.Add(businessProfile);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BusinessProfile> x = await _db.AddAsync(businessProfile);
// _db.SaveChanges();
//await _db.BusinessProfiles.AddAsync(businessProfile);
await _db.SaveChangesAsync();
return businessProfile;
}
catch(Exception ex)
{
throw ex;
}
}
Output (Error:):
An unhandled exception occurred while processing the request.
InvalidOperationException: The entity of type BusinessProfile is sharing the table BusinessProfiles with entities of type Address, but there is no entity of this type with the same key value that has been marked as Added. Consider using DbContextOptionsBuilder.EnableSensitiveDataLogging to see the key values.
public async Task Save(BusinessProfile bp)
{
try
{
int EnumPhoneNumber = 0;
string[] values = Enum.GetNames(typeof(PhoneNumberEnum.PhoneNumber));
if (values[0] == bp.Phones.Type)
{
EnumPhoneNumber = (int)PhoneNumber.FixedPhone;
}
else if (values[1] == bp.Phones.Type)
{
EnumPhoneNumber = (int)PhoneNumber.MobilePhone;
}
var businessProfile = new BusinessProfile() { ID = bp.ID, IsActive = bp.IsActive, Logo = bp.Logo, TaxNumber = bp.TaxNumber, StateRegisterNumber = bp.StateRegisterNumber, Website = bp.Website };
businessProfile.Address = new Address(bp.Address.StreetName, bp.Address.Number, bp.Address.Complement, bp.Address.PostalCode, bp.Address.Neighborhood, bp.Address.City, bp.Address.State);
businessProfile.Phones = new Phones(Convert.ToString(EnumPhoneNumber), bp.Phones.AreaCode, bp.Phones.PhoneNumber, bp.Phones.Department);
businessProfile.Emails = new Emails(bp.Emails.EmailAddress, bp.Emails.Department);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BusinessProfile> x = await _db.AddAsync(businessProfile);
await _db.SaveChangesAsync();
return businessProfile;
}
catch (Exception ex)
{
throw ex;
}
}

Invalid object name 'AspNetRoleClaims' exception when logging in

So I implemented Identity for my core project. I have successfully completed my Registration. So while trying to login using the _signInManager.PasswordSignInAsync I am getting the exception Invalid object name 'AspNetRoleClaims'.
I know this is because the AspNetRoleClaims table is not present in my database. But idont know the structure of this table nor do I know how to create it automatically like in mvc.
Can somebody enlighten me why this table is used. Or at least what is the expected structure.
public async Task<IActionResult> RegisterSubmit(Registermodel rm)
{
if (rm.role == "" || rm.role.Trim() == "-1")
{
return View();
}
else
{
var user = new ApplicationUser { UserName = rm.username, Email = rm.username, DeptName = rm.role };
var result = await _userManager.CreateAsync(user, rm.Password);
if (result.Succeeded)
{
_userManager.GenerateEmailConfirmationTokenAsync(user);
await _signInManager.SignInAsync(user, isPersistent: false);
var roleexists = await _roleManager.RoleExistsAsync(rm.role);
if (!roleexists)
{
var role = new IdentityRole();
role.Name = rm.role;
await _roleManager.CreateAsync(role);
}
await _userManager.AddToRoleAsync(user, rm.role);
user.Claims.Add(new IdentityUserClaim<string>
{
ClaimType = "ProductUploadRequest",
ClaimValue = "Allow"
});
}
return View("Login");
}
}
This is my login method.
public async Task<IActionResult> Login(LoginIdentityModel lim)
{
var result = await _signInManager.PasswordSignInAsync(lim.username, lim.password,false, lockoutOnFailure: false); //exception comes here
if (result.Succeeded)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
UserProfileInfo userProfileInfo = new UserProfileInfo();
userProfileInfo.UserId = new Guid(user.Id);
userProfileInfo.FirstName = "test";
userProfileInfo.UserName = lim.username;
userProfileInfo.LastVisit = DateTime.Now;
string query2 = "select ud.UserId,dp.Id DeptId,dp.Name DeptName,rd.Id RoleId,rd.Name RoleName,ud.[ReadWrite] from UserInDepartment ud inner join Department dp on ud.DeptId=dp.Id inner join RolesInDepartment rd on dp.Id=rd.DeptId and ud.RoleId=rd.Id where ud.UserId='" + user.Id + "' and dp.IsEnable=1 and rd.IsEnable=1 and ud.IsEnable=1";
var userProfile = await _departMentalContext.UserProfiles.FromSql(query2).SingleOrDefaultAsync();
if (userProfile != null)
{
Dictionary<int, string> deptValues = new Dictionary<int, string>() { { userProfile.DeptId, userProfile.DeptName } };
userProfileInfo.Dept = deptValues;
Dictionary<int, string> roleValues = new Dictionary<int, string>() { { userProfile.RoleId, userProfile.RoleName } };
userProfileInfo.Role = roleValues;
userProfileInfo.ReadOrWrite = userProfile.ReadWrite;
HttpContext.Session.SetObject(UserProfileSessionName, userProfileInfo);
}
return View("/Home/DashBoard");
}
return View();
}
As you are using EF, you should be able to update your model database.
You can use CLI command (learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet).
Or if you are using Visual Studio, in the package manager console, you can execute those commands :
Add-Migration "init"
Update-Database
Commands allows you tu update table in your database. Also, it will create migrations files, which are a "picture" of your models. When the command Update-Database is executed, it loads the last migration file.

CRM Dynamics Plugin Error - Given Key not found in Dictionary

Hi i developed a plugin and once deployed, i'm getting an error on save of a record.
Given key was not found in Dictionary. It's a pretty generic error, do you see anything or possibly know of a way to go about debugging ? `
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Quad.SalesEstimating.MSCRMPlugins.PluginHelpers;
using Sybase.Data.AseClient;
namespace CRMSolution.Plugins
{
public class PreTitleUpdate : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity entity;
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target business entity from the input parmameters.
entity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents an contact.);
if (entity.LogicalName != "qg_title") { return; }
}
else
{
return;
}
try
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)
serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(
context.UserId);
IOrganizationService elevatedService = serviceFactory.CreateOrganizationService(null);
Entity preImage = context.PreEntityImages["PreImage"];
//Entity postImage = context.PostEntityImages["PostImage"];
#region Variable Setup
const string PREMEDIA_PC = "100000000";
const string RETAIL_INSERTS_PC = "9";
const string COMMERCIAL_PC = "12";
const string DIRECT_MAIL_PC = "7";
const string INSTORE_PC = "13";
string creditAccountID = null;
string creditCustomerID = null;
//string previousTitleCode = null;
string accountId = null;
string creditId = null;
string productType = string.Empty;
int vertisId = 0;
string vertisCustId = string.Empty;
string vertisParentCustId = string.Empty;
string message = string.Empty;
#endregion
#region Get Entity Values
EntityReference titleidLookup = new EntityReference();
if (entity.Contains("qg_titleid"))
{
var titleGuid = (Guid)entity["qg_titleid"];
titleidLookup = (EntityReference)new EntityReference("qg_title", titleGuid);
}
else if (preImage.Contains("qg_titleid"))
{
var titleGuid = (Guid)preImage["qg_titleid"];
titleidLookup = (EntityReference)new EntityReference("qg_title", titleGuid);
}
EntityReference accountIdLookup = new EntityReference();
if (entity.Contains("qg_accountid"))
{
accountIdLookup = (EntityReference)entity["qg_accountid"];
accountId = accountIdLookup.Id.ToString();
}
else if (preImage.Contains("qg_accountid"))
{
accountIdLookup = (EntityReference)preImage["qg_accountid"];
accountId = accountIdLookup.Id.ToString();
}
EntityReference creditIdLookup = new EntityReference();
if (entity.Contains("qg_creditid"))
{
creditIdLookup = (EntityReference)entity["qg_creditid"];
if (creditIdLookup != null)
{
creditId = creditIdLookup.Id.ToString();
}
else
{
entity.SetValue("qg_customerid", string.Empty);
}
}
else if (preImage.Contains("qg_creditid"))
{
creditIdLookup = (EntityReference)preImage["qg_creditid"];
if (creditIdLookup != null)
{
creditId = creditIdLookup.Id.ToString();
}
else
{
entity.SetValue("qg_customerid", string.Empty);
}
}
//if (entity.Contains("qg_previoustitlecode"))
//{
// previousTitleCode = entity.GetValue("qg_previoustitlecode");
//}
//else if (preImage.Contains("qg_previoustitlecode"))
//{
// previousTitleCode = preImage.GetValue("qg_previoustitlecode");
//}
if (entity.Contains("qg_producttype"))
{
productType = entity.GetValue("qg_producttype");
//this.LogItemToFile("QG_TitlePreUpdate productType from entity.");
}
else if (preImage.Contains("qg_producttype"))
{
productType = preImage.GetValue("qg_producttype");
//this.LogItemToFile("QG_TitlePreUpdate productType from preImage.");
}
if (entity.Contains("qg_vertiscustomerid"))
{
vertisCustId = entity.GetValue("qg_vertiscustomerid");
//this.LogItemToFile("QG_TitlePreUpdate qg_vertiscustomerid from entity.");
}
else if (preImage.Contains("qg_vertiscustomerid"))
{
vertisCustId = preImage.GetValue("qg_vertiscustomerid");
//this.LogItemToFile("QG_TitlePreUpdate qg_vertiscustomerid from preImage.");
}
#endregion
if (accountId != null)
{
#region Credit Business Unit
if (creditId != null)
{
// get credit business unit
ColumnSet creditcolumns = new ColumnSet(new string[] {"qg_accountid", "qg_customerid"});
Guid creditIdGUID = new Guid(creditId);
Entity qg_credit = elevatedService.Retrieve("qg_credit", creditIdGUID, creditcolumns);
if (qg_credit.Attributes.Contains("qg_accountid"))
{
EntityReference creditAccount = (EntityReference)qg_credit["qg_accountid"];
creditAccountID = creditAccount.Id.ToString();
}
if (qg_credit.Attributes.Contains("qg_customerid"))
{
creditCustomerID = qg_credit.GetValue("qg_customerid").ToString();
}
}
#endregion
#region Validate Customer ID
// If the Customer has been selected, validate account and get the customer ID.
// Validate that the Credit record and Title are under the same Account
if (creditId != null)
{
if (creditAccountID != accountId)
{
throw new InvalidPluginExecutionException(" " +
"Credit Record must be under the same Account as the Title.");
}
if (creditCustomerID != null)
{
// Set the customerid on the Title
entity.SetValue("qg_customerid", creditCustomerID);
// service.Update(entity);
}
else
{
// something went wrong so stop processing...
throw new InvalidPluginExecutionException(" " + "Could not update the Customer ID.");
}
}
#endregion
//#region Validate Previous Title Code
//// if a previous title code has been selected, validate that it exists...
//if (!String.IsNullOrEmpty(previousTitleCode))
//{
// if (!TitleCodeExists(previousTitleCode))
// {
// throw new InvalidPluginExecutionException(" " + "Previous Title Code is not valid. Please select a Title Code that previously existed.");
// }
//}
//#endregion
#region Approved for QG Paper
try
{
string ownerDomainName = null;
string aprvdForQGPaper = "";
ColumnSet ownerColumns = new ColumnSet(new string[] { "businessunitid", "domainname", });
Entity systemuser = service.Retrieve("systemuser", context.InitiatingUserId, ownerColumns);
if (entity.Contains("qg_aprvdforqgppr"))
{
aprvdForQGPaper = entity.GetValue("qg_aprvdforqgppr");
}
if (systemuser.Attributes.Contains("domainname"))
{
ownerDomainName = systemuser.GetValue("domainname").ToString();
}
// Set the Approved for QG Paper last changed
if (aprvdForQGPaper == "1")
{
entity.SetValue("qg_aprvdforqgpprdt", DateTime.Now);
entity.SetValue("qg_aprvdforqgpprby", ownerDomainName);
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(
" " + "An error occurred in the plug-in." + ex.Message, ex);
}
#endregion
#region Validate Classification
//try
//{
// if (entity.Contains("qg_producttype") && preImage.Contains("qg_producttype"))
// {
// bool validateProdType = true;
// // Allow Credit to change product type regardless of Sales Staff being assigned.
// if (this.DoesUserHaveRole(context.InitiatingUserId, service, "Quad Credit") ||
// this.DoesUserHaveRole(context.InitiatingUserId, service, "System Administrator"))
// {
// validateProdType = false;
// }
// if (validateProdType)
// {
// OptionSetValue preProdType = (OptionSetValue)preImage["qg_producttype"];
// OptionSetValue postProdType = (OptionSetValue)entity["qg_producttype"];
// if (preProdType.Value != postProdType.Value)
// {
// // The only valid Product Classification change is within MagCat/SIP.
// List<int> validprodclasschangelist = new List<int>(new int[] { 2, 3, 5 });
// List<int> salesRoles = new List<int>(new int[] { 52, 30, 33, 35, 41, 48 });
// QueryExpression query = new QueryExpression();
// query.NoLock = true;
// ColumnSet columns = new ColumnSet(new string[] { "qg_titleid", "qg_employeerole" });
// ConditionExpression condition = new ConditionExpression();
// condition.AttributeName = "qg_employeerole";
// condition.Operator = ConditionOperator.In;
// foreach (var role in salesRoles)
// {
// condition.Values.Add(role);
// }
// query.EntityName = "qg_titleemployeerole";
// query.ColumnSet = columns;
// query.Criteria.AddCondition("qg_titleid", ConditionOperator.Equal, titleidLookup.Id);
// query.Criteria.AddCondition(condition);
// EntityCollection resultSet = service.RetrieveMultiple(query);
// if (resultSet.Entities.Count > 0)
// {
// if (!validprodclasschangelist.Contains(preProdType.Value) ||
// !validprodclasschangelist.Contains(postProdType.Value))
// {
// throw new InvalidPluginExecutionException("Product Classification change is not valid.");
// }
// }
// }
// }
// }
//}
//catch (Exception ex)
//{
// throw new InvalidPluginExecutionException(
// " " + "An error occurred in the plug-in." + ex.Message, ex);
//}
#endregion
#region Vertis Ids
string accountBUID = null;
string accountBUName = null;
// if the account doesn't have a VertisParentCustomerID get the last five digits of the VMAC ID
// to build the parent customer id
ColumnSet accountcolumns = new ColumnSet(new string[] { "owningbusinessunit", "qg_vertisparentcustid" });
Guid accountIdGUID = new Guid(accountId);
Entity accountService = service.Retrieve("account", accountIdGUID, accountcolumns);
if (accountService.Attributes.Contains("owningbusinessunit"))
{
EntityReference accountBusinessUnit = (EntityReference)accountService["owningbusinessunit"];
accountBUID = accountBusinessUnit.Id.ToString();
}
if (accountService.Attributes.Contains("qg_vertisparentcustid"))
{
vertisParentCustId = accountService.GetValue("qg_vertisparentcustid");
}
ColumnSet buColumns = new ColumnSet(new string[] { "name" });
// GUID from above
Guid buIdGUID = new Guid(accountBUID);
Entity buService = service.Retrieve("businessunit", buIdGUID, buColumns);
if (buService.Attributes.Contains("name"))
{
accountBUName = buService.GetValue("name").ToString();
}
// if productClass has been selected, see if we need to pull VertisCustIds..
if (accountBUName.Equals("Corporate Print") && string.IsNullOrEmpty(vertisCustId))
{
// if product class is 'Retail Inserts', 'Premedia', or 'Commercial' we need to pull Vertis Ids
if (productType.Equals(RETAIL_INSERTS_PC) || productType.Equals(DIRECT_MAIL_PC) ||
productType.Equals(COMMERCIAL_PC) || productType.Equals(PREMEDIA_PC) || productType.Equals(INSTORE_PC))
{
bool vertisIdResult = false;
// get the last five digits of the VMAC ID to build the customer id
vertisIdResult = this.GetNextId("VERTIS_CUST_ID", "TITLE", ref vertisId, ref message);
if (string.IsNullOrEmpty(vertisParentCustId))
{
// get the last five digits of the VMAC ID to build the parent customer id
//vertisIdResult = this.GetNextId("VERTIS_CUST_ID", "TITLE", ref vertisId, ref message);
accountService.SetValue("qg_vertisparentcustid", "9" + vertisId.ToString());
service.Update(accountService);
}
if (vertisIdResult)
{
if (productType.Equals(DIRECT_MAIL_PC))
{
vertisCustId = "5" + vertisId.ToString();
}
else if (productType.Equals(RETAIL_INSERTS_PC))
{
vertisCustId = "0" + vertisId.ToString();
}
else { vertisCustId = "1" + vertisId.ToString(); }
//this.LogItemToFile("TitlePreCreate vertisCustId: " + vertisCustId);
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
}
}
else if (!string.IsNullOrEmpty(vertisCustId))
{
// if the product class changed, we may need to change the VertisCustomerID
if (entity.Contains("qg_producttype") && preImage.Contains("qg_producttype"))
{
OptionSetValue preProdType = (OptionSetValue)preImage["qg_producttype"];
OptionSetValue postProdType = (OptionSetValue)entity["qg_producttype"];
if (preProdType.Value != postProdType.Value)
{
//if (Convert.ToInt32(vertisCustId.Substring(1)) < 67000)
//{
// throw new InvalidPluginExecutionException(" " + "Product Class may not be changed for Customers that originated from Vertis.");
//}
//else
//{
// check the validity of the VertisId
// if (productType.Equals(DIRECT_MAIL_PC)) vertisCustId = "5" + vertisId.ToString();
// if (productType.Equals(RETAIL_INSERTS_PC)) vertisCustId = "0" + vertisId.ToString();
// else { vertisCustId = "1" + vertisId.ToString();
if (productType.Equals(DIRECT_MAIL_PC) && !vertisCustId.Substring(0, 1).Equals("5"))
{
vertisCustId = vertisCustId.Substring(1);
vertisCustId = "5" + vertisCustId;
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
else if (productType.Equals(RETAIL_INSERTS_PC) && !vertisCustId.Substring(0, 1).Equals("0"))
{
vertisCustId = vertisCustId.Substring(1);
vertisCustId = "0" + vertisCustId;
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
else if (productType.Equals(PREMEDIA_PC) && !vertisCustId.Substring(0, 1).Equals("1"))
{
vertisCustId = vertisCustId.Substring(1);
vertisCustId = "1" + vertisCustId;
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
//}
}
}
}
#endregion
}
else
{
throw new InvalidPluginExecutionException(" " + "An error occurred in the plug-in. Owner ID, Account ID or Credit ID is Null.");
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(" " + "An error occurred in the plug-in." + ex.Message, ex);
}
}
/// <summary>
/// Use Ase command to determine is title code exists
/// </summary>
/// <param name="titlecode">The title code to use in the select </param>
/// <returns>A true/false value indicating success or failure</returns>
public bool TitleCodeExists(string titlecode)
{
int TitleCodeCount = 0;
string CmndText = "select count(*) as cnt from QUAD0024.dbo.TITLE_VW where _TITLE_CODE = '" + titlecode + "'";
// connect to Sybase to see if Title Code exists in the Title View.
try
{
using (AseConnection dbcon = new AseConnection(this.GetSybaseDbConnectionString()))
{
dbcon.Open();
AseCommand cmd = new AseCommand(CmndText, dbcon);
IDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
TitleCodeCount = (int)reader["cnt"];
}
if (TitleCodeCount == 0)
{
//throw new InvalidPluginExecutionException(" " + " TitleCodeExists: Return False.");
return false;
}
else
{
//throw new InvalidPluginExecutionException(" " + " TitleCodeExists: Return True.");
return true;
}
}
}
catch (Exception e)
{
this.LogExceptionEvent(new Exception("Message", e));
throw new InvalidPluginExecutionException(" " + " TitleCodeExists Failed" + e.Message);
}
}
}
}
`
Its better to check before we are trying to access any attribute in an object.
In this particular code, one catch is that while accessing the images we are not trying to check whether the object contains that image or not.
Similar way check any other miss.
It may also be possible that we are checking for a particular attribute and accessing a different one because of a typo.
Hope this helps you to pin point the issue.

How to get the published date of a page using the Core Service?

I have to create a custom page having list of all pages with its published date within a publication. Can someone guide me how to use this code to get published date in custom page?
private ItemType GetTridionItemType(RepositoryLocalObjectData source)
{
string itemType = source.GetType().Name;
switch (itemType)
{
case "PageData":
return ItemType.Page;
}
return ItemType.UnknownByClient;
}
private string CreateNewItemCopy(string title, RepositoryLocalObjectData source,
string filename)
{
ItemType tridionItemType = GetTridionItemType(source);
string orgItemUri = source.LocationInfo.OrganizationalItem.IdRef;
var newItem = client.Copy(source.Id, orgItemUri, true, new ReadOptions());
newItem.Title = title;
if (tridionItemType == ItemType.Page)
{
PageData pageData = newItem as PageData;
pageData.FileName = filename;
client.Update(pageData, new ReadOptions());
}
else
{
client.Update(newItem, new ReadOptions());
}
return newItem.Id;
}
We can get the publish info from coreservice
TridionGeneration Generation = new TridionGeneration();
Generation.Settings = GetImportSetting();
var objclient = new CoreService2010Client();
objclient.ClientCredentials.Windows.ClientCredential.UserName = Generation.Settings.Username;
objclient.ClientCredentials.Windows.ClientCredential.Password = Generation.Settings.Password;
objclient.Open();
Generation.client = objclient;
var objectList = Generation.client.GetListPublishInfo([object tcm uri]);
PublishEngine.GetPublishInfo returns the Publish Info of an Item. Which contains the Published Date. (PublishInfo.PublishedAt).
You can also use CoreService.GetListPublishInfo.

Creating user in active directory

I'm gonna build a webpart for creating user in active directory .
For creating user account i use method like this :
public string CreateUserAccount(string ldapPath, string userName,
string userPassword)
{
try
{
string oGUID = string.Empty;
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
DirectoryEntry newUser = dirEntry.Children.Add
("CN=" + userName, "user");
newUser.Properties["samAccountName"].Value = userName;
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { userPassword });
newUser.CommitChanges();
dirEntry.Close();
newUser.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingwith --> E.Message.ToString();
}
return oGUID;
}
When executing this method the following error occurred:
"The server is not operational"
say we have active directory installed with domain TestDomain.com and you have a OU ( Organization Unit ) called USERS and you have a user in it called TestUser
so we can saye the following
ldapDomain: the fully qualified domain as TestDomain.com or dc=contoso,dc=com
objectPath: the fully qualified path to the object: CN=TestUser, OU=USERS, DC=TestDomain, DC=com
userDn: the distinguishedName of the user: CN=TestUser, OU=USERS, DC=TestDomain, DC=com
in creating user you should determine where you want to create by determining its path ( ldap path )
In our sample we can consider it as below :
string ldapPath = "LDAP://OU=USERS, DC=TestDomain, DC=com"
For more information check the following links :
http://www.selfadsi.org/ldap-path.htm
http://www.informit.com/articles/article.aspx?p=101405&seqNum=7
http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path.aspx
Using System.DirectoryServices
To use this namespace you need to add reference System.DirectoryServices.dll
DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");
for (int i = 3; i < 6; i++)
{
try
{
DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user");
childEntry.CommitChanges();
ouEntry.CommitChanges();
childEntry.Invoke("SetPassword", new object[] { "password" });
childEntry.CommitChanges();
}
catch (Exception ex)
{
}
}
Using System.DirectoryServices.AccountManagement
To use this namespace you need to add reference System.DirectoryServices.AccountManagement.dll
PrincipalContext ouContex = new PrincipalContext(ContextType.Domain, "TestDomain.local", "OU=TestOU,DC=TestDomain,DC=local");
for (int i = 0; i < 3; i++)
{
try
{
UserPrincipal up = new UserPrincipal(ouContex);
up.SamAccountName = "TestUser" + i;
up.SetPassword("password");
up.Enabled = true;
up.ExpirePasswordNow();
up.Save();
}
catch (Exception ex)
{
}
}

Resources