Saturday, 31 December 2011

Left outer join in linq

Let's have a scenario in which there are two tables Teachers and Teacher_Courses .Teachers are assigned courses having teacherid in Teacher_Courses table as the foreign key. So to pick up all the Teacher's list with no of courses assigned regardless of having been assigned a course or not in linq you will be using left outer join as follows.


     using (TeacherContext context = new TeacherContext())
     {
         var Teachers = context.Teachers;
         var TeacherCourse = context.TeacherCourses;
         var q = from c in Teachers
                 join o in TeacherCourse on
                 c.int_TeacherId equals o.int_TeacherId into j
                 from Course in j.DefaultIfEmpty().GroupBy(m=>m.int_TeacherId)                        
                 select new
                 {
                      Teachers = c.vcr_TeacherName,
                      Courses =  Course.Count() == 0 ? "(no Courses Assigned)" :  Course.Where(m => m.int_TeacherId == 
c.int_TeacherId).Count().ToString()
                 };

                 foreach (var item in q.ToList())
                    Console.WriteLine(string.Format("Teacher: {0} No of Courses {1}",item.Teachers, item.Courses));  
     }

Sunday, 20 November 2011

Dotnetnuke Inter-module communication (IMC) simplified on version 06.00.02 with c#

Few days ago I developed a module in which I used IMC which really interested me so I decided to write about it. I will try to explain in this post everything that is necessary to make IMC work in the modules.

What is Inter Module Communication?

As the name implies if you want to communicate or in other words send data from one module to another IMC is one way of doing it.

I will be using module A and module B as the names in my post.

An Observation:

One thing I observed while playing around with it that if module A is on page 1 and module B is on page 2 then the data doesn't get passed. If both the modules are on the same page then only the data get passed.

Example:

The basic exercise that I will be performing is to take input from the textbox in Module A and display it in label in Module B.

1) You will be using IModuleCommunicator and IModuleListener interfaces to make this communication works. You will be implementing IModuleCommunicator in the class in the module you want to send the data from and IModuleListener will be implemented in the class in the module in which you want to receive the data.

2) You can have multiple listeners as well . if this is the case then every listener will act as a receiver for the data the communicator module is sending.

3) You will be using ModuleCommunicationEventArgs class to send the data from communicator module class to the Listener module class.

4) DotNetNuke.Entities.Modules.Communications is the namespace that is used in the process.

Module A (Communicator)  
A.ascx

<asp:TextBox ID="txtdisplay" runat="server"></asp:TextBox>
<asp:Button ID="btnclick" runat="server" Text="Button" OnClick="btnclick_Click" />


A.ascx.cs
   using DotNetNuke;   
   using DotNetNuke.Common.Utilities;
   using DotNetNuke.Entities.Modules;
   using DotNetNuke.Entities.Modules;

   using DotNetNuke.Entities.Modules.Actions;
   using DotNetNuke.Security;
   using DotNetNuke.Services.Exceptions;
   using DotNetNuke.Services.Localization;
   using DotNetNuke.Entities.Modules.Communications;


   partial class A : PortalModuleBase,IModuleCommunicator
   {
    public event ModuleCommunicationEventHandler ModuleCommunication;

    protected void btnclick_Click(object sender, EventArgs e)
    {
       try
       {
          ModuleCommunicationEventArgs MCArgs = new ModuleCommunicationEventArgs();
          MCArgs.Sender = "anyname";
          MCArgs.Target = "anything to send in the target to be used as u wish";
          MCArgs.Text =  txtdisplay.Text;
          MCArgs.Value = txtdisplay.Text;

             if (ModuleCommunication != null)
             {
                  ModuleCommunication(this, MCArgs);
             }
       }
           // other implementation
       catch (Exception exc) //Module failed to load
       {
             Exceptions.ProcessModuleLoadException(this, exc);
       }
    }
   }

Module B (Listener) 
B.ascx
<label id="lbldisplay" runat="server" text="Label"></label>
B.ascx.cs
   using DotNetNuke;
   using DotNetNuke.Common.Utilities;
   using DotNetNuke.Entities.Modules;
   using DotNetNuke.Entities.Modules;

   using DotNetNuke.Entities.Modules.Actions;
   using DotNetNuke.Security;
   using DotNetNuke.Services.Exceptions;
   using DotNetNuke.Services.Localization;
   using DotNetNuke.Entities.Modules.Communications;

   partial class B: PortalModuleBase, IModuleListener
   {
         public void OnModuleCommunication(object s, ModuleCommunicationEventArgs e)
         {
            if (e.Sender == "anyname")
            {
                lbldisplay.Text= (string)e.Value;
            }
          }
           // other implementation
   }

