Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 30 June 2016

Macro for connecting Visual Studio to windows service for debugging

Got this through today from my old colleague Kevin McConaghy,…
 
1.  Hack for service OnStart event, essentially to stall the service for long enough for the VS Extension to connect after starting it, only in debug mode and only if you send a special argument.
 
        protected override void OnStart(string[] args)
        {
#if DEBUG
            // If the "WaitForDebugger" argument is passed, wait for 15 seconds for a debugger to become attached.
            if (args.OfType<string>().Contains("WaitForDebugger"))
            {
                for (var i = 1; i <= 15; i++)
                {
                    if (Debugger.IsAttached)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                }
                // If no debugger is attached, abort attempt to start service.
                if (!Debugger.IsAttached)
                {
                    Stop();
                    return;
                }
            }
#endif
2. The vCmd script, this automates the starting of the service if it is not started, and then the connection of the debugger to the process.
using EnvDTE;
using EnvDTE80;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.ServiceProcess;
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        var serviceName = "MessagingService";
        using(var serviceController = new ServiceController(serviceName))
        using(var serviceManagement = new ManagementObject("Win32_Service.Name='"+serviceName+"'"))
        {
            // Start service with "WaitForDebugger" parameter, if the service is stopped.
            if (serviceController.Status == ServiceControllerStatus.Stopped)
            {
                serviceController.Start(new []{"WaitForDebugger"});
            }
            // Attach debugger to process.
            var servicePath = serviceManagement.Properties["PathName"].Value.ToString().Trim('\"');
            try
            {
                var serviceProcess = DTE.Debugger.LocalProcesses.OfType<Process>().Single(x => x.Name == servicePath);
                serviceProcess.Attach();
                return;
            }
            catch(Exception ex)
            {
                System.Windows.MessageBox.Show(string.Format("Could not find process: {0}, {1}.", servicePath, ex.Message));
            }
        }
    }
}
3. The script requires the following references, added via the button.
System.Core
System.Linq
System.ServiceProcess
System.Management





Thursday, 3 September 2015

How to convert C# bool to Javascript boolean in Razor .cshtml views

I was wanting a clean way to convert a C# Boolean property on a view model into a javascript true / false bit of text for passing into our Typescript context settings constructors, and stumbled upon this way …

@Json.Encode(Model.BoolPropertyName)

clip_image002

Works a treat too!

clip_image004

Thursday, 14 May 2015

C# 6 and Roslyn plugins to VS 2015 RC

In order to get the refactoring support listed here...

https://github.com/DustinCampbell/CSharpEssentials

you can simply install the following versions of the Tools, Extensions and Updates in Visual Studio 2015 RC.

image

Monday, 2 February 2015

MVC / Jquery unobtrusive validation

http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1

Also for how do attach a new client side method to unobtrusive validation e.g.

jQuery.validator.unobtrusive.adapters.add(adapterName, [params], fn);

see this article...

http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

 

Note: For any element a in your <form>, you can do this to figure out what validation is attached to the containing <form> for that element...


$.data(a.form, "validator").settings.rules

e.g.

$.data(a.form, "validator").settings.rules.MiddleInitial
Object {maxlength: "1", __dummy__: true}

$.data(a.form, "validator").settings.messages.MiddleInitial
Object {maxlength: "The middle initial must be a single charater"}

Wednesday, 14 January 2015

How to do data dash data- attributes in Razor

Answer: Use an underscore

In the cshtml view file definition when declaring the attributes in the new {} object class for the attributes, use data_mycustomdataattribute to render out data-mycustomdataattribute

@Html.Hidden("controlName", "valueHere", new { @data_mycustomdataattribute = "testing dash"})

This will render the following...

<input data-mycustomdataattribute="testing dash" id="controlName" name="controlName" type="hidden" value="valueHere">

Thursday, 18 September 2014

Watermarks in ASP.NET MVC 4

...using the jquery.overlabel plugin

1. Stick a DisplayName attribute for the watermark on your model property

[RequiredIf("Mode", UnderOfferModelMode.SetUnderOffer, ErrorMessage = "Please enter a comment")]

[DisplayName("Please enter your comment text here")]

public string UnderOfferComment { get; set; }

2. Add an Html.LabelFor and an Html.TextAreaFor your model property

3. Import the jquery.overlabel.js by including "overlabel" in your require imports

4. Add a line in the document.ready to call the .overlabel() method on the label selector (or use a class selector as I have)

