Convert a String to Call a Public Class ASP.NET VB - asp.net

I have looked at this link and I cannot seem to get it to work
Creating a New control of the same type as another control that is already declared
I have also tried this from searches:
Dim ClassToCreate As String = "TestClass1.CountItems"
Dim myInstance = Activator.CreateInstance(Type.GetType(ClassToCreate), True)
Error is:
"Value cannot be null.
Parameter name: type"
Problem:
I have multiple classes and want to change which one is called based on a string.
(example is not correct of course)
Dim strClassToCall = "TestClass1.CountItems"
'then convert the string to the actual class so it can be called like this:
Dim strResult = TestClass1.CountItems(strSomeParameter)
Thanks for your help!

Based on the error message it sounds like your Type is not getting loaded properly as it is null. The method you are using will create the object like you need assuming you get the valid Type to pass to the activator. Is the type coming from an referenced DLL?
Here is one method you could use to get the type if just using the string representation is not working. This uses reflection to find the type:
// Sorry this is c# :)
System.Reflection.Assembly pAssembly = System.Reflection.Assembly.Load(
System.Reflection.Assembly.GetExecutingAssembly().
GetReferencedAssemblies().Single(a => a.Name.Equals("YourNamespace.ClassName")));
yourType = pAssembly.GetTypes().First(c => (c.FullName != null) &&
c.FullName.Equals("YourNamespace.ClassName"));
var yourObject = Activator.CreateInstance(yourType, true);

Related

Accessing the query string value using ASP.NET

I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004

How to get the keyword from category name in C# TBB?

I am trying to fetch the keyword present in the Category using C# TBB to use the output in following DWT TBB.
For that I have a component with the Category field.
I am trying to write the following C# TBB to get the keyword value.
<%#Import NameSpace="Tridion.ContentManager.Templating.Expression" %>
try
{
string className = package.GetValue("Component.Fields.title");
KeywordField keywordField = package.GetKeywordByTitle(className);
package.PushItem("Class", package.CreateStringItem(ContentType.Text, keywordField.Value.Key));
}
catch(TemplatingException ex)
{
log.Debug("Exception is " + ex.Message);
}
But I am getting following compilation error.
Could not compile template because of: error CS0246: The type or namespace name 'KeywordField' could not be found (are you missing a using directive or an assembly reference?) error CS1061: 'Tridion.ContentManager.Templating.Package' does not contain a definition for 'GetKeywordByTitle' and no extension method 'GetKeywordByTitle' accepting a first argument of type 'Tridion.ContentManager.Templating.Package' could be found (are you missing a using directive or an assembly reference?)
Please suggest me how can I achieve it?
Thanks in advance
Af Jeremy suggested you should study API, I am providing you example of getting keywords from categories. Hope it may help
Include files
using Tridion.ContentManager;
using Tridion.ContentManager.CommunicationManagement;
using Tridion.ContentManager.Templating.Assembly;
using Tridion.ContentManager.ContentManagement;
using Tridion.ContentManager.ContentManagement.Fields;
using Tridion.ContentManager.Templating;
Sample Code, You can use Key and Value from loop here as per your requirement.
string catID = package.GetByName("CategoryID").GetAsString();
TcmUri catURI = new TcmUri(int.Parse(catID), ItemType.Category, PubId);
var theCategory = m_Engine.GetObject(catURI) as Category;
catKeywords = GetCatKeywords(theCategory);
string strSelect = "<select>";
foreach (Keyword k in catKeywords)
{
k.Key // Keyowrd key
k.Value // KEyword Value
}
//keyword list
private IList<Keyword> GetCatKeywords(Category category)
{
IList<Keyword> keywords;
if (!Utilities.IsNull(category))
{
Filter filter = new Filter();
filter.BaseColumns = ListBaseColumns.IdAndTitle;
keywords = category.GetKeywords(filter);
if (!Utilities.IsNull(keywords))
{
return keywords;
}
}
return null;
}
The error message is absolutely clear what the problem is - there's no reference to the KeywordField class. You need to import the relevant namespace:
<%#Import NameSpace="Tridion.ContentManager.ContentManagement.Fields" %>
Also absolutely clear is the fact that the Package object doesn't have a method called GetKeywordByTitle. There is a GetByName method, but this is for retrieving a named item from the Package, not for getting an object from the respository.
Tridion.ContentManager.ContentManagement.Category does have a GetKeywordByTitle method, but to use this you will have to get the category first, which will likely mean having to know the URI of the category.
Perhaps you need to study the API docs some more?
"GetKeywordByTitle" is not a method on Package, its a method on Category.
Can't you just new-up Keyword?
string selectedKeyword= package.GetValue("Component.Fields.title");
Keyword keyword = new Keyword(selectedKeyword, engine.GetSession());
Cheers

"Unexpected list type" exception when invoking ISessionAwareCoreService.GetList()