Sunday, 5 June 2011

Jquery form plugin with asp.net mvc flavour

I am a great fan of jquery form plugin which is one of my favorites. It's really simple to integrate Ajax in your web pages with jquery form with very thorough documentation found at the site. Basically it really speed up the things. I had extended some of the examples found in the documentation and had created a small implementation of login in Asp.net mvc. So here how it goes.

Model:

    public class User
    {
       public string UserName { get; set; }
       public string Password { get; set; }        
    }

Controller:

     public ActionResult JqueryFormDemo()
     {
        return View();
     }

     public string Login(User User)
     {
       if(User.UserName=="mazhar" && User.Password=="mazhar")
           return "You are successfully login" ;
       else
           return "Login Failed";
     }


View:

@model MvcApplication5.Models.User

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        var options = {
            target: '#output1',   // target element(s) to be updated with server response 
            beforeSubmit: Validate,  // pre-submit callback 
          
        };
        $('#myForm').ajaxForm(options);

    });

    function Validate() {
        var usernameValue = $('input[name=UserName]').fieldValue();
        var passwordValue = $('input[name=Password]').fieldValue();
        
        if (!usernameValue[0] || !passwordValue[0]) {
            alert("UserName or password cannot be empty");
            return false;
        }
        return true;
    }      
   
</script>

<div id="output1"></div>
@using (Html.BeginForm("Login", "JQueryFormDemo", FormMethod.Post, new { id = "myForm" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)           
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)          
        </div>

        <p>
            <input type="submit" value="Login" />
        </p>
    </fieldset>
}

Monday, 30 May 2011

Asp.net mvc razor render partial view using ajax helper

This is the extension to my blog in which I demonstrated rendering of the partial view using jquery Ajax . I want to demonstrate here yet another way by which partial view can be rendered without page refresh. Here is the implementation.

Step 1:

I will again be using DisplayData class in my demo. Here is it.

  
    public class DisplayData
    {
       public int ID { get; set; }
       public DisplayData(int ID)
       {
              this.ID = ID;
       }
    }

Step 2:

Create a PartialDemo page

@model IEnumerable<MvcApplication5.Models.DisplayData>
@{
    ViewBag.Title = "PartialDemo";
}


