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

Wednesday, October 14, 2015

PowerPoint 2016 or Word 2016 crash or stops working with error while opening files

PowerPoint 2016 crashes while opening certain power point presentations you have received
Word 2016 gives error and crash when opening certain power point presentations

with messages like below:
Microsoft PowerPoint
Microsoft PowerPoint has stopped working
A problem caused the program to stop working correctly. Please close the program.

Workaround:
1. Save the file on disk
2. Right click on file, select properties (see screenshot below)
3. Select "Unblock" checkbox at the end of the properties box
4. Click OK

After this change, the document should open as normal in power point or word





















Tested in office 2016 on Windows 10

Thursday, June 18, 2015

Visual Studio Web performance or Load testing, requests always go through a proxy

In, Visual Studio 2013, Web Performance Testing project, Select your WebTest
In root element, select properties and check the proxy value. This (proxy value) is always set to "default"

Sometimes its preferable for tests to not go through a proxy as a proxy has its own bottleneck. Visual Studio will not allowing you to change this value to blank (to not use a proxy). If you remove the proxy value, VS will put default back again automatically.

This is because "default" means use the system proxy while running tests. If you do not want your test runs to use a proxy, disable the proxy in the system.
To do this, go to Internet Explorer, Select Tools, Internet Options, Connections, LAN Settings, and un-check all proxy enable check boxes

Tuesday, June 16, 2015

Windows domain account getting locked

Domain account was getting locked out at random times.

Turns out Windows 8.1 mail was configured and I missed to update the password there and it kept retrying with the old password and locking it.

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...