Tuesday, February 16, 2016

C# formatting JSON as rtf document (can be useful to display on Richtext controls or exporting rtf files)

C# code that converts JSON string to RTF


sInJSON = sInJSON.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Replace(Environment.NewLine, "\\line" + Environment.NewLine);
string sRTFOut = @"{\rtf1\ansi\deff0
{\colortbl;\red0\green0\blue0;\red255\green140\blue0;\red255\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;\red255\green0\blue255;\red0\green0\blue128;\red0\green128\blue128}" +
    Regex.Replace(
        sInJSON,
        @"(¤(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\¤])*¤(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)".Replace('¤', '"'),
        match =>
        {
            var cls = "\\cf2";
            if (Regex.IsMatch(match.Value, @"^¤".Replace('¤', '"')))
            {
                if (Regex.IsMatch(match.Value, ":$"))
                {
                    cls = "\\cf3";
                }
                else {
                    cls = "\\cf4";
                }
            }
            else if (Regex.IsMatch(match.Value, "true|false"))
            {
                cls = "\\cf5";
            }
            else if (Regex.IsMatch(match.Value, "null"))
            {
                cls = "\\cf6";
            }
            return cls + match + "\\cf1";
        })
+ "}";


Please review the RTF code outputted down below.

Points to Note: The RTF file always start with {\rtf1\ansi\deff0
After this, you can declare your color palatte as: {\colortbl;\red0\green0\blue0;\red255\green140\blue0;\red255\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;\red255\green0\blue255;\red0\green0\blue128;\red0\green128\blue128}
and each of these can be later referred to as \cf1, \cf2 etc
Please also note that chars \, { and } are considered special characters. If you have it in your text, please override with \. For example, } should be changed as \} to display }

Example RTF code output:

{\rtf1\ansi\deff0
{\colortbl;\red0\green0\blue0;\red255\green140\blue0;\red255\green0\blue0;\red0\green128\blue0;\red0\green0\blue255;\red255\green0\blue255;\red0\green0\blue128;\red0\green128\blue128}\{\line
    \cf3"firstName":\cf1 \cf4"John"\cf1,\line
    \cf3"lastName":\cf1 \cf4"Smith"\cf1,\line
    \cf3"isAlive":\cf1 \cf5true\cf1,\line
    \cf3"age":\cf1 \cf225\cf1,\line
    \cf3"address":\cf1\line
    \{\line
        \cf3"streetAddress":\cf1 \cf4"21 2nd Street"\cf1,\line
        \cf3"city":\cf1 \cf4"New York"\cf1,\line
        \cf3"state":\cf1 \cf4"NY"\cf1,\line
        \cf3"postalCode":\cf1 \cf4"10021-3100"\cf1\line
    \},\line
    \cf3"phoneNumbers":\cf1\line
    [\line
        \{\line
            \cf3"type":\cf1 \cf4"home"\cf1,\line
            \cf3"number":\cf1 \cf4"212 555-1234"\cf1\line
        \},\line
        \{\line
            \cf3"type":\cf1 \cf4"office"\cf1,\line
            \cf3"number":\cf1 \cf4"646 555-4567"\cf1\line
        \}\line
    ],\line
    \cf3"children":\cf1\line
    [\line
    ],\line
    \cf3"spouse":\cf1 \cf6null\cf1\line
\}\line
}

Displayed as RTF:

