PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label datatable. Show all posts
Showing posts with label datatable. Show all posts

Thursday, October 27, 2022

[FIXED] How to get input value with no id using JavaScript?

 October 27, 2022     asp.net-mvc, datatable, html, javascript, jquery     No comments   

Issue

I have an editable DataTabe and when edit mode, the generated html is exactly as shown below:

<td><form><input autocomplete="off" name="value" ></form></td>

There is s TextBox as input and I need t get the value of this input. However, I cannot give id as there is no configuration of DataTable and I decided to get the value using Javaascipt. I have tried many different methods like closest() as shown below, but cannot get the value. Is it possible to grab it?

var $row = $(this).closest("tr"); 
$tds = $row.find("td");

Solution

You might use document.querySelector:

var input = document.querySelector('[name="value"]`);

Or, using jQuery, you could also use the same selector:

var input = $('[name="value"]');


Answered By - Matías Fidemraizer
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 20, 2022

[FIXED] How to match a parameter value which contains ("${") using Cucumber DataTable in Java

 September 20, 2022     cucumber, datatable, hashmap, java, rest-assured     No comments   

Issue

I have the below Cucumber scenario with data table. I want to set query parameters in REST Assured framework. Here we have key= at and value=${atToken} which I am trying to get runtime value instead of passing hardcoded value through data table. In the below setParams method, I am trying to match the ${atToken} using param.contains("${"), but I am not able to get the desired result. Please let me know what I need to change in this for loop.

for (String param : params.keySet()) {
    if (param.contains("${")) {
        params.replace(param, RUN_TIME_DATA.get(param));
    }
}

Feature file:

  And I set query parameters
  | location     | NY         |
  | at           | ${atToken} |

Stepdefintion:

@And("set {} parameters")
public void set_query_parameters(String query, DataTable params) throws IOException {
    POC.setParams(query, params.asMap());
}

Utils file:

public void setParams (String type, Map < String, String > params) throws IOException {
    for (String param : params.keySet()) {
        if (param.contains("${")) {
            params.replace(param, RUN_TIME_DATA.get(param));
        }
    }
    switch (type.toLowerCase()) {
        case "form":
            request.formParams(params);
            break;
        case "query":
            request.queryParams(params);
            break;
        case "path":
            request.pathParams(params);
            break;

    }
}

Hooks file:

@Before
public void beforeScenario() throws Exception {
    RUN_TIME_DATA.put("atToken", POC.createAuth());
}

Solution

If I understood correctly your quetion, there are a few issues with your implementation.

First of all, you have a gherkin instruction as And I set query parameters but the step definition is @And("set {} parameters")

As you defined "query" in your step definition, I assume that you have a scenario like this.

Scenario Outline: Params scenario
Given ...
When ...
Then ...
    And I set "<queryType>" parameters
      | location | NY         |
      | at       | ${atToken} |
    Examples:
      | queryType |
      | form      |
      | path      |

Second problem is that params.asMap() does not create a mutable map but your setParams method will need a mutable one.

@And("I set {string} parameters")
public void set_query_parameters(String queryType, DataTable params) throws IOException {
    // POC.setParams(queryType, params.asMap()); // not mutable map
    POC.setParams(queryType, new HashMap(params.asMap()));
}

The main issue in your loop was that you were searching $ symbol in key instead of value.

public void setParams (String type, Map<String, String> params) throws IOException {
      for (Map.Entry<String, String> entry : params.entrySet()) {
         final String key = entry.getKey();
         final String value = entry.getValue();

         // if value is parameterized
         if (value.contains("${")) {
            // you are using stripped value as key in your RUN_TIME_DATA
            final String keyInRuntimeMap = getParamKeyFrom(value);                      
            params.replace(key, RUN_TIME_DATA.get(keyInRuntimeMap));
         }
      }

      switch (type.toLowerCase()) {
         case "form":
            request.formParams(params);
            break;
         case "query":
            request.queryParams(params);
            break;
         case "path":
            request.pathParams(params);
            break;
        // what should happen if unknown type given
         default:
            throw new IllegalArgumentException("unknown type=" + type);
      }
   }

     /**
    * Will strip someKey from ${someKey}
    *
    * @param text
    * @return stripped text or the original text
    */
   private String getParamKeyFrom(final String text) {
      // pattern to match -> ${someKey}
      final Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
      final Matcher matcher = pattern.matcher(text);

      if (matcher.find()) {
         return matcher.group(1);
      }

      // if pattern does not match return the same string
      return text;
   }

Hope it helps.



Answered By - ocos
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 9, 2022

[FIXED] Why will data not bind if success and error are defined - datatables ajax

 September 09, 2022     ajax, datatable, jquery, json     No comments   

Issue

My ajax call is:

var networkslisttab = null;

...

networkslisttab = $('#networkslisttable').DataTable({
    "ajax": { "url": networkstoolboxURL, "dataType": "json", "dataSrc": '', "success": function (data) { networkslisttab.processing(false); console.log(data); }, "error": function (error) { console.log("error in networks"); } },
    //"dataSrc": '',        
    "columns": [
        {
            "data": 'reference_id',
            "width": '15%',
        },
        { "data": 'name' },
        {
            "data": 'num_points',
            "width": '15%',
        },
        {
            "data": 'num_sections',
            "width": '15%',
        }
    ],
    "order": [[0, "desc"]],
    "processing": true,
    "autoWidth": false, // need this to handle rendering issues in bootstrap and during re-size.  Note handlers at end of page.
    "scrollY": "200px",  // make it a small scrolling table
    "scrollX": true,
    "paging": false,
    "info": false,
    "language": {
        "processing": '<span style="width:100%;"><img src="/Content/icons/ajax-loader-orange-med.gif" /></span>'
    },
    "searching": false
});

console.log in "success" gives me the following json array but it is not bound to the datatable

[{reference_id: '873', name: 'MapTest', details: 'Sourced from Open Street Maps', num_points: 0, num_sections: 23}, {reference_id: '899', name: 'Albury C roads', details: 'Sourced from Open Street Maps', num_points: 0, num_sections: 0}]

but it is not bound to the table what am I missing?

Update

By removing the success and error properties, data started binding..Why?

networkslisttab = $('#networkslisttable').DataTable({
    "ajax": {
        "url": networkstoolboxURL,
        "dataSrc": ''
        
    }             
    "columns": [
        {
            "data": 'reference_id',
            "width": '15%',
        },
        { "data": 'name' },
        {
            "data": 'num_points',
            "width": '15%',
        },
        {
            "data": 'num_sections',
            "width": '15%',
        }
        
    ],
    "order": [[0, "desc"]],
    "processing": true,
    "autoWidth": false, // need this to handle rendering issues in bootstrap and during re-size.  Note handlers at end of page.
    "scrollY": "200px",  // make it a small scrolling table
    "scrollX": true,
    "paging": false,
    "info": false,
    "language": {
        "processing": '<span style="width:100%;"><img src="/Content/icons/ajax-loader-orange-med.gif" /></span>'
    },
    "searching": false
});

enter image description here


Solution

As you have seen, you should not override the jQuery Ajax success option in your DataTables ajax option.

As documented here:

...the success option of ajax should not be altered - DataTables uses it internally to execute the table draw when the data load is complete.

Use the dataSrc option instead, for any custom processing you may want to do after receiving the JSON response via Ajax.


(I have not experimented with the error property of the DataTables ajax option - it may be the same situation as the success option. It's not mentioned in the documentation I linked to.)



Answered By - andrewJames
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 8, 2022

[FIXED] How to call a post handler from a ajax render function and pass the value

 September 08, 2022     ajax, asp.net-core, datatable, post, razor-pages     No comments   

Issue

Here's my code. The post handler in the render function does not get called. It keeps going to the GET handler when clicked. The a href tag works fine but i dont want to pass the id value in the url. So, I want to call a post and then do a redirect.

@section Scripts {
        <script>
 
            $(document).ready(function () {
               
                    $.ajax({
                        serverSide: true,
                        type: "Get",
                        url: "/SRes?handler=Json",
                        dataType: "json",
                        success: OnSuccess,
                        beforeSend: function () {
                            console.log('before send')
                            $('#loadModal').show();
                        },
                        complete: function () {
                            console.log('complete send')
                            $('#loadModal').hide();
 
                        }
 
                    });
 
 
            });
 
 
            function OnSuccess(response) {
                console.log(response.data)
 
                $('#myTable').DataTable(
                    {
                        "dom": '<"top"Blf>rt<"bottom"rip><"clear">',
                        buttons: [
 
                            'excel', 'pdf', 'print'
                        ],
 
                        scrollY: "400",
                        pageLength: 25,
                        data: response.data,
                        columns: [{
                            className: 'details-control',
                            orderable: false,
                            data: null,
                            defaultContent: ''
 
                        },
 
                        {
                            "data": "Id",
                            "render": function (data, type, row, meta) {
                                if (type === 'display') {
                                    /* data = '<a target="_blank" href="/details?id=' + data + '">' + data + '</a>';*/
                                    /*  data = '<asp:LinkButton ID="LinkButton1" runat="server" OnClick="Details">Test</asp:LinkButton>';*/
                                    data = '<form asp-page-handler=”Details” method=”post”><button type=”submit” class=”btn btn-default”>Save Data</button></form>';
                                }
 
                                return data;
                            }
 
                        },
                        { "data": "name" },
                        { "data": "desc" },
                        { "data": "address" },
                        { "data": "Type" },
                            /* { "data": "status" }*/
                        ],
 
                        initComplete: function (settings, json) {
 
                            $('#myTable').DataTable().columns.adjust();
                            $('#myTable').DataTable().fixedHeader.adjust();
                        },
 
                    });
 
 
                $('#myTable tbody').on('click', 'td.details-control', function () {
                    var table = $('#myTable').DataTable();
                    var tr = $(this).closest('tr');
                    var row = table.row(tr);
 
                    if (row.child.isShown()) {
                        row.child.hide();
                        tr.removeClass('shown');
                    }
                    else {
                        row.child(format(row.data())).show();
                        tr.addClass('shown');
                    }
                });
 
 
            };
 
            function format(rowData) {
                //var div = $('<div/>')
 
                //div.append(rowData.DOB);
                //div.append(rowData.filingDate);
                //div.append(rowData.type);
                // `d` is the original data object for the row
                return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
                    '<tr>' +
                    '<td>Case Filing Date:</td>' +
                    '<td>' + rowData.recDate + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>Case Type:</td>' +
                    '<td>' + rowData.type + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>Date of Birth:</td>' +
                    '<td>'+ rowData.DOB + '</td>' +
                    '</tr>' +
                    '</table>';
 
 
                return div;
            }
 
 
        </script>
    }
 
 

Here's my code behind. I would like to pass the value of the id to this function. I am using razor pages.

  public IActionResult OnPostDetails()
            {
                return RedirectToPage("./cust");
            }

Solution

You need to use html code rather than tag helper in DataTable.It will not be generated to html code automatically.When using action in post form,the AntiForgeryToken will not be included in the form.So you need to add it to the forms in initComplete.Try to use the following code: html:

<div id="AntiForgeryToken">
    @Html.AntiForgeryToken()
</div>
...

js:

$('#myTable').DataTable(
                    {
                        "dom": '<"top"Blf>rt<"bottom"rip><"clear">',
                        buttons: [
 
                            'excel', 'pdf', 'print'
                        ],
 
                        scrollY: "400",
                        pageLength: 25,
                        data: response.data,
                        columns: [{
                            className: 'details-control',
                            orderable: false,
                            data: null,
                            defaultContent: ''
 
                        },
 
                        {
                            "data": "Id",
                            "render": function (data, type, row, meta) {
                                if (type === 'display') {
                                  
                                    data = '<form name="testForm" action="?handler=Details" method="post"><input name="id" hidden value="'+data+'" /><button type="submit" class="btn btn-default">Save Data</button></form>';
                                }
 
                                return data;
                            }
 
                        },
                        { "data": "name" },
                        { "data": "desc" },
                        { "data": "address" },
                        { "data": "Type" },
                            /* { "data": "status" }*/
                        ],
 
                        initComplete: function (settings, json) {
                             $("form[name='testForm']").each(function (index) {
                            $("form[name='testForm']")[index].innerHTML = $("form[name='testForm']")[index].innerHTML + document.getElementById("AntiForgeryToken").innerHTML;
                        })
                            $('#myTable').DataTable().columns.adjust();
                            $('#myTable').DataTable().fixedHeader.adjust();
                        },
 
                    });

OnPostDetails:

public IActionResult OnPostDetails(int id)
            {
                return RedirectToPage("./cust");
            }


Answered By - Yiyi You
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 6, 2022

[FIXED] how to add custom action buttons in jquery datatable edit/delete

 September 06, 2022     ajax, datatable, jquery     No comments   

Issue

I tried adding the action buttons in my ajax datatable edit/delete but its not working. I tried adding it using data option but its messing up the ajax call here is the code

<script type="text/javascript">
                
    $(document).ready(function(){

       $(document).on("click" , "#add-stockin" , function(){

        window.location.href = './stockin.php';

     }); 
 
    var table = $('#table1').DataTable( {
        dom: "Bfrtip",
      ajax: {
        url : "http://localhost/cokeinventory/rest-api/api-search-stockin.php",
        dataSrc: "doc",
        
       
      },
      columns: [
        { data: 'stock_id'},
        { data: 'item_name'},
        { data: 'unit' },
        { data: 'stockin_qty' },
        { data: 'barcode_number' },
        { data: 'barcode_label' },
        { data: 'balquantity' },
        {data: "stock_id" , render : function ( data, type, row, meta ) {
              return type === 'display'  ?
                '<a href="" id='deletebtn';?>'+ data +'" >Delete<i class="fe fe-delete"></i></a>' :
                
            }},

      ],
    });

  });

    </script>

Solution

Below is the code to add custom action links to jQuery datatable:

Here please refer official documentation for the same: https://editor.datatables.net/examples/simple/inTableControls.html

$(document).ready(function(){
        $(document).on("click" , "#add-stockin" , function(){
            window.location.href = './stockin.php';
        });

        var table = $('#table1').DataTable( {
            dom: "Bfrtip",
            ajax: {
                url : "http://localhost/cokeinventory/rest-api/api-search-stockin.php",
                dataSrc: "doc",
            },
            columns: [
                { data: 'stock_id'},
                { data: 'item_name'},
                { data: 'unit' },
                { data: 'stockin_qty' },
                { data: 'barcode_number' },
                { data: 'barcode_label' },
                { data: 'balquantity' },
                {
                    data: null,
                    className: "dt-center editor-delete",
                    orderable: false,
                    "mRender" : function ( data, type, row ) {
                        return '<a href="" id="deletebtn_' + data.stock_id+'" >Delete <i class="fe fe-delete"></i></a>';
                    }
                }

            ],
        });

    });


Answered By - Aniket Panchal
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 28, 2022

[FIXED] How to read a CSV file into a .NET Datatable

 August 28, 2022     .net, c#, csv, datatable     No comments   

Issue

How can I load a CSV file into a System.Data.DataTable, creating the datatable based on the CSV file?

Does the regular ADO.net functionality allow this?


Solution

Here's an excellent class that will copy CSV data into a datatable using the structure of the data to create the DataTable:

A portable and efficient generic parser for flat files

It's easy to configure and easy to use. I urge you to take a look.



Answered By - Jay Riggs
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, August 27, 2022

[FIXED] How do you create a data table from json in C# (visual basic)

 August 27, 2022     c#, csv, datatable, json, visual-studio     No comments   

Issue

I have inherited a project using Visual Studio (.NET Framework 4.7.2, I think). I'm receiving a response from an API endpoint with multiple entries which looks like so:

[
    {
        "transaction_id": "00000352",
        "transaction_type": "New",
        "transaction_date": "2018-08-23T00:00:00",
        "sold_to_id": "00026",
        "customer_po_number": "34567",
        "po_date": "2018-08-23T00:00:00",
        "notes": null,
        "batch_code": "######",
        "location_id": "MN",
        "req_ship_date": "2018-08-28T00:00:00",
        "fiscal_period": 8,
        "fiscal_year": 2018,
        "currency_id": "USD",
        "original_invoice_number": null,
        "bill_to_id": "00026",
        "customer_level": null,
        "terms_code": "30-2",
        "distribution_code": "01",
        "invoice_number": null,
        "invoice_date": "2018-08-23T00:00:00",
        "sales_rep_id_1": null,
        "sales_rep_id_1_percent": 100,
        "sales_rep_id_1_rate": 0,
        "sales_rep_id_2_id": "SA",
        "sales_rep_id_2_percent": 100,
        "sales_rep_id_2_rate": 10,
        "ship_to_id": null,
        "ship_via": null,
        "ship_method": null,
        "ship_number": null,
        "ship_to_name": "",
        "ship_to_attention": null,
        "ship_to_address_1": null,
        "ship_to_address_2": null,
        "ship_to_city": null,
        "ship_to_region": null,
        "ship_to_country": "USA",
        "ship_to_postal_code": null,
        "actual_ship_date": null,
        "order_line_list": [
            {
                "entry_number": 1,
                "item_id": "5' Glass/Wood Table",
                "description": "Glass/ Wood Combo Coffee Table",
                "customer_part_no": null,
                "additional_description": null,
                "location_id": "MN",
                "quantity_ordered": 11,
                "units": "EA",
                "quantity_shipped": 0,
                "quantity_backordered": 0,
                "req_ship_date": null,
                "unit_price": 599.99,
                "extended_price": 6599.89,
                "reason_code": null,
                "account_code": null,
                "inventory_gl_account": "120000",
                "sales_gl_account": "400000",
                "cogs_gl_account": "500000",
                "sales_category": null,
                "tax_class": 0,
                "promo_id": null,
                "price_id": null,
                "discount_type": 0,
                "discount_percentage": 0,
                "discount_amount": 0,
                "sales_rep_id_1": null,
                "sales_rep1_percent": null,
                "sales_rep1_rate": null,
                "sales_rep_id_2": "SA",
                "sales_rep2_percent": 100,
                "sales_rep2_rate": 5,
                "unit_cost": 241.4467,
                "extended_cost": 2655.91,
                "status": "Open",
                "extended_list": [],
                "serial_list": []
            }
        ],
        "tax_group_id": "ATL",
        "taxable": false,
        "tax_class_adjustment": 0,
        "freight": 0,
        "tax_class_freight": 0,
        "tax_location_adjustment": null,
        "misc": 0,
        "tax_class_misc": 0,
        "sales_tax": 0,
        "taxable_sales": 0,
        "non_taxable_sales": 6599.89,
        "payment_list": []
    }
]

I would like to select individual key-value pairs from this response and create a data table. I'm extremely new (and somewhat allergic) to C# but I have tried doing this:

var doc = JsonDocument.Parse(response.Content);
JsonElement root = doc.RootElement;

//Console.WriteLine(doc.RootElement);
Console.WriteLine(String.Format("Root Elem: {0}", doc.RootElement));

//creat data table
var jsonObject = JObject.Parse(response.Content);
Console.WriteLine(String.Format("jsonObject col: {0}", jsonObject));
DataTable jsdt = jsonObject[doc.RootElement].ToObject<DataTable>();

int totalRows = jsdt.Rows.Count;


Console.WriteLine(String.Format("jsonObject col: {0}", jsonObject));

Console.WriteLine(String.Format("totalRows col: {0}", totalRows));
Console.WriteLine(String.Format("jsdt col: {0}", jsdt.Rows.Count));

I can't seem to get the DataTable to log to the console and have no idea if I'm actually creating the DataTable at all. I can loop through the JSON response to find individual key-value pairs but writing things to a DataTable is where I'm stuck. This is how I'm looping through the JSON:

var users = root.EnumerateArray();

while (users.MoveNext())
{
    var user = users.Current;
    //System.Console.WriteLine(user);

    var props = user.EnumerateObject();

    while (props.MoveNext())
    {
        var prop = props.Current;
        //Console.WriteLine($"{prop.Name}: {prop.Value}");
        if (prop.Name == "transaction_date") {
            //Console.WriteLine(String.Format("key: {0}", $"{prop.Name}: {prop.Value}"));
        }
    }
}

How would one go about creating a DataTable in this way?

Update:

My ultimate purpose is to create a CSV and ship it to another server.

I recognize that a CSV file is basically a 2d array of primitive values but that my JSON objects contain nested arrays of complex objects (e.g. [*].order_line_list[*]) which will need to be flattened somehow. For this purpose flattening into multiple rows would be fine, e.g. parent name, parent info, nested item info 1; parent name, parent info, nested item info 2;


Solution

Your basic problem here is that you have a JSON array containing JSON objects with possibly non-primitive object and array values, and you would like to eventually export that to CSV. However, a CSV file is essentially a 2d array of primitive values, so you will need to flatten the non-primitives into primitives. In order to do this, you may either

  1. Extend the CSV horizontally by adding extra columns for nested values.
  2. Extend the CSV vertically by adding extra rows for nested values.

You chose option 2, Multiple rows would be fine, eg parent name, parent info, nested item info 1; parent name, parent info, nested item info 2;

To do that, we're going to need two third-party tools, the LINQ to JSON from Json.NET to parse your arbitrary JSON objects, and CsvWriter from CsvHelper to write a CSV file.

First, introduce the following extension method to flatten a LINQ to JSON JObject into an enumerable of enumerable of key/value pairs of primitive JSON values:

public static partial class JsonExtensions
{
    public static IEnumerable<IEnumerable<KeyValuePair<string, JValue>>> FlattenChildrenIntoRows(this JObject obj)
    {
        bool anyReturned = false;
        var simpleChildren = obj.Properties().Where(p => p.Value is JValue).Select(p => new KeyValuePair<string, JValue>(p.Name, (JValue)p.Value)).ToList();
        var complexChildren = obj.Properties().Where(p => !(p.Value is JValue)).Select(p => new KeyValuePair<string, JToken>(p.Name, p.Value));
        foreach (var property in complexChildren)
        {
            foreach (var flattenedItems in FlattenChildrenIntoRows(property))
            {
                yield return simpleChildren.Concat(flattenedItems);
                anyReturned = true;
            }
        }

        if (!anyReturned)
            yield return simpleChildren;
    }

    static IEnumerable<IEnumerable<KeyValuePair<string, JValue>>> FlattenChildrenIntoRows(KeyValuePair<string, JToken> property) 
    {
        if (property.Value is JValue value)
        {
            yield return new[] { new KeyValuePair<string, JValue>(property.Key, value) };
        }
        else if (property.Value is JArray array)
        {
            foreach (var item in array)
                foreach (var flattenedItem in FlattenChildrenIntoRows(new KeyValuePair<string, JToken>(property.Key, item)))
                    yield return flattenedItem;
        }
        else if (property.Value is JObject obj)
        {
            foreach (var flattenedItems in FlattenChildrenIntoRows(obj))
                yield return flattenedItems.Select(p => new KeyValuePair<string, JValue>(property.Key + "." + p.Key, p.Value));
        }
        else // JRaw, JContainer
        {
            throw new NotImplementedException();
        }
    }
}

Next, introduce the following method to write a list of Dictionary<string, string> objects to a CSV file, making the dictionary keys be the CSV column names:

public static partial class CsvExtensions
{
    public static void WriteCsv(TextWriter writer, IReadOnlyList<IDictionary<string, string>> objects, CsvConfiguration config)
    {
        var headers = objects.SelectMany(o => o.Keys).Distinct();
        using (var csv = new CsvWriter(writer, config))
        {
            foreach (var header in headers)
                csv.WriteField(header);
            csv.NextRecord();
            foreach (var obj in objects)
            {
                foreach (var header in headers)
                    if (obj.TryGetValue(header, out var value))
                        csv.WriteField(value);
                    else
                        csv.WriteField(null);
                csv.NextRecord();
            }
        }           
    }
}

And now we can combine these two methods to read a JSON array, flatten it, and write to CSV as follows:

public static partial class CsvExtensions
{
    /// Convert a JSON file to a CSV file
    public static void ConvertJsonToCsv(string inputPath, string outputPath)
    {
        using var reader = new StreamReader(inputPath);
        using var writer = new StreamWriter(outputPath);
        ConvertJsonToCsv(reader, writer);
    }
    
    /// Read JSON from the incoming TextReader, convert to CSV and write to the incoming TextWriter
    public static void ConvertJsonToCsv(TextReader reader, TextWriter writer)
    {
        // Disable reformatting of dates
        var settings = new JsonSerializerSettings
        {
            DateParseHandling = DateParseHandling.None,
        };
        
        using var jsonReader = new JsonTextReader(reader) { CloseInput = false };
        
        // Deserialize to an array of objects
        
        var array = JsonSerializer.CreateDefault(settings).Deserialize<List<JObject>>(jsonReader);
        
        // Flatten and convert to a List<Dictionary<string, string>>
        
        var list = array
            // Flatten each child into an enumerable of enumerable of primitive key/value pairs
            .Select(o => o.FlattenChildrenIntoRows())
            // Project and flatten to an overall enumerable of enumerable of pairs
            .SelectMany(pairs => pairs)
            // Convert to an overall enumerable of dictionaries
            .Select(pairs => pairs.ToDictionary(p => p.Key, p => p.Value.Value == null ? null : (string)Convert.ChangeType(p.Value.Value, typeof(string), CultureInfo.InvariantCulture)))
            // Materialize as a list of dictionaries
            .ToList();
        
        // Write to CSV
        var config = new CsvConfiguration(CultureInfo.InvariantCulture);
        CsvExtensions.WriteCsv(writer, list, config);
    }
}

Which you might call like:

using var reader = new StringReader(response.Content);
using var writer = new StringWriter();

CsvExtensions.ConvertJsonToCsv(reader, writer);

var csvText = writer.ToString();

Console.WriteLine(csvText);

Demo fiddle here.



Answered By - dbc
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, August 13, 2022

[FIXED] How to make a output result as a table form in R

 August 13, 2022     dataframe, datatable, output, r     No comments   

Issue

I am having the three output results as below,

structure(c("[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", 
"[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", "[1] \"lls_loess\" \"lls_rlr\"   \"lls_vsn\"  "
), dim = c(1L, 3L), dimnames = list(NULL, c("Based_on_PCV", "Based_on_PEV", 
"Based_on_PMAD")))

I have used the names() code for extracting the names from the result output.

And I want to give the output to the user in the format as in the picture. example result format

Please suggest some R code for this matter.


Solution

Well... this is some quite ugly data, one possible solution

x=structure(c("[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", 
            "[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", "[1] \"lls_loess\" \"lls_rlr\"   \"lls_vsn\"  "
), dim = c(1L, 3L), dimnames = list(NULL, c("Based_on_PCV", "Based_on_PEV", 
                                            "Based_on_PMAD")))
df=data.frame(x)

data.frame(
  sapply(
    sapply(
      df,
      function(i){
        strsplit(
          gsub('"',",",gsub('\\[[0-9]+\\]| ',"",i)),
          ","
        )
      }
    ),
    function(j){j[j!=""]}
  )
)

  Based_on_PCV Based_on_PEV Based_on_PMAD
1    lls_loess    lls_loess     lls_loess
2      lls_rlr      lls_rlr       lls_rlr
3    knn_loess    knn_loess       lls_vsn


Answered By - user2974951
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] Why 0/0 is NaN but 0/0.00 isn't

 August 11, 2022     c#, datatable, decimal, double, formula     No comments   

Issue

Using DataTable.Compute, and have built some cases to test:

dt.Compute("0/0", null); //returns NaN when converted to double

dt.Compute("0/0.00", null); //results in DivideByZero exception

I have changed my code to handle both. But curious to know what's going on here?


Solution

I guess, that it happens because literals with decimal points are threated as System.Decimal and cause the DivideByZeroException

According to DataColumn.Expression

Integer literals [+-]?[0-9]+ are treated as System.Int32, System.Int64 or System.Double

Real literals without scientific notation, but with a decimal point, are treated as System.Decimal. If the number exceeds the maximum or minimum values supported by System.Decimal, then it is parsed as a System.Double.

Accroding to DivideByZeroException

The exception that is thrown when there is an attempt to divide an integral or Decimal value by zero.

For System.Double it returns Nan, because if the operation is a division and the constants are integers it changes to a double result type, according to reference source (Thanks @steve16351 for nice found)



Answered By - Pavel Anikhouski
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 2, 2022

[FIXED] How to add Current Date and Time into Table?

 August 02, 2022     datatable, datetime, function, html-table, javascript     No comments   

Issue

how can I add the current date and time with this format: 2022-07-17 17:50:20?

I already managed it with an input value but I need the current time.


Solution

You should use built-in Date object in Javascript, like this:

let currentdate = new Date(); 
let datetime = currentdate.getFullYear() + "-"
                + String((currentdate.getMonth() + 1)).padStart(2,"0")  + "-" 
                + String(currentdate.getDate()).padStart(2,"0") + " "
                + String(currentdate.getHours()).padStart(2,"0") + ":"  
                + String(currentdate.getMinutes()).padStart(2,"0") + ":" 
                + String(currentdate.getSeconds()).padStart(2,"0");
//The `+1` on the getMonth() is used because in Javascript January is 0.
console.log(datetime);

By the way, I suggest you make all your vars into lets as that's the current standard. There's a very fine difference between them (let is block scoped while var is functional scoped).



Answered By - TheBooker66 aka Ethan
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 12, 2022

[FIXED] How to change default p:dataTable emptyMessage message

 July 12, 2022     datatable, internationalization, jsf, messages, primefaces     No comments   

Issue

I am using PrimeFaces' dataTable. I get "No records found." when table has no element. I want to change this message to something like "No result" and make this message i18n type.

I don't want to use

<p:dataTable 
    id="idTable" 
    ...
    emptyMessage="#{messages['general.message.EmptyList']}"
>

for every table.

How can I change p:dataTable default emptyMessage message?


Solution

From the PrimeFaces 3.5 DataTable source code:

210    public java.lang.String getEmptyMessage() {
211        return (java.lang.String) getStateHelper().eval(PropertyKeys.emptyMessage, "No records found.");
212    }

So, it's hard coded and there's no way to change it in a single place other way than hacking the PrimeFaces source or creating a tagfile (not composite!) <my:dataTable> which wraps the <p:dataTable> with the desired message set.

<ui:composition ...>
    <p:dataTable id="#{id}" value="#{value}" var="item" 
        emptyMessage="#{messages['general.message.EmptyList']}">
        <ui:insert />
    </p:dataTable>
</ui:composition>
<my:dataTable id="foo" value="#{bean.items}">
    <p:column>#{item.foo}</p:column>
    <p:column>#{item.bar}</p:column>
</my:dataTable>

If you actually don't want to change the message, but merely want to hide it altogether, then you could also opt for a pure CSS solution:

.ui-datatable-empty-message {
    display: none;
}


Answered By - BalusC
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, June 25, 2022

[FIXED] How to solve a "cannot assign to 'this' as it is readonly" error c#

 June 25, 2022     c#, compiler-errors, datatable, json, this     No comments   

Issue

I am creating a class that creates my own custom table using DataTable.

I want it so that if a json file with the DataTable's info is on my computer; the code will put the json file into that instance of the object (done in the constructor)

This is how i am trying to do it

public Table(string jsonfile)
    {
        if(File.Exists(jsonfile))
        {
            this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return;
        }
        formatRegisterTable(jsonfile);
    }

this line is causing the error

this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));

