Friday, 22 September 2017

Create & Download PDF from Byte[] Array using jQuery AJAX and WebMethod

//convert BASE64 string to Byte{} array
function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}

//save Byte[] array and download
function saveByteArray(reportName, byte) {
    var blob = new Blob([byte]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    var fileName = reportName + ".pdf";
    link.download = fileName;
    link.click();
}

//in this case we are exporting a post based on id
function export(id) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/ConvertToPdfAndDownload",
        data: '{postId: "' + id + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            if (response.d == '')
                alert('There is a problem exporting the file');
            else {
                var sampleArr = base64ToArrayBuffer(response.d);
                saveByteArray("File-" + id, sampleArr);
            }
        },
        failure: function (response) {
            alert("Cannot export thefile: Error in calling Ajax");
        }
    });
}


// C# code behind
// using Pdf generator from https://www.nrecosite.com/pdf_generator_net.aspx
[WebMethod]
public static string ConvertToPdfAndDownload(string postId)
{
    string result = "";

    try
    {    
        // convert HTML to PDF Byte[] array and return as Base64 string to AJAX
        string post = "<h2>Here is a test</h2>";
        var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
        result = Convert.ToBase64String(htmlToPdf.GeneratePdf(post));        
    }
    catch (Exception e) { result = e.Message; }
    return result;
}

Thursday, 14 September 2017

C# ASP.NET Convert DataTable to CSV and Download

StringBuilder sb = new StringBuilder();
DataTable dt = ds.Tables[0];

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = row
                                 .ItemArray
                                 .Select(field => string
                                 .Concat("\"", field
                                 .ToString()
                                 .Replace("\"", "\"\""), "\""));
    sb.AppendLine(string.Join(",", fields));
}

Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "inline;filename=export.csv");
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "text/csv";
Response.Write(sb);
Response.End();


Dropdownlist with Checkboxes in ASP.NET

Dropdownlist with checkboxes in asp.net more...


// required to make drop down list works with postback and update panel
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        //Binding Code Again
        $('.multi-select').SumoSelect({ okCancelInMulti: true, selectAll: true });
}

Saturday, 12 August 2017

Add HTML Button to Page from Code Behind with Click Event

Page:
<div id='PlaceHolder' runat='server'></div>

<script type="text/javascript">
$('.className').on('click', function (event) {
event.stopPropagation();
event.stopImmediatePropagation();

$.ajax({
type: "POST",
url: "DesirePage.aspx/DesireMethod",
data: '{object: "' + this.id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d) {
window.location = (response.d).ToString();
}
else {
alert('Not Successfull');
}
},
failure: function (response) {
alert('Failed');
}
});
});
</script>



Code Behind:
public static void Test()
{
Button btn = new Button();
btn.ID = empRow[0].ToString().Trim();
btn.Text = "click here";
btn.Attributes.Add("class", "className");
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
cloneButton.RenderControl(htmlWriter);

PlaceHolder.InnetHtml = sb.ToString();
}


[System.Web.Services.WebMethod]
public static object DesireMethod (object input)
{
// do some operation and return result
}


Saturday, 5 August 2017

C# Split a List into Sub-Lists and run in Parallel

static void Main(string[] args)
{
    // create a dummy list
    List<string> data = GetTheListOfData();
  
    // split the list into sub-lists - in this case N items in each sub-list
    List<List<string>> subLists = splitList<string>(data, N);

    // get each list from sub-lists
    foreach (List<string> list in subLists)
    {
        // parallel operation on each element on selected list
        Parallel.ForEach(list, element =>
  {
            Console.WriteLine(element);
  });
    }  
}

// split the list into sub-lists 
public static List<List<string>> splitList<T>(List<string> bigList, int numElementsInEachSubList)
{
    var list = new List<List<string>>();

    for (int i = 0; i < bigList.Count; i += numElementsInEachSubList)
        list.Add(bigList.GetRange(i, Math.Min(numElementsInEachSubList, bigList.Count - i)));

    return list;
}

Parallel.ForEach uses some intelligence to decide how many parallel threads to run simultaneously, with a max of 63. To set the max degree of parallelism, add 
new ParallelOptions { MaxDegreeOfParallelism = 5 } 
as the second argument to Parallel.ForEach

Parallel.ForEach(list, new ParallelOptions { MaxDegreeOfParallelism = 10 }, element =>
{
  Console.WriteLine(element);
});


Monday, 31 July 2017

HTTP Error 503 When Enabling 32-Bits Application in IIS

When enabling the 32-bits application mode in IIS, the application pool stops and and generate HTTP Error 503 indicating that the service is not available.

The problem might be due to corrupted IIS URL Rewrite module or incompatibility of the versions due to server upgrade. To resolve this issue, un-install the URL Rewrite module and re-install it again.


Resolve HTTP Error 500.19 - 0x8007007e

To fix this, disable the WSUS compression by running the following command on the server:

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/httpCompression /-[name='xpress']

To enable WSUS compression again by running this command:

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/httpCompression /+[name='xpress',doStaticCompression='false',dll='%windir%\system32\inetsrv\suscomp.dll']


Analysis Service in Power BI Report Server

 We couldn’t connect to the Analysis Services server. Make sure you’ve entered the connection string correctly... link