@Ajax.ActionLink("Click 1", "PartialDemo", "PartialDemo", new {Data= "1" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" })
@Ajax.ActionLink("Click 2", "PartialDemo", "PartialDemo", new {Data= "2" }, new  AjaxOptions { UpdateTargetId = "rsvpmsg" })

<div id="rsvpmsg">
@{ Html.RenderPartial("PartialDemoUC", this.Model);}
</div>


Step 3:

Create a User Control PartialDemoUC.cshtml

@model IEnumerable<dynamic>

@foreach(var items in Model)
{
   @items.ID    
}


Step 4:

In a PartialDemo controller create an Action method for rendering the partial view on the first call to the method and then on an ajax call(on the click of the link)

  
    public ActionResult PartialDemo(string Data)
    {
       List<DisplayData> Display = new List<DisplayData>();

       if (Request.IsAjaxRequest())
       {
          if (Data == "1")
          {
             Display.Add(new DisplayData(3));
             Display.Add(new DisplayData(4));
          }
          else
          {
            Display.Add(new DisplayData(5));
            Display.Add(new DisplayData(6));
          }
          return PartialView("PartialDemoUC",Display);
       }
       else
       {
           Display.Add(new DisplayData(1));
           Display.Add(new DisplayData(2));
           return View("PartialDemo", Display);
       }
    }

Thursday, 14 April 2011

Asp.net mvc razor render partial view using jquery Ajax

I will going to demonstrate how we can render PartialViews using Jquery Ajax. I will be clicking an a href link ,then I will be calling the controller through jquery Ajax which will fill the partialview for a really nice user experience.

Step 1:

First of all we will be creating an DisplayData class for the use for this example in the model.
    public class DisplayData
    {
       public int ID { get; set; }
       public DisplayData(int ID)
       {
              this.ID = ID;
       }
    }


Step 2:

We will create a Clicks page and write the following code on it. Specially note empty here which will going to empty and then fill partialview with new records.
     $(document).ready(function () {
        $('.msg').click(function () {
            var id = this.id;
            $.ajax({
                url: "/Category/Display",
                data: { data: id },
                success: function (mydata) {
                    $("#link").empty().append(mydata);
                },
                type: "POST"
            });
            return false;
        });
    }); 


<a class="msg" href="#" id="1">Click Me</a>
<a class="msg" href="#" id="2">AND Click Me</a>
<div id="link">
</div>

Step 3:

Create a User Control ClicksUC for partial rendering
foreach(var items in Model)
{  
    @items.ID  
}

Step 4:

And Finally Create an action methods inside the Category controller for calling the view and then rendering the partialview.

     public ActionResult Clicks()
     {
         return View();
     }
          
     public ActionResult Display(int data)
     {
         List<DisplayData> Display = new List<DisplayData>();
         if (data == 1)
         {
           Display.Add(new DisplayData(3));
           Display.Add(new DisplayData(4));
         }
         else
         {
           Display.Add(new DisplayData(1));
           Display.Add(new DisplayData(2));
         }
          
         return PartialView("ClicksUC", Display);
     }

Sunday, 3 April 2011

Google voice actions for android

While playing with my new android phone I came to know of the voice actions which really interested me, so I decided to share it on my blog. Voice actions let you control your phone by voice commands which is really very cool , for example you can search, send text, do browsing all by voice commands.

My Review: It is not very exact in some of the cases but it is working.

Watch the video for more details

Sunday, 27 March 2011

Asp.net mvc 3 built in json model binding

One of the things in mvc3 that recently caught my eyes is built in json model binding support which I have recently used in my project and want to write about it today. JsonValueProviderFactory Class which do all the stuff regarding json model binding is now built-in in mvc 3 which was not in mvc2. To use it in mvc2 you have to register the JsonValueProviderFactory class in global.asax after referencing Microsoft.Web.Mvc from Mvc Futures Library . Here how the thing goes in mvc3

Model Class

  public class Category
  { 
     public string CategoryName { get; set; }
  }
The Controller
  public ActionResult Create()
  {   
     return View();
  }
   
  [HttpPost]
  public ActionResult Create(Category category )
  {
     string Cat = category.CategoryName; 
     var data = new { message = "ok" };
     return Json(data); 
  }

The View
$(document).ready(function () { 
    $('#save').click(function () {

        var CategoryName = { CategoryName: $('#CategoryName').val() };

        $.ajax({
            url: "/Category/Create",
            data: JSON.stringify(CategoryName),
            contentType: "application/json; charset=utf-8",
            success: function (mydata) {
                $("#message").html(mydata["message"]);
            },         
            type: "POST",
            datatype: "json"
        });
        return false;
    });
}); 

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
@Html.EditorFor(model => model.CategoryName) @Html.ValidationMessageFor(model => model.CategoryName)
}

For Model binding to work in Mvc2 Add JsonValueProviderFactory
in Global.asax after referencing Microsoft.Web.Mvc
   protected void Application_Start() 
   {
     RegisterRoutes(RouteTable.Routes);
     ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
   }

Thursday, 24 March 2011

My Asp.net mvc,Asp.net, linq and jquery Faqs

Here I want to make the list of every thing about Asp.mvc, linq and jquery I have been involved in or I can get my hands on or find very interesting. The list will keep on growing over time.

How to get the current Route Id in the view from Url?

<%=Url.RequestContext.RouteData.Values["id"] %> 

What is difference between Html.Partial and Html.RenderPartial?

Good complete answer here.

What is Mvc Futures Library?

Please refer here for the answer.
http://stackoverflow.com/questions/2734316/asp-net-mvc-futures-refresh-for-mvc2.

What is TempData?

Answer here

What is Difference between ViewData and ViewBag?

See here And here

Many to Many Relationship in linq to sql ?

http://geekswithblogs.net/WinAZ/archive/2010/01/09/simplified-many-to-many-relationships-with-linq-to-sql.aspx
http://www.codeproject.com/KB/linq/linq-to-sql-many-to-many.aspx
http://www.iaingalloway.com/many-to-many-relationships-in-linq-to-sql-part-2

How to catch error in Jquery's load ?
To Invoke It: Call throw new Exception() from controller's catch
 
var ph = $("#Cat");
            ph.load("/Categories/Index", function (responseText, textStatus, req) {
                if (textStatus == "error") {
                    window.location = "../User/Logon";
                }
                else {
                alert(textstatus);
                }
            });

 
How to Create comma seperated string using linq?
 var Tags = _db.TagPosts.Where(m => m.bint_PostId == id);
 return string.Join(",", (from p in Tags select p.Tag.vcr_TagName)); 

Linq to sql case insensitive string matching?

if (string.Equals(string1,string2,StringComparison.OrdinalIgnoreCase)) 
{ 
}


Exporting Gridview DataSet to Excel


http://stackoverflow.com/questions/5621577/export-from-sql-server-to-excel-file-using-asp-net-and-vb-net

Get the text and value of the selected item of dropdown in jquery
alert($("#selectlist option:selected").text());
alert($("#selectlist option:selected").val());

Find out If a particular element exists in jquery
if ($("#row-" + exist).length) {

  }

Tuesday, 22 February 2011

Asp.net mvc having multiselect with the listbox

Populate the Listbox with MultiSelect.
Controller:
  public ActionResult Create()
  { 
     var Degree=DegreeRepository.GetAllDegree();      
     ViewData["Degree"] = new MultiSelectList(Degree, "DegreeId", "DegreeName");
     return View(); 
  }

Here I want to mention if you want the single selection for the Listbox you can use SelectList as I mentioned here

View
<%: Html.ListBoxFor(model => model.DegreeId, ViewData["Degree"] as MultiSelectList) %>  

Population and then selection of item in the dropdownList. 

Controller:

  public ActionResult Edit(int id)
  {       
     var Users=UserRepository.GetUser(id);    
     var Degree=DegreeRepository.GetAllDegree();   
     ViewData["Degree"] = new SectList(Degree,"DegreeId","DegreeName",Users.DegreeId);
     return View();
  }


View:

<%: Html.DropDownListFor(model => model.DegreeId, ViewData["Degree"]) %>

Asp.net mvc Dropdownlist population and selection

Populate the dropdownList.

Controller

     public ActionResult Create()
     {       
        var Degree=DegreeRepository.GetAllDegree();
        ViewData["Degree"] = new SelectList(Degree, "DegreeId", "DegreeName");
        return View();
     }

View

<%: Html.DropDownListFor(model => model.DegreeId, ViewData["Degree"]%>

Population and then selection of item in the dropdownList.

Controller

   public ActionResult Edit(int id)
   {       
     var User=UserRepository.GetUser(id);  // Get Single User
     var Degree=DegreeRepository.GetAllDegree();   // Get All Degrees
     ViewData["Degree"] = new selectList(Degree,"DegreeId",DegreeName",User.DegreeId);  
     return View();
   }

View
<%: Html.DropDownListFor(model => model.DegreeId, ViewData["Degree"]  %>

Friday, 11 February 2011

Asp.net mvc c# changing the dateformat

There are times when you need to change the datetime format of the default date generated by System.DateTime.Now to some other.

Here how you can do it
string datetFormat = "dd-MMMM-yyyy hh:mm";
string date = Convert.ToDateTime(datetime).ToString(datetFormat);
It will generate 11-February-2011 06:13

Wednesday, 9 February 2011

How to use Asp.net mvc JavaScriptResult practically

I am usually very excited about knowing something that can make my life easy and JavaScriptResult is one of that thing. It is used to execute JavaScript code immediately on the client sent from the server. Here is the small code snippet for its implementation.

View: 
<%: Ajax.ActionLink("display", "Display", new AjaxOptions()) %>
<%: Html.TextBox("name","mazhar") %>
<%: Ajax.ActionLink("checks", "Checks", new AjaxOptions()) %> 

Controller:
  public ActionResult Display()
  {        
    var  script = "$('#message').append('Display');";
    return JavaScript(script);
  }

  public ActionResult Checks()
  {        
    string script = "var textboxvalue=$('#name').val();";
    script += "$('#message').append(textboxvalue);";
    return JavaScript(script);
  } 

Output:

1) Clicking on the first link will display Display in the message div.
2) Clicking on the second link will display mazhar in the message div.

It's usage in the light of Asp.net Mvc:

Asp.net mvc is the design pattern which is all about separation of concern . It has the model, view and controller. Each doing it part and not intermingling with each other directly. My Advice would be to not use it but this thing is present if it become necessary.