How can I do this without the error?

The full code of the class if needed:

using System.IO;
using System.Data;
using Newtonsoft.Json;

namespace abc.classess._table
{
     class Table
    {
        public DataTable mTable = new DataTable("table");
        private DataColumn mColumn;
        private DataRow mRow;
        

        public Table(string jsonfile)
        {
            if(File.Exists(jsonfile))
            {
                this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
                return;
            }
            formatRegisterTable(jsonfile);
        }

        private void formatRegisterTable(string jsonfile) 
        {
            //formatting table code

            File.WriteAllText(jsonfile,JsonConvert.SerializeObject(this));
        }
    }
}

Solution

Something like this should solve your problem:

Inside you Table class create the following function:

 public static Table Create(string jsonfile)
 {
       if (File.Exists(jsonfile))
       {
            Table table = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return table;
        }
        
        return new Table(jsonfile);
  }

Your table constructor should look now like this:

 public Table(string jsonfile)
 {
    formatRegisterTable(jsonfile);
 }

Then you can use it in ur code var newTable = Table.Create(jsonFile);



Answered By - Somar Zein
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 12, 2022

[FIXED] The error in that show from the datatable query

 March 12, 2022     codeigniter, datatable, php     No comments   

Issue

Can I know why when I use the join query in my get datatable part, it will show the error, but if I just do in normal select query, it will has no problem. Can somebody help me about this issue? Thanks.

