برچسب: Studio

  • How to create custom snippets in Visual Studio 2022 | Code4IT

    How to create custom snippets in Visual Studio 2022 | Code4IT


    A simple way to improve efficiency is knowing your IDE shortcuts. Let’s learn how to create custom ones to generate code automatically.

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    One of the best tricks to boost productivity is knowing your tools.

    I’m pretty sure you’ve already used some predefined snippets in Visual Studio. For example, when you type ctor and hit Tab twice, VS automatically creates an empty constructor for the current class.

    In this article, we will learn how to create custom snippets: in particular, we will design a snippet that automatically creates a C# Unit Test method with some placeholders and predefined Arrange-Act-Assert blocks.

    Snippet Designer: a Visual Studio 2022 extension to add a UI to your placeholders

    Snippets are defined in XML-like files with .snippet extension. But we all know that working with XMLs can be cumbersome, especially if you don’t have a clear idea of the expected structure.

    Therefore, even if not strictly necessary, I suggest installing a VS2022 extension called Snippet Designer 2022.

    Snippet Designer 2022 in VS2022

    This extension, developed by Matthew Manela, can be found on GitHub, where you can view the source code.

    This extension gives you a UI to customize the snippet instead of manually editing the XML nodes. It allows you to customize the snippet, the related metadata, and even the placeholders.

    Create a basic snippet in VS2022 using a .snippet file

    As we saw, snippets are defined in a simple XML.

    In order to have your snippets immediately available in Visual Studio, I suggest you create those files in a specific VS2022 folder under the path \Documents\Visual Studio 2022\Code Snippets\Visual C#\My Code Snippets\.

    So, create an empty file, change its extension to .snippet, and save it to that location.

    Save snippet file under the My Code Snippets folder in VS2022

    Now, you can open Visual Studio (it’s not necessary to open a project, but I’d recommend you to do so). Then, head to File > Open, and open the file you saved under the My Code Snippets directory.

    Thanks to Snippet Designer, you will be able to see a nice UI instead of plain XML content.

    Have a look at how I filled in the several parts to create a snippet that generates a variable named x, assigns to it a value, and then calls x++;

    Simple snippet, with related metadata and annotations

    Have a look at the main parts:

    • the body, which contains the snippet to be generated;
    • the top layer, where we specified:
      • the Snippet name: Int100; it’s the display name of the shortcut
      • the code language: C#;
      • the shortcut: int100; it’s the string you’ll type in that allows you to generate the expected snippet;
    • the bottom table, which contains the placeholders used in the snippet; more on this later;
    • the properties tab, on the sidebar: here is where you specify some additional metadata, such as:
      • Author, Description, and Help Url of the snippet, in case you want to export it;
      • the kind of snippet: possible values are MethodBody, MethodDecl and TypeDecl. However, this value is supported only in Visual Basic.

    Now, hit save and be ready to import it!

    Just for completeness, here’s the resulting XML:

    <?xml version="1.0" encoding="utf-8"?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
          <Title>Int100</Title>
          <Author>
          </Author>
          <Description>
          </Description>
          <HelpUrl>
          </HelpUrl>
          <Shortcut>int100</Shortcut>
        </Header>
        <Snippet>
          <Code Kind="method decl" Language="csharp" Delimiter="$"><![CDATA[int x = 100;
    x++;]]></Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>
    

    Notice that the actual content of the snippet is defined in the CDATA block.

    Import the snippet in Visual Studio

    It’s time to import the snippet. Open the Tools menu item and click on Code Snippets Manager.

    Code Snippets Manager menu item, under Tools

    From here, you can import a snippet by clicking the Import… button. Given that we’ve already saved our snippet in the correct folder, we’ll find it under the My Code Snippets folder.

    Code Snippets Manager tool

    Now it’s ready! Open a C# class, and start typing int100. You’ll see our snippet in the autocomplete list.

    Int100 snippet is now visible in Visual Studio

    By hitting Tab twice, you’ll see the snippet’s content being generated.

    How to use placeholders when defining snippets in Visual Studio

    Wouldn’t it be nice to have the possibility to define customizable parts of your snippets?

    Let’s see a real example: I want to create a snippet to create the structure of a Unit Tests method with these characteristics:

    • it already contains the AAA (Arrange, Act, Assert) sections;
    • the method name should follow the pattern “SOMETHING should DO STUFF when CONDITION”. I want to be able to replace the different parts of the method name by using placeholders.

    You can define placeholders using the $ symbol. You will then see the placeholders in the table at the bottom of the UI. In this example, the placeholders are $TestMethod$, $DoSomething$, and $Condition$. I also added a description to explain the purpose of each placeholder better.

    TestSync snippet definition and metadata

    The XML looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
          <Title>Test Sync</Title>
          <Author>Davide Bellone</Author>
          <Description>Scaffold the AAA structure for synchronous NUnit tests</Description>
          <HelpUrl>
          </HelpUrl>
          <Shortcut>testsync</Shortcut>
        </Header>
        <Snippet>
          <Declarations>
            <Literal Editable="true">
              <ID>TestMethod</ID>
              <ToolTip>Name of the method to be tested</ToolTip>
              <Default>TestMethod</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>DoSomething</ID>
              <ToolTip>Expected behavior or result</ToolTip>
              <Default>DoSomething</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>Condition</ID>
              <ToolTip>Initial conditions</ToolTip>
              <Default>Condition</Default>
              <Function>
              </Function>
            </Literal>
          </Declarations>
          <Code Language="csharp" Delimiter="$" Kind="method decl"><![CDATA[[Test]
    public void $TestMethod$_Should_$DoSomething$_When_$Condition$()
    {
        // Arrange
    
        // Act
    
        // Assert
    
    }]]></Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>
    

    Now, import it as we already did before.

    Then, head to your code, start typing testsync, and you’ll see the snippet come to life. The placeholders we defined are highlighted. You can then fill in these placeholders, hit tab, and move to the next one.

    Test sync snippet usage

    Bonus: how to view all the snippets defined in VS

    If you want to learn more about your IDE and the available snippets, you can have a look at the Snippet Explorer table.

    You can find it under View > Tools > Snippet Explorer.

    Snippet Explorer menu item

    Here, you can see all the snippets, their shortcuts, and the content of each snippet. You can also see the placeholders highlighted in green.

    List of snippets available in Snippet Explorer

    It’s always an excellent place to learn more about Visual Studio.

    Further readings

    As always, you can read more on Microsoft Docs. It’s a valuable resource, although I find it difficult to follow.

    🔗 Create a code snippet in Visual Studio | Microsoft docs

    I prefer working with the UI. If you want to have a look at the repo of the extension we used in this article, here’s the link:

    🔗 SnippetDesigner extension | GitHub

    This article first appeared on Code4IT 🐧

    Wrapping up

    There are some tips that may improve both the code quality and the developer productivity.

    If you want to enforce some structures or rules, add such snippets in your repository; when somebody joins your team, teach them how to import those snippets.

    I hope you enjoyed this article! Let’s keep in touch on Twitter or LinkedIn! 🤜🤛

    Happy coding!

    🐧





    Source link

  • [ENG] Improving Your Code Coverage | Microsoft Visual Studio YouTube channel



    [ENG] Improving Your Code Coverage | Microsoft Visual Studio YouTube channel



    Source link

  • JavaScript and TypeScript Projects with React, Angular, or Vue in Visual Studio 2022 with or without .NET

    JavaScript and TypeScript Projects with React, Angular, or Vue in Visual Studio 2022 with or without .NET



    I was reading Gabby’s blog post about the new TypeScript/JavaScript project experience in Visual Studio 2022. You should read the docs on JavaScript and TypeScript in Visual Studio 2022.

    If you’re used to ASP.NET apps when you think about apps that are JavaScript heavy, “front end apps” or TypeScript focused, it can be confusing as to “where does .NET fit in?”

    You need to consider the responsibilities of your various projects or subsystems and the multiple totally valid ways you can build a web site or web app. Let’s consider just a few:

    1. An ASP.NET Web app that renders HTML on the server but uses TS/JS
      • This may have a Web API, Razor Pages, with or without the MVC pattern.
      • You maybe have just added JavaScript via <script> tags
      • Maybe you added a script minimizer/minifier task
      • Can be confusing because it can feel like your app needs to ‘build both the client and the server’ from one project
    2. A mostly JavaScript/TypeScript frontend app where the HTML could be served from any web server (node, kestrel, static web apps, nginx, etc)
      • This app may use Vue or React or Angular but it’s not an “ASP.NET app”
      • It calls backend Web APIs that may be served by ASP.NET, Azure Functions, 3rd party REST APIs, or all of the above
      • This scenario has sometimes been confusing for ASP.NET developers who may get confused about responsibility. Who builds what, where do things end up, how do I build and deploy this?

    VS2022 brings JavaScript and TypeScript support into VS with a full JavaScript Language Service based on TS. It provides a TypeScript NuGet Package so you can build your whole app with MSBuild and VS will do the right thing.

    NEW: Starting in Visual Studio 2022, there is a new JavaScript/TypeScript project type (.esproj) that allows you to create standalone Angular, React, and Vue projects in Visual Studio.

    The .esproj concept is great for folks familiar with Visual Studio as we know that a Solution contains one or more Projects. Visual Studio manages files for a single application in a Project. The project includes source code, resources, and configuration files. In this case we can have a .csproj for a backend Web API and an .esproj that uses a client side template like Angular, React, or Vue.

    Thing is, historically when Visual Studio supported Angular, React, or Vue, it’s templates were out of date and not updated enough. VS2022 uses the native CLIs for these front ends, solving that problem with Angular CLI, Create React App, and Vue CLI.

    If I am in VS and go “File New Project” there are Standalone templates that solve Example 2 above. I’ll pick JavaScript React.

    Standalone JavaScript Templates in VS2022

    Then I’ll click “Add integration for Empty ASP.NET Web API. This will give me a frontend with javascript ready to call a ASP.NET Web API backend. I’ll follow along here.

    Standalone JavaScript React Template

    It then uses the React CLI to make the front end, which again, is cool as it’s whatever version I want it to be.

    React Create CLI

    Then I’ll add my ASP.NET Web API backend to the same solution, so now I have an esproj and a csproj like this

    frontend and backend

    Now I have a nice clean two project system – in this case more JavaScript focused than .NET focused. This one uses npm to startup the project using their web development server and proxyMiddleware to proxy localhost:3000 calls over to the ASP.NET Web API project.

    Here is a React app served by npm calling over to the Weather service served from Kestrel on ASP.NET.

    npm app running in VS 2022 against an ASP.NET Web API

    This is inverted than most ASP.NET Folks are used to, and that’s OK. This shows me that Visual Studio 2022 can support either development style, use the CLI that is installed for whatever Frontend Framework, and allow me to choose what web server and web browser (via Launch.json) I want.

    If you want to flip it, and put ASP.NET Core as the primary and then bring in some TypeScript/JavaScript, follow this tutorial because that’s also possible!


    Sponsor: Make login Auth0’s problem. Not yours. Provide the convenient login features your customers want, like social login, multi-factor authentication, single sign-on, passwordless, and more. Get started for free.




    About Scott

    Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

    facebook
    bluesky
    subscribe
    About   Newsletter

    Hosting By
    Hosted on Linux using .NET in an Azure App Service










    Source link

  • Webcam randomly pausing in OBS, Discord, and websites – LSVCam and TikTok Studio

    Webcam randomly pausing in OBS, Discord, and websites – LSVCam and TikTok Studio



    I use my webcam constantly for streaming and I’m pretty familiar with all the internals and how the camera model on Windows works. I also use OBS extensively, so I regularly use the OBS virtual camera and flow everything through Open Broadcasting Studio.

    For my podcast, I use Zencastr which is a web-based app that talks to the webcam via the browser APIs. For YouTubes, I’ll use Riverside or StreamYard, also webapps.

    I’ve done this reliably for the last several years without any trouble. Yesterday, I started seeing the most weird thing and it was absolutely perplexing and almost destroyed the day. I started seeing regular pauses in my webcam stream but only in two instances.

    • The webcam would pause for 10-15 seconds every 90 or so seconds when access the Webcam in a browser
    • I would see a long pause/hang in OBS when double clicking on my Video Source (Webcam) to view its properties

    Micah initially said USB but my usb bus and hubs have worked reliably for years. Thought something might have changed in my El Gato capture device, but that has also been rock solid for 1/2 a decade. Then I started exploring virtual cameras and looked in the windows camera dialog under settings for a list of all virtual cameras.

    Interestingly, virtual cameras don’t get listed under Cameras in Settings in Windows:

    List of Cameras in Windows

    From what I can tell, there’s no user interface to list out all of your cameras – virtual or otherwise – in windows.

    Here’s a quick PowerShell script you can run to list out anything ‘connected’ that also includes the string “cam” in your local devices

    Get-CimInstance -Namespace root\cimv2 -ClassName Win32_PnPEntity |
    Where-Object { $_.Name -match 'Cam' } |
    Select-Object Name, Manufacturer, PNPDeviceID

    and my output

    Name                                     Manufacturer        PNPDeviceID
    ---- ------------ -----------
    Cam Link 4K Microsoft USB\VID_0FD9&PID_0066&MI_00\7&3768531A&0&0000
    Digital Audio Interface (2- Cam Link 4K) Microsoft SWD\MMDEVAPI\{0.0.1.00000000}.{AF1690B6-CA2A-4AD3-AAFD-8DDEBB83DD4A}
    Logitech StreamCam WinUSB Logitech USB\VID_046D&PID_0893&MI_04\7&E36D0CF&0&0004
    Logitech StreamCam (Generic USB Audio) USB\VID_046D&PID_0893&MI_02\7&E36D0CF&0&0002
    Logitech StreamCam Logitech USB\VID_046D&PID_0893&MI_00\7&E36D0CF&0&0000
    Remote Desktop Camera Bus Microsoft UMB\UMB\1&841921D&0&RDCAMERA_BUS
    Cam Link 4K (Generic USB Audio) USB\VID_0FD9&PID_0066&MI_03\7&3768531A&0&0003
    Windows Virtual Camera Device Microsoft SWD\VCAMDEVAPI\B486E21F1D4BC97087EA831093E840AD2177E046699EFBF62B27304F5CCAEF57

    However, when I list out my cameras using JavaScript enumerateDevices() like this

    // Put variables in global scope to make them available to the browser console.
    async function listWebcams() {
    try {
    const devices = await navigator.mediaDevices.enumerateDevices();
    const webcams = devices.filter(device => device.kind === 'videoinput');

    if (webcams.length > 0) {
    console.log("Connected webcams:");
    webcams.forEach((webcam, index) => {
    console.log(`${index + 1}. ${webcam.label || `Camera ${index + 1}`}`);
    });
    } else {
    console.log("No webcams found.");
    }
    } catch (error) {
    console.error("Error accessing media devices:", error);
    }
    }
    listWebcams();

    I would get:

    Connected webcams:
    test.html:11 1. Logitech StreamCam (046d:0893)
    test.html:11 2. OBS Virtual Camera (Windows Virtual Camera)
    test.html:11 3. Cam Link 4K (0fd9:0066)
    test.html:11 4. LSVCam
    test.html:11 5. OBS Virtual Camera

    So, what, what’s LSVCam? And depending on how I’d call it I’d get the pause and

    getUserMedia error: NotReadableError NotReadableError: Could not start video source

    Some apps could see this LSVCam and others couldn’t. OBS really dislikes it, browsers really dislike it and it seemed to HANG on enumeration of cameras. Why can parts of Windows see this camera and others can’t?

    I don’t know. Do you?

    Regardless, it turns that it appears once in my registry, here (this is a dump of the key, you just care about the Registry PATH)

    Windows Registry Editor Version 5.00

    [HKEY_CLASSES_ROOT\CLSID\{860BB310-5D01-11d0-BD3B-00A0C911CE86}\Instance\LSVCam]
    "FriendlyName"="LSVCam"
    "CLSID"="{BA80C4AD-8AED-4A61-B434-481D46216E45}"
    "FilterData"=hex:02,00,00,00,00,00,20,00,01,00,00,00,00,00,00,00,30,70,69,33,\
    08,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00,00,00,00,00,30,74,79,33,00,\
    00,00,00,38,00,00,00,48,00,00,00,76,69,64,73,00,00,10,00,80,00,00,aa,00,38,\
    9b,71,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00

    If you want to get rid of it, delete HKEY_CLASSES_ROOT\CLSID\{860BB310-5D01-11d0-BD3B-00A0C911CE86}\Instance\LSVCam

    WARNING: DO NOT delete the \Instance, just the LSVCam and below. I am a random person on the internet and you got here by googling, so if you mess up your machine by going into RegEdit.exe, I’m sorry to this man, but it’s above me now.

    Where did LSVCam.dll come from, you may ask? TikTok Live Studio, baby. Live Studio Video/Virtual Cam, I am guessing.

    Directory of C:\Program Files\TikTok LIVE Studio\0.67.2\resources\app\electron\sdk\lib\MediaSDK_V1

    09/18/2024 09:20 PM 218,984 LSVCam.dll
    1 File(s) 218,984 bytes

    This is a regression that started recently for me, so it’s my opinion that they are installing a virtual camera for their game streaming feature but they are doing it poorly. It’s either not completely installed, or hangs on enumeration, but the result is you’ll see hangs on camera enumeration in your apps, especually browser apps that poll for cameras changes or check on a timer.

    Nothing bad will happen if you delete the registry key BUT it’ll show back up when you run TikTok Studio again. I still stream to TikTok, I just delete this key each time until someone on the TikTok Studio development team sees this blog post.

    Hope this helps!




    About Scott

    Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

    facebook
    bluesky
    subscribe
    About   Newsletter

    Hosting By
    Hosted on Linux using .NET in an Azure App Service










    Source link