ASP.NET: Store Email Template in .NET

Standard

Simple and Easy to edit way to store email templates in your .net project is string email body in html file.

Step 1: Create a HTML mail message

2016-10-04-16_04_18-_c__users_hassan-muhammad_desktop_new-14-html-notepad

Step 1(a): You can introduce as many as variable in HTML template by any character scheme (@PARAMETER@ or #PARAMETER# or $$PARAMETER$$). Replace all names/variables with things like #VaraibleName#
The confirmation number is: <b>#confirmNumber#</b>
Step 2: Right click on web project and select Properties from right click menu

2016-10-04-16_08_58-recruiting-microsoft-visual-studio-administrator

Step 3: Select Resources tab from left, choose Add Resource, select Add Existing File and choose appropriate html file

2016-10-04-16_24_57-recruiting-microsoft-visual-studio-administrator

Step 4: File will be visible in Resources display pan

2016-10-04-16_26_31-recruiting-microsoft-visual-studio-administrator

Step 5: For Server side C# code

You can refer to HTML email template from Properties.Resources.EmailTemplate. You can use it as a string. Replace the #PARAMETER# text with the actual values.

private void SendConfirmationEmail(string email, string confirmNumber)
{
    var emailBody = Properties.Resources.EmailTemplate.Replace("#confirmNumber#", confirmNumber);
    MailMessage message =
        new MailMessage
        {
            From =
            new MailAddress("Sender Email Address"),
            Subject = "Email Subject Content",
            Body = string.Format(emailBody),
            IsBodyHtml = true
        };
 
    message.To.Add(new MailAddress(email));
    SmtpClient client = new SmtpClient("11.111.111.11");
    client.Send(message);
}

C#: Sending SOAP request and receiving response without using the WSDL or proxy classes

Standard

In order to send and receive SOAP messages from server in c# environment without the help of WSDL or Proxy classes.

Below major steps are involved:

  1. Mention Web Service URL and Method
  2. Create Web Request
  3. Create SOAP Envelope
  4. Insert SOAP Envelope into Web Request
  5. Capture SOAP response

Snippet

       public String SOAPManual()
       {
            const string url = "URL";
            const string action = "METHOD_NAME";
 
            XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
            HttpWebRequest webRequest = CreateWebRequest(url, action);
 
            InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
 
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
 
        private static HttpWebRequest CreateWebRequest(string url, string action)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", action);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }
 
        private static XmlDocument CreateSoapEnvelope()
        {
            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                    <soap:Body>
                    <Method xmlns=""http://www.sample.com/path/"">
                    <Parameter1>param1</Parameter1>
                    <Parameter2>param2</Parameter2>
                    </Method>
                    </soap:Body>
                    </soap:Envelope>");
            return soapEnvelopeXml;
        }
 
        private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
        {
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }
        }

Entity Framework: Use Expression Trees to Build Dynamic Queries or Filter using Expression tree

Standard

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. Entity Framework or LINQ to SQL operates with expression trees to construct SQL queries from lambda expressions.

Look at below syntax:

void Delete<T>(Expression<Func<T, bool>> expression) where T : class, new()

A “predicate” is any device that says “yes” or “no” to the question “is this thing a member of that set?” So a predicate for the set “integers even positive integers” would be x=> x > 0 && x % 2 == 0.

This method probably has the semantics of “delete from the collection all members of the collection that are in the set identified by the predicate”.  The predicate is passed to the method in the form of an expression tree, which is a way of passing the structure of the predicate in a manner that can be analyzed at runtime and transformed.

  • Use Expression<Func<EntityName, bool>> rather than Expression<Predicate<EntityName>>, because that’s what Queryable.Where expects
  • Pass it directly in .Where, combining them using multiple .Where calls instead of &&.Unfortunately there’s no way to use Predicate<T> in EF linq since it’s impossible to map it on SQL query. This can be done with Expressions only because they can be parsed and converted to SQL.In fact there are 4 language features that made linq possible:
    1. Extension methods
    2. Type inference
    3. Closures
      and for linq2sql especially
    4. Expressions

    Code Example

public Course EditCourse(Course obj)
{
   return courseRepo.Update(obj, x => x.CourseId == obj.CourseId);
}
public virtual T Update(T obj, Expression<Func<T, bool>> match)
{
     using (var context = new PluralSightContext())
     {
        if (obj == null)
           return null;
 
         T existing = context.Set<T>().SingleOrDefault(match);
 
         if (existing != null)
         {
              context.Entry(existing).CurrentValues.SetValues(obj);                    
              context.SaveChanges();
         }
         return existing;
      }
}

So now map Expression<Func<T, bool>> in above example: bool is return type and T refers to Course Entity, so Expression x => x.CourseId == obj.CourseId stores the info about that expression and that there’s a T x, that you’re accessing the property CourseId (T corresponds to Course entity)

Calling the == operator with the int value provided by user. When EF looks at that, it might turn it into something like [Course_Table].[CourseID_Column] == parameter value

MSDN Reference Link

MSDN Reference Link2

 

Entity Framework: error The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

Standard

“The ObjectContext instance has been disposed and can no longer be used for operations that require a connection”: this error is quite common for all those operation which involves entities containing navigational properties/graph data/related data

2016-02-18 07_23_25-MyHomepage (Debugging) - Microsoft Visual Studio

In the above case, I was updating Course entity while Technology entity was navigational property in Course. As you can see all properties of Course have been pulled from database except of Technology data. Just go through code below:

Snapshot of Context class code:

 

2016-02-18 07_28_46-MyHomepage - Microsoft Visual Studio

Repository Class code:

        public T GetByID(int key)
        {
            using (var context = new PluralSightContext())
            {
                T existing = context.Set<T>().Find(key);
                return existing;
            }
        }
 
        public virtual T Update(T obj, int key)
        {
            using (var context = new PluralSightContext())
            {
                if (obj == null)
                    return null;
 
                T existing = GetByID(key);
                if (existing != null)
                {
                    context.Entry(existing).CurrentValues.SetValues(obj);
                    context.SaveChanges();
                }
                return existing;
            }
        }

Solution 1 (least appropriate):

Since lazy loading is activated as you can see from context class constructor code, By default Entity Framework uses lazy-loading for navigation properties. That’s why these properties should be marked as virtual – EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading, so in order to resolve your problem either use eager loading (.include(), .attach()) or explicit loading(.load()) and remove Virtual keyword from navigational properties. But I wont recommend this technique because it has performance impact, it will start loading all graph data for all entities, in order to make it happen only for single entity you have to write extra line of codes in context class.

MSDN Reference Link on Loading Strategies

Solution 2:

As you can see from above code we are creating two context first for GetByID function and the for Update function, I have using block around existing usage. Which disposes context before entities are returned. When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.

I am ending your context prematurely: a DbContext should be available throughout the unit of work being performed, only disposing it when you’re done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.

So if we move GetByID logic under one using statement, so this will resolve above issue:

        public virtual T Update(T obj, int key)
        {
            using (var context = new PluralSightContext())
            {
                if (obj == null)
                    return null;
 
                T existing = context.Set<T>().Find(key);
                if (existing != null)
                {
                    context.Entry(existing).CurrentValues.SetValues(obj);
                    context.SaveChanges();
                }
                return existing;
            }
        }

Entity Framework : Data Annotations – Foreign Key Attribute

Standard

ForeignKey attribute can be applied to properties of a class. Default Code-First convention for ForeignKey relationship expects foreign key property name match with primary key property.
1) Use ForeignKey (with an associated property) – version 1

