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

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.

Related

dont show help page in web api

I want to create help pages for ASP.NET Web API.
I created a new ASP.NET Web application project and select the Web API project template. It added Areas/HelpPage.
When I run the application, the home page contains a link to the API help page. From the home page, the relative path is /Help. It shows ValuesController action, but when I add another controller, the help page doesn't show that controller and any of its actions.
public class CalendarController : ApiController
{
private readonly string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
private readonly CalendarService calendarService;
public CalendarController()
{
calendarService = new CalendarService();
}
[HttpPost]
public async Task<ResponseModel<List<ApiCalendarViewModel>>> Paging(JObject param)
{
try
{
var startIndex = Convert.ToInt32(param["StartIndex"]);
var pageSize = Convert.ToInt32(param["PageSize"]);
var CalendarList = await calendarService.SelectAllAsync(startIndex, pageSize);
var list = CalendarList.Select(m => new ApiCalendarViewModel()
{
Author = m.Author,
Date = PersianDateTime.ToLongDateWithDayString(m.CreatedDate),
Excerpt = m.Excerpt,
Id = m.Id,
MainImage = siteUrl + m.Image,
Title = m.Title,
StartYear = m.StartYear,
EndYear = m.EndYear,
Semester = m.Semester.GetDisplayName()
}).ToList();
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = true,
Data = list
};
}
catch (Exception e)
{
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = false,
Message = e.Message
};
}
}
[HttpGet]
public async Task<ResponseModel<List<ApiCalendarViewModel>>> GetAll()
{
try
{
var CalendarList = await calendarService.SelectAllAsync();
var list = CalendarList.Select(m => new ApiCalendarViewModel()
{
Author = m.Author,
Date = PersianDateTime.ToLongDateWithDayString(m.CreatedDate),
Excerpt = m.Excerpt,
Id = m.Id,
MainImage = siteUrl + m.Image,
Title = m.Title,
StartYear = m.StartYear,
EndYear = m.EndYear,
Semester = m.Semester.GetDisplayName()
}).ToList();
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = true,
Data = list
};
}
catch (Exception e)
{
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = false,
Message = e.Message
};
}
}
}

how we can return a status code for the serialized JSON object using Newtonsoft.net