{
   "firstName":"John",
  
"lastName":"Smith",
  
"isAlive":true,
  
"age":,
  
"address":
   {
      
"streetAddress":"21 2nd Street",
      
"city":"New York",
      
"state":"NY",
      
"postalCode":"10021-3100"
   },
  
"phoneNumbers":
   [
       {
          
"type":"home",
          
"number":"212 555-1234"
       },
       {
          
"type":"office",
          
"number":"646 555-4567"
       }
   ],
  
"children":
   [
   ],
 

You can also use this method to save/export to RTF files using your winform or ASP.Net web application

Microsoft OneDrive for Business stops sync with error the server you are trying to access is using an authentication protocol not supported

After a local windows password change, OneDrive for business stopped working with error
- the server you are trying to access is using an authentication protocol not supported

This error also kept pooping up during random times (guessing onedrive was trying to do a Sync)

Turns out the cached password is not updated in the Windows credential manager.

To Solve
Go to:
  1. Control Panel
  2. User Accounts
  3. Credential Manager
  4. Windows Credentials
  5. Look for the credential thats named like Microsoft* and on expanding the username matching the one you use to login
  6. Delete this credential. If in doubt, you can delete all of them and no harm is done as windows will ask for the credentials again as needed
  7. Now, go to onedrive.com, and login as usual. Once on the One Drive page, click Sync
  8. this should open your local OneDrive for buiness app and it should start normally at this time

I encountered this problem with Office 2016 on Windows 10, and this might be a problem for other versions of Office as well

Thursday, February 11, 2016

asp.net save GridView as HTML text


GridView1 is the gridview you want to save as HTML code

System.Web.UI.HtmlTextWriter htmlwriter = new System.Web.UI.HtmlTextWriter(new StringWriter());
GridView1.RenderControl(htmlwriter);
string htmlString = htmlwriter.ToString();


Change font styles on a asp.net GridView

While defining the asp.net GridView, you can set the below font related properties to adjust as you need


    Font-Bold="True|False"
    Font-Italic="True|False"
    Font-Names="string"
    Font-Overline="True|False"
    Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|Large|X-Large|XX-Large"
    Font-Strikeout="True|False"
    Font-Underline="True|False"

Below is an example

:GridView 
 ID="GridView1" 
 runat="server" 
 Font-Names="Times New Roman" 
 Font-Size="Medium">
</asp:GridView>

Wednesday, February 10, 2016

C# Cancel / abort an async method call/function with a web call as an example


Make the web method call.

string result = await MakeWebCall();

public async Task<string> MakeWebCall()
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.mysite.com");
    req.Method = WebRequestMethods.Http.Get;
    string result = null;

    try
    {
        using (WebResponse resp = await req.GetResponseAsync((ctGetResponse = new CancellationTokenSource()).Token))
        {
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            result = await reader.ReadToEndAsync();
        }
    }
    catch (Exception ex)
    {
        return (ex.ToString());
    }
    return result;
}

Register the cancellationtoken

public static class Extensions
{
    public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
    {
        using (ct.Register((state) => ((HttpWebRequest)state).Abort(), request, false))
        {
            try
            {
                var response = await request.GetResponseAsync();
                return (HttpWebResponse)response;
            }
            catch (WebException ex)
            {
                // WebException is thrown when request.Abort() is called,
                if (ct.IsCancellationRequested)
                    // the WebException will be available as Exception.InnerException
                    throw new OperationCanceledException(ex.Message, ex, ct);
                // Abort not caled, throw the original Exception
                throw;
            }
        }
    }
}

Define the token globally

private CancellationTokenSource ctGetResponse;

call cancellation as required. In this example, its called when a link is clicked on the winform

private void linkLabelCancel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
            ctGetResponse.Cancel();
}

Format a timespan object in c# for display


new timespan initialized to 0
and then read as minutes:seconds:milliseconds (precision 2 digits)

TimeSpan ts = new TimeSpan(0, 0, 0); 
string tsString = ts.ToString("mm':'ss':'ff"); 

Read or Send an eTag header with a HTTP web request


This will add a eTag value to the header

string sEtag = "11234244";
System.Net.HttpWebRequest req1 = (HttpWebRequest)WebRequest.Create("https://mysite.com");
req1.Headers.Add("ETag", (new System.Net.Http.Headers.EntityTagHeaderValue("\"" + sEtag + "\"")).Tag);


And we can read it back easily from the response object (resp is WebResponse)

sEtag = resp.Headers.Get("ETag");

How to return value of the identity column after an insert in SQL server


Table MyTable with Id as an IDENTITY column (auto insert records)

CREATE TABLE [dbo].[MyTable] (
[Id] int IDENTITY(1, 1) NOT NULL,
[Component] varchar(50));

A Sample procedure that inserts a record and returns the id of the record inserted

CREATE PROCEDURE [dbo].[InsertRetId] 
@Component [VARCHAR](50),
@Id int output
AS
BEGIN

INSERT INTO [dbo].[MyTable]
           ([Component]
     VALUES
           (@Component);

select @Id = Scope_Identity();

END

Turn on Windows 11 Fast Boot

If windows starting is slow, to enable windows 11 fast startup/boot,  Press Windows + R, type powercfg.cpl, and hit Enter.  This will direct...