Thursday 28 December 2017

1. Download MongoDB from here
2. Install the MongoDB using "Custom" and set the path to C:\MongoDB
3. After install is completed, open "Command Prompt" as "Administrator"
4. Issue the following command to create folder for databases and logs
    C:\MongoDB>md log
    C:\MongoDB>md data\db
5. Navigate to C:\MongoDB\Bin and run the following command
    mongod --directoryperdb --dbpath C:\MongoDB\data\db --logpath C:\MongoDB\log\mongo.log --logappend --rest --install
6. Run the service:
  C:\MongoDB\Bin>net start MongoDB
7. Type "mongo.exe" to open the shell
8. Useful commands:
cls : clear screen
show dbs : show the list of databases
use customers : create database 'customers' and switch to it
db : give the current database name
9. Assign role to database
db.createUser ({
user: "admin",
pwd: "admin",
roles: ["readWrite","dbAdmin"]
    });


MongoDB manual and reference: click here
MongoDB Download centre: click here


Monday 11 December 2017

Windows 10 100% disk usage in Task Manager

Create AJAX Modal

On the page:

<style>
  .modalPopup
  {
    background-color: #FFFFFF;
    border-width: 3px;
    border-style: solid;
    border-color: black;
    padding-top: 10px;
    padding-left: 10px;
    padding-right: 10px;
    min-width: 300px;
    min-height: 120px;
  }
</style> 

<asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>
<cc1:ModalPopupExtender 
    ID="ModalPopupExtender1" 
    BehaviorID="mpe" 
    runat="server"
PopupControlID="pnlPopup" 
    TargetControlID="lnkDummy" 
    BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>

<asp:Panel 
    ID="pnlPopup" 
    runat="server" 
    CssClass="modalPopup" 
    Style="display: none; 
    overflow:auto; 
    max-height: 600px;">
  <div>
    <b runat="server" 
       id="modalHeader" 
       style="font-weight:600; 
       font-size:18px;">
    </b>
  </div>

  <hr />

  <div>
<div runat="server" 
       id="modalContent" 
       style="font-size: 14px"> 
    </div>

    <br /> <br />
    <asp:Button ID="btnHide" 
            runat="server" 
            Text="OK" 
            OnClientClick="return HideModalPopup()" />

    <br /> <br />
  </div>
</asp:Panel>

<script type="text/javascript">
  function ShowModalPopup() {
$find("mpe").show();
return false;
}
function HideModalPopup() {
$find("mpe").hide();
return false;
}
</script>



Call from code behind:

public void DisplayMessage(string header, string body)
{
modalHeader.InnerHtml = header;
modalContent.InnerHtml = body;
  ModalPopupExtender1.Show();
}

Sunday 10 December 2017

Windows 10 Disable Delay Time in Launching Startup Programs

Windows 10 delays on load and startup for few second. To resolve this issue:

  1. Open Windows Registry Editor: Windows + R > regedit
  2. Navigate to: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer
  3. Under Explorer key, create a new key and set its name as Serialize
  4. Select Serialize key and in right-side pane, create a new DWORD StartupDelayInMSecand set its value to 0 to disable startup delay time:
  5. Close Registry Editor and restart your computer to take effects.


Wednesday 29 November 2017

Browse UNC path using Windows CMD


  • PUSHD <UNC PATH> will create a temporary virtual drive and get into it
  • POPD will delete the temporary drive and get you back to the path you were when you entered pushd


Thursday 16 November 2017

Convert HTML to Docx and Pdf using Microsoft.Office.Interop.Word

// use _Application and _Document instead of var to avoid ambiguities 
_Application word = new Application();
_Document document = word.Documents.Open(FileName: @"C:\index.html", ConfirmConversions: false, ReadOnly: false);

word.Visible = false;

// impersonated user must have read-write access to the following locations

var pdfOutputFile = @"C:\Temp\document.pdf";
var docOutputFile = @"C:\Temp\document.docx";

byte[] Content = null;

.
.
.
case "pdf":
document.SaveAs2(FileName: pdfOutputFile, FileFormat: WdSaveFormat.wdFormatPDF);
document.Close();
word.Quit();
Content = File.ReadAllBytes(pdfOutputFile);
break;

