Thursday, June 15, 2017

Cloning c# Objects in generic way

Here is the simple solution for cloning the c# objects in generic way

Use this below extension method to clone the obejcts



public static T Clone<T>(T source)
{
    var serialized = JsonConvert.SerializeObject(source);
    return JsonConvert.DeserializeObject<T>(serialized);
}

Closing a MessageBox after several seconds in c# WPF

Here is the solution for the closing message box aumatically after a few seconds.

here is the class implemented to auto close the Message box in the c# WPF


CustomAutoClosingMessageBox.Show("Text", "Caption", 1000);



public class CustomAutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
    }
    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        _result = _timerResult;
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

wait for async method to complete in c#?

we often gets the requirement for making asynchronous calls to synchronous due to various reasons here is the best solution to wait for asyncmethod to complete Solution is to run your method in task and get the result out of it


var result = Task.Run(async() => { return await yourAsyncMethod(); }).Result;


 This is best solution for wait until your async call complete

 There are other solutions which you can try

 YourAsyncMethod().GetAwaiter().GetResult();
 or
YourAsyncMethod().Result;

How to open or trigger a default browser in C#

Here is the simple solution to how trigger default browser with C# with required url

we can write simple method Gotowebsite as below



public void gotoWebSite(string mySiteUrl)
{
     System.Diagnostics.Process.Start(mySiteUrl);
}

by calling this method, it trigger the defualt browser with url we passed to the method.

How to access LinkButton in Inner DataList?

How to access LinkButton in Inner DataList?

we need to use OnItemCommand in the inner datalist

Check the below code for implememtaion:

Asp.net Page:



<asp:DataList ID="dlItems" runat="server" OnItemCommand="dlItems_ItemCommand">

Implement OnItemCommand in serverside as below


protected void dlItems_ItemCommand(object source, DataListCommandEventArgs e)
{
  
    if (e.CommandName == "Update")
    {
        TextBox txtname = e.Item.FindControl("txtName") as TextBox;

        lblName.Text = txtname.Text;
    }
}

Friday, June 2, 2017

Adding dynamic properties and values to the c# Object

Adding dynamic properties and values to the c# Object:

Below C# code snippet allows to add dynamic properties and values to the c# object dynamically..




            var expandoObject = new ExpandoObject();
            var myObject = expandoObject as IDictionary<String, object>;
            myObject ["youtPropertyName"] = "yourvalue";
            

Monday, May 8, 2017

file.openbinarydirect throws exception sharepoint 2013: Resolved

I was trying download the byte stream from the share point document using share point library in C# MVC application with OpenBinaryDirect method in file class, but it's throwing on exception
file.openbinarydirect throws exception

Code which has an exception:


            Uri filename = new Uri(filePath);
            string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
            string serverrelative = filename.AbsolutePath;

            Microsoft.SharePoint.Client.FileInformation file = Microsoft.SharePoint.Client.File.OpenBinaryDirect(this.ClientContext, serverrelative);
            return file.Stream;
Here we are getting the exception







We are getting the issue because of File.OpenBinaryDirect can not evaluate the app token when you try to get the share point documents with OAuth authorization

Actual Code with resolution is below


            Uri filename = new Uri(filePath);
            string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
            string serverrelative = filename.AbsolutePath;

            Microsoft.SharePoint.Client.File file = this.ClientContext.Web.GetFileByServerRelativeUrl(serverrelative);
            this.ClientContext.Load(file);
            ClientResult<Stream> streamResult = file.OpenBinaryStream();
            this.ClientContext.ExecuteQuery();
            return streamResult.Value;