clip_image001

5. In your css then you just need

label.overlabel {

position: absolute;

margin-left: 70px;

margin-top: 10px;

z-index: 1;

color: #999;

}

And you end up with a lovely little unobtrusive watermark that doesn't interfere with your model validation in anyway.

Friday, 23 May 2014

How to determine event subscriptions at runtime

Forgot this again, so thought I'd repost it...

http://consultingblogs.emc.com/merrickchaffer/archive/2011/02/02/how-to-determine-event-subscriptions-at-runtime.aspx

((System.Delegate)myObject.MyEventName).GetInvocationList()

Executing that in the immediate window will spawn you out a list of the attached event handlers to your event at runtime.

Also, if you're trying extract the invocation list of a dotNetBar 11.8.0.1 ButtonItem control's click handler, then the following code is necessary due to the obsfucation of the code that dotNetBar controls have within them. The strange Convert.ToChar(2694) is required in order to ensure that the code page of the C# file remains as ANSI (or Windows 1252), instead of asking you to switch to UTF-8 if you use the actual character code that the private event is stored as.

image

var buttonItem = sender as ButtonItem;
            var clickHandler = string.Empty;
            if (buttonItem != null)
            {

                var clickEvent = typeof(BaseItem).GetField(Convert.ToChar(2694).ToString(CultureInfo.InvariantCulture), BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

                if (clickEvent != null)
                {
                    var clickEventDelegate = clickEvent.GetValue(buttonItem) as Delegate;
                    if (clickEventDelegate != null)
                    {
                        var invocationList = clickEventDelegate.GetInvocationList();
                        if (invocationList.Length > 0)
                        {
                            clickHandler = invocationList[0].Method.Name;
                        }
                    }
                }
            }

            MessageBox.Show(
                string.Format(
                    "The click event {0} is yet to be implemented. If you're attached the debugger will now launch",
                    clickHandler), "Click event handler not yet implemented yet", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Debugger.Break();

Wednesday, 21 May 2014

BrowserLink and other new VS 2013 features

Perhaps the most significant enhancement to creating web applications in Visual Studio for many years. Check out how you can edit your pages in line in the browser, and it updates the source code back in visual studio directly, using the new BrowserLink feature...

http://www.asp.net/visual-studio/overview/2013/visual-studio-2013-web-editor-features-browser-link

More features worth a look are all listed under the parent page here...

http://www.asp.net/visual-studio/overview/2013

Tuesday, 20 May 2014

Macros in Visual Studio 2012 / 2013

Use the following visual studio extension in order to recreate the macros that you were used to using in VS 2010 and below
http://vlasovstudio.com/visual-commander/
image
Also to run the macro, try using the Ctrl+Q shortcut menu in VS 2013, as follows
image

Or customise your toolbar


The attach to process macro will now look like this as a new Visual Commander command using VB v4.0 language
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualBasic

Public Class C
    Implements VisualCommanderExt.ICommand

    Sub Run(DTE As EnvDTE80.DTE2, package As Microsoft.VisualStudio.Shell.Package) Implements VisualCommanderExt.ICommand.Run
        AttachToProcess("MyProcessName.exe", DTE)
    End Sub

    Private Sub AttachToProcess(ByVal ProcessName As String, DTE As EnvDTE80.DTE2, Optional ByVal Script As Boolean = False)
        Try
            Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
            Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
            Dim dbgeng(1) As EnvDTE80.Engine
            If Script Then
                dbgeng(0) = trans.Engines.Item("Script")
                'Array.Resize(dbgeng, 1)
            Else
                dbgeng(0) = trans.Engines.Item("Managed")
            End If
            Dim proc2 As EnvDTE80.Process2 = dbg2.GetProcesses(trans, System.Environment.MachineName).Item(ProcessName)
            Call proc2.Attach2(dbgeng)
        Catch ex As System.Runtime.InteropServices.COMException
            Select Case ex.ErrorCode
                Case -2147352565
                    ShowMessage(ProcessName & " is not currently a running process")
                Case -1989083106
                    ShowMessage("You are already attached to " & ProcessName)
                Case Else
                    ShowMessage("Unhandled error message from Attach to process macro")
            End Select
        Catch ex As System.Exception
            MsgBox("Unhandled exception occurred: " & ex.Message)
        End Try

    End Sub
    Private Sub ShowMessage(ByVal message As String)
        Call MsgBox(message, MsgBoxStyle.Exclamation, "Attach to process macro")
    End Sub


End Class

Friday, 16 May 2014

Unshelving just the items you want in VS2013

Say you have a large shelve set and you only want to unshelve certain file types from that shelve set, like the project references changes you've made.

  1. Find your shelve set
  2. Open it in VS2013
  3. In the filter box type *.csproj
  4. Select all in the results and then right click
  5. Choose Exclude unselected from the context menu
    image
  6. Unshelve the resulting items, which should just be the csproj files.
    image

Monday, 10 March 2014

Friday, 14 February 2014

Monday, 9 December 2013

Using the DataContractSerializer to serialize and deserialize

 

To serialize a Business object marked with [DataContract] and properties marked with [DataMember] attributes…

public static string DataContractSerializeObject<T>(T objectToSerialize)

        {

using (var output = new StringWriter())

            {

using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })

                {

var dataContractSerializer = new DataContractSerializer(typeof(T), EntityUtilities.GetAllKnownTypes(), int.MaxValue, true, true, null);

                    dataContractSerializer.WriteObject(writer, objectToSerialize);

return output.GetStringBuilder().ToString();

                }

            }

        }