I have this Action method which act as an API end point inside our ASP.NET MVC-5, where it search for a username and return the username Phone number and Department from Active Directory (we are serializing the object using Newtonsoft.net):-
public ActionResult UsersInfo2()
{
DomainContext result = new DomainContext();
try
{
// create LDAP connection object
DirectoryEntry myLdapConnection = createDirectoryEntry();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
string ADusername = System.Web.Configuration.WebConfigurationManager.AppSettings["ADUserName"];
string ADpassword = System.Web.Configuration.WebConfigurationManager.AppSettings["ADPassword"];
using (var context = new DirectoryEntry("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword))
using (var search = new DirectorySearcher(context))
{
// create search object which operates on LDAP connection object
// and set search object to only find the user specified
// DirectorySearcher search = new DirectorySearcher(myLdapConnection);
// search.PropertiesToLoad.Add("telephoneNumber");
search.Filter = "(&(objectClass=user)(sAMAccountName=test.test))";
SearchResult r = search.FindOne();
ResultPropertyCollection fields = r.Properties;
foreach (String ldapField in fields.PropertyNames)
{
// cycle through objects in each field e.g. group membership
// (for many fields there will only be one object such as name)
string temp;
// foreach (Object myCollection in fields[ldapField])
// {
// temp = String.Format("{0,-20} : {1}",
// ldapField, myCollection.ToString());
if (ldapField.ToLower() == "telephonenumber")
{
foreach (Object myCollection in fields[ldapField])
{
result.Telephone = myCollection.ToString();
}
}
else if (ldapField.ToLower() == "department")
{
foreach (Object myCollection in fields[ldapField])
{
result.Department = myCollection.ToString();
}
}
// }
}
string output = JsonConvert.SerializeObject(result);
return Json(output,JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return View(result);
}
now the return JSON will be as follow:-
"\"DisplayName\":null,\"Telephone\":\"123123\",\"Department\":\"IT\",\"Name\":null,\"SamAccountName\":null,\"DistinguishedName\":null,\"UserPrincipalName\":null}"
but in our case we need to return a status code beside the return json data. for example inccase there is an exception we need to return an error code,also if we are able to get the user's info we need to pass succes code 200, and so on.. so how we can achieve this?
you can try something like this
var statusCode=200;
string output = JsonConvert.SerializeObject( new { result = result, StatusCode = statusCode);
but nobody usually do this. When users call API they can check status code that HTTP Client returns, using code like this
var response = await client.GetAsync(api);
//or
var response = await client.PutAsJsonAsync(api, data);
var statusCode = response.StatusCode.ToString();
//or usually
if (response.IsSuccessStatusCode) {...}
else {...}

Report localization in Telerik self hosted service (.trdx)

I have telerik REST web API(ASP.NET ) which is working fine. Now I need to localize the reports (report are in .trdx extension).
From documentation of telerik I found the code which have place in my BaseTelerikReportsController but this also not working, and even not show any error.
Telerik Localization Documentation
public class BaseTelerikReportsController : ReportsControllerBase
{
static readonly Telerik.Reporting.Services.ReportServiceConfiguration ConfigurationInstance;
static BaseTelerikReportsController()
{
var resolver = new CustomReportResolver();
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("aa-iq"); //<-- Line 1
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; //<-- Line 2
var reportsPath = HttpContext.Current.Server.MapPath("~/Reports");
ConfigurationInstance = new Telerik.Reporting.Services.ReportServiceConfiguration
{
HostAppId = "TBReportApp",
ReportResolver = resolver,
// ReportResolver = new ReportFileResolver(reportsPath),
Storage = new Telerik.Reporting.Cache.File.FileStorage(),
};
}
public BaseTelerikReportsController()
{
ReportServiceConfiguration = ConfigurationInstance;
}
}
Note
There is a similar question but don't guide me to any right direction Here
Update 1
I have added below function in Global.asax.cs.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("ar");
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
// Set the language for dynamic text (i.e. date, time, money)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
}
After above line (see image) data under red mark is localize but i need to localize yellow one(i.e heading)
I figure out how to localize the report header. Following are the some summarized steps.
Add App_GlobalResources folder and .resx accordingly your languages (See the figure 1-1).
Send language attribute from 'HTML5 Viewer'.
var viewer = $("#report-viewer").data("telerik_ReportViewer");
var model = {
//other attributes
Language: this.selectedLanguage //Here value may be ,en Or ar
};
viewer.reportSource({
report: reportSettings,
parameters: model
});
On server side based on that attribute change label accordingly.
private static void Localization(ref Report reportInstance)
{
ResourceManager currentResource = null;
switch (_language)
{
case "en":
currentResource = new ResourceManager("Resources.en", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
case "ar":
currentResource = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
}
// var MyResourceClass = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = currentResource.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string key = entry.Key.ToString();
string value = entry.Value.ToString();
var items = reportInstance.Items.Find(key,true);
foreach (var singleItem in items)
{
var singleItemType = singleItem.GetType();
//if (singleItem.GetType().FullName == "") ;
if (singleItemType.FullName == "Telerik.Reporting.TextBox")
{
var castItem = (Telerik.Reporting.TextBox) singleItem;
castItem.Value = value;
}
}
}
}
On Telerik Standalone Report Designer
Change your report(.trdx) Textbox value which matches your .resxname value pair.
Resource file values

.NET Already Open DataReader

I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)

Reading a RSS feed using visual C#

I am trying to a read a RSS feed and display in my C# application. i have used the code below and it works perfectly for other RSS feeds. I want to read this RSS feed ---> http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml and the code below doesn't work for it. I don't get any errors but nothing happens, the text box which i want the RSS feed to be displayed is empty. Please help. What am I doing wrong?
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
public class RssReader
{
public static List<RssNews> Read(string url)
{
var webResponse = WebRequest.Create(url).GetResponse();
if (webResponse == null)
return null;
var ds = new DataSet();
ds.ReadXml(webResponse.GetResponseStream());
var news = (from row in ds.Tables["item"].AsEnumerable()
select new RssNews
{
Title = row.Field<string>("title"),
PublicationDate = row.Field<string>("pubDate"),
Description = row.Field<string>("description")
}).ToList();
return news;
}
}
private string covertRss(string url)
{
var s = RssReader.Read(url);
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s)
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
return sb.ToString();
}
//Form Load code///
string readableRss;
readableRss = covertRss("http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml");
textBox5.Text = readableRss;
It seems that the DataSet.ReadXml method fails because there category is specified twice in the item, however under a different namespace.
This seems to work better:
public static List<RssNews> Read(string url)
{
var webClient = new WebClient();
string result = webClient.DownloadString(url);
XDocument document = XDocument.Parse(result);
return (from descendant in document.Descendants("item")
select new RssNews()
{
Description = descendant.Element("description").Value,
Title = descendant.Element("title").Value,
PublicationDate = descendant.Element("pubDate").Value
}).ToList();
}

Resources