Here is the image for my error in view: enter image description here

Here is the code for my view:

    <div class="container">
        <div class="container">
            <div class="card">
                <div class="card-body">
                    <h1 class="display-4" id="heading"><?php echo $content_heading ?></h1>
                    <div class="row col-12">
                        <button class="btn btn-primary" onclick="reloadTable()"> Reload</button>
                        <button type="button" id="btnFilterClear" class="btn btn-success ml-5" > All</button>
                        <button type="button" id="btnFilterFTKKP" class="btn btn-success ml-2" > FTKKP</button>
                        <button type="button" id="btnFilterFTKEE" class="btn btn-success ml-2" > FTKEE</button>
                        <button type="button" id="btnFilterFTKMA" class="btn btn-success ml-2" > FTKMA</button>
                        <button type="button" id="btnFilterFTKA" class="btn btn-success ml-2" > FTKA</button>
                        <button type="button" id="btnFilterFTKPM" class="btn btn-success ml-2" > FTKPM</button>
                        <button type="button" id="btnFilterFK" class="btn btn-success ml-2" > FK</button>
                        <button type="button" id="btnFilterFIST" class="btn btn-success ml-2" > FIST</button>
                        <button type="button" id="btnFilterFIM" class="btn btn-success ml-2" > FIM</button>
                    </div>
                    <!-- DataTables -->
                    <table class="table table-striped table-hover" id="dataTable">
                        <thead>
                            <tr>
                                            <!--<th>No</th>-->
                                            <th>Subject ID</th>
                                            <th>Subject Name</th>
                                            <th>Department</th>
                                            <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