[Table("WIDGETENTITIES")]
public class WidgetEntity {

    [Column("WIDGETENTITY_ID")]
    public int Id { get; set; }

    [Column("WIDGETSEQUENCE_ID")]
    public int WidgetSequenceId { get; set; }

    [ForeignKey("WidgetSequenceId")] //Has to be a property name, not table column name
    public WidgetSequence Sequence { get; set; }

    // and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence { 

    [Column("WIDGETSEQUENCE_ID")]
    public int Id { get; set; }

    [Column("NUMBER")]
    public int Number { get; set; }
}

1.2) Use ForeignKey (with an associated property) – version 2

[Table("WIDGETENTITIES")]
public class WidgetEntity {

    [Column("WIDGETENTITY_ID")]
    public int Id { get; set; }

    [ForeignKey("Sequence")] //Has to be a property name, not table column name
    [Column("WIDGETSEQUENCE_ID")]
    public int WidgetSequenceId { get; set; }

    public WidgetSequence Sequence { get; set; }

    // and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence { 

    [Column("WIDGETSEQUENCE_ID")]
    public int Id { get; set; }

    [Column("NUMBER")]
    public int Number { get; set; }
}

2) You can also use the InversePropertyAttribute.

[Table("WIDGETENTITIES")]
public class WidgetEntity {

