Thursday, November 28, 2019

Asynchronous file uploads in ASP.NET Web API

File upload is quite an important topic for Web API endpoints or for API-driven applications, and sure enough there are some nice changes to the MultiPartFormDataStreamProvider

Let’s have a look at how you could upload files to your ASP.NET Web API.

MultipartFormPost
This method has five parameters. You can increase/decrease the number of parameters according to your requirement. These five parameters are, 
  • Posturl 
    This must be the url to which you want to post the form.
  • userAgentThis is up to your requirement; if needed, then pass the value as required.
  • postParametersThis is of type Dictionary. You can pass the parameter name and value as “key-value”
  • headerkeyThis must be the name of the header that needs to be passed. In this example, I have used it as a string which can be used to pass a single header. If the header is not required, you can ignore this parameter.
  • headervalueThis must be the value of the header to be passed.

Let’s modify our controller now

Returning some meaningful info

Finally, you may want to return some information about the uploaded files to the client. If that’s the case, one way to do it is to use a helper class (which was used already in the older post):

2
3
4
5
6
7
8
9
10
11
12
13
public class FileDesc
{
public string Name { get; set; }
public string Path { get; set; }
public long Size { get; set; }
 
public FileDesc(string n, string p, long s)
{
            Name = n;
            Path = p;
            Size = s;
}
}

However, now, you can easily derive from the default MultiPartFormDataStreamProvider and provide your own naming mechanism.

Let’s have a look at such simple example:

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path)
{}
 
        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
            return name.Replace(""",string.Empty); //this is here because Chrome submits files in quotation marks which get treated as part of the filename and get escaped
        }
}


So now, instead of void we return a List<FileDesc> which can provide the client information about each of the uploaded files: its name, path and size.




Friday, November 8, 2019

How to remove elements from a generic list while iterating over it?

You can't use .Remove(element) inside a foreach (var element in X) (because it results in Collection was modified; enumeration operation may not execute. exception)... you also can't use for (int i = 0; i < elements.Count(); i++) and .RemoveAt(i) because it disrupts your current position in the collection relative to i.
You can't use foreach, but you could iterate forwards and manage your loop index variable when you remove an item, like so:
Solution:- 
static void Main(string[] args)
        {
            var s = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

            for (int i = s.Count -1; i >= 0; i--)
            {
                if ((int) Convert.ToChar(s[i])%2 == 1)
                {
                    s.RemoveAt(i);
                }
            }

            Console.ReadKey();
        }

Adapter Pattern c#

Adapter pattern acts as a bridge between two incompatible interfaces. This pattern involves a single class called adapter which is responsible for communication between two independent or incompatible interfaces.

UML Diagram & Implementation



The classes and objects participating in this pattern are:
  • Target  :- defines the domain-specific interface that Client uses.
  • Adapter   adapts the interface Adaptee to the Target interface.
  • Adaptee  Defines an existing interface that needs adapting.
  • Client   collaborates with objects conforming to the Target interface.

/// <summary>
/// The 'Client' class
/// </summary>
public class ThirdPartyBillingSystem
{
 private ITarget employeeSource;
 
 public ThirdPartyBillingSystem(ITarget employeeSource)
 {
 this.employeeSource = employeeSource;
 }
 
 public void ShowEmployeeList()
 {
 List<string> employee = employeeSource.GetEmployeeList();
 //To DO: Implement you business logic
 
 Console.WriteLine("######### Employee List ##########");
 foreach (var item in employee)
 {
 Console.Write(item); 
 }
 
 }
}

/// <summary>
/// The 'ITarget' interface
/// </summary>
public interface ITarget
{
 List<string> GetEmployeeList();
}

/// <summary>
/// The 'Adaptee' class
/// </summary>
public class HRSystem
{
 public string[][] GetEmployees()
 {
 string[][] employees = new string[4][];
 
 employees[0] = new string[] { "100", "Deepak", "Team Leader" };
 employees[1] = new string[] { "101", "Rohit", "Developer" };
 employees[2] = new string[] { "102", "Gautam", "Developer" };
 employees[3] = new string[] { "103", "Dev", "Tester" };
 
 return employees;
 }
}

/// <summary>
/// The 'Adapter' class
/// </summary>
public class EmployeeAdapter : HRSystem, ITarget
{
 public List<string> GetEmployeeList()
 {
 List<string> employeeList = new List<string>();
 string[][] employees = GetEmployees();
 foreach (string[] employee in employees)
 {
 employeeList.Add(employee[0]);
 employeeList.Add(",");
 employeeList.Add(employee[1]);
 employeeList.Add(",");
 employeeList.Add(employee[2]);
 employeeList.Add("\n");
 }
 
 return employeeList;
 }
}

/// 
/// Adapter Design Pattern Demo
/// 
class Program
{
 static void Main(string[] args)
 {
 ITarget Itarget = new EmployeeAdapter();
 ThirdPartyBillingSystem client = new ThirdPartyBillingSystem(Itarget);
 client.ShowEmployeeList();
 
 Console.ReadKey();
 
 }
}





When to use it?

  1. Allow a system to use classes of another system that is incompatible with it.
  2. Allow communication between a new and already existing system which are independent of each other
  3. Ado.Net SqlAdapter, OracleAdapter, MySqlAdapter are the best example of Adapter Pattern.









Part 7 — Enterprise RAG Reference Architecture

  "Architecture is not about connecting components. It is about defining responsibilities that can evolve independently." Welcome ...