Category: MVC 4

MVC Export List of objects to Excel-Word-PDF-CSV-HTML-XML–Razor style

This is the second part of the demo of the Exporter  in action  – this time in MVC .

It is a little more complicated, because you need to show to the exporter the full path where to put the generated file

string filePathExport = Server.MapPath(“~/exports/a” + ExportBase.GetFileExtension((ExportToFormat)id));

All others are the same easy stuff  -add Nuget package and export in 3 lines – and all action code is 6 lines long:

            List<Electronics> list = Electronics.GetData();
            ExportList<Electronics> exp = new ExportList<Electronics>();
            exp.PathTemplateFolder = Server.MapPath("~/ExportTemplates/electronics");
            string filePathExport = Server.MapPath("~/exports/a" + ExportBase.GetFileExtension((ExportToFormat)id));
            exp.ExportTo(list, (ExportToFormat)id, filePathExport);
            return this.File(filePathExport, "application/octet-stream", System.IO.Path.GetFileName(filePathExport));

 

 

 

 

GitHub Demo at https://github.com/ignatandrei/Export_Word_Excel_PDF_CSV_HTML

The Nuget package is at http://www.nuget.org/packages/Exporter/

YouTube demo at http://youtu.be/DHNRV9hzG_Y

Same object edited by 2 users–proactively notifying users

This is a practical example about how two users that comes on the same page will be notified one about other( after an idea of Adrian Petcu) . See the picture :

image

With the NuGet package you can install in your application in this steps:

To run :
1. install package from Nuget
2. in Filter.Config add following line:  filters.Add(new SameIdAlert.SameIdFilter());
3. In Route.Config, after
routes.MapHubs();
GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator) ,() => new SameIdAlert.SameIdAssemblyLocator());
4. In the View that you want the user to be notified add the following lines in the @section scripts{
<!–Script references. –>
<!–The jQuery library is required and is referenced by default in _Layout.cshtml. –>
<!–Reference the SignalR library. –>
<script src=”~/Scripts/jquery.signalR-1.1.3.js”></script>  <!–or whatever signalr library version you have –>
<!–Reference the autogenerated SignalR hub script. –>
<script src=”~/signalr/hubs”></script>
<!–SignalR script to update the chat page and send messages.–>

and somewhere:

@{Html.RenderPartial(“SameId”);}

5. In _Layout  move jquery declaration
@Scripts.Render(“~/bundles/jquery”)

before RenderBody

6. If you decide to put into _Layout and you want to skip an action, please put  [SameIdSkipAttribute] to the action

7. If you want more action parameters than the default id , just put
[SameIdAttribute(“parameter name 1″,”parameter name2”)
to the action
8. If you decide that you want just several actions then modify
filters.Add(new SameIdAlert.SameIdFilter(false));
and put
[SameIdAttribute]
View online at http://SameId.apphb.com

Source code at https://github.com/ignatandrei/SameId

NuGet package at https://www.nuget.org/packages/sameid

Video demo at http://youtu.be/wjkoMs98Z8U

If you want to help me, see the issues that can be solved here:https://github.com/ignatandrei/SameId/issues

MVC , JsonResult , DateTime and TimeZone

The jsonresult of date time is serializing to the string /Date and some integer value starting with 1970 . The problem is that the browser interprets this value accordingly to the LOCAL TimeZone – and thus the same date is going to be interpreted with a difference.

I was thinking that I can adjust from UTC time offset of the server( obtained with .NET from TimeZoneInfo.Local.BaseUtcOffset.TotalMinutes) and the UTC time offset of the client( obtained with (new Date()).getTimezoneOffset() + UTCServerMinutes; ). Unfortunately, the code does not work for SAMOA ( 13 hours difference).

Pay attention that the server is sending SAME data – just the browser is interpreting from the local user time zone.

So the solution is to convert the  date to a string ( I have chosed yyyy-MM-ddTHH:mm:ss) and interpret in javascript( see date2 below).

The server code – I have put my birthdate 16 april 1970

DateTime res = new DateTime(1970, 04, 16, 22, 0, 0);
[HttpPost]
        public JsonResult GetDateBirth()
        {

            var str = res.ToString("s");
            return Json(new { date =res, datestring=str, ok = true });

        }

The Javascript code:

function GetJsonDate() {
        $.ajax({
            type: "POST",
            url: '@Url.Action("GetDateBirth")',
            datatype: "JSON",
            contentType: "application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok) {
                    window.alert('The server is sending:' + returndata.date + " -- " + returndata.datestring);
                    var d = parseInt(returndata.date.substr(6));
                    var date1 = new Date(d);
                    var date2 = dateFromSortable(returndata.datestring);
                    var date3= getDateString(returndata.date);
                    window.alert('original: ' + date1  + '\r\n'  + ' iso correct:'+ date2 + '\r\n'+ ' utc difference not good:' + date3);

                }
                else {
                    //this is an error from the server
                    window.alert(' error : ' + returndata.message);
                }

            }
        }
        );
    }
    function dateFromSortable(dateStr) {
        var parts = dateStr.match(/\d+/g);
        return new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
    }
    
    function getDateString(jsonDate) {
        //does not work correctly for SAMOA - it have some hours difference
        var UTCServerMinutes = @serverMinutes;
        if (jsonDate == undefined) {
            return "";
        }
        var utcTime = parseInt(jsonDate.substr(6));

        var dateUtc = new Date(utcTime);

        var minutesOffset = (new Date()).getTimezoneOffset() + UTCServerMinutes;

        var milliseconds = minutesOffset * 60000;
        var d = new Date(dateUtc.getTime() + milliseconds)
        return d;
    }