    [Column("WIDGETENTITY_ID")]
    public int Id { get; set; }

    [InverseProperty("WidgetEntities")]
    public WidgetSequence Sequence { get; set; }

    // and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence { 

    [Column("WIDGETSEQUENCE_ID")]
    public int Id { get; set; }

    [Column("NUMBER")]
    public int Number { get; set; }

    public virtual List<WidgetEntity> WidgetEntities { get; set; }
}

Reference

Bing Search Using Angular Material and Angular UI Bootstrap

Standard

Using Angular Material, Angular UI Bootstrap, ASP.NET WebAPI and Bing API in implementing Bing clone SPA

Angular Material Directive used

Angular UI Bootstrap Directive used

  1. App Directory Structure

1

2. Module Directory Structure

2

3. Logical Module Division

3

4. App Config contains routing info and App Run contains startup logic

4

5. Lazy Loading for search page

  • bing.search module will not be loaded on page load, it will be loaded once user searched any keyword, this is done by resolving promises during route change.

5

6. Controller Structure

  • JS closure using IIFE
  • Controller As implementation to avoid $scope var every time in code
  • Named function for controller
  • Function declarations to abstract underline detail
  • Bindable members upfront at the top
  • DI using $inject to overcome issues during bundling and minification.
  • Wrapping members in init() method for controller activation promises.

6

7. Service Structure

  • Function declarations to abstract underline detail
  • Accessible members upfront at the top
  • Singleton object
  • SRP

7

8. Directive Structure

  • DOM manipulation using directive
  • Controller As and Controller activation promises
  • Restrict of directive to Element and Attribute only
  • Usage of shared and isolated scope (two way and behavioral binding)
  • Accessible members upfront & Function declarations to hide detail
  • SRP

8

9. Shared Services Structure – Example 1

  • This will be shared service which will be consumed by all modules for executing CRUD operation, Request Type, URL, Parameter Object will be passed to this shared service, so it will make code more maintainable readble and scaleble. If we dont go through this method then we have to use $http.get() or $http.post method very where in services files of each module, content negotiation issues can be simply handled over here, If you want to append anything with each URL like ‘Http:\bing\’ then instead of copy it on every service file just hardcode this thing in this file and append URL from thier respective services. We dont need to mention protocol and hostname now in every URL request. It also handles http communication exceptions globally.

9

10. Shared Services Structure – Example 2

  • Below service is used to store value of search text and selected text throughout application using angular factory.

10

11. WebAPI Structure

  • Weather transaction is for images, web, news or composite search, every http call will hit Get function first, and then on basis of mode it will redirect to actual BING api call. We can change underline structure anytime for image, news, web & composite search (for instance we can use google search api), but for client, service contract will be same as GET function is acting as facade here.

11

12. Credentials are stored in web.config and accessed through static class

12

13. Introduction of Template in HTML Structure for SPA

13

14. WebPage Snapshot

  • HomePage

15

  • Autocomplete

14

  • Main Search Page

16

  • Web Search Page

17

  • News Search Page

18

  • Images Search Page

19

  • Notification: In case of communication error message and vertical loader is spinning

21

  • Notification: If search button is pressed without any keyword

20

WebAPI: Multiple actions were found that match the request

Standard

If you have two or more web methods and using the “HttpGet” attribute

[HttpGet]
public HttpResponseMessage GetRelatedSearch(HttpRequestMessage request)
{
     return request.CreateResponse(HttpStatusCode.OK); 
}
 
[HttpGet]
public HttpResponseMessage GetWebSearch(HttpRequestMessage request) 
{
     return request.CreateResponse(HttpStatusCode.OK);
}

You will receive error:

2015-11-30_18-44-11

Solution:

Your by-default web api config setting would be like below in WebApiConfig.cs file under App_Start folder:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });

But in order to have multiple actions with the same http method you need to provide webapi with more information in terms of action name via the route like so:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });

Notice that the routeTemplate now includes an action.

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api