Then to deserialize back to your DataContract type, use this logic…

public static T Deserialize<T>(string xml)

        {

using (Stream stream = new MemoryStream())

            {

byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);

                stream.Write(data, 0, data.Length);

                stream.Position = 0;

var dataContractSerializer = new DataContractSerializer(typeof(T), EntityUtilities.GetAllKnownTypes(), int.MaxValue, true, true, null);

return (T)dataContractSerializer.ReadObject(stream);

            }

        }

Thursday, 5 December 2013

Cross platform mobile development in C#

http://blog.xamarin.com/microsoft-and-xamarin-partner-globally/

Microsoft Virtual Academy - ASP.NET MVC

I’ve just got into the Microsoft Virtual Academy, and I have to say it has a wealth of up to date, excellent training videos.

http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=4099&m=4093&ct=19601#?fbid=_Oyn-vcRqgr

Razor syntax escape characters…

image

Html anti forgery token..

http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

ASP.NET MVC 4 Content Map

http://www.asp.net/mvc/overview/getting-started/aspnet-mvc-content-map

Script including - always use the longhand version for the <script></script> tag, otherwise your script file will not be downloading to the client browser

JSBin.com - http://jsbin.com/ a fantastic javscript, jquery, html and css online playground like jsfiddle.net and plnkr.co. The nice thing about this one though is that you can download the entire finished article file as a single html page.

What's coming in ASP.NET - www.asp.net/vnext

Signed nightly builds of asp.net vnext - https://aspnetwebstack.codeplex.com/

Getting started with web api - http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Web API 2 (video) - http://channel9.msdn.com/Events/Build/2013/3-504

Thursday, 17 October 2013

No Cache Attribute in MVC

    using System;
using System.Web;
using System.Web.Mvc;
using RRA.Core.Services.Utilities;

///
/// Disables browser caching.
///

