<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ADOMD CellSet &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/adomd-cellset/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:18:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>ADOMD CellSet &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Export MDX Result As Excel</title>
		<link>https://mail.sibeeshpassion.com/export-mdx-result-as-excel/</link>
					<comments>https://mail.sibeeshpassion.com/export-mdx-result-as-excel/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 28 Oct 2015 09:10:06 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MDX Query]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[Export CellSet in MVC]]></category>
		<category><![CDATA[Export In MDX]]></category>
		<category><![CDATA[Export MDX Result As Excel]]></category>
		<category><![CDATA[MDX]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[SSAS]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10841</guid>

					<description><![CDATA[In this post we will see how we can export mdx query result. Here we are going to use MVC with the help of jQuery Ajax. We will run the MDX query and get the cell set and then we will convert this cell set to html table so that we can render this html table easily in client side. Once we render the html table we will do some manipulations with the data, to increase the readability. We use one jQuery Ajax Call, One Controller, One function to execute the query and get cell set, and another function to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can export mdx query result. Here we are going to use MVC with the help of jQuery Ajax. We will run the MDX query and get the cell set and then we will convert this cell set to html table so that we can render this html table easily in client side. Once we render the html table we will do some manipulations with the data, to increase the readability. We use one jQuery Ajax Call, One Controller, One function to execute the query and get cell set, and another function to convert the cell set to html table. And at last the controller will return the html table to the ajax success. And then we will export the data in client side. Simple right? Then let us move on. I hope you will like this article.</p>
<p>You can always read the about Microsoft ADOMD, MDX Queries and Cell Set here: <a href="http://sibeeshpassion.com/category/microsoft-adomd/" target="_blank" rel="noopener">Microsoft ADOMD,MDX,CellSet</a></p>
<p><strong>Background</strong></p>
<p>Recently I got a requirement to export the MDX query result to Excel. When a user clicks on a button I needed to export the MDX query result of the cube given. Here in this post I am sharing you the process I have done. </p>
<p><strong>Using the code</strong></p>
<p>First of all you need to create a button in your page to fire the click event.</p>
<p>[html]<br />
 &lt;input type=&quot;submit&quot; class=&quot;exprotbutton&quot; value=&quot;Export to Excel&quot; id=&#8217;excelExport&#8217; /&gt;<br />
[/html]</p>
<p>Now you need to load the jQuery reference to the page.</p>
<p>[js]<br />
&lt;script src=&quot;Scripts/jquery-1.11.1.min.js&quot;&gt;&lt;/script&gt;<br />
[/js]</p>
<p>The next thing is to fire the click event.</p>
<p>[js]<br />
 $(&#8216;#excelExport&#8217;).bind(&#8216;click&#8217;, function (e) {<br />
        try {<br />
        } catch (e) {<br />
            console.log(&#8216;Excel Export Grid: &#8216; + e.message);<br />
        }<br />
    });<br />
[/js]</p>
<p>Now we will create an ajax call to our controller. </p>
<p>[js]<br />
$.ajax({<br />
                url: &#8216;../Exporting/Export/&#8217;,<br />
                type: &#8216;GET&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                contentType: &#8216;application/json; charset=utf-8&#8217;,<br />
                success: function (data) {<br />
                },<br />
                error: function (xhrequest, ErrorText, thrownError) {<br />
                    console.log(&#8216;Excel Export Grid: &#8216; + thrownError);<br />
                }</p>
<p>            });<br />
[/js]</p>
<blockquote><p>Here Exporting is the controller name and Export is the action name</p></blockquote>
<p>Have you noticed that we have not created the action yet. No worries we will create it now.</p>
<p>[csharp]<br />
public JsonResult Export()<br />
        {<br />
            StringBuilder sbConnectionString = new StringBuilder();<br />
            sbConnectionString.Append(&quot;Provider=MSOLAP;data source=&quot;);<br />
            sbConnectionString.Append(serverName + &quot;;initial catalog=&quot; + databaseName + &quot;;Integrated Security=SSPI;Persist Security Info=False;&quot;);</p>
<p>            string readString = myModel.ExCellSet(query, sbConnectionString.ToString());<br />
            return Json(readString, JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<blockquote><p> Here serverName, databaseName and query are the global variable I set. You can pass your own here.</p></blockquote>
<p>Now we are passing the query and connection string to our model myModel and fire call the function ExCellSet. This ExCellSet function will execute the query and return the cell set. So shall we create that model function?</p>
<p>[csharp]<br />
 public string ExCellSet(string query, string adoMDConnection)<br />
        {<br />
            string readerString = string.Empty;<br />
            CellSet cst = null;<br />
            AdomdConnection conn = new AdomdConnection(adoMDConnection);<br />
            try<br />
            {<br />
                try<br />
                {<br />
                    conn.Open();<br />
                }<br />
                catch (Exception){<br />
                }</p>
<p>                using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
                {<br />
                    cmd.CommandTimeout = connectionTimeout;<br />
                    cst = cmd.ExecuteCellSet();<br />
                }<br />
                if (cst.Axes != null)<br />
                {<br />
                    readerString = BuildHTML(cst);<br />
                    return readerString;<br />
                }<br />
                else<br />
                    return null;<br />
            }</p>
<p>            catch (Exception)<br />
            {<br />
                cst = null;<br />
                throw;<br />
            }<br />
            finally<br />
            {<br />
                conn.Close(false);<br />
                cst = null;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>So our cell set is ready now we need to convert this cell set to the HTML table right? For that I strongly recommend you to read here: <a href="http://sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/" target="_blank" rel="noopener">Convert CellSet to HTML Table</a></p>
<p>Anyway I am pasting the code here for your reference.</p>
<p>[csharp]</p>
<p>try<br />
            {<br />
                System.Text.StringBuilder result = new System.Text.StringBuilder();<br />
                //check if any axes were returned else throw error.<br />
                int axes_count = cst.Axes.Count;<br />
                if (axes_count == 0)<br />
                    throw new Exception(“No data returned for the selection”);<br />
                //if axes count is not 2<br />
                if (axes_count != 2)<br />
                    throw new Exception(“The sample code support only queries with two axes”);<br />
                //if no position on either row or column throw error<br />
                if (!(cst.Axes[0].Positions.Count &gt; 0) &amp;&amp; !(cst.Axes[1].Positions.Count &gt; 0))<br />
                    throw new Exception(“No data returned for the selection”);<br />
                int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;<br />
                cur_row = cur_col = col_count = row_count = col_dim_count = row_dim_count = 0;<br />
                //Number of dimensions on the column<br />
                col_dim_count = cst.Axes[0].Positions[0].Members.Count;<br />
                //Number of dimensions on the row<br />
                if (cst.Axes[1].Positions[0].Members.Count &gt; 0)<br />
                    row_dim_count = cst.Axes[1].Positions[0].Members.Count;<br />
                //Total rows and columns<br />
                row_count = cst.Axes[1].Positions.Count +<br />
                    col_dim_count;  //number of rows + rows for column headers<br />
                col_count = cst.Axes[0].Positions.Count +<br />
                    row_dim_count;  //number of columns + columns for row headers<br />
                //gridPanel.ClientIDMode = System.Web.UI.ClientIDMode.AutoID;<br />
                //////lets clear any controls under the grid panel<br />
                //gridPanel.Controls.Clear();<br />
                ////Add new server side table control to gridPanel<br />
                Table tblgrid = new Table();<br />
                tblgrid.Attributes.Add(“Id”, “myhtmltab”);<br />
                tblgrid.Attributes.Add(“class”, “display”);<br />
                //We will use label control to add text to the table cell<br />
                Label lbl;<br />
                string previousText = “”;<br />
                int colSpan = 1;<br />
                for (cur_row = 0; cur_row &lt; row_count; cur_row++)<br />
                {<br />
                    //add new row to table<br />
                    TableRow tr = new TableRow();<br />
                    for (cur_col = 0; cur_col &lt; col_count; cur_col++)<br />
                    {<br />
                        //create new cell and instance of label<br />
                        TableCell td = new TableCell();<br />
                        TableHeaderCell th = new TableHeaderCell();<br />
                        lbl = new Label();<br />
                        //check if we are writing to a ROW having column header<br />
                        if (cur_row &lt; col_dim_count)<br />
                        {<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this should be empty cell — it’s on top left of the grid.<br />
                                //result.Append(” ,”);<br />
                                lbl.Text = ” “;<br />
                                td.CssClass = “titleAllLockedCell”; //this locks<br />
                                    //the cell so it doesn’t scroll upwards nor leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is a column header cell — use member caption for header<br />
                                //result.Append(cst.Axes[0].Positions[cur_col –<br />
                                //    row_dim_count].Members[cur_row].Caption + “,”);<br />
                                //if (cur_row &lt; 1)<br />
                                //{<br />
                                    lbl.Text = cst.Axes[0].Positions[cur_col – row_dim_count].Members[cur_row].Caption;<br />
                                    th.CssClass = “titleTopLockedCell”; // this lockeders<br />
                                            //the cell so it doesn’t scroll upwards<br />
                                //}<br />
                                if (lbl.Text == previousText)<br />
                                {<br />
                                    colSpan++;<br />
                                }<br />
                                else<br />
                                {<br />
                                    colSpan = 1;<br />
                                }<br />
                            }<br />
                        }<br />
                        else<br />
                        {<br />
                            //We are here.. so we are writing a row having data (not column headers)<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this is a row header cell — use member caption for header<br />
                                lbl.Text = cst.Axes[1].Positions[cur_row –<br />
                                col_dim_count].Members[cur_col].Caption.Replace(“,”, ” “);<br />
                                td.CssClass = “titleLeftLockedCell”; // this lockeders<br />
                                    //the cell so it doesn’t scroll leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is data cell.. so we write the Formatted value of the cell.<br />
                                lbl.Text = cst[cur_col – row_dim_count, cur_row – col_dim_count].FormattedValue;<br />
                                //td.InnerText = cst[cur_col – row_dim_count,<br />
                                //cur_row – col_dim_count].FormattedValue;<br />
                                td.CssClass = “valueCell”; //this  right<br />
                                        //aligns the values in the column<br />
                            }<br />
                            //turn the wrapping off for row header and data cells.<br />
                            td.Wrap = true;<br />
                        }<br />
                        if (((lbl.Text != previousText) || (lbl.Text == ” “))<br />
                            &amp;&amp; (cur_row &lt; col_dim_count))<br />
                        {<br />
                            tr.TableSection = TableRowSection.TableHeader;<br />
                            th.Text = “HEADER”;<br />
                            th.Controls.Add(lbl);<br />
                            tr.Cells.Add(th);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else if ((lbl.Text != previousText) || (lbl.Text == ” “) ||<br />
                            (lbl.Text == null) || (lbl.Text == “”))<br />
                        {<br />
                            td.Controls.Add(lbl);<br />
                            tr.Cells.Add(td);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else<br />
                        {<br />
                            try<br />
                            {<br />
                                tr.Cells[tr.Cells.Count – 1].ColumnSpan = colSpan;<br />
                            }<br />
                            catch<br />
                            {<br />
                            }<br />
                        }<br />
                        if (cur_row &lt; col_dim_count)<br />
                            previousText = lbl.Text;<br />
                    }<br />
                    //result.AppendLine();<br />
                }<br />
                using (StringWriter writer = new StringWriter())<br />
                {<br />
                    HtmlTextWriter htw = new HtmlTextWriter(writer);<br />
                    tblgrid.RenderControl(htw);<br />
                    return htw.InnerWriter.ToString();<br />
                }<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                throw ex;<br />
            }<br />
[/csharp]</p>
<p>So it seems everything is set, now we have our html table, the controller will return this string to json, do you remember we have given the type as json in our ajax call?</p>
<p>[csharp]<br />
 return Json(readString, JsonRequestBehavior.AllowGet);<br />
[/csharp]</p>
<p>Since our data is ready, we will re write our ajax function as follows.</p>
<p>[js]<br />
  $(&#8216;#excelExport&#8217;).bind(&#8216;click&#8217;, function (e) {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;../Exporting/Export/&#8217;,<br />
                type: &#8216;GET&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                contentType: &#8216;application/json; charset=utf-8&#8217;,<br />
                success: function (data) {<br />
                    data = &#8216;&lt;div&gt;&#8217; + data + &#8216;&lt;/div&gt;&#8217;;<br />
                    var updateHtmlDom = $.parseHTML(data);<br />
                    var AppliedHtml = updateHtmlDom[0].innerHTML;<br />
                    AppliedHtml = tableToExcel(AppliedHtml, title + &quot;.xls&quot;);<br />
                    saveText($(&#8216;#SubmitForm&#8217;), title + &quot;.xls&quot;, AppliedHtml, &#8216;text/xls;charset=utf-8&#8217;);<br />
                },<br />
                error: function (xhrequest, ErrorText, thrownError) {<br />
                    console.log(&#8216;Excel Export Grid: &#8216; + thrownError);<br />
                }</p>
<p>            });<br />
        } catch (e) {<br />
            console.log(&#8216;Excel Export Grid: &#8216; + e.message);<br />
        }<br />
    });<br />
[/js]</p>
<p>The first step we are doing is parsing the html we got by using $.parseHTML in jQuery. Next we are passing the parsed data to the the function tableToExcel so that the table can be formatted in the format of excel data. Here is the code for the function tableToExcel.</p>
<p>[js]<br />
var tableToExcel = (function (table) {<br />
    var uri = &#8216;data:application/vnd.ms-excel;base64,&#8217;<br />
, template = &#8216;&lt;html xmlns:o=&quot;urn:schemas-microsoft-com:office:office&quot; xmlns:x=&quot;urn:schemas-microsoft-com:office:excel&quot; xmlns=&quot;http://www.w3.org/TR/REC-html40&quot;&gt;&lt;head&gt;&lt;!&#8211;[if gte mso 9]&gt;&lt;xml&gt;&lt;x:ExcelWorkbook&gt;&lt;x:ExcelWorksheets&gt;&lt;x:ExcelWorksheet&gt;&lt;x:Name&gt;{worksheet}&lt;/x:Name&gt;&lt;x:WorksheetOptions&gt;&lt;x:DisplayGridlines /&gt;&lt;/x:WorksheetOptions&gt;&lt;/x:ExcelWorksheet&gt;&lt;/x:ExcelWorksheets&gt;&lt;/x:ExcelWorkbook&gt;&lt;/xml&gt;&lt;![endif]&#8211;&gt;&lt;/head&gt;&lt;body&gt;&lt;table&gt;{table}&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;&#8217;<br />
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }<br />
    , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }<br />
    return function (table, name) {<br />
        var length = name.replace(&#8216;.xls&#8217;, &#8221;).length;<br />
        if (length &gt; 30) {<br />
            name = name.slice(0, 25) + &#8216;&#8230;&#8217;;<br />
        }<br />
        else<br />
            name.replace(&#8216;.xls&#8217;, &#8221;);<br />
        var ctx = { worksheet: name || &#8216;Worksheet&#8217;, table: table }<br />
        return format(template, ctx)<br />
    }<br />
})()<br />
[/js]</p>
<p>Now we have formatted the html data to the one which excel supports. We are passing the data to the function saveText as follows.</p>
<p>[js]<br />
saveText($(&#8216;#SubmitForm&#8217;), title + &quot;.xls&quot;, AppliedHtml, &#8216;text/xls;charset=utf-8&#8217;);<br />
[/js]</p>
<p>Here title is the file name of the excel file to generated. The below is the definition of saveText function.</p>
<p>[js]<br />
function saveText(ref, fname, text, mime) {<br />
    var blob = new Blob([text], { type: mime });<br />
    saveAs(blob, fname);<br />
    return false;<br />
}<br />
[/js]</p>
<p>Next we are going to export the data using blob export technology in HTML5. </p>
<blockquote><p>If you are new to blog, you can check here <a href="http://sibeeshpassion.com/compress-xml-string-variables-in-client-side-and-export-in-html5-using-jquery/" target="_blank" rel="noopener">Using blob</a> to understand how to use it.
</p></blockquote>
<p>Everything is set now. Build your application and check the output now. Just click on the export button, I am sure an excel file will be downloaded.</p>
<blockquote><p>
The time taken for the exporting is completely depends on how many data your query returns. I suggest you to export maximum of 5000 for a query, so that it won&#8217;t affect any other process.
</p></blockquote>
<div id="attachment_10843" style="width: 332px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Excel_Export_In_MDX.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-10843" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Excel_Export_In_MDX.png" alt="Excel Export In MDX" width="322" height="251" class="size-full wp-image-10843" srcset="/wp-content/uploads/2015/10/Excel_Export_In_MDX.png 322w, /wp-content/uploads/2015/10/Excel_Export_In_MDX-300x234.png 300w" sizes="(max-width: 322px) 100vw, 322px" /></a><p id="caption-attachment-10843" class="wp-caption-text">Excel Export In MDX</p></div>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/export-mdx-result-as-excel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Convert Microsoft ADOMD Cell Set to JSON</title>
		<link>https://mail.sibeeshpassion.com/convert-microsoft-adomd-cell-set-to-json/</link>
					<comments>https://mail.sibeeshpassion.com/convert-microsoft-adomd-cell-set-to-json/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 29 Mar 2015 20:08:15 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[CellSet JSON]]></category>
		<category><![CDATA[Convert CellSet to JSON]]></category>
		<category><![CDATA[Convert Microsoft ADOMD Cell Set to JSON]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=1381</guid>

					<description><![CDATA[In this article we will learn how we can convert Microsoft ADOMD cell sets to JSON. There are few possible ways to convert a CellSet to JSON, Here by I am sharing you one among that options. We will create a function which accepts cellset as the argument and we will loop through the axes of cellset and bind the values according to a string builder using a JsonWriter class. I hope you will like it. Background For the past few months I have been working with Microsoft ADOMD data sources. And I have written some article also that will [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can convert Microsoft ADOMD cell sets to JSON. There are few possible ways to convert a CellSet to JSON, Here by I am sharing you one among that options. We will create a function which accepts cellset as the argument and we will loop through the axes of cellset and bind the values according to a string builder using a JsonWriter class. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>For the past few months I have been working with Microsoft ADOMD data sources. And I have written some article also that will describe the problems I have encountered so far. If you are new to ADOMD I strongly recommend that read my previous articles that you may find useful when you work with ADOMD data sources. You can find those article links here.</p>
<li><a href="http://sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/" target="_blank" rel="noopener">How to Convert Microsoft ADOMD Data Source to JSON</a></li>
<li><a href="http://sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/" target="_blank" rel="noopener">Convert CellSet to HTML Table and From HTML to JSON and to Array</a></li>
<p><strong>Why </strong></p>
<p>You might think, why am I again using the methods described in the preceding two articles. I will answer that. I have encountered some issues with those methods. When you use a data adapter or data reader as explained in the first link (How to Convert Microsoft ADOMD Data Source to JSON) you always get the values as normal values instead of formatted values. For example even if the value contains $ or %, you will always get values without those symbols. So your application won&#8217;t let the user identify which one is currency or which one is %. In my case it was high chart and high maps. When the user hovers over a specific area, I need to show the measure values in the tooltip. </p>
<p>So in that case I was forced to use the cell set again, where there is an option that we can select the formatted value. I will show you that in my function.</p>
<p><strong>Using the code</strong></p>
<p>The following is the function that does what was explained above.<br />
[csharp]<br />
private string BuildBubbleMap(CellSet cst)<br />
{<br />
    try<br />
    {<br />
        StringBuilder sb = new StringBuilder();<br />
        StringWriter sw = new StringWriter(sb);<br />
        string columnName = string.Empty;<br />
        string fieldVal = string.Empty;<br />
        //check if any axes were returned else throw error.<br />
        int axes_count = cst.Axes.Count;<br />
        if (axes_count == 0)<br />
            throw new Exception(&quot;No data returned for the selection&quot;);  </p>
<p>        //if axes count is not 2<br />
        if (axes_count != 2)<br />
            throw new Exception(&quot;The code support only queries with two axes&quot;);  </p>
<p>        //if no position on either row or column throw error<br />
        if (!(cst.Axes[0].Positions.Count &gt; 0) &amp;&amp; !(cst.Axes[1].Positions.Count &gt; 0))<br />
            throw new Exception(&quot;No data returned for the selection&quot;);  </p>
<p>        int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;<br />
        row_dim_count = 0;  </p>
<p>        //Number of dimensions on the column<br />
        col_dim_count = cst.Axes[0].Positions[0].Members.Count;  </p>
<p>        //Number of dimensions on the row<br />
        if (cst.Axes[1].Positions.Count &gt; 0)<br />
        {<br />
            if (cst.Axes[1].Positions[0].Members.Count &gt; 0)<br />
                row_dim_count = cst.Axes[1].Positions[0].Members.Count;<br />
        }<br />
        //Total rows and columns<br />
        row_count = cst.Axes[1].Positions.Count + col_dim_count;  //number of rows + rows for column headers<br />
        col_count = cst.Axes[0].Positions.Count + row_dim_count;  //number of columns + columns for row headers  </p>
<p>        using (JsonWriter myJson = new JsonTextWriter(sw))<br />
        {<br />
            myJson.WriteStartArray();<br />
            for (cur_row = 0; cur_row &lt; row_count-1; cur_row++)<br />
            {<br />
                myJson.WriteStartObject();<br />
                for (cur_col = 0; cur_col &lt; col_count-1; cur_col++)<br />
                {<br />
                    //Looping for dimension headers<br />
                    columnName = cst.Axes[1].Positions[cur_row].Members[cur_col].ParentLevel.ToString().Replace(&quot;{&quot;, &quot;&quot;).Replace(&quot;}&quot;, &quot;&quot;).Trim();<br />
                    fieldVal = cst.Axes[1].Positions[cur_row].Members[cur_col].Caption.Replace(&quot;,&quot;, &quot; &quot;);<br />
                    //If the value is null, I dont need that to be included<br />
                    if ((columnName == null || columnName == &quot;&quot; || columnName.ToLower() == &quot;undefined&quot; || columnName.ToLower() == &quot;null&quot; ||<br />
                        columnName.ToLower() == &quot;(null)&quot; || columnName.ToLower() == &quot;unknown&quot;)||(fieldVal == null || fieldVal == &quot;&quot; ||<br />
                        fieldVal.ToLower() == &quot;undefined&quot; || fieldVal.ToLower() == &quot;null&quot; ||<br />
                        fieldVal.ToLower() == &quot;(null)&quot; || fieldVal.ToLower() == &quot;unknown&quot;))<br />
                        break;<br />
                    //Map expect the header as lat and lon, so here we are changing that.<br />
                    if (columnName.ToLower() == &quot;latitude&quot;)<br />
                        columnName = &quot;lat&quot;;<br />
                    else if (columnName.ToLower() == &quot;longitude&quot;)<br />
                        columnName = &quot;lon&quot;;                              </p>
<p>                    myJson.WritePropertyName(columnName);<br />
                    myJson.WriteValue(fieldVal);<br />
                }<br />
                //Looping for measure headers<br />
                myJson.WritePropertyName(cst.Axes[0].Positions[0].Members[0].Caption.Replace(&quot;,&quot;, &quot; &quot;).Trim());<br />
                myJson.WriteValue(cst[cur_row].FormattedValue);<br />
               //Please be noted that we are using FormattedValue here.<br />
                myJson.WriteEndObject();<br />
            }<br />
            myJson.WriteEndArray();<br />
        }<br />
        cst = null;<br />
        return sw.ToString();<br />
    }<br />
    catch (Exception)<br />
    {<br />
        cst = null;<br />
        throw;<br />
    }<br />
}<br />
[/csharp]</p>
<p>You can see that this function expects the parameter cell set. Here we are finding the axis (Axis0 and Axis 1). According to my ADOMD query my dimensions are in Axis 1, so that I need to determine the caption for each dimension from the cell set. Once I determine the dimensions I am writing that to the <em>StringBuilder </em>using the method <em>WritePropertyName() </em> of the <a href="http://sibeeshpassion.com/tag/json/" target="_blank" rel="noopener">JSON </a> Writer class. To use this class you must include the Newtonsoft DLL as in the following.<br />
[csharp]<br />
using Newtonsoft.Json;<br />
[/csharp]</p>
<p>Once that is over, I am writing the value for those dimensions using the WriteValue() method of the JSON writer class.</p>
<p>I am doing that for the measures also. You can see these implementations in my code. Finally I am creating the proper JSON here and returning that.</p>
<p>To use this function you need to build the cell set first. You can do that as follows.<br />
[csharp]<br />
using (AdomdConnection conn = new AdomdConnection(myConnection))<br />
{<br />
    conn.Open();<br />
    using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
    {<br />
    cmd.CommandTimeout = connectionTimeout;<br />
    cst = cmd.ExecuteCellSet();<br />
    }<br />
 }<br />
[/csharp]</p>
<p>Once you get the cell set, just pass the cell set to the preceding function, it will return the JSON you need. You can easily bind it to any client-side tool (for example, High Chart and High Maps).</p>
<p><strong>Conclusion</strong></p>
<p>Have you ever gone through this kind of requirement. Did I miss anything that you may think which is needed?. I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C-Sharp Corner, Stack Overflow, Asp.Net Forums or Code Project instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I am able to.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/convert-microsoft-adomd-cell-set-to-json/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Convert Microsoft ADOMD Data Source to JSON</title>
		<link>https://mail.sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/</link>
					<comments>https://mail.sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 29 Jan 2015 20:04:54 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[CellSet JSON]]></category>
		<category><![CDATA[Convert CellSet to JSON]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=1331</guid>

					<description><![CDATA[Introduction Hi all, I hope you are all fine. This article helps you to understand how to convert your ADOMD data source into the JavaScript Object Notation (JSON) format. If you are new to ADOMD, please read here. As I said, we will convert the source to JSON, so you must understand what JSON is and its importance. Am I right? Important of JSON JSON stands for JavaScript Object Notation (basically JSON itself is JavaScript). It is a data format that we can format and analyze using JavaScript. It is easy to use. You can get more here. Background For [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Hi all, I hope you are all fine. This article helps you to understand how to convert your ADOMD data source into the JavaScript Object Notation (JSON) format. If you are new to ADOMD, please read <a href="https://technet.microsoft.com/en-us/library/ms123477(v=sql.110).aspx" rel="nofollow">here</a>.</p>
<p>As I said, we will convert the source to JSON, so you must understand what JSON is and its importance. Am I right?</p>
<p><strong>Important of JSON</strong></p>
<p>JSON stands for JavaScript Object Notation (basically JSON itself is JavaScript). It is a data format that we can format and analyze using JavaScript. It is easy to use. You can get more <a href="http://xfront.com/json/index.html" rel="nofollow">here</a>.</p>
<p><strong>Background</strong></p>
<p>For the past few months I am working on ADOMD data sources. When you have become experienced in SQL, you may encounter some difficulties to play with sources. As far as my experience is concerned, playing with the data is not as easy as in SQL in ADOMD. The ADOMD data source may be an Excel file. In my case what exactly the client is doing was uploading the Excel files that they have created, to the DB.</p>
<p>Getting back to the point, when you have a client-side grid that accepts data in only JSON format in your ADOMD application, what will you do? I have searched for a solution to convert the source to the JSON for many days. But I could not find a solution. So I came up with the idea of converting the ADOMD data source (Cell Set) to a HTML table and in the client-side convert that to JSON. You can read that article <a href="http://sibeeshpassion.com/Convert-CellSet-to-HTML-table-And-From-HTML-To-Json-To-Array.html" rel="nofollow">here</a>.</p>
<p>Now that was in the initial stage, where I was new to ADOMD. We developers never stop Googling, right? To be frank I am passionate about R&amp;D work (in which we may need to search more and more). Now I have discovered some more methods to convert the source to JSON. I thought to share that information, so that someone may determine it is useful.</p>
<p>I am working in MVC, and I am using the below namespace for the process.</p>
<p><csharp>using Newtonsoft.Json;</csharp></p>
<p><strong>The Process</strong></p>
<p>In this I am not taking the ADOMD data source as a Cell Set that is popularly used in such applications. Here I will explain two methods or ways to do the process.</p>
<li>Using the ADOMD data adapter</li>
<li>Using the ADOMD data reader</li>
<p>In the first part we will use an adapter and fill the data into the data table and convert that to the JSON in the server-side itself. The problem in this method is, it needs many loops for formatting and creating.</p>
<p>In the second part we will use a data reader, while the object reads we will do the formatting and creating the JSON that needs only one loop. Sounds cool, right?</p>
<p><strong>Using the code</strong></p>
<p>Let us explain the first method.</p>
<li><strong>Using the ADOMD data adapter</strong></li>
<p>When you use an adapter and fill in the data table, the problem here you encounter is, the data table column name would be different and it will contain the hierarchy of the cube cells.</p>
<p><strong>For example:</strong> The data table header contains “.<strong>[MEMBER_CAPTION]</strong>”</p>
<p>So here I am just determining the actual header name from all the header columns. I am using a loop for that.</p>
<p>Please note that it is completely based on my requirements. You may want to do a different process of formatting.</p>
<p>To format I am using the following function.</p>
<p>[csharp]<br />
public DataTable HiMapColumnExcuteQuery(string query, string adoMDConnection)<br />
{<br />
    string readerString = string.Empty;<br />
    try<br />
    {<br />
        using (AdomdConnection conn = new AdomdConnection(adoMDConnection))<br />
        {<br />
            conn.Open();<br />
            using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
            {<br />
                    DataTable dt = new DataTable();<br />
                    AdomdDataAdapter da = new AdomdDataAdapter(cmd);<br />
                    da.Fill(dt);<br />
                    List&lt;string&gt; curColumn = new List&lt;string&gt;();<br />
                    string col = string.Empty;<br />
                    if (dt.Rows.Count &gt; 0 &amp;&amp; dt.Columns.Count &gt; 0)<br />
                    {<br />
                        for (int i = 0; i &lt; dt.Columns.Count; i++)<br />
                        {<br />
                            string columnName = dt.Columns[i].ColumnName.Replace(“.[MEMBER_CAPTION]”, “”).Trim();<br />
                            curColumn = columnName.Split(new string[] { “.” }, StringSplitOptions.None).ToList();<br />
                            col = curColumn[curColumn.Count – 1].Replace(“[“, “”).Replace(“]”, “”);<br />
                            if (Convert.ToString(col.Trim()).ToLower() == “latitude”)<br />
                                col = “lat”;<br />
                             if (Convert.ToString(col.Trim()).ToLower() == “longitude”)<br />
                                col = “lon”;<br />
                            dt.Columns[i].ColumnName = col;<br />
                        }<br />
                        dt.AcceptChanges();<br />
                    }<br />
                    return dt;<br />
            }<br />
        }<br />
    }<br />
    catch (Exception)<br />
    {<br />
        throw;<br />
    }<br />
    finally<br />
    {<br />
    }<br />
}<br />
[/csharp]</p>
<p>The function expects two parameters, one is the query that you need to execute and other is the connection. Here I am using this source for the Hi maps, as you all know it is important to provide the lat and lon for loading the map. So I am doing such formatting here.</p>
<p>Once the formatting is done, I can convert the data to the JSON foramt. For that I am using another function. You can see the function below.</p>
<p>[csharp]<br />
public string GetJsonWithZeroForNull(DataTable dt)<br />
{<br />
    try<br />
    {<br />
        if (dt == null)<br />
        {<br />
            throw new ArgumentNullException(“dt”);<br />
        }<br />
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();<br />
        serializer.MaxJsonLength = int.MaxValue;<br />
        List&lt;Dictionary&lt;string, object&gt;&gt; rows =<br />
          new List&lt;Dictionary&lt;string, object&gt;&gt;();<br />
        Dictionary&lt;string, object&gt; row = null;<br />
        foreach (DataRow dr in dt.Rows)<br />
        {<br />
            row = new Dictionary&lt;string, object&gt;();<br />
            foreach (DataColumn col in dt.Columns)<br />
            {<br />
                if (dr[col] == null || Convert.ToString(dr[col]).ToLower() == “undefined” || Convert.ToString(dr[col]).ToLower() == “unknown”)<br />
                    continue;<br />
                else<br />
                row.Add(col.ColumnName.Trim(), dr[col]);<br />
            }<br />
            rows.Add(row);<br />
        }<br />
        return serializer.Serialize(rows);<br />
    }<br />
    catch (Exception)<br />
    {<br />
        throw;<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here I am omitting the data that all are not valid. At the end it will just serialize our rows and return the data in the format of JSON.</p>
<p>You can determine that if the data is greater then looping through the data twice may impact the performance.</p>
<p>And also we all know that a data reader is much better than a data adapter. If you do not understand why, please read <a href="http://stackoverflow.com/questions/1676753/sqldataadapter-vs-sqldatareader" rel="nofollow">here</a>.</p>
<li><strong>Using the ADOMD data reader</strong></li>
<p>Now we will move to the next part. Please see the following function for doing that.</p>
<p>[csharp]<br />
public string createJsonFromDataReader(string query, string adoMDConnection)<br />
   {<br />
      string readerString = string.Empty;<br />
      try<br />
      {<br />
          List&lt;string&gt; curColumn = new List&lt;string&gt;();<br />
          StringBuilder sb = new StringBuilder();<br />
          StringWriter sw = new StringWriter(sb);<br />
          string columnName = string.Empty;<br />
          string fieldVal = string.Empty;<br />
          string prevFieldVal = string.Empty;<br />
          AdomdDataReader rdr;<br />
          using (AdomdConnection conn = new AdomdConnection(adoMDConnection))<br />
          {<br />
              conn.Open();<br />
              using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
              {<br />
                  //cmd.Properties.Add(“ReturnCellProperties”, true);<br />
                  rdr = cmd.ExecuteReader();<br />
                  if (rdr != null)<br />
                  {<br />
                      using (JsonWriter myJson = new JsonTextWriter(sw))<br />
                      {<br />
                          myJson.WriteStartArray();<br />
                          while (rdr.Read())<br />
                          {<br />
                              myJson.WriteStartObject();<br />
                              int fields = rdr.FieldCount;<br />
                              for (int i = 0; i &lt; fields; i++)<br />
                              {<br />
                                  if (rdr[i] != null )<br />
                                  {<br />
                                      fieldVal = rdr[i].ToString();<br />
                                      if (i != 0 &amp;&amp; rdr[i-1] != null)<br />
                                          prevFieldVal = rdr[i – 1].ToString();<br />
                                      else<br />
                                          prevFieldVal = “First”;<br />
                                      if ((fieldVal == null || fieldVal.ToLower().Trim() == “undefined” || fieldVal.ToLower().Trim() == “unknown”)<br />
                                          &amp;&amp; (prevFieldVal == null || prevFieldVal.ToLower().Trim() == “undefined” || prevFieldVal.ToLower().Trim() == “unknown”))<br />
                                      {<br />
                                          continue;<br />
                                      }<br />
                                      else<br />
                                      {<br />
                                          columnName = rdr.GetName(i).Replace(“.[MEMBER_CAPTION]”, “”).Trim();<br />
                                          curColumn = columnName.Split(new string[] { “.” }, StringSplitOptions.None).ToList();<br />
                                          columnName = curColumn[curColumn.Count – 1].Replace(“[“, “”).Replace(“]”, “”);<br />
                                          if (Convert.ToString(columnName.Trim()).ToLower() == “latitude”)<br />
                                              columnName = “lat”;<br />
                                          if (Convert.ToString(columnName.Trim()).ToLower() == “longitude”)<br />
                                              columnName = “lon”;<br />
                                          myJson.WritePropertyName(columnName);<br />
                                          myJson.WriteValue(rdr[i]);<br />
                                      }<br />
                                  }<br />
                              }<br />
                              myJson.WriteEndObject();<br />
                          }<br />
                          myJson.WriteEndArray();<br />
                      }<br />
                  }<br />
                  else<br />
                  {<br />
                      return “No Records to display”;<br />
                  }<br />
              }<br />
          }<br />
          return sw.ToString();<br />
      }<br />
      catch (Exception)<br />
      {<br />
          throw;<br />
      }<br />
      finally<br />
      {<br />
      }<br />
}<br />
[/csharp]</p>
<p>Please understand that I have created an object (myJson) for the class JsonWriter. Our complete process is based on this object. Again the complete logic and formatting conditions are based on my requirements.</p>
<p>Here we are using built-in functions of the JsonWriter class. Let us list them.</p>
<li>WriteStartArray()</li>
<li>WritePropertyName()</li>
<li>WriteValue()</li>
<li>WriteEndObject()</li>
<li>WriteEndArray()</li>
<p>You can see that I am doing both the formatting and creating of the JSON with one loop that will improve the performance.<br />
In the process we are appending the values to the string builder and finally the function will return the JSON in the required format.</p>
<p>You have done it. Great.</p>
<p>Please use StringBuilder in your applications instead of string. Use a string variable only if it is necessary. Using string variables will create separate memory allocations whenever you assign values to it. Please read more here.</p>
<li><a href="http://stackoverflow.com/questions/18453458/string-builder-vs-string-concatenation" rel="nofollow">String builder vs string concatenation</a></li>
<li><a href="http://stackoverflow.com/questions/3069416/difference-between-string-and-stringbuilder-in-c-sharp" rel="nofollow">Difference between string and StringBuilder in C#</a></li>
<p><strong>Note: </strong>I have implemented this for loading high maps. That&#8217;s why I have formatted it in this way. Please use your own formatting depending on your requirements.</p>
<p><strong>Point of interest</strong></p>
<p>ADOMD, ADOMD data source to JSON, ADOMD Cell Set to JSON, ADOMD data adapter to JSON, ADOMD data reader to JSON.</p>
<p><strong>Conclusion</strong></p>
<p>Please do not forget to give your valuable suggestions.</p>
<p>That is all for the day, will see you in another article.</p>
<p>Kindest Regards<br />
<a href="http://sibeeshpassion.com" rel="nofollow">Sibeesh Venu</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Convert CellSet to HTML Table and From HTML to JSON and to Array</title>
		<link>https://mail.sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/</link>
					<comments>https://mail.sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 29 Oct 2014 19:19:46 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[Microsoft Technologies]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD Cell]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[CellSet]]></category>
		<category><![CDATA[CellSet JSON]]></category>
		<category><![CDATA[Convert CellSet to JSON]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=591</guid>

					<description><![CDATA[Introduction For the past few days I have been working on ADOMD and MDX. I encountered a situation where I need to convert my Cell Set to a HTML table and render it to the client-side Grid. So I thought of sharing that with you all. This article has been selected as article of the day Monday, November 10, 2014 in http://www.asp.net/community/articles (Convert CellSet to HTML Table, and from HTML to Json, Array) Background If you are new to ADOMD, you can refer to the following links: Microsoft Analysis Services 2005: Displaying a grid using ADOMD.NET and MDX Manipulate and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>For the past few days I have been working on ADOMD and MDX. I encountered a situation where I need to convert my Cell Set to a HTML table and render it to the client-side Grid. So I thought of sharing that with you all.</p>
<p>This article has been selected as article of the day Monday, November 10, 2014 in http://www.asp.net/community/articles (Convert CellSet to HTML Table, and from HTML to Json, Array)</p>
<p><strong>Background</strong></p>
<p>If you are new to ADOMD, you can refer to the following links:</p>
<p><a href="http://www.codeproject.com/Articles/28290/Microsoft-Analysis-Services-Displaying-a-grid" target="_blank" rel="noopener">Microsoft Analysis Services 2005: Displaying a grid using ADOMD.NET and MDX</a><br />
<a href="http://www.microsoft.com/msj/0899/mdx/mdx.aspx" target="_blank" rel="noopener">Manipulate and Query OLAP Data Using ADOMD and Multidimensional Expressions</a></p>
<p><strong>Why</strong></p>
<p>As I have already said, in my current project we are using MDX cubes, so in the server-side we will get only a CellSet. So I have tried very much to convert the CellSet to the JSON for this JQX grid alone (all other Grids in the project use a HTML table as the data source). But I couldn’t find any good way for that. So I thought of getting the HTML table from the CellSet as in the other grid at the server side. And I knew how to formulate the Array and JSON from an HTML table. Here I am sharing that information.</p>
<p>Please provide your valuable suggestions for improvement.</p>
<p><strong>Using the Code</strong></p>
<p>We modify the code as per our needs from the preceding specified articles and bind to an HtmlTextWriter. We have created a function called renderHTML() that will accept CellSet as an argument. Here, I will show the code.<br />
[csharp]<br />
try<br />
            {<br />
                System.Text.StringBuilder result = new System.Text.StringBuilder();<br />
                //check if any axes were returned else throw error.<br />
                int axes_count = cst.Axes.Count;<br />
                if (axes_count == 0)<br />
                    throw new Exception(“No data returned for the selection”);<br />
                //if axes count is not 2<br />
                if (axes_count != 2)<br />
                    throw new Exception(“The sample code support only queries with two axes”);<br />
                //if no position on either row or column throw error<br />
                if (!(cst.Axes[0].Positions.Count &gt; 0) &amp;&amp; !(cst.Axes[1].Positions.Count &gt; 0))<br />
                    throw new Exception(“No data returned for the selection”);<br />
                int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;<br />
                cur_row = cur_col = col_count = row_count = col_dim_count = row_dim_count = 0;<br />
                //Number of dimensions on the column<br />
                col_dim_count = cst.Axes[0].Positions[0].Members.Count;<br />
                //Number of dimensions on the row<br />
                if (cst.Axes[1].Positions[0].Members.Count &gt; 0)<br />
                    row_dim_count = cst.Axes[1].Positions[0].Members.Count;<br />
                //Total rows and columns<br />
                row_count = cst.Axes[1].Positions.Count +<br />
                    col_dim_count;  //number of rows + rows for column headers<br />
                col_count = cst.Axes[0].Positions.Count +<br />
                    row_dim_count;  //number of columns + columns for row headers<br />
                //gridPanel.ClientIDMode = System.Web.UI.ClientIDMode.AutoID;<br />
                //////lets clear any controls under the grid panel<br />
                //gridPanel.Controls.Clear();<br />
                ////Add new server side table control to gridPanel<br />
                Table tblgrid = new Table();<br />
                tblgrid.Attributes.Add(“Id”, “myhtmltab”);<br />
                tblgrid.Attributes.Add(“class”, “display”);<br />
                //We will use label control to add text to the table cell<br />
                Label lbl;<br />
                string previousText = “”;<br />
                int colSpan = 1;<br />
                for (cur_row = 0; cur_row &lt; row_count; cur_row++)<br />
                {<br />
                    //add new row to table<br />
                    TableRow tr = new TableRow();<br />
                    for (cur_col = 0; cur_col &lt; col_count; cur_col++)<br />
                    {<br />
                        //create new cell and instance of label<br />
                        TableCell td = new TableCell();<br />
                        TableHeaderCell th = new TableHeaderCell();<br />
                        lbl = new Label();<br />
                        //check if we are writing to a ROW having column header<br />
                        if (cur_row &lt; col_dim_count)<br />
                        {<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this should be empty cell — it’s on top left of the grid.<br />
                                //result.Append(” ,”);<br />
                                lbl.Text = ” “;<br />
                                td.CssClass = “titleAllLockedCell”; //this locks<br />
                                    //the cell so it doesn’t scroll upwards nor leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is a column header cell — use member caption for header<br />
                                //result.Append(cst.Axes[0].Positions[cur_col –<br />
                                //    row_dim_count].Members[cur_row].Caption + “,”);<br />
                                //if (cur_row &lt; 1)<br />
                                //{<br />
                                    lbl.Text = cst.Axes[0].Positions[cur_col – row_dim_count].Members[cur_row].Caption;<br />
                                    th.CssClass = “titleTopLockedCell”; // this lockeders<br />
                                            //the cell so it doesn’t scroll upwards<br />
                                //}<br />
                                if (lbl.Text == previousText)<br />
                                {<br />
                                    colSpan++;<br />
                                }<br />
                                else<br />
                                {<br />
                                    colSpan = 1;<br />
                                }<br />
                            }<br />
                        }<br />
                        else<br />
                        {<br />
                            //We are here.. so we are writing a row having data (not column headers)<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this is a row header cell — use member caption for header<br />
                                lbl.Text = cst.Axes[1].Positions[cur_row –<br />
                                col_dim_count].Members[cur_col].Caption.Replace(“,”, ” “);<br />
                                td.CssClass = “titleLeftLockedCell”; // this lockeders<br />
                                    //the cell so it doesn’t scroll leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is data cell.. so we write the Formatted value of the cell.<br />
                                lbl.Text = cst[cur_col – row_dim_count, cur_row – col_dim_count].FormattedValue;<br />
                                //td.InnerText = cst[cur_col – row_dim_count,<br />
                                //cur_row – col_dim_count].FormattedValue;<br />
                                td.CssClass = “valueCell”; //this  right<br />
                                        //aligns the values in the column<br />
                            }<br />
                            //turn the wrapping off for row header and data cells.<br />
                            td.Wrap = true;<br />
                        }<br />
                        if (((lbl.Text != previousText) || (lbl.Text == ” “))<br />
                            &amp;&amp; (cur_row &lt; col_dim_count))<br />
                        {<br />
                            tr.TableSection = TableRowSection.TableHeader;<br />
                            th.Text = “HEADER”;<br />
                            th.Controls.Add(lbl);<br />
                            tr.Cells.Add(th);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else if ((lbl.Text != previousText) || (lbl.Text == ” “) ||<br />
                            (lbl.Text == null) || (lbl.Text == “”))<br />
                        {<br />
                            td.Controls.Add(lbl);<br />
                            tr.Cells.Add(td);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else<br />
                        {<br />
                            try<br />
                            {<br />
                                tr.Cells[tr.Cells.Count – 1].ColumnSpan = colSpan;<br />
                            }<br />
                            catch<br />
                            {<br />
                            }<br />
                        }<br />
                        if (cur_row &lt; col_dim_count)<br />
                            previousText = lbl.Text;<br />
                    }<br />
                    //result.AppendLine();<br />
                }<br />
                using (StringWriter writer = new StringWriter())<br />
                {<br />
                    HtmlTextWriter htw = new HtmlTextWriter(writer);<br />
                    tblgrid.RenderControl(htw);<br />
                    return htw.InnerWriter.ToString();<br />
                }<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                throw ex;<br />
            }<br />
[/csharp]</p>
<p>Finally, the function will return the output as an HTML table with the id “myhtmltab” where all the th, tr and td tags are rendered.</p>
<p>Now if you want, you can convert the HTML table to an Array, JSON in the client side.</p>
<p>Now what we need to do is just add the dynamic HTML to the DOM. You can do that as follows:<br />
[js]<br />
$(‘#your element id’).html(data);<br />
[/js]</p>
<p>Please read here for more information: <a href="http://api.jquery.com/html/" target="_blank" rel="noopener">Get the HTML contents of the first element in the set of matched elements.</a></p>
<p><strong>Convert HTML to Array Dynamically in jQuery</strong></p>
<p>Let’s say you have an Ajax jQuery function that will return the output as I have shown in the output image.</p>
<p>If you are new to jQuery Ajax function, please read here:</p>
<p><a href="http://www.codeproject.com/Tips/688228/Bind-Dropdownlist-in-ASP-NET-using-jQuery-AJAX" target="_blank" rel="noopener">Bind Dropdownlist in ASP.NET using jQuery AJAX</a><br />
<a href="http://www.codeproject.com/Articles/224827/Jquery-Ajax-Calling-functions" target="_blank" rel="noopener">Jquery Ajax Calling Functions</a><br />
<a href="http://www.codeproject.com/Articles/631438/Code-Builder-for-jQuery-AJAX-Calling-Web-Services" target="_blank" rel="noopener">Code Builder for jQuery AJAX (Calling Web Services)</a></p>
<p>Then in the success of the Ajax function, you can write the code like this to formulate an array.</p>
<p>Next is to get the columns and rows from the dynamic HTML table that you just formulated using CellSet:<br />
[js]<br />
var rows = $(“#myhtmltab tbody tr”); //Select Rows , looping through every tr<br />
var columns = $(“#myhtmltab thead th”); //Select columns , looping through every th<br />
[/js]<br />
Now what we need is an Array where we can populate the data. 🙂<br />
[js]<br />
var data = [];<br />
for (var i = 0; i &lt; rows.length; i++) {<br />
    var row = rows[i];<br />
    var datarow = {};<br />
    for (var j = 0; j &lt; columns.length; j++) {<br />
        // get column’s title.<br />
        var columnName = $.trim($(columns[j]).text());<br />
        // select cell.<br />
        var cell = $(row).find(‘td:eq(‘ + j + ‘)’);<br />
        datarow[columnName] = $.trim(cell.text());<br />
    }<br />
    data[data.length] = datarow;<br />
}<br />
[/js]</p>
<p>Now this is the time to formulate a JSON from the table. 🙂</p>
<p><strong>Convert Dynamic HTML to JSON Dynamically in jQuery</strong></p>
<p>As we discussed above, here also we are looping through the column and rows. The intent behind this is to formulate a dynamic JSON to assign data to my JQX Grid (You can check this out: <a href="http://sibeeshpassion.com/Working-With-JQX-Grid-With-Filtering-And-Sorting/" target="_blank" rel="noopener">Working With JQX Grid With Filtering And Sorting</a>).<br />
[js]<br />
var varDataFields = ‘[‘;<br />
var varDataColumns = ‘[‘;<br />
var typ = ‘string’;<br />
var align = ‘center’;<br />
var width = ‘200’;<br />
var myColumns = $(“#myhtmltab thead th”);<br />
for (var j = 0; j &lt; myColumns.length; j++) {<br />
    var column = myColumns[j];<br />
    var col = $(column).text().trim();<br />
    //col = col.replace(‘&lt;span&gt;’, ”);<br />
    //col = col.replace(‘&lt;/span&gt;’, ”);<br />
    //var col = $(columns).find(‘th:get(‘ + j + ‘).find(‘ &lt; span &gt; ‘).text()’);<br />
    //if (!col == ”) {<br />
    varDataFields = varDataFields +<br />
    ‘ { \”name\” : \”‘ + col + ‘\” , \”type\” : \”‘ + typ + ‘\”},’;<br />
    varDataColumns = varDataColumns +<br />
    ‘ { \”text\” : \”‘ + col + ‘\” , \”dataField\” :  \”‘ +<br />
    col + ‘\” , \”align\” :  \”‘ + align + ‘\” , \”width\” : \”‘ + width + ‘\”},’;<br />
    //}<br />
    if (j == myColumns.length – 1) {<br />
        varDataFields = varDataFields.slice(0, -1);<br />
        varDataColumns = varDataColumns.slice(0, -1)<br />
    }<br />
}<br />
varDataFields = varDataFields + ‘]’;<br />
varDataColumns = varDataColumns + ‘]’;<br />
varDataFields = varDataFields.trim();<br />
varDataColumns = varDataColumns.trim();<br />
var DataFields = $.parseJSON(varDataFields);<br />
var DataColumns = $.parseJSON(varDataColumns);<br />
[/js]</p>
<p>So in DataFields, DataColumns, I will get the JSON in the way that I want. This I can directly bind to the JQX Grid. 🙂</p>
<p><strong>Points of Interest</strong></p>
<p>ADOMD, MDX</p>
<p><strong>History</strong></p>
<p>First version: 27-Oct-2014</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
