List Keys in JScript object using VBScript (Classic ASP) - asp-classic

I am using the JSON2 script in an asp page to parse JSON post data.
After parsing the data, I have an object in VBScript that allows for notations such as:
jsonData.key
I wish to parse through all the keys, however, I have no knowledge of the key names.
How would I go about doing this?
Example JSON:
{ "dbtable":"TABLE1", "dbcommand": "INSERT", "dbfilter": "ID" }
Thanks

You need to enumerate the property names of the object however this is a very alien thing to do in VBScript. You will need to build some other Jscript functions to assist converting the object into something more easily consumed in VBScript.
If the data is really as simplistic as the example in the question then you could use this function:-
function toDictionary(o)
{
var result = Server.CreateObject("Scripting.Dictionary");
for (var key in o)
result.Add(key, o[key]);
return result;
}
Now in VBScript:-
Dim myData: Set myData = toDictionary(jsonData);
For Each Key In myData
'' // Each Key is a property for jsonData
Next

Related

Newtonsoft Json JsonSerializationException with simple string

My datasource creates the JSON representing an array of integers as "1,2,3,4,5". I can't do anything about this (Like changing it to [1,2,3,4,5]), it is an enterprise CMS that we have to just deal with.
I'm trying to read up on how the newtonsoft ToObject method handles the following code:
JValue theValue = new JValue("1,2,3")
List<int> x = theValue.ToObject<List<int>>();
I get a Newtonsoft.Json.JsonSerializationException. Could not cast or convert from System.String to System.Collections.Generic.List`1[System.String]. I understand this fully, but I'd like to know if the Newtonsoft JSON libraries have a built in way to convert from a comma delimited string to a List.
I'd like to think there's a better way than trying to check if the variable is a comma delimited list or not and then converting it to a List<> manually, or maybe a JArray, but I've been wrong before !
EDIT
I wanted to share my solution:
dynamic theValue = new JValue("1,2,3,4"); /// This is just passed in, i'm not doing this on purpose. Its to demo.
if (info.PropertyType == typeof (List<int>))
{
if (info.CanWrite)
{
if (theValue.GetType() == typeof (JValue) && theValue.Value is string)
{
theValue = JArray.Parse("[" + theValue.Value + "]");
}
info.SetValue(this, theValue.ToObject<List<int>>());
}
} else {
// do other things
You have three problems from what I can see:
You should be using JArray not JValue. You are intending this to be an array of things, so you need to use the equivalent class in Newtonsoft to represent an array. (A JValue, as best I can tell, represents a simple type--e.g. string, number, Date, etc.)
You should use the Parse method versus using the constructor. Parse will read the content of the string as an array, however...
...in order for it to do that, you will need to surround the data that you get with the square brackets or JArray can't correctly the parse the data. There is no need to fiddle with the CMS; just do a string concat before you parse.
e.g.
JArray theValue = JArray.Parse("[" + "1,2,3" + "]");

Getting Error "No best type found for implicitly-typed array" using LINQ and Entity Framework

var allCategories = _db.Categories;
var result = from c in allCategories
select new[] { c.CategoryID, c.Name, c.SortOrder};
when i use select new {...}; but i get result as object array.
But when i try to use select new[] {...}; i get the following error.
No best type found for implicitly-typed array
Below is my complete Method of Controller.
public ActionResult Index(jQueryDataTableParamModel param=null)
{
if (Request.IsAjaxRequest() && param!=null)
{
var allCategories = _db.Categories;
var result = from c in allCategories
select new[] { c.CategoryID, c.Name, c.SortOrder};
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allCategories.Count(),
iTotalDisplayRecords = allCategories.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
return View();
}
If i am doing wrong way please guide me to right path as i am new to ASP.NET MVC.
Update:
I am getting JSON Array like this:
{"sEcho":"1","iTotalRecords":3,"iTotalDisplayRecords":3,"aaData":[{"CategoryID":1,"Name":"Computers","SortOrder":1},{"CategoryID":2,"Name":"Laptops","SortOrder":1},{"CategoryID":3,"Name":"Mobiles","SortOrder":1}]}
where as i want Json Array like this
{"sEcho":"1","iTotalRecords":3,"iTotalDisplayRecords":3,"aaData":[["CategoryID":1,"Name":"Computers","SortOrder":1],["CategoryID":2,"Name":"Laptops","SortOrder":1],["CategoryID":3,"Name":"Mobiles","SortOrder":1]]}
The reason behind this is datatables is not showing data in grid, so i guess this is the reason behind not showing data. As i am getting the array like the second one in PHP and datatables works fine over there.
Update: 2
I Just Tried like this,
select new [] { Convert.ToString(c.CategoryID), c.Name, Convert.ToString(c.SortOrder)};
as everything will become string. but now after this error is gone i am not getting the error relating to converting of string.
LINQ to Entities does not recognize the method 'System.String
ToString(Int32)' method, and this method cannot be translated into a
store expression.
What you want is not valid JSON. You could create it using string concatenation, but it would not be possible to parse it as JSON.
If you want to produce something that is possible to parse as JSON you need to follow the syntax rules.
If you want a collection of keys and values, you use an object:
{"CategoryID":1,"Name":"Computers","SortOrder":1}
If you use an array you only have values, no keys:
[1,"Computers",1]
Ok. After many tries i finally got the result somehow in arrays rather then in objects.
Many Thanks to #Guffa Also as He helped Alot in Fixing my Problem.
He Finally gave the reply
new object[] { c.CategoryID.ToString(), c.Name, c.SortOrder.ToString() }
Which should have solved my problem but for some reason asp.net LINQ is not supporting .ToString() functions and i did got this error.
The array type 'System.Object[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List1[System.Object]' instead.
I am not good in ASP.NET MVC specially with Databases and C# so i start back to googeling.
I think i had to call query two times.
first result is converted ToList() ToList i think supports the ToString Function.
var categories = (from category in allCategories
select category).ToList();
Then here when returning Json i wrote the query back again but here i used the Categories from First Query and then .ToString was working.
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allCategories.Count(),
iTotalDisplayRecords = allCategories.Count(),
aaData = (from category in categories
select new [] {category.CategoryID.ToString(), category.Name, category.SortOrder.ToString()}).ToArray()
},
It gave me the result i wanted but i am not sure if this is the right way. What should be the Professional way or good way to have a secure and quick response controller. As i don't want to make a mess of my Code.

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 can i extract XML and use it as a datasource?

I am using asp.net VB and I have an XML file containing a set of data, I would like to use it in something like a datalist and where usually you would use a database i would like to use the XML file to produce the information.
Does anyone know how to do this, i have read about transform files but surely i will format the information in the control?
The file has multiple records so in some cases i would need to perform queries on the information through the datasource.
I would maybe look into XML serialization and de-serialization. Using de-serialization you could read your XML into a List(T) object containing a list of your own class objects and use that as a data source for your application.
Heres a link that you may find useful:
http://msdn.microsoft.com/en-us/library/ms731073.aspx
Hope this helps.
Dim ds As New DataSet()
ds.ReadXml(MapPath("data.xml"))
First you have to parse the XML and store that into custom C# object or you can directly pass the XML to your stored procedure and do the codding there for saving it into DB.
Passing the xml to stored procedure and manipulating it there is bit difficult so what I suggest is to parse it in C# and then get a custom object. Once you get it you can do whatever you want to.
Below is the sample code that parse a XML file and generate a custom C# object from it.
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
XDocument xDoc = XDocument.Load(path);
XElement xElement = XElement.Parse(xDoc.ToString());
List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
{
Code = Convert.ToString(d.Element("CategoryCode").Value),
CategoryPath = d.Element("CategoryPath").Value,
Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
}).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
return catSubCatList;
}

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);

Resources