[AttributeUsage(AttributeTargets.Method)]
public class NoCacheAttribute : ActionFilterAttribute
{
///
/// Called by the ASP.NET MVC framework before the action result executes.
///

/// The filter context.
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetETag((Guid.NewGuid()).ToString());
filterContext.HttpContext.Response.Cache.SetExpires(SystemDateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}


Tuesday, 15 October 2013

My VS macros

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Public Module Module1
    'Empty routine that just causes VS to flush its memory to disk
    Sub ReleaseMemory()
    End Sub
    Sub RebuildDocumentationUpwards()
        DTE.ExecuteCommand("ReSharper.ReSharper_GotoPrevMethod")
        DTE.ExecuteCommand("Tools.SubMain.GhostDoc.RebuildDocumentation")
    End Sub
    Sub AttachToW3p()
        AttachToProcess("w3wp.exe")
    End Sub
    Sub AttachToLocalWebDev()
        AttachToProcess("WebDev.WebServer40.EXE")
    End Sub
    Sub AttachToMyProcess()
        AttachToProcess("MyProcess.exe")
    End Sub
    Sub AttachToMyProcessScript()
        AttachToProcess("MyProcess.exe", True)
    End Sub
    Private Sub AttachToProcess(ByVal ProcessName As String, Optional ByVal ScriptOnly As Boolean = False)
        Try
            Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
            Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
            Dim dbgeng(2) As EnvDTE80.Engine
            dbgeng(0) = trans.Engines.Item("Script")
            If ScriptOnly Then
                Array.Resize(dbgeng, 1)
            Else
                dbgeng(1) = trans.Engines.Item("Managed")
            End If
            Dim proc2 As EnvDTE80.Process2 = dbg2.GetProcesses(trans, System.Environment.MachineName).Item(ProcessName)
            Call proc2.Attach2(dbgeng)
        Catch ex As System.Runtime.InteropServices.COMException
            Select Case ex.ErrorCode
                Case -2147352565
                    ShowMessage(ProcessName & " is not currently a running process")
                Case -1989083106
                    ShowMessage("You are already attached to " & ProcessName)
                Case Else
                    ShowMessage("Unhandled error message from Attach to process macro")
            End Select
        Catch ex As System.Exception
            MsgBox("Unhandled exception occurred: " & ex.Message)
        End Try
    End Sub
    Private Sub ShowMessage(ByVal message As String)
        Call MsgBox(message, MsgBoxStyle.Exclamation, "Attach to process macro")
    End Sub
End Module

Tuesday, 23 July 2013

Unit of work pattern in WCF

See here for an example of how to implement a unit of work pattern in WCF (using Unity).

http://blogs.5dlabs.it/post/2012/05/23/Implementing-Repository-and-UnitOfWork-patterns-in-a-WCF-service-using-Unity.aspx

public class CustomServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
  {
return new CustomServiceHost(serviceType, baseAddresses);
  }
}

public class CustomServiceHost : ServiceHost
{
static IUnityContainer _container;
static CustomServiceHost()
  {
    _container = new UnityContainer();
    _container.RegisterType<ICompanyRepository, CompanyRepository>();
    _container.RegisterType<IUnitOfWork, DbUnitOfWork>();
    _container.RegisterType<SVCContext>(new ServiceInstanceLifeTimeManager());
  }
public CustomServiceHost(Type serviceType, params Uri[] : base(serviceType, baseAddresses)
  {
  }
protected override void ApplyConfiguration()
  {
base.ApplyConfiguration();
    Description.Behaviors.Add(_container.Resolve<UnityServiceBehavior>());
  }
}

public class UnityServiceBehavior : BehaviorExtensionElement , IServiceBehavior
{
IUnityContainer _container;
public UnityServiceBehavior(IUnityContainer container) : base()
  {
    _container = container;
  }
public void AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters)
  {
  }
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
  {
Type serviceType = serviceDescription.ServiceType;
IInstanceProvider instanceProvider = new UnityInstanceProvider(_container, serviceType);
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
    {
foreach (EndpointDispatcher endpointDispatcher in dispatcher.Endpoints)
      {
        endpointDispatcher.DispatchRuntime.InstanceProvider = instanceProvider;
        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
new UnitOfWorkMessageInspector(_container)
        );
      }
    }
  }
public void Validate(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
  {
  }
public override Type BehaviorType
  {
get { return this.GetType(); }
  }
protected override object CreateBehavior()
  {
return this;
  }
}

public class UnityInstanceProvider : IInstanceProvider
{
IUnityContainer _container;
Type _serviceType;
public UnityInstanceProvider(IUnityContainer container, Type serviceType)
  {
    _container = container;
    _serviceType = serviceType;
  }
public object GetInstance(InstanceContext instanceContext, Message message)
  {
return _container.Resolve(_serviceType);
  }
public object GetInstance(InstanceContext instanceContext)
  {
return this.GetInstance(instanceContext, null);
  }
public void ReleaseInstance(InstanceContext instanceContext, object instance)
  {
  }
}

 

 

public interface IUnitOfWork
{
void Commit();
}

public class DbUnitOfWork : IUnitOfWork
{
SVCContext _context;
public DbUnitOfWork(SVCContext context)
  {
    _context = context;
  }
public void Commit()
  {
    _context.SaveChanges();
  }
}

 

public class UnitOfWorkMessageInspector : IDispatchMessageInspector
{
IUnityContainer _container;
public UnitOfWorkMessageInspector(IUnityContainer container)
  {
    _container = container;
  }
public object AfterReceiveRequest(ref Message request, IClientChannel channel,
InstanceContext instanceContext)
  {
return _container.Resolve<IUnitOfWork>();
  }
public void BeforeSendReply(ref Message reply, object correlationState)
  {
    ((IUnitOfWork)correlationState).Commit();
  }
}

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...