Monday, November 18, 2019

Usefull extension methods


// foreach with a "manual" index
int index = 0;
foreach (var item in collection)
{
    DoSomething(item, index);
    index++;
}
// normal for loop
for (int index = 0; index < collection.Count; index++)
{
    var item = collection[index];
    DoSomething(item, index);
}
It’s something that has always annoyed me; couldn’t we have the benefits of both foreach and for?
It turns out that there’s a simple solution, using Linq and tuples. Just write an extension method like this:
using System.Linq;
...
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
    return source.Select((item, index) => (item, index));
}
Do this:
foreach (var (item, index) in collection.WithIndex())
{
    DoSomething(item, index);
}

----------------------------------------------------------------------------------------------------------------


Multilist collection by Tuple
           IList<Tuple<string, string, string, string, string>> listOfData = new List<Tuple<string, string, string, string, string>>();
            foreach (var item in interactionDataSetInformation)
            {
                listOfData.Add(new Tuple<string, string, string, string, string>(item.ICNOcurs, item.MessageType, item.Revision, item.EntityState, item.EntityStatus));
            }
Multilist collection by ArrayList

            ArrayList listOfData = new ArrayList();
            foreach (var item in interactionDataSetInformation)
            {
                listOfData.Add(new string[] { item.ICNOcurs, item.MessageType, item.Revision, item.EntityState, item.EntityStatus });
            }
            ArrayList listOfData = interactionDataSetInformation.ToArrayList<InteractionDataSetInformation>();

Extension methods
  public static DataTable ToDataTable<T>(this IEnumerable<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
            {
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            }
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }

        public static List<T> ToList<T>(this ArrayList arrayList)
        {
            List<T> list = new List<T>(arrayList.Count);
            foreach (T instance in arrayList)
            {
                list.Add(instance);
            }
            return list;
        }

        public static ArrayList ToArrayList<T>(this IEnumerable<T> list)
        {
            ArrayList arrayList = new ArrayList();
            foreach (T item in list)
            {
                List<string> listString = new List<string>();
                foreach (PropertyInfo prop in typeof(T).GetProperties())
                {
                    listString.Add((prop.GetValue(item) == null) ? string.Empty : prop.GetValue(item).ToString());
                }
                string[] _item = listString.ToArray();
                arrayList.Add(_item);
            }
            return arrayList;
        }
    }
-------------------------------------------------------------------------------------------------------------------------

Friday, November 1, 2019

Unity Dependency Injection with N-Layer Project


Web/Web Api
-----------
public class SubProjApiProductController : ApiController
    {

        private readonly IWebApiBusinessFactory _webApiBusinessFactory;

        public SubProjApiProductController(IWebApiBusinessFactory webApiBusinessFactory)
        {
            _webApiBusinessFactory = webApiBusinessFactory;
        }


        [Route("api/products")]
        [HttpPost]
        public async Task<IHttpActionResult> GetProducts([FromBody] IDictionary<string, string> data)
        {
            try
            {
                return Ok(await _webApiBusinessFactory.QueryProductService().GetProductsAsync(data).ConfigureAwait(false));
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.NotFound, ex.Message);
                //return NotFound();
            }
        }


        [Route("api/addproduct")]
        [HttpPost]
        public async Task<IHttpActionResult> AddProduct([FromBody] Product product)
        {
            try
            {
                await _webApiBusinessFactory.CommandProductService().InsertAsync(product).ConfigureAwait(false);
                return Ok();
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.NotFound, ex.Message);
                //return NotFound();
            }
        }

     }

public static class UnityConfig

    {
        public static void RegisterTypes(IUnityContainer container)
        {

            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();
            // container.AddNewExtension<BusinessUnityContainerExtension>(); //for non-parameter 
            container.AddExtension(new BusinessUnityContainerExtension(_connectionString, _connectionTimeout));

            //Product Api
            container.RegisterType<SubProjApiProductController>(new InjectionConstructor(new ResolvedParameter<IWebApiBusinessFactory>()));

        }
}

Business Layer
--------------
public class BusinessUnityContainerExtension : UnityContainerExtension
    {
        #region Fields

        private readonly string _connectionString;
        private readonly int? _connectionTimeout;

        #endregion Fields

        public BusinessUnityContainerExtension(string connectionString, int? connectionTimeout)
        {
            _connectionString = connectionString;
            _connectionTimeout = connectionTimeout ?? 0;
        }

        protected override void Initialize()
        {
            Container.RegisterType<IUnitOfWorkFactory, UnitOfWorkFactory>(new HierarchicalLifetimeManager());

            Container.RegisterType<IWebApiBusinessFactory, WebApiBusinessFactory>(new HierarchicalLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IUnitOfWorkFactory>()));


        }

    }

Friday, October 11, 2019

Class diagram, Entity relationship diagram ,Layer Diagrams, Code Maps



Class Diagram


  • Goto Class View and right-click --> View --> view class diagram
  • Select all typeson the diagram by pressing Ctrl+A
  • Expand all types by pressiong the “+” key on the numeric keypad
  • Right-click on the diagram and select Adust shapes width
  • Right-click on the diagram and select Layout Diagram
  • Right-click on the diagram and select Export diagram as image


Entity Relationship Diagram

 entity relationship diagram. It was tested in VS2012
  1. Open Visual Studio
  2. Create a project or open an existing project (must be Visual Basic, Visual C# project, or Console Application)
  3. Right-click the project and choose Add -> New Item…
  4. Under Visual C# Items select “Data”
  5. Select the template “ADO.NET Entity Data Model”
  6. Give it a name and click “Add”
  7. Select “Generate from database” or “Empty model”
  8. If “Generate from database” selected enter connection info, choose the database objects and done!

The model is stored as a “.edmx” file.


Layer Diagram

Create and drag projects

Code Maps

Create and drag projects

Sequence Diagram

Removed from newer version of visual studio

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...