Git and Team Services made easy with Visual Studio 2017

Git distributed version control system can be used to manage code in the Visual Studio Team Services repository. Visual Studio 2017 IDE provides easy access to Git and VSTS.

Here are some important information to begin with.

If you come across error 400 when you are cloning, first of all check whether you have spaces in the git repository URL and replace the spaces with %20 as suggested here.

How to add Log4Net to your ASP.Net MVC (C#) project

  1. Add log4net dll to your references using Nuget Package Manager.
  2. Add this line to your AssemblyInfo.cs file
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
  3. Add the following xml code to your Web.config file, inside the configurations tags. The value for version should be the version of your log4net dll.
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
    </configSections>
  4. Also add the following lines to the Web.config file inside the configuration tags. Here I am logging to a file called “Jumppage.log” inside a folder named “Log”.
    <!-- Log4net Logging Setup -->
    <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
    <file value="Log\Jumppage.log" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="INFO" />
    <levelMax value="FATAL" />
    </filter>
    </appender><root>
    <level value="DEBUG" />
    <appender-ref ref="FileAppender" />
    </root>
    </log4net>
    
  5. Go to your class file and add the namespace, log4net as follows.
    using log4net;
  6. Add following code inside your class. You need to write your class name inside the typeof() method. In this project my class name is “AnnouncementController”.
    private static readonly ILog Logger = LogManager.GetLogger(typeof(AnnouncementController));
  7. Then you can log your error as follows.
    Logger.Error("Error in posting announcements. error message:"+ ex.Message + ", stacktrace:" + ex.StackTrace);

File upload control using ASP.Net MVC (C#)

HTML code
<input id="file-upload-control" name="UploadFile" type="file"/>
<button id="file-upload-button" class="button tiny" style="border: 1px solid #cccccc;">Upload</button>

JQuery code

var selectedFiles;
$('#file-upload-control').on('change', function (e) {
        selectedFiles = e.target.files;
    });

    $('#file-upload-button').on('click', function () {
        var files = selectedFiles;

        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }

                $.ajax({
                    type: "POST",
                    url: 'File/UploadFile',
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {
                        console.log(result);
                        showInfo("File upload was successful! ");
                    },
                    error: function (xhr, status, p3, p4) {
                        var err = "Error " + " " + status + " " + p3 + " " + p4;
                        if (xhr.responseText && xhr.responseText[0] == "{")
                            err = JSON.parse(xhr.responseText).Message;
                        console.log(err);
                        showInfo("Something went wrong uploading file! ");
                    }
                });
            } else {
                alert("This browser doesn't support HTML5 file uploads!");
            }
        }
    });

FileController code

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace DHI.Controllers
{
public class FileController : Controller
{
[HttpPost]
public async Task UploadFile()
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
using (var fileStream = System.IO.File.Create(path))
{
stream.CopyTo(fileStream);
}
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Upload failed");
}

return Json("File uploaded successfully");
}
}
}

Visual C# Code Snippets

What is a code snippet?

Code snippet is a ready made few lines of code, which is ready to insert into your code. Say you want to add a property to your class in C#. Type prop and press tab key twice, you will have a property inserted in your class which is waiting to be modified according to your requirement.

C# code snippets make day to day life of a C# programmer is very easy.

How to use code snippets?

Here is the link to default code snippets supported in Visual Studio: https://msdn.microsoft.com/en-us/library/z41h7fat.aspx

How to create a code snippet?

Steps to create your own method snippet is as follows.

1. Create a new text file and name it as method.snippet

2. Copy and paste the following code in to the method.snippet file.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>method</Title>
            <Shortcut>method</Shortcut>
            <Description>Code snippet for method</Description>           
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>methodname</ID>
                    <ToolTip>Method name</ToolTip>
                    <Function>MethodName()</Function>
                    <Default>MethodNamePlaceholder</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[public void $methodname$ ()
    {
        $end$
    }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

3. Copy your file into visual studio’s snippet folder.

 My snippets folder located at : C:Program Files (x86)Microsoft Visual Studio 12.0VC#Snippets1033Visual C#

4. Restart visual studio if you have already running it.

5. Open visual studio C# class and type method and press tab key twice.

6. You will see a method created as follows

public void MethodNamePlaceholder()
    {

    }

7. Go ahead and change your method as you want.

Credits:

 http://stackoverflow.com/a/19247785/778101

https://msdn.microsoft.com/en-us/library/ms165394.aspx

have fun with code snippets!