How to test it:

Run the project. Click “Get Json Date” – and you will see the three dates equal.

image

Now change the time zone to Samoa ( or other, if you live in Samoa Winking smile)

image

Click again on “Get Json Date”  – the date will  same 16 april 1970 just for the date2  – obtained from dateFromSortable javascript function.

image

Please note that the local time zone is NOT affecting the values transmitted via ViewBag/ViewData/Model, but just the ones transmitted via Json.

The project can be downloaded from here

MVC and auto persisting values

When you have a textbox in HTML (let’s say

<input name=”FirstName” type=”text” />

)
And it binds to “FirstName” Property of a Model, and in HttpPost Action you do modify the value and return the same view, the value shown in the textbox is the posted one, not the modified one. ( The first thought is that HttpPost is not executing – but it is a false impression!)
The solution is:
ModelState.Remove(“FirstName”)

or, better

http://lennybacon.com/2010/09/07/RemovingPropertiesFromTheModelStateTheTypedWay

(and it’s not a bug, it’s a feature: classical example: numeric textbox/ numeric property and user enters “aaa” – the validation error appears and the textbox must have aaa, not 0 or default value for the property )

Clearer MVC

In every application there are some variables that are set by the ASP.NET  application(  ASP.NET_SessionId  cookie ) and some that are set by the programmer( cached data in Application/Session/Cache/Cookies and so on).

I wanted every time to have a page where I can “clear” / delete those – and not found. So it’s the Clearer project.

It consists of :

  1. ClearerController with 2 Actions:   Index and DeleteItem
  2. 2 Views : Index.cshtml and EditAppData.cshtml
  3. Different Models:
    • SourceData  – enum  – can be  :  None ,        Application ,        Cache ,        Session ,        Cookies
    • AppData –  maintains Key/Value and SourceData pairs
    • ListAppData – loads data from Application , Cache , Session , Cookies  – and deletes.

To make an example, I have put in the Application_Start and Session_Start different values. So the screen is the following:

image

What I learn from the code:

  1. The Cookies, Applications, Session , Cache items can be easily converted to an DictionaryEntry and the code can be like this:
     DictionaryEntry de = new DictionaryEntry(item, sess[item.ToString()]);
     AddNew(de, SourceData.Session);
    
  2. Code must be error prone – what if some item in Session is null ? So , if I have the Key, all is good:
    private void AddNew(DictionaryEntry de, SourceData sd)
            {
                AppData ap = new AppData() { source = sd, Key = de.Key.ToString() };
                try
                {
                    var obj = de.Value;
                    ap.Value = (obj == null) ? Null : obj.ToString();
                }
                catch (Exception ex)
                {
    
                    ap.Value = string.Format(ErrorToString, ex.Message);
                }
                this.Add(ap);
            }
    
  3. The dog-food is good: I have followed my advice from msprogrammer.serviciipeweb… and it works ( used for Remove )
       [HttpPost]
            public JsonResult DeleteItem(string TheKey, int Source)
            {
                try
                {
                    var lad = new ListAppData();
                    lad.DeleteItem(TheKey, (SourceData)Source);
                    return Json(new { ok = true, message = "" });
                }
                catch (Exception ex)
                {
                    return Json(new { ok = false, message = ex.Message });
                }
                
            }
    
  4. When you pass strings in Javascript, there is a simple way to encode: HttpUtility.JavaScriptStringEncode
    <a href="javascript:removeItem('@HttpUtility.JavaScriptStringEncode(Model.Key)','@((int)Model.source)','@id')">Remove</a>
    

Possible uses:

  1. For developers –  when they want to see what happens when a cache item no longer exists
  2. For developers – to put to site admins some simple tool to reload data from Cache/Application . Just edit the LoadAll function to load only Cache/Application Winking smile
  3. For developers  – to test easily the session. Just delete ASP.NET_SessionId  cookie – you will get another one when you refresh the page.

You can view online at http://clearer.apphb.com/Clearer
The project could be found at http://clearer.codeplex.com and have all – source code, downloadable project .

Next week it will be a Nuget item.

For more features , please leave me a comment here or on codeplex at issues
Nuget package at http://nuget.org/packages/Clearer

First version of Messaging system

image

Realized the first version. When you logon on the system, the application sends you an email and you can see it.

Lots of thing done – however, the testing is not complete.

Logging was the difficult part- since I want to work with various loggers( LOG4NET, NLOG, MS TRACE, and so on). I required to a duck typing from  DeftTech. See logging assembly for more details.

You can download the files from http://messagemvc.codeplex.com/– however, you may want to wait for a NuGET version.

If you want to help me further , please send me an email via http://messagemvc.codeplex.com/.

Implementations GUI details

When creating a GUI you must think to give user some good feeling about what the software can do – so I started to MVC 4 website, that have mobile support integrated.

More, you must demonstrate some features right away to the user – so what’s best if not a message from system admin to the user  to “welcome” him ?

For this , I have to  implement a template with RazorEngine – simple to used from his code

string template = "Hello @Model.Name! Welcome to Razor!";
  string result = Razor.Parse(template, new { Name = "World" });

Summary of modifications for this simple operation – send and display a message  from Admin when a user registers

  1. Add connectionstrings to web.config – to connect to database + SiteUtils static class to retrieve it.
  2. RegisterAdmin user in Application_Start – in order to have user Admin in the database ( generate a GUID and put into a const)
  3. Add “welcome.txt” file
  4. Add RazorEngine to parse message
  5. Modify  Register action in order to send message after a user registers
  6. Add an area “Messaging” in order to can have the messaging separated from main site( to be easier to xcopy)
  7. Add an Index action( display read/unread messages) + View
  8. Add an DisplayMessage action (display a message) + View

All for this picture where it shows number of unread messages(1) and list :

image

You will find code at http://messagemvc.codeplex.com/SourceControl/changeset/changes/81924

Homework:

Think about the user actions . He will be interested in the following for existing messages:

  1. Unread messages
  2. View of all messages (paginating)
  3. Search messages:
    • Messages from a date
    • Messages from someone
    • Search

What do you think it will be done for implementing those?

Creating Edmx files and testing

The favorite ORM in .NET world for me it is edmx files. It gives you the database plain – and have generators for POCO (http://blogs.msdn.com/b/adonet/archive/2010/01/25/walkthrough-poco-template-for-the-entity-framework.aspx) as for EF4.1 DBContext(http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx).

I will use this one – because of the new ! But the template is over simplistic  -so I improved . I do not want you to bother you with my experience – I want to say that, after playing with Data attributes – I decide that Fluent Configuration suits all. The template is here:

DBContext-SecondVersion.zip

 

For example, the default template

Also for testing I use the fact the default EF4.1  Model1.Context.tt generates this code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

( see playing on safe side to NOT drop the existing database?!)

Mine Model1.Context.tt generates this:


 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
    		var prefix = System.Configuration.ConfigurationManager.AppSettings["prefixTable"]??"";
    		bool Continue=true;
            OnBeginModelCreating(modelBuilder,prefix, ref Continue);
    		if(!Continue)
    			return;
    
    		//construct default
    		#region smsg_Message 
    		modelBuilder.Entity<smsg_Message>().ToTable(prefix  + "smsg_Message");
    		modelBuilder.Entity<smsg_Message>().HasKey(item => item.IDMessage);
    
    
    		#endregion
    		#region smsg_Message_Archive 
    		modelBuilder.Entity<smsg_Message_Archive>().ToTable(prefix  + "smsg_Message_Archive");
    		modelBuilder.Entity<smsg_Message_Archive>().HasKey(item => item.IDMessageArchive);
    
    
    		#endregion
    		#region smsg_MessageThread 
    		modelBuilder.Entity<smsg_MessageThread>().ToTable(prefix  + "smsg_MessageThread");
    		modelBuilder.Entity<smsg_MessageThread>().HasKey(item => item.IDMessageThread);
    
    		modelBuilder.Entity<smsg_MessageThread>()
                    .HasRequired(item => item.IDMessage_IDMessageInitial)
                    .WithMany(u => u.IDMessage_IDMessageInitial)
                    .HasForeignKey(x => x.IDMessageInitial)
                    .WillCascadeOnDelete(false);
    
    		
    		modelBuilder.Entity<smsg_MessageThread>()
                    .HasRequired(item => item.IDMessage_IDMessageReply)
                    .WithMany(u => u.IDMessage_IDMessageReply)
                    .HasForeignKey(x => x.IDMessageReply)
                    .WillCascadeOnDelete(false);
    
    		
    		modelBuilder.Entity<smsg_MessageThread>()
                    .HasRequired(item => item.IDMessageArchive_IDMessageInitial)
                    .WithMany(u => u.IDMessageArchive_IDMessageInitial)
                    .HasForeignKey(x => x.IDMessageInitial)
                    .WillCascadeOnDelete(false);
    
    		
    		modelBuilder.Entity<smsg_MessageThread>()
                    .HasRequired(item => item.IDMessageArchive_IDMessageReply)
                    .WithMany(u => u.IDMessageArchive_IDMessageReply)
                    .HasForeignKey(x => x.IDMessageReply)
                    .WillCascadeOnDelete(false);
    
    		
    
    		#endregion
    	
    		OnFinishModelCreating(modelBuilder, prefix);
    		
        }

More, for giving you a smell of what the templates generates, look at this function for reading messages sent:


 public  IEnumerable<IUserMessage<IUser<String>,string>> RetrieveMessageSent(DateTime dt)
        {
            using (smsg_Message_List ml = new smsg_Message_List(ConnectionMessaging))
            {
                ml.LoadFromDB.AddToCustomPredicate(smsg_Message_FindDB.fexp_FromUser(this.Key));
                ml.LoadFromDB.AddToCustomPredicate(smsg_Message_FindDB.fexp_DateInsertedBetweenEqDate(dt, dt));
                ml.LoadFromDB.LoadFindCustomPredicate();
                return ml;
            }
        }

The class smsg_Message_List and the AddToCustomPredicate , LoadFindCustomPredicate and the expression fexp_FromUser and fexp_DateInsertedBetweenEqDate are automatically generated by the template.
I do not think that the template is perfect – it just helps me a lot!

For the database tests, I was thinking of NUnit – but was deprecated by xUnit. It has a nice project, named SpecificationExample – and it generates data in BDD style .
For example, this code:


 public void CreateUsersAndSendMessage()
        {
            
            List<SimpleUser> users = null;

            "When create two users".Context(() => users = CreateUsersAndDeleteItFirst());
            "it will be friends".Assert(() => FindFriend(users).ShouldNotBeNull());
            
            "and when send message from first user to second user".Do(() => SendMessage(users));

            
            "we will retrieve it searching message from first user ".Assert(() => RetrieveMessageSent( users[0]).ShouldEqual(1));

            "we will NOT retrieve it searching message from second user".Assert(() => RetrieveMessageSent(users[1]).ShouldEqual(0));

            "we will retrieve searching messages received by second user".Assert(() => RetrieveMessageReceived(users[1]).ShouldEqual(1));

            "we will retrieve count of unread messages :1 ".Assert(() => RetrieveMessageUnreadCount(users[1]).ShouldEqual(1));

            


        }

run by this command:

xunit.console.clr4.x86.exe "$(TargetPath)" /html "$(TargetDir)a.html" 

in Build events it will generate the following HTML


————————————————————————

✔  When create two users and when send message from first user to second user, it will be friends

Output
Before : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage
After : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage

0.060s

✔  When create two users and when send message from first user to second user, we will NOT retrieve it searching message from second user

Output
Before : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage
After : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage

0.099s

✔  When create two users and when send message from first user to second user, we will retrieve count of unread messages :1

Output
Before : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage
After : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage

0.032s

✔  When create two users and when send message from first user to second user, we will retrieve it searching message from first user

Output
Before : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage
After : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage

0.053s

✔  When create two users and when send message from first user to second user, we will retrieve searching messages received by second user

Output
Before : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage
After : testXunit.clsTestUserSendMessage.CreateUsersAndSendMessage

—————————————–


Nice , isn’t it?

Homework :
1. use the ITLIst.tt template , search for

//TODO: prefix

and make generating same prefix for the table as in the Model1.Context.tt( search prefix)
( Do not forget the change the edmx file name in the .tt file!)
2. Make a .t4 file to share commonalities( such as edmx name)

Interfaces and more

 

Summary:

If you want common behavior, you need an interface. And from the first one is a small step to re-organizing the program.

Body:

When you make a component for other people, you must make the possibility for those to

1. customize your software with their software

2. provide a default implementation

For the messaging component, the first customization is to provide a way for the site using the messaging to use their users.

The first step is to create a custom project which can provide guidance to the users that want to implement. VS provides XML documentation –I have checked and put also “warnings as error”

clip_image002

Next , I have create the User interface:

/// <summary>
    /// the user that can send messages
    /// TODO version 2: make pagination
    /// </summary>
    /// <typeparam name="UserPrimaryKey">the type of primary key</typeparam>
    public interface IUser<UserPrimaryKey>
    {
        /// <summary>
        /// the user primary key
        /// </summary>
        UserPrimaryKey Key { get; set; }
        /// <summary>
        /// the user name to be displayed
        /// </summary>
        string UserNameToDisplay { get; set; }
        /// <summary>
        /// other info for the user
        /// </summary>
        string OtherInfo { get; set; }

        /// <summary>
        /// find friends
        /// </summary>
        /// <param name="search">find user by name</param>
        /// <returns></returns>
        IEnumerable<KVPNew<UserPrimaryKey, string>> FindFriends(string search);

        /// <summary>
        /// find friends online
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        IEnumerable<KVPNew<UserPrimaryKey, string>> FindFriendsOnline(string search);

        /// <summary>
        /// sends a message 
        /// </summary>
        /// <param name="message"></param>
        void SendMessage(IUserMessage<IUser<UserPrimaryKey>, UserPrimaryKey> message);

    }
 

Two methods are interesting : SendMessage and FindFriends

Let’s take first SendMessage. It was obviously clear that I need another interface – the message to be sent. So the next interface created:

/// <summary>
    /// the message to be sent to the user
    /// TODO version 2: allow messaging for more than 1 user
    /// TODO version 2: message importance
    /// </summary>
    /// <typeparam name="TheUser">user interface</typeparam>
    ///  /// <typeparam name="UserPrimaryKey">user primary key</typeparam>
    public interface IUserMessage<TheUser, UserPrimaryKey>
        where TheUser : IUser<UserPrimaryKey>
    {
        /// <summary>
        /// subject of the message
        /// </summary>
        string Subject { get; set; }
        /// <summary>
        /// body of the message
        /// </summary>
        string Body { get; set; }
        /// <summary>
        /// to the user
        /// </summary>
        TheUser To { get; set; }
        /// <summary>
        /// from the user
        /// </summary>
        TheUser From { get; set; }
        /// <summary>
        /// cc - as in email
        /// </summary>
        TheUser CC { get; set; }

        /// <summary>
        /// date of message
        /// </summary>
        DateTime DateInserted { get; set; }

        /// <summary>
        /// if recipient have read
        /// </summary>
        bool MessageRead { get; set; }
        // <summary>
        // bcc - as in email
        // </summary>
        //TheUser BCC { get; set; }



    }

Let’s take the other : IEnumerable<KVPNew<UserPrimaryKey, string>> FindFriends(string search);

It is clear that a user can send emails to friends( maybe to anybody if we make an intranet site for an enterprise) and I must somehow have the names and id’s of the friends. I could use KeyValuePair – but it is a struct and can not be compared with null . More, usually I need more data to be transferred – so I have created long ago a KVPNew class:

 /// <summary>
    /// this is the correspondent class of KeyValuePair structure from .net
    /// The features:
    /// 1. it is a class-  can be compared fastly with null
    /// 2. can be used in a search and display <paramref name="AdditionalData">AdditionalData </paramref>
    /// </summary>
    /// <typeparam name="TKEY">Key - it is compared in equals and GetHashCode</typeparam>
    /// <typeparam name="TValue">Value to be displayed</typeparam>
    public class KVPNew<TKEY, TValue>
    {
        public KVPNew() { }
        public KVPNew(TKEY key, TValue value):this()
        {
            this.Key = key;
            this.Value = value;

        }
        public TKEY Key { get; set; }
        public TValue Value { get; set; }
        public string AdditionalData { get; set; }
        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            var o = obj as KVPNew<TKEY, TValue>;
            if (o == null)
                return false;
            return this.Key.Equals(o.Key);

        }
        public override int GetHashCode()
        {
            return this.Key.GetHashCode();
        }
    }

And, being to interfaces, I have created also an interface for admin people to find users

/// <summary>

/// used by application to load plugins to find users

/// because each application can have it’s own way to find users

/// <summary>
    /// used by application to load plugins to find users
    /// because each application can have it's own way to find users
    /// used by admins to find users
    /// Improvement version 2 : pagination 
    /// </summary>
    /// <typeparam name="T">user </typeparam>
    /// <typeparam name="UserKey">user key </typeparam>
    public interface IUsersFind<T,UserKey>
        where T:IUser<UserKey>
    {
        /// <summary>
        /// used to find users online to send message
        /// </summary>
        /// <param name="UserThatMakesTheSearch"> the user that makes the search </param>
        /// <param name="Search">search string - could be null</param>
        /// <returns> a list of users</returns>
        IEnumerable<KVPNew<T, string>> FindUsersOnline(T UserThatMakesTheSearch, string Search);
        /// <summary>
        /// used to find users (online or not )to send message
        /// </summary>
        /// <param name="UserThatMakesTheSearch"> the user that makes the search </param>
        /// <param name="Search">search string - could be null</param>
        /// <returns> a list of users</returns>
        IEnumerable<KVPNew<T, string>> FindUsers(T UserThatMakesTheSearch, string Search);
        /// <summary>
        /// find a user by his key
        /// </summary>
        /// <param name="key">the user key</param>
        /// <returns></returns>
        IUser<UserKey> FindUser(UserKey key);
            
    }


/// <summary>
    /// operations with the database
    /// </summary>
    /// <typeparam name="User"></typeparam>
    /// <typeparam name="UserPrimaryKey"></typeparam>
    public interface IUserList<User, UserPrimaryKey>: IDisposable
        where User : IUser<UserPrimaryKey>
    {
        /// <summary>
        /// fast delete all from database - good for testing
        /// </summary>
        void FastDeleteAll();
        
        /// <summary>
        /// add to internal list
        /// </summary>
        /// <param name="u">the user to be added </param>
        void Add(User u);
         
        /// <summary>
        /// save changes for new and old members
        /// </summary>
        void SaveNew();
        /// <summary>
        /// save changes for old members
        /// </summary>
        void SaveExisting();

        /// <summary>
        /// for retrieving 
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        User Find(int i);
        
    }

The final interfaces are in this picture:

clip_image004

Next time we will create the database EF4.1 files from DatabaseFirst and we will modify .tt templates to behave nicely with relationships.

Homework:

  • Add to IUserMessage a BCC field
  • What if To from IUserMessage will be directed to more than one person ?How do you implement it?
  • Do you think that is something missed from KVPNew class?( Hint == operator and GetHashCode)

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.