News

 

Suppose that you have a interface in your project

  1:  namespace Configuration.Logger
2: {
3: public interface ILogger
4: {
5: void Write();
6: }
7: }


and a few his implementations.

  1:      public class FileLogger : ILogger
2: {
3: public void Write()
4: {
5: Console.WriteLine("Writing to file");
6: }
7: }
8:
9: public class DatabaseLogger : ILogger
10: {
11: public void Write()
12: {
13: Console.WriteLine("Writing to the database");
14: }
15: }


Depending on the situation, you want use first of them, another time the second. But how (and where) change it? The simplest possibility is to change it in the source code, but this is associated with recompilation of the entire project. So what else we can do?

The .NET Framework comes to us with a System.Configuration namespace which is responsible for working with the configuration files (Machine.config, Web.config, App.config). Now I think, the answer is simple – create and work with own config file. Thanks to him we can change the concrete implementation of the interface without recompilation the entire project.

So let’s create one.

  1:  <?xml version="1.0" encoding="utf-8" ?>
2: <configuration>
3: <configSections>
4: <section name="loggerMappingsConfiguration"
5:
type="Configuration.Configuration.LoggerSettings,
6: Configuration,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"
/>
7: </configSections>
8: <loggerMappingsConfiguration>
9: <loggerMappings>
10: <loggerMapping interfaceShortTypeName="ILogger"
11:
concreteFullTypeName="Configuration.Logger.DatabaseLogger,
12: Configuration,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"
/>
13: </loggerMappings>
14: </loggerMappingsConfiguration>
15: </configuration>


This is a simple App.config with one section only. As I mentioned earlier, System.Configuration provides classes to work with it. What we have to do is inherit from them and create a new for this example. We need to create a three classes derived from :


The forth class this will be a helper class contains a string values for configuration element. Let’s start from her.

  1:      internal static class LoggerMappingConstants
2: {
3: public const string ConfigurationPropertyName = "loggerMappings";
4: public const string ConfigurationElementName = "loggerMapping";
5: public const string InterfaceShortTypeNameAttributeName = "interfaceShortTypeName";
6: public const string ConcreteFullTypeNameAttributeName = "concreteFullTypeName";
7: public const string LoggerMappingsConfigurationSectionName = "loggerMappingsConfiguration";
8: }


These values are used in other classes several times, so create a static class with them is a good idea. Class derived from ConfigurationElement is show below

  1:      public sealed class LoggerMappingElement : ConfigurationElement
2: {
3: [ConfigurationProperty(LoggerMappingConstants.InterfaceShortTypeNameAttributeName,
4: IsKey = true, IsRequired = true)]
5: public string InterfaceShortTypeName
6: {
7: get
8: {
9: return (string)this[
10: LoggerMappingConstants.InterfaceShortTypeNameAttributeName];
11: }
12: set
13: {
14: this[LoggerMappingConstants.InterfaceShortTypeNameAttributeName] = value;
15: }
16: }
17:
18: [ConfigurationProperty(LoggerMappingConstants.ConcreteFullTypeNameAttributeName,
19: IsRequired = true)]
20: public string ConcreteFullTypeName
21: {
22: get
23: {
24: return (string)this[LoggerMappingConstants.ConcreteFullTypeNameAttributeName];
25: }
26: set
27: {
28: this[LoggerMappingConstants.ConcreteFullTypeNameAttributeName] = value;
29: }
30: }
31: }


Contain a two methods mapping to the appropriate properties from config file. Class derived from ConfigurationElementCollection

  1:      public sealed class LoggerMappingCollection : ConfigurationElementCollection
2: {
3:
4: protected override ConfigurationElement CreateNewElement()
5: {
6: return new LoggerMappingElement();
7: }
8:
9: protected override object GetElementKey(ConfigurationElement element)
10: {
11: return ((LoggerMappingElement)element).InterfaceShortTypeName;
12: }
13:
14: public override ConfigurationElementCollectionType CollectionType
15: {
16: get
17: {
18: return ConfigurationElementCollectionType.BasicMap;
19: }
20: }
21:
22: protected override string ElementName
23: {
24: get
25: {
26: return LoggerMappingConstants.ConfigurationElementName;
27: }
28: }
29:
30: public new LoggerMappingElement this[string interfaceShortTypeName]
31: {
32: get
33: {
34: return
35:
(LoggerMappingElement)this.BaseGet(interfaceShortTypeName);
36: }
37: }
38: }
39:


And the last class:

  1:  public class LoggerSettings : ConfigurationSection
2: {
3: [ConfigurationProperty(LoggerMappingConstants.ConfigurationPropertyName,
4: IsDefaultCollection = true)]
5: public LoggerMappingCollection LoggerMappings
6: {
7: get
8: {
9: return
10:
(LoggerMappingCollection)base[LoggerMappingConstants.ConfigurationPropertyName];
11: }
12: }
13: }


To test these classes, we can build a factory that will create objects depending on the settings in the configuration file

  1:  public static class LoggerFactory
2: {
3: public static ILogger CreateLogger()
4: {
5: ILogger logger;
6: string interfaceShortName = typeof(ILogger).Name;
7:
8: LoggerSettings settings = (LoggerSettings)ConfigurationManager.GetSection(
9: LoggerMappingConstants.LoggerMappingsConfigurationSectionName);
10:
11: logger = Activator.CreateInstance(
12: Type.GetType(settings.LoggerMappings[interfaceShortName]
13: .ConcreteFullTypeName)) as ILogger;
14:
15: return logger;
16: }
17: }


And finally check the result

  1:  class Program
2: {
3: static void Main(string[] args)
4: {
5: ILogger logger = new DatabaseLogger();
6: ILogger loggerFromFactory = LoggerFactory.CreateLogger();
7:
8: Debug.Assert(loggerFromFactory.GetType() == logger.GetType());
9: }
10: }


Source code is available here (click the blue button called "Pobierz plik").



 

Wrzuta.pl, this is a polish site similar to youtube. It allows to watch movies and listen to music, but does not allow direct downloading them to disk. In this post I would like to show how to achieve that using Ext JS and MVC.

Create a new ASP.NET MVC project and add there a Ext JS library. I have written here how to do that.

First step is create a form where user can paste the url.


Ext.onReady(function()
{
    Ext.QuickTips.init();
    var form = new Ext.form.FormPanel({
        frame: true,
        renderTo: 'form',
        width: 380,
        title: 'Insert a link',
        items: [{
            xtype: 'textfield',
            allowBlank: false,
            anchor: '100%',
            vtype: 'LinkValidate', //(1)
            hideLabel: true,
            name: 'link'
}],
            buttons: [{
                text: 'Download',
                handler: function()
                {
                    }
}]
            });



This is a simple form with only one TextField, where user can insert a specified link and one button for submitting the form to the server. This field has a custom validation (1):


            Ext.form.VTypes['LinkValidateVal'] = /^http:\/\/([A-Za-z0-9\.-]+)\.wrzuta\.pl\/([A-Za-z0-9\._\/-]+)$/;
            Ext.form.VTypes['LinkValidateText'] = 'Invalid link';
            Ext.form.VTypes['LinkValidate'] = function(arg)
            {
                return Ext.form.VTypes['LinkValidateVal'].test(arg);
            }


This validation check if the inserted link corresponds to the pattern of url for wrzuta.pl.
About custom validation I have written here.


Second step is create a controller with a Download action where the inserted link is converted to the absolute path to the file for download

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Download()
        {
            string link = Request.Form["link"];
            string login, file_key;
            string retString = "{success: false, error: \"Error. Probably the link is broken.\"}";
            if (!String.IsNullOrEmpty(link))
            {
                Regex re = new Regex(@"^http://([A-Za-z0-9-]+)\.wrzuta\.pl/(audio|film)/([A-Za-z0-9]+)/([A-Za-z0-9\._-]+)$");
                Match match = re.Match(link);
                login = match.Groups[1].Value;
                file_key = match.Groups[3].Value;

                if (!String.IsNullOrEmpty(login) && !String.IsNullOrEmpty(file_key))
                {

                    link = "http://" + login + ".wrzuta.pl/sr/f/" + file_key;

                    retString = "{success:true, url:\"" + link + "\"}";

                    return Content(retString);
                }
            }

            return Content(retString);
        }


ASP.NET MVC provides a RedirectResult, but Ext needs a response in JSON format, so the ContentResult is used and the redirect to the link is placed in the form handler:

            handler: function()
                {
                    if (form.getForm().isValid())
                    {
                        form.getForm().submit({
                            url: 'Wrzuta/Download',
                            success: function(a, b)
                            {
                                window.location = b.result.url;
                            },
                            failure: function(a, b)
                            {
                                Ext.Msg.alert('Result', b.result.error);
                            }
                        });
                    }
                }


Full source code is available here (click the blue button called "Pobierz plik").



 

  • ASP.NET MVC
  • ASP.NET
  • Ext JS
  • Silverlight
  • VSTO/OPEN XML SDK
  • CSS
  • Windows Communication Foundation
  • Gimp
  • design patterns
  • other

 

This is a part of EXT JS Tutorial

In this article I will cover information about creating, submitting and validating a forms with Ext JS library.
Submitting form to the server will be based on ASP.NET MVC page, so create a new MVC project in Visual Studio and add a EXT JS library into it. How to do it I have written here. So let’s create our first form.

How to create a simple form – first example.

              var form = new Ext.form.FormPanel({ //(1)

                    renderTo: Ext.getBody(), //(2)

                    url: 'Home/SubmitForm',

                    frame: true,

                    title: 'Tell me sth about yourself',

                    width: 200,

                    items: [{ //(3)

                        xtype: 'textfield',

                        fieldLabel: 'Your name',

                        name: 'name'

                    }, {

                        xtype: 'numberfield',

                        fieldLabel: 'Age',

                        name: 'age'

              }]

                    });


Listing above shows:

            (1) FormPanel is used to group fields in a single panel. It corresponds to a <form> tag in XHTML. FormPanel takes one argument which is a config object.
            (2) In the config object you can specify the form properties, one by line in this example, but this is not required. You can write all in one line remembers only to separate them with a colon (,). Placing them one after another may improve readability.
            (3) All fields, like html textbox, combobox and other in FormPanel are definied as elements of the items collection. One record for one field. In EXT JS you can create these fields in two ways. Above is presented first. The second looks like:

           var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name'

                });

                var ageNumberField = new Ext.form.NumberField({

                    fieldLabel: 'Age',

                    name: 'age'

                });

 

                var form = new Ext.form.FormPanel({ //(1)

                    renderTo: Ext.getBody(), //(2)

                    url: 'Home/SubmitForm',

                    frame: true,

                    title: 'Tell me sth about yourself',

                    width: 200,

                    items: [ //(3)

                nameTextField,

                ageNumberField

]

                });


In both situations the result looks the same:







Other fields

Except TextField and NumberField we can use:

-radio buttons

 

                    {

                        xtype: 'radio',

                        fieldLabel: 'Sex',

                        name: 'sex',

                        boxLabel: 'male'

                    }, {

                        xtype: 'radio',

                        name: 'sex',

                        hideLabel: false,

                        boxLabel: 'female'

                    }


Important is here to set the name to the same value. Thanks to it, it is possible to check the value in action method on the server.

-checkbox
 

 

                    {

                        xtype: 'checkbox',

                        name: 'siblings',

                        fieldLabel: 'Siblings'

                    }


-combobox

To combobox field are added pairs, with key and the value. The key can be read after submitting the form in the server side code, value this is what user can see in the browser when he selected one from the available options.
EXT provides special store objects, where data can be kept. This feature will be covered in one of the next parts.
At this point look only for below example, which is used to work with combobox field:

                var answers = new Ext.data.SimpleStore({

                    fields: ['id', 'answer'],

                    data: [['1', 'yes'], ['2', 'no']]

                });


and the combo:

                   {

                        xtype: 'combo',

                        store: answers,

                        mode: 'local',

                        fieldLabel: 'available answers',

                        name: 'answer',

                        anchor: '90%',

                        displayField: 'answer',

                        valueField: 'id'

                    }


As you can see, in the combo to the store config option is link the SimpleStore object with handle the data. To the displayField and valueField are assigned fields from used store.




-datefield

 

                    {

                        xtype: 'datefield',

                        name: 'date',

                        fieldLabel: 'Select date',

                        anchor: '90%',

                        disabledDays: [0,6]

                    }
















-timefield

                    {

                        xtype: 'timefield',

                        name: 'time',

                        fieldLabel: 'Time',

                        anchor: '90%'

                    }























-textarea

                    {

                        xtype: 'textarea',

                        name: 'area',

                        fieldLabel: 'Enter some text',

                        anchor: '90%',

                        multiline: true

                    }


Listeners

For each field in documentation you can find a lot of events. This is very easy to listen to them in EXT JS. Look at example of using a invalid event:

                var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name',

                    allowBlank: false,

                    listeners: {

                        invalid: function(field, msg)

                        {

                            Ext.Msg.alert('', msg);

                        }

                    }

                });


In this code, when you leave blank the Name field, the error message you will see in the alert dialog instead of baloon.










Submitting form to the server

In previous paragraph I have showed how to create a form to take data from user. Now I would like to concentrate how to send and use these data in a server side code. To be able to send the data to the server, form must have a button to do that. FormPanel contain similar to the items collection, collection of buttons. Look at this code

               buttons: [{

                    text: 'Save',

                    handler: function()

                    {

                        form.getForm().submit({

                            success: function(a, b)

                            {

                                Ext.Msg.alert('Success', 'ok');

                            },

                            failure: function(a, b)

                            {

                                Ext.Msg.alert('Failure', b.result.error);

                            }

                        });

                    }

                }, {

                    text: 'Reset',

                    handler: function()

                    {

                        form.getForm().reset();

                    }

                 }]


In code below there are created two buttons, one for submit the form and one for reset it. Both have a handler methods. In handler method you can specify, what will be done when the button is pressed. In the Save button there is called the submit method and checked the result .
Before we can submit the form, we must create a action method in the controller class:

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult SubmitForm(FormCollection collection)

        {

            string response = String.Empty;

            //validation here

            try

            {

                string name = collection.GetValue("name").AttemptedValue;

                int age = Convert.ToInt32(Request.Form["age"]);

                response = "{success: true}";

            }

            catch (Exception)

            {

                response = "{success: false, error: \”an error occurred\”}";

            }

            return Content(response);

        }


In this code, in action method the submitted data should be validated if it hasn’t been done in the client code. The next two paragraphs are devoted to client side validation.

Developer can determine in the submit method, if the result is successful or not. Both, success and failure takes two arguments, which determine: the first is the form that requested this action, the second: the response from the server.

Build-in validation

At this point when you click the Save button, everything seems to work fine. However in the fields for name and age you can almost insert whatever you want. That’s true, in the numberfield you can insert only numbers, but these numbers can be negative too. Negative age it isn’t something what we want.












As I mentioned earlier, you can validate these fields on the server, but better way would seem to be validate it from the client side. EXT JS provides the stuff to do it. Suppose that, we would like to have the possibility to insert into the Name field only a alphabetic characters and this field must have a value (can’t be empty). For validation we can use a build-in vtype types. We can distinguish the basics: url, email, alpha and alphanum. These names are so obvious that I don't need to describe them, I think . Ok, it’s time to show how to use them

                var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name',

                    vtype: 'alpha',

                    allowBlank: false

                });


As you can see I added two new lines. Thanks to the first line you can not add anything that is not a sign from the alphabet now. Second defines that, the field can’t be empty. When you try to submit the form without the value in the Name field, you will see an error










The field in underlined and nothing else. You can customize it by adding a new line

            Ext.QuickTips.init();


just under the Ext.onReady function. Using it, when you mouse over the field, you will see a balloon with the message showing what went wrong












To validate an Age field you can use config options, like maxValue, allowNegative, allowDecimals, allowBlank and minValue.

               var ageNumberField = new Ext.form.NumberField({

                    fieldLabel: 'Age',

                    name: 'age',

                    maxValue: 100,

                    allowNegative: false,

                    allowDecimals: false,

                    allowBlank: false,

                    minValue: 10

               });


Custom validation

Using EXT JS you can create your own, custom validation. The build-in vtypes are very limited. For example in the field where user must write his name, there are available only characters from ASCII, or in other words only characters which appear in English alphabet. In this situation I’m not able to put there my name, which contains polish specified characters. Everyone with different locale that English will be have this problem.
To create a custom vtype we need to add it to the vtype definition. Lets see an example. This code allows to use a polish letters in the TextField, additionally the first letter for surname and first for firstname will be capitalized.

                Ext.form.VTypes['ValidNameVal'] = //(1)

                        /^[A-ZLZ][A-ZZLSZa-zaleózzncs\-]+ [A-ZLZ][A-ZZLSZa-zaleózzncs\-]+$/;

                Ext.form.VTypes['ValidNameMask'] = /[A-ZZLSZa-zaleózzncs\- ]/; //(2)

                Ext.form.VTypes['ValidNameText'] = 'Invalid name'; //(3)

                Ext.form.VTypes['ValidName'] = function(arg) //(4)

                {

                    return Ext.form.VTypes['ValidNameVal'].test(arg);

                }


At first glance it may look horrible. Especially because of the used regular expression (regex) if you are not familiar with this syntax. Each vtype definition has a:

            (1) Value – here is the regex to match to the user input
            (2) Mask – here are specified characters, which user can input in the field,
            (3) Text – this is the message with the error description
            (4) The last require element – the function for testing

Below example shows how it look like in the web browser. To use this custom vtype, you must change the definition for TextField from

            var nameTextField = new Ext.form.TextField({

                fieldLabel: 'Your name',

                name: 'name',

                vtype:alpha,

                allowBlank: false

            });


to

               var nameTextField = new Ext.form.TextField({

                    fieldLabel: 'Your name',

                    name: 'name',

                    vtype: 'ValidName',

                    allowBlank: false

                });


Result










As you can see, with polish letters I have no problem any more. If error occur (first letter for my surname is not capitalize) , validation works properly:










Summary

In this part I have covered how to work with forms using the EXT JS library and ASP.NET MVC. I’ve showed how to create, validate and submit them to the server. And at the end the possibility of creating own custom validation. That’s not all what is related to forms in this library. In next parts there will be explained how to create and use them with the layouts, further will be showed how to work with data stores and other.
The source code with above examples is available here (click the blue button called "Pobierz plik").



 

  1. How to hide the tab with sheets in the bottom of the workbook.
  2. How to hide the headings.
  3. How to use a build-in function.
  4. How to send a keybord shortcut to the Excel.
  5. How to merge all cells in the sheet.


1. How to hide the tab with sheets in the bottom of the workbook.

             this.Application.ActiveWindow.DisplayWorkbookTabs = false;

2. How to hide the headings.

             this.Application.ActiveWindow.DisplayHeadings = false;

3. How to use a build-in function.

            Excel.WorksheetFunction func = this.Application.WorksheetFunction;
            string dec2bin = func.Dec2Bin(13, 8);


4. How to send a keybord shortcut to the Excel.

            SendKeys.Send("%cm");
or
             SendKeys.Send("{HELP}");

where

Key

Argument

ALT

 %
 CTRL
 ^

 SHIFT
 +


BACKSPACE


{BACKSPACE}, {BS}, or {BKSP}

BREAK

{BREAK}

CAPS LOCK

{CAPSLOCK}

DEL or DELETE

{DELETE} or {DEL}

DOWN ARROW

{DOWN}

END

{END}

ENTER

{ENTER} or ~

ESC

{ESC}

HELP

{HELP}

HOME

{HOME}

INS or INSERT

{INSERT} or {INS}

LEFT ARROW

{LEFT}

NUM LOCK

{NUMLOCK}

PAGE DOWN

{PGDN}

PAGE UP

{PGUP}

PRINT SCREEN

{PRTSC}

RIGHT ARROW

{RIGHT}

SCROLL LOCK

{SCROLLLOCK}

TAB

{TAB}

UP ARROW

{UP}

F1 throught F16

{F1}through {F16}


5. How to merge all cells in the sheet.

            this.Application.Cells.Select();
            this.Application.Cells.Merge(System.Type.Missing);

 

In this short article I would like to show how to upload an image file to the server using Ext JS library and ASP.NET MVC.



First step is create a new ASP.NET MVC project and add to him the Ext JS library. I have written here how to do it.
We will use a user extension called Ext.ux.form.FileUploadField to upload a file. It is not included in the library, so add to project these files:

       - FileUploadField.js
       - FileUploadField.css

Now let’s add a new form with the fileuploadfield field

        Ext.onReady(function()

        {

            var form = new Ext.FormPanel({

                renderTo: 'fi-form', //(5)

                fileUpload: true, //(1)

                width: 400,

                frame: true,

                title: 'File Upload',

                bodyStyle: 'padding: 10px 10px 0 10px;',

                labelWidth: 50,

                items: [{

                    xtype: 'fileuploadfield',

                    emptyText: 'Select an image',

                    fieldLabel: 'Image',

                    name: 'file', //(2)

                    buttonText: 'Choose a file'

}],

                    buttons: [{

                        text: 'Save',

                        handler: function()

                        {

                            if (form.getForm().isValid())

                            {

                                form.getForm().submit({

                                    url: 'Home/Upload',

                                    waitMsg: 'Uploading your photo...',

                                    success: function(form, o) //(3)

                                    {

                                        Ext.Msg.show({

                                            title: 'Result',

                                            msg: o.result.result,

                                            buttons: Ext.Msg.OK,

                                            icon: Ext.Msg.INFO

                                        });

                                    },

                                    failure: function(form, o) //(4)

                                    {

                                        Ext.Msg.show({

                                            title: 'Result',

                                            msg: o.result.error,

                                            buttons: Ext.Msg.OK,

                                            icon: Ext.Msg.ERROR

                                        });

                                    }

                                });

                            }

                        }

}]

                    });

                });


      (1) As you can see form must have fileUpload property set to true.
      (2) This name we use in our upload action in the controller to take the data from user
      (3), (4) Result from submitting the form to the server. One from success, second from failure.
      (5) Form will be render in the div with specific id. Remember to add this div with id manually in the master page or in view page.

That’s all what is related to Ext JS.

Now in the Home controller (for example) create an Upload action with code like below

       [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Upload()

        {

            string[] supportedTypes = new string[]{

                "png", "gif", "tiff", "bmp", "jpg", "jpeg" //(1)

            };

 

            HttpPostedFileBase postedFile = Request.Files["file"];

            if (postedFile != null) //(2)

            {

                string x = Path.GetExtension(postedFile.FileName);

 

                if (supportedTypes.Contains(x.TrimStart('.'))) //(3)

                {

                    //to do sth with the file

                    return Content("{success:true, result:\"File uploaded correctly\"}"); //(4)

                }

                else //(5)

                {

                    //unsupported file type

                    return Content("{success:false, error:\"Unsupported file type\"}");

                }

            }

 

            return new JsonResult() //(6)

            {

                ContentType = "text/html",

                Data = new { success = false, error = "File uploaded error" }

            };

        }


(1) This uploader form is intended only to upload an image files.
(2) If the file has been posted to the server, check to see if the extension of posted file is in the array of acceptable extensions. If so, return a JSON string from the action (3) with success value set to true, else return with string with success set to false (5).

Notice that, the returned JSON string must have content type set to text/html. We can achieve that using a ContentResult or a JsonResult with ContentType set manually to text/html. If the result won’t be returned as a html, the web browser will want to download a file with this result.

Full source code is available here (click the blue button called 'Pobierz plik').

Summary

In this article I wanted to show how easy is to upload a file with specific extension to the server using Ext and MVC framework. FileUploadField it is only one possibility to upload a file to the server in Ext JS. This add-in can upload only one file at time. If you want to upload multiple files at time, let’s look at the UploadForm in the Ext JS wiki here.