I am invoking the Tridion 2011 SP1 core service via the shipped client assembly. When I attempt to list the contents of a publication, I get an exception.
The code (simplified) looks like this:
ItemsFilterData filter = new Tridion.ContentManager.CoreService
.Client.RepositoryItemsFilterData.RepositoryItemsFilterData();
filter.ItemTypes = new ItemType[] {
ItemType.Folder,
ItemType.StructureGroup
};
filter.Recursive = false;
IEnumerable<IdentifiableObjectData> childItems = core.GetList("tcm:0-15-1", filter);
Note: the variable "core" refers to an ISessionAwareCoreService which I can successfully use to call, for example core.GetSystemWideList()
When .GetList is invoked, I get the following exception:
System.ServiceModel.FaultException`1 was unhandled
Message=Unexpected list type:
Tridion.ContentManager.Data.ContentManagement.RepositoryItemsFilterData.
What are the possible causes of this problem? Can you suggest a good general approach for interpreting this kind of message?
You can't get the direct children of a Publication using GetList. Instead you should just load the PublicationData with a client.Read and then access the RootFolder and RootStructureGroup on that.
PublicationData pub = (PublicationData)core.Read("tcm:0-1-1", new ReadOptions());
string rootFolder = pub.RootFolder.IdRef;
string rootSG = pub.RootStructureGroup.IdRef;
Alternatively you can call GetListXml with your RepositoryItemsFilterData and extract the items from the XML yourself.
XElement listResult = core.GetListXml(parent.ID, filter);

How to override VBScript GetObject method in .NET

I am having below code in VBScript
' Retrieve the keyword category for page section names
Set SectionCat = TDSE.GetObject(WebdavToUri(getPublicationWebDav(WEBDAV_SECTION_CAT)), 1)
' Retrieve the localized section keyword
Set SectionKeyword = SectionCat.GetKeywordByTitle(meta)
' Open the English translated section keyword
Set SectionKeyword = TDSE.GetObject(SectionKeyword.Id, 1, WEBDAV_UKEN_PUB)
SectionName = SectionKeyword.Title
Where WEBDAV_UKEN_PUB is the WebDavPath, now in VBScript GetObject method we have got option to pass three parameters 1) Item.ID, 2) TDSDefines.OpenModeEditWithFallback and 3) WebDavPath from where to make the object.
Now I want to write same logic in 2009 .Net templating, below is the sample code, I am trying to write but not able to get rid of VBScript Object.
Category cat = engine.GetSession().GetObject(WebdavToUri(getPublicationWebDav(Constants.WEBDAV_SECTION_CAT,package,engine), engine)) as Category;
if (cat != null)
{
//_log.Info("Category" + cat.Title);
Keyword keyword = cat.GetKeywordByTitle(meta);
//_log.Info("keyword 1" + keyword.Title);
keyword = engine.GetObject(Constants.WEBDAV_UKEN_PUB) as Keyword;
//_log.Info("keyword 2 " + keyword.Title);
if (keyword != null)
{
sectionName = keyword.Title;
}
keyword = null;
I am able to create Category object, however when I am trying to make Keyword object its getting failed and giving object reference error.
Do we have any class or method which work same like VBScript GetObject which will make the Object from the passed webdavpath or can somebody can give sample code on this.
I think your problem is here:
keyword = engine.GetObject(Constants.WEBDAV_UKEN_PUB) as Keyword;
You are using the WEBDav URL of a publication, and then attempting a dynamic cast to Keyword. You can't cast a Publication to a Keyword, so the cast fails and your keyword variable is assigned null.
Using dynamic casts in this way is an easy way to fool yourself. The "As" keyword (C# keyword not Tridion keyword) should be used when you don't know at compile time what type you expect. If you know that you expect an item of type Keyword, then you should write:
keyword = (Keyword)engine.GetObject(Constants.WEBDAV_UKEN_PUB);
This way - when the cast fails, you'll get an exception that identifies the problem correctly.
In TOM.NET we cannot get an object and specify which pub to read it from, we need to modify the TcmUri to be in context.
So:
Repository context = (Repository)session.GetObject(WEBDAV_UKEN_PUB);
TcmUri keywordInContext = new TcmUri(keyword.Id.ItemId, keyword.Id.ItemType, context.Id.ItemId);
Keyword keyword = (Keyword)session.GetObject(keywordInContext);

sending Json array failed

I am building a JSON/WCF app and need to send an array of objects back to the server. For some reason it is not accepting the array. Using script manager I can get data fine.
var month = $("#ddlStartMonth").val();
var year = $("#ddlStartYear").val();
var items = JSON.stringify(calendarItems);
WebService.SaveCalendar(items, new Date(year, month, 01).toDateString(), new Date(year, month, 01).toDateString(), Submit, onPageError);
I have tried with and without the JSON stringify. The function onPageError is activated and the only error info it produces is "The server method 'SaveCalendar' failed". Yet the breakpoint on the first line of the web method is not activated.
<OperationContract()>
<WebGet(ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)>
<WebMethod(EnableSession:=True)>
Public Function SaveCalendar(ByVal _jsonImages As String()(), ByVal _selectedMonth As String, ByVal _selectedYear As String) As Boolean
Dim _calenderItems As New List(Of CalenderItem)
'_calenderItems = New JavaScriptSerializer().Deserialize(Of List(Of CalenderItem))(_jsonImages)
HttpContext.Current.Session("calenderItems") = _calenderItems
HttpContext.Current.Session("selectedMonth") = New Date(_selectedMonth)
HttpContext.Current.Session("selectedYear") = New Date(_selectedYear)
Return True
End Function
Any Ideas?
I've had similar issues working with MVC. I think .NET's deserializer actually expects that the object it is passed will be a JSON object rather than an array (i.e. it should always start with "{" and end with "}". You could:
Create a POCO class to act as your DTO which simply has a List/Array of CalenderItems inside of it, or
Use a more "lenient" deserializer like Newtonsoft's JSON.NET
Of course this second option would only work if you can somehow convince WCF to run the method in the first place. Looking at your code again, though, I'm wondering if your declaring _jsonImages as a double-array of strings might be causing some difficulty.

Resources