case "docx":

foreach (InlineShape image in document.InlineShapes)
{
// make sure images are embeded
if (image.LinkFormat != null)
{
try
{
image.LinkFormat.SavePictureWithDocument = true;
image.LinkFormat.BreakLink();
}
catch { /* do nothing */ }
}
}
document.SaveAs2(FileName: docOutputFile, FileFormat: WdSaveFormat.wdFormatDocumentDefault);
document.Close();
word.Quit();
Content = File.ReadAllBytes(docOutputFile);
break;
.
.
.

// download file as byte[]
if (Content != null)
{
Response.AddHeader("content-disposition", "attachment; filename=" + (pdfOutputFile or docOutputFile));
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
}


Important notes: 


  1. In order to be able to save document, create a new "Desktop" directory inside of "C:\Windows\SysWOW64\config\systemprofile\"
  2. The library will not work on Server 2016 with O365 or Office 2016. On server 2016, need to use Office 2013.



Tuesday 31 October 2017

MS-SQL: Strip NON-Alphabetic Characters From String

Create Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^a-z]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

TEST:
Select dbo.RemoveNonAlphaCharacters('abc1234def5678ghi90jkl')


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']


Wednesday 28 June 2017

SQL Server - HTML to TEXT

CREATE FUNCTION [dbo].[HTMLtoText] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS

BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('<',@HTMLText) SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText)) 
SET @Length = (@End - @Start) + 1 WHILE @Start > 0
AND @End > 0
AND @Length > 0
BEGIN
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
SET @Start = CHARINDEX('<',@HTMLText) SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
END
  RETURN LTRIM(RTRIM(@HTMLText))
END
GO

Command to Test:
SELECT dbo.HTMLtoText('<h1>Everything is possible, nothing is <span style="color: red"><b>impossible.</b> </span>:)</h1>')


Tuesday 27 June 2017

C# ASP.NET Rich Text Box/Editor

The most-used free ASP.NET WYSIWYG HTML editor featured in open source and commercial projects more...


Friday 26 May 2017

Register ASP.NET 4.x

Dialog box may be displayed to users when opening projects in Microsoft Visual Studio after installation of Microsoft .NET Framework 4.6 more...


Sunday 30 April 2017

Calling ASP.Net Code Behind using jQuery AJAX

Ajax (Asynchronous Javascript and XML) is a technique of sending the request and receiving the response from the server without reloading the entire page. To avoid PostBack call in C# ASP .Net, we can use jQuery Ajax to call code behind more…


Friday 7 April 2017

How to Reset Your Forgotten Windows Password the Easy Way

Forgetting Windows password is never any fun, but there’s a easy way to reset the password. All you need to do is to follow the below steps: 
  1. Boot your PC from Windows disk
  2. Select the "Repair Your Computer"
    image
  3. Go to "Command Prompt"
    image
  4. Backup the original sticky keys file: 
    copy c:\windows\system32\sethc.exe c:\
  5. Copy the command prompt executable (cmd.exe) over top of the sticky keys executable
    copy c:\windows\system32\cmd.exe c:\windows\system32\sethc.exeimage
  6. Restart the PC
  7. Once you get to the login screen, hit the Shift key 5 times, and you’ll see an administrator mode command promptimage
  8. Use the following command, replacing the username and password with the combination you want to reset the user password:
    net user geek <NewPassword>
    image
  9. Put the original sethc.exe file back, which you can do by rebooting into the installation CD, opening the command prompt, and copying the c:\sethc.exe file back to
    c:\windows\system32\sethc.exe

  • NOTE: If the local account is not exist, issue the following commands to create it:
    net user <username> /add
    net 
    localgroup administrators <username> /add

Thursday 9 March 2017

Monday 6 March 2017

ASP.NET 4.5 Web Forms Code Generator

Generate ASP.NET 4.5 Web Forms, Middle-Tier, Data-Tier, and Stored Procedures (or Dynamic SQL) in One Click*. AspxFormsGen 4.5 generates databound ASP.NET 4.5 web forms. AspxFormsGen 4.5 is a combination of our AspxFormsGen 4.5 engine (generates ASP.NET web forms) and AspxCodeGen 4.5 engine which generates Middle-Tier, Data-Tier, and Stored procedures or Dynamic SQL codes more...