<script>
    var table;
    var base_url = '<?php echo base_url();?>';

    $(document).ready(function() {

    $("#image").change(function() {
            photoPreview(this,"service");
    });

    $("input").keydown(function(){
        $(this).removeClass('is-invalid');
        $(this).next().empty();
    });
    $("textarea").keydown(function(){
        $(this).removeClass('is-invalid');
        $(this).next().empty();
    });
    $("select").change(function(){
        $(this).removeClass('is-invalid');
        $(this).next().empty();
    });
        $("input").change(function(){
        $(this).removeClass('is-invalid');
        $(this).next().empty();
    });

        //Datatables
        table = $('#dataTable').DataTable({

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.
        "lengthMenu": [ 5, 10, 25, 50 ],
        "pageLength": 5,
        "language": {
                "infoFiltered": ""
        },

                // Load data for the table's content from an Ajax source
                "ajax": {
                    "url": "<?php echo site_url('attendance/ajax_list_attendance_for_all_student')?>",
                    "type": "POST"
                },

                //Set column definition initialisation properties.
                "columnDefs": [
                {
                        "targets": [ -1 ], //last column
                        "orderable": false, //set not orderable
                    },
                    {
                        "width": "2%", "targets": -1,
                    },
                    ],
                });

            $( "#dataTable_filter" ).addClass( "float-md-right" );
            $( "#dataTable_paginate" ).addClass( "float-md-right" );
            $( "#dataTable_length" ).addClass( "form-inline" );
            $( "#dataTable_length" ).parent().addClass( "my-md-auto" );

        $('#btnFilterClear').on( 'click', function () {
            table.search("", true, false, true).draw();
        } );

        $('#btnFilterFTKKP').on( 'click', function () {
            table.search("Faculty of Chemical and Process Engineering Technology (FTKKP)", true, false, true).draw();
        } );

        $('#btnFilterFTKEE').on( 'click', function () {
            table.search("Faculty of Electrical and Electronics Engineering Technology (FTKEE)", true, false, true).draw();
        } );

        $('#btnFilterFTKMA').on( 'click', function () {
            table.search("Faculty of Mechanical and Automotive Engineering Technology (FTKMA)", true, false, true).draw();
        } );

        $('#btnFilterFTKA').on( 'click', function () {
            table.search("Faculty of Civil Engineering Technology (FTKA)", true, false, true).draw();
        } );

        $('#btnFilterFTKPM').on( 'click', function () {
            table.search("Faculty of Manufacturing and Mechatronic Engineering Technology (FTKPM)", true, false, true).draw();
        } );
        $('#btnFilterFK').on( 'click', function () {
            table.search("Faculty of Computing (FK)", true, false, true).draw();
        } );
        $('#btnFilterFIST').on( 'click', function () {
            table.search("Faculty of Industrial Sciences and Technology (FIST)", true, false, true).draw();
        } );
        $('#btnFilterFIM').on( 'click', function () {
            table.search("Faculty of Industrial Management (FIM)", true, false, true).draw();
        } );
        });

        function reloadTable()
        {
        table.ajax.reload(null,false); //reload datatable ajax
    }

//view Service
function clickviewallstudentattendance(subject_id)
{
        window.location.href = "<?php echo site_url('attendance/student_attendance_by_date/')?>"+subject_id; // redirect to student_attendance_detail
}
</script>

Here is my code for my controller:

    public function ajax_list_attendance_for_all_student()
    {
        $list = $this->attendance->get_datatables_attendance_for_all_student(2); 
        $data = array();
        $no = $_POST['start'];
        $i = 1;
        foreach ($list as $attendance) {
            $no++;
            $row = array();
            //$row[] = $attendance->id;
            $row[] = $attendance->subject_id;
            $row[] = $attendance->subject_name;
            $row[] = $attendance->department;
            $row[] = '<button class="btn btn-warning m-0" href="javascript:void(0)" onclick="clickviewallstudentattendance('."'".$attendance->subject_id."'".')">View</button>';
            $data[] = $row;
        }

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->attendance->count_all_attendance_for_all_student(),
                        "recordsFiltered" => $this->attendance->count_filtered_attendance_for_all_student(2),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }

Here is the code for my model:

    private function _get_datatables_query_attendance_for_all_student()
    {
        $this->db->select("a.subject_id, a.subject_name, s.department");
        $this->db->from('attendance a');
        $this->db->join('student s', 'a.student_id=s.student_id', 'inner');
        $this->db->group_by('a.subject_id');

        $i = 0;

        foreach ($this->column_search_attendance_for_all_student as $item) // loop column
        {
            if($_POST['search']['value']) // if datatable send POST for search
            {
                if($i===0) // first loop
                {
                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                    $this->db->like($item, $_POST['search']['value']);
                }
                else
                {
                    $this->db->or_like($item, $_POST['search']['value']);
                }

                if(count($this->column_search_attendance_for_all_student) - 1 == $i) //last loop
                    $this->db->group_end(); //close bracket
                }
                $i++;
            }

        if(isset($_POST['order'])) // here order processing
        {
            $this->db->order_by($this->column_order_attendance_for_all_student[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        }
        else if(isset($this->order))
        {
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        }
    }

        function get_datatables_attendance_for_all_student()
    {
        $this->_get_datatables_query_attendance_for_all_student();
        if($_POST['length'] != -1)
            $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    }

        function count_filtered_attendance_for_all_student()
    {
        $this->_get_datatables_query_attendance_for_all_student();
        $query = $this->db->get();
        return $query->num_rows();
    }

        public function count_all_attendance_for_all_student()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

This is the working query that I do in my model:

    private function _get_datatables_query_student_attendance_for_every_subject_by_lecturer()
    {
        $this->db->select('*');
        $this->db->from('attendance');
        $user_id = $this->session->userdata("id");
        $this->db->where('lecturer_id', $user_id);

        $i = 0;

        foreach ($this->column_search_student_attendance_detail as $item) // loop column
        {
            if($_POST['search']['value']) // if datatable send POST for search
            {
                if($i===0) // first loop
                {
                    $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
                    $this->db->like($item, $_POST['search']['value']);
                }
                else
                {
                    $this->db->or_like($item, $_POST['search']['value']);
                }

                if(count($this->column_search_student_attendance_detail) - 1 == $i) //last loop
                    $this->db->group_end(); //close bracket
                }
                $i++;
            }

        if(isset($_POST['order'])) // here order processing
        {
            $this->db->order_by($this->column_order_student_attendance_detail[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        }
        else if(isset($this->order))
        {
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        }
    }

        function get_datatables_student_attendance_for_every_subject_by_lecturer()
    {
        $this->_get_datatables_query_student_attendance_for_every_subject_by_lecturer();
        if($_POST['length'] != -1)
            $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    }

        function count_filtered_student_attendance_for_every_subject_by_lecturer()
    {
        $this->_get_datatables_query_student_attendance_for_every_subject_by_lecturer();
        $query = $this->db->get();
        return $query->num_rows();
    }

        public function count_all_student_attendance_for_every_subject_by_lecturer()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

Solution

The dataTables error you're getting is a general error that can be triggered if the server responds with anything other than a valid HTTP 2xx response. I see in your ajax that you're using a type of POST, and CodeIgniter usually will require CSRF with POSTs. Either switch this to GET, or add CSRF fields to the POST request, as below:

var csrfdata = {<?= csrf_token() ?>:"<?= csrf_hash() ?>"};


"ajax": {
            "url": "<?php echo site_url('attendance/ajax_list_attendance_for_all_student')?>",
            "type": "POST",
            "data": csrfdata
        },

For reference, CodeIgniter Security page: https://codeigniter.com/user_guide/libraries/security.html



Answered By - James
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, March 7, 2022

[FIXED] create personaliced filter in datatable with select

 March 07, 2022     datatable, datatables, jquery, laravel-5     No comments   

Issue

i want to create in my datatable one filter personaliced with dropdown but i don´t know where to begin... Sorry it´s my question it´s very bad. I´m reading documentation from datatable reading any forum, and other post from stackoverflow but i don´t know how i can to do.

i need create one filter with this param:

  • new
  • pending
  • null
  • confirm
  • commercialiced
  • confirm-absent
  • confirm-null

i need other dropdown filter but if i do the firts o can to do next.

I need create one select personaliced with this data, and after i need create event and function to controller, etc? i´m working in backend with laravel 5.6. Now i have this code:

initComplete: function () {
            // bottom filter
            this.api().columns([6,8,9]).every( function () {
                var column = this;
                var select = $('<select class="form-control"><option value=""></option></select>')
                    .appendTo( $(column.footer()).empty() )
                    .on( 'change', function () {
                        var val = $(this).val();
                        column.search( this.value ).draw();
                    } );
                
                // If I add extra data in my JSON, how do I access it here besides column.data?
                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                } );
            } );
        },

but this return actual data en my table and create select. I need create select with x option and after to can search data and fill datatable.

Sorry for my question, and thanks for help me


Solution

With this code i can solve my question:

initComplete: function () {
            // DATE FILTER
            this.api().columns([3]).every( function () {
                var column = this;
                var select = $('<select class="form-control"><option value=""></option></select>')
                    .appendTo( $(column.footer()).empty() )
                    .on('change', function () {
                        var val = $(this).val();
                        column.search( this.value ).draw();
                    } );
                
                // If I add extra data in my JSON, how do I access it here besides column.data?
                select.append( '<option value="nueva">Nueva</option>'+
                                '<option value="confirmada">Confirmada</option>'+
                                '<option value="pendiente">Pendiente</option>'+
                                '<option value="nula">Nula</option>'+
                                '<option value="aplazada">Aplazada</option>'+
                                '<option value="ausente">Ausente</option>'+
                                '<option value="venta">venta</option>'
                            );
            } );

in my question i´m using this code to get all header from my table and created filter. i thinked that i would can use this for created one select in position 3 with my values... And it´s ok



Answered By - scorpions78
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing