1st Place Winner of Barama HackDay


1457765890_dA few weeks ago Azercell’s Barama Innovation Center announced 36 hours hackathon which is took place on 10 March 2016. I as a team leader with my two teammates from work decided to team up and participate. 12 March was the first day of the competition and they announced that the topic of the hackathon is “Food Industry”. After 36 hours non-stop codding we came up with idea of data analyzing and statistics of food sector. The project analyzes the data that either imported from JSON ,XML etc. files or directly API transactions. Afterwards analyzing the data it shows detailed graphs and statistics which might be useful for market researches.Besides that the project enables user to send Email/SMS to exact target who are interested in particular products, as we know we receive many unwanted notification from different advertising companies on daily basis so we solved the problem (or we think we are) mentioned above and won 1st place.
After all, solving some problems feels good.

Set up Git and initial commit to remote repository


As software developers, often we tend to work on local machine and upload a project when we’re done. This case is fine when the only developer who works on project is you and the changes are small.However when you are dealing with large project with more than one person , you will need to store source code and share it between developers in order to work on the same project.This case lead us to use version control software. The basic concept of version control is :

  • Check out the project from the repository
  • Make changes
  • Check in/commit/submit changes to the repository

Let’s start by downloading version control software (Git) to our machine. You can download it from http://git-scm.com/ and as a Git solution i’m going to use BitBucket, you can use GitHub or other services, the explanation above applies most of them.

Since i use Windows, after installing Git in the right click appears Git Bash Here and Git GUI Here options, do right click the folder that you want to Git to use and select Git Bash Here and it’ll automatically open console from that directory.

First thing you have to do is assign the folder as local git folder in order to do so run code below

git init # assigning the folder as local repository
git remote add origin https://UserName@bitbucket.org/UserName/RepositoryName.git # adding remote git URL

Now you almost done.The URL above in the code is remote URL of git repository.You can get it by simple creating repository on BitBucket.

As we don’t have any other branch except master which is default ,if you want to create new branch just run

git branch BranchName # will create branch

and to switch new branch

git checkout BranchName

checking which branch you are currently using and which files are not tracking or need to be commit

get status

So far we create local repository and branch and added new remote one.Time to commit some codes/files, since i have an existing project i’ll push the project to server.Before pushing our code optionally we can set our user name and email to git.

blog
as i mentioned above i have already project that i want to push if i run get status Git will show me that the folder that my project located is not tracking therefore we need to add project folder to tracking system of Git by doing

get add .
After add, . (period) indicates including whole files and folders.Now we can push our project.
It will ask your password which is you set when you registered on Git repository service. 
blog1

In case you want to fetch a project from repository into your local use
git pull origin/master

Those are basic concept of Git,there are a lot more than this so go ahead and check documentation https://git-scm.com/doc

Happy coding!

Entity Framework – NotMapped Attribute


If you include a property in the model,EF will attempt to read/write value from/to the database. In case if we want to exclude a property from the model,we just have to set it without a getter or setter.However there is another convenient/right way to do so by using Data Annotations attribute [NotMapped] which is located in System.ComponentModel.DataAnnotations

public class Company
{
   public int CompanyId { get; set; }
   public string CompanyName{ get; set; } 

   [NotMapped]
   public DateTime EstablishedDate { get; set; }
}

Another approach is to use Fluent API as shown below

class ExampleContext : DbContext
    {
        public DbSet<Company> Companies{ get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Company>()
                // here we ignore EstablishedDate from creating
.Ignore(b => b.EstablishedDate);
        }
}

Javascript file is not updating


settingsRecently i wanted to change my JS code and updated it however in development mode the code didn’t work because of the caching. As we know, most of the browsers are caching js/css etc. files in order to reduce load times of pages so when you update your code you have to clear browsing data.
To avoid this we can disable caching in `development mode`, in Chrome as well as Opera has option to disable it.Particularly in Chorme,while in DevTools (you can open it by doing Ctrl+Shift+I), the second of option in the Settings (F1) is Disable cache (while DevTools is open).

[ASP.NET MVC] The ForeignKeyAttribute on property is not valid


You might encounter the error (below) when working on ASP.NET MVC project stating that :

The ForeignKeyAttribute on property 'EmployeeId' on type 'EmployeeSalary' 
is not valid. The navigation property 'Employee' was not found on the dependent 
type 'EmployeeSalary'. The Name value should be a valid navigation property name.

This error occurred when you trying to set ForeignKey attribute without indicating navigate
property name.

Here our EmployeeSalary table :
public partial class EmployeeSalary 
 {
 [Key]
 public int id { get; set; }
 [ForeignKey("Employee")]
 public int EmployeeId { get; set; }
 public decimal Salary{ get; set; }
 }

As you might have already seen we didn’t assign navigate property name,therefore,the error above occurred.In order to solve this problem we should just add property as this:

public virtual Employee Employee { get; set; }

ASP.NET MVC Telerik Grid – file upload on popup mode


Supposing that you need to upload file(s) on popup mode of kendo grid.If your table has relationship with another table then you might want to assign id or whatsoever.
Firstly, let’s create our grid and some JavaScript codes.

@(Html.Kendo().Grid<ModelName>()
      .Name("grid")
      .Columns(columns =>
      {
        columns.Bound(c => c.ColumnName);
        columns.Bound(c => c.ColumnName2);
        // ...
        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(180);
      })
      .ToolBar(toolbar => {
            toolbar.Create();
            toolbar.Excel();
      }) 

// AddContractDialog is our template for popup editing mode.
      .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("AddContractDialog"))
      .Scrollable()
      .DataSource(dataSource => dataSource
          .Ajax()
          .Model(model => model.Id(p => p.idSome))
          .Read(read => read.Action("Grid_Read", "ControllerName"))
              .Create(create => create.Action("Grid_Create", "ControllerName").Data("additionalDetail"))
          .Update(update => update.Action("Grid_Update", "ControllerName"))
          .Destroy(destroy => destroy.Action("Grid_Destroy", "ControllerName"))
      )
        )
<script>
    function additionalDetail() {
        return {
            filename: window.UploadedFile
        }
    }
</script>
<script>
   var UploadedFile;
    function onSuccess(e) {
        UploadedFile = e.response.fileName;
    }
</script>

What I did is add UploadedFile value that will pass the detail that comes from Success event of upload widget.By defining additionalDetail, we’ll pass our file name to grid’s create event.
Here is our kendo upload widget
(AddContractDialog.cshtml)

    @(Html.Kendo().Upload()
    .Name("attachments")
    .Async(async => async
        .Save("Save", "ControllerName")
    )
            .Events(c => c
                .Success("onSuccess")
            )
    )

For saving uploaded file and pass file name (in my case,you can pass whatever detail you want) to the Success event.

   public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
        {
            string attachmentName = null;
           
            if (attachments != null)
            {
                foreach (var file in attachments)
                {
                    attachmentName = Path.GetFileName(file.FileName);
// Don't forget create CategoryImage folder.
                    var physicalPath = Path.Combine(Server.MapPath("~/CategoryImage/"), attachmentName );

                     file.SaveAs(physicalPath);
                }
            }

            // Return file name string to success event
          return Json(new { fileName = attachmentName }, "text/plain");
        }

and in Grid’s create event we add some extra parameter to get our file name.
Contract is just an example model

 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Grid_Create([DataSourceRequest]DataSourceRequest request, Contract contract, string filename)
        {

Now you will receive your file’s name as parameter in the Grid_Create (as filename).

Resources:
http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/upload/metadata#receiving-metadata-from-the-save-handler
http://www.telerik.com/forums/grid-with-upload-in-custom-editor-template-popup#KXXGIwt6bUmZQHwFPjlojw

Load and Save ASP.NET MVC Settings


We have been using Settings both in WPF and WinForm.You might need to use Settings on your ASP.NET MVC application as well.Contrary to others, in MVC we should use web.config file to save and load our setting values.About security measures, if you are going to use web.config to save your password or other sensitive data,you need to encrypt them.

Firstly, we should add our value to the web.config file :

    <add key="returnEmployee" value="true">

to load our setting you should call OpenWebConfiguration method which is belongs WebConfigurationManager class.

 var mySetting = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~\\Views");
 var mySettingValue = mySetting.AppSettings.Settings["returnEmployee"].Value;

Keep in mind that “~\\Views” is a path of your web.config file.For saving your setting you just need to set some data to your setting and call Save() method as shown below.

  var mySetting = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~\\Views");
    mySetting.AppSettings.Settings["returnEmployee"].Value = "someValue";
    mySetting.Save();
Follow

Get every new post delivered to your Inbox.

Join 123 other followers