Thursday 23 February 2017

Remote Server Hangs on Startup

Computer showing the "Applying Group Policy..." and does nothing else on Windows startup. To resolve the issue, restart IIS remotely and enforce group policy:

IISRESET <computer-name> /restart
INVOKE-COMMAND -ComputerName <computer-name> { GPUPDATE /force } 


Setup Connection to new Remote SQL Server

After installing the new instance of SQL Server, the remote user might not be able to login remotely while can as local SQL user. To resolve this issue, follow the link more...


Wednesday 22 February 2017

Open a Bootstrap Modal on Another Bootstrap Modal

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  </head>

<body>
  <!-- Button for test -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#test1">Open First Modal</button>

  <!-- Modal 1 -->
  <div id="test1" class="modal fade" role="dialog" style="z-index: 1200;">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-body">
          <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#test2">
            Open Second Modal
          </button>
        </div>      
      </div>
    </div>
  </div>

  <!-- Modal 2 -->
  <div id="test2" class="modal fade" role="dialog" style="z-index: 1600;">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">  
        <div class="modal-body">
          Your content comes here
        </div>      
      </div>
    </div>
  </div>

</body>
</html>


Tuesday 21 February 2017

C# .NET Get the List of Elements Which are in List1 but not in List2 and Vice Versa

// define the lists
List<string> list1 = new List<string>() { "a", "b", "c", "d", "e", "zz","ZZ" };
List<string> list2 = new List<string>() { "ZZ", "H","b" };

// convert the list elements to lowercase
list1 = list1.Select(x => x.ToLower()).ToList();
list2 = list2.Select(x => x.ToLower()).ToList();

// create desire lists
List<string> ItemsInList1NotInList2 = list1.Except(list2).ToList();
List<string> ItemsInList2NotInList1 = list2.Except(list1).ToList();


Sunday 19 February 2017

Convert HTML to PDF in .NET

1. Download HtmlRenderer.PdfSharp Nuget packages: more...
Install-Package HtmlRenderer.PdfSharp -Version 1.5.0.6

2. Create a method in C# to convert html to pdf
public static void CreatePdfFromHtml (string html)
{
    Byte[] res = null;
    using (MemoryStream ms = new MemoryStream())
    {
var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf (html, PdfSharp.PageSize.A4);
pdf.Save(ms);
res = ms.ToArray();
    }
    File.WriteAllBytes("c:\\output.pdf", res);
}


Wednesday 8 February 2017

C# Embed Image to Email

If the image is not embedded in the email, the recipient might not be able to see the image (e.g. in email signature). So use the following code to embed the image into HEML email:

// get the actual image url and assign id (content id) and assign a unique id to the image
Attachment imgAtt = new Attachment(@"C:\Images\DesireImage.jpg");
imgAtt.ContentId = "image";
email.Attachments.Add(imgAtt);

Add the image (with its unique id) to the body of the html email:
<img src='cid:image' />


Tuesday 7 February 2017

C# ASP.NET Disable the Button After First Click Until the Process is Finished

Simply add the following properties to the desired button:

  • UseSubmitBehavior = "false" 
  • OnClientClick = "this.disabled=true; this.value='Processing. Please Wait...';"   more...

Monday 30 January 2017

C# ASP.NET Hide Image Path on the Page

public void DrawImage(string imageURL)
{
    // convert image to bytes array
    WebClient wClient = new WebClient();
    byte[] imageBytes = wClient.DownloadData(@imageURL);

         // create memory stream of bytes array and convert image to base 64 and display it

    MemoryStream imgStream = new MemoryStream(imageBytes);
    ImageBox.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(imgStream.ToArray(), 0, imgStream.ToArray().Length);
}

*ImageBox is a image control on the page.
*Sample call: DrawImage("c:\windows\image.jpg")



Upgrade Windows 11 Home to Windows 11 Pro

Disable internet connection (Wi-Fi, Internet, etc.) Change the product key using the following Generic product key:                     VK7J...