Tuesday, August 28, 2012

Simple Javascript Regex

some overview about what JS offer in terms of regex
http://www.javascriptkit.com/javatutors/redev3.shtml
more info about the use of RegExp object
\http://www.w3schools.com/jsref/jsref_obj_regexp.asp
and a simple example i found somewhere for PW check:

$(function () {
   $('#txtNewPW').keyup(function () {
      $('div.errorRegexPw').hide();
      var inputVal = $(this).val();
      var numericReg = /<%= PWRegex %>/;
      if (!numericReg.test(inputVal)) {
          $(this).after('<div class="errorRegexPw">Not A Valid Password.</div>');
      }
   });
});

thing is that to init the RegExp obj u just need to do var regex = /pattern/; with the 2 '/'.
now all u need to do is regex.test(string_to_test) and get true or false like:

var regex = /ariel/;
var t = regex.test("ariel");
var f = regex.test("arik");
here t will be true and f will be false

Monday, August 27, 2012

Pass Complex Data / Class / Form to WebMethod with PageMethods / Ajax

http://encosia.com/using-complex-types-to-make-calling-services-less-complex/
this is how to use JS / JQuery to make an object to JSON and pass it to a webmethod

but id i want to use PageMethods?
it even simpler - just pass the object as is
[WebMethod]
public static void AddPerson2(Person NewPerson)
{
   NewPerson.Add();
}
public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string Zip { get; set; }
  public void Add()
  {     // Magic happens here.
  }
}


Client Side:

var NewPerson = new Object();
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();

PageMethods.AddPerson2(NewPerson , OnPageMethodComplete);

So lets make the most of it, or my original will - post a form in ajax:

function SendDataJson() {
   var myform = document.getElementById("formCreateNewUser");
   var nodes = myform.getElementsByTagName("input");
   var userDetails = {};
   for (var i = 0; i < nodes.length; i++) {
       if (nodes[i].type != 'text') { continue; }
       userDetails[nodes[i].id] = nodes[i].value;
   }
   PageMethods.CreateUserWebMethodFormObject(userDetails, OnCreateComplete);
}



Tuesday, August 21, 2012

JQuery Modal Dialog with Aspx Page Postback example

hi all!
this is kinda the next part of this where i explain how to get a modal with ans aspx page in it
http://bresleveloper.blogspot.co.il/2012/05/jquery-modal-dialog-with-aspx-page.html

now i got into the part where i want to post the the secondary page but guess what? the response it the secondary page so i lose my main page, which is logical cuz the server doesnt keeps track for which page exactly i'm in but rather he gets a request and send the according resposne.

so we cant use postback. nope, Response.End() isnt good either and always the page will be refreshed, u just cant not response the request.

so the Dear God gave MS the wisdom of ajax! sais who that my form must be submitted? i can send an ajax request! here is how to ajax:
http://bresleveloper.blogspot.co.il/2012/04/ajax-3-simle-ways.html

so lets say i have at my main page a big story and if u want to subscribe i open a modal with an apsx page with all kinda stuff, (p.s. the $(func({...}); will work cuz u return a DOM document so there will be all the usual events), lets say for the example i have a string name and int age.

i think that server-side easiest thing would be a webmethod like this:
       
[WebMethod]
public static bool btnSave_Click(string name, int age){...}

now client side i u can choose either JQ or PageMethods, i choose by if i already use JQ on the page, otherwise the 10K of the PageMethods is less than JQ lib's 90K

so now u know what u need to do to post ur data. but the modal doesnt closes!
after experimenting a bit i found that the bets thing in order to post, close the dialog, get the callback and update the main page is a JS object in the main page like that:

function divOpenConversation(){};

divOpenConversation.destroyDialog = function () {
    var conv = $("#divModalForSecondaryPage");
    var name = conv.find("#txtName").val();
    var age = conv.find("#txtAge").val();

    var options = {
       type: "POST",
       url: "Subscribe.aspx/btnSave_Click",
       data: "{ 'name' : '" + nane+ "' , 'age' : " + age+ "' }",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
              if (msg.d == true) {
                 $("#divModalForSecondaryPage").dialog('destroy');
                 $("#divModalForSecondaryPage").html("");

                 PageMethods.GetLastInsertedRow(OnGetLastInsertedRow);
              }
              else {
                 alert(msg.d);
              }
       }
    };
    $.ajax(options);
};

notice i user dialog('destroy') and html('') cuz when i get the html again every time.
you could switch to dialog('close') and get the apsx page once and do dialog('open') and close many times, and i should've done this but i took it from another page where input was needed

anyway the secondary page know the JS obj so i have there this:
$(function () {
    $("#divIbtSave").click(function () {
        divOpenConversation.destroyDialog();
    });
});

what happens is that on the save click the main page JS start working, making the ajax post, and on success destroying the dialog, and making his own ajax to get updated

extra - in GetLastInsertedRow i just save the LAST_INSERT_ID() from our prevois post in session and query by id the new row i need and add it so OnGetLastInsertedRow looks like:

function OnGetLastInsertedRow(result) {
    var r = document.createElement("tr");
    for (var p in result) {
       if (p=="__type") { continue;}
       var td = document.createElement("td");
       td.innerText = result[p];
       r.appendChild(td);
    }
    //dgvConversations
    var tbl = document.getElementById("dgvConversations");
    var tbody = tbl.getElementsByTagName("tbody")[0];
    tbody.appendChild(r);
}

Monday, August 20, 2012

Join and Count from 1 table

what i initally wanted to do is that
SELECT  _users.ID,
        _users.FullName AS 'Name',
        MAX(_users_logins.LastLogin )AS 'Last Login',
        COUNT(_users_companies.Company_ID) AS 'No. of Costumers',
        COUNT(_users_companies.Company_ID) AS 'No. of companies in talk'
but u cant do it with joins purly cuz it will count the result
so my good Chief Moshe tought me this
SELECT _users.ID,
       _users.FullName AS 'Name',
       _LOGINS.LastLogin AS 'Last Login',
       _COMP.costumers AS 'No. of Costumers',
       _TALKS.TALKS AS 'No. of companies in talk'
FROM _users
LEFT JOIN (SELECT MAX( representative_logins.Login_Datetime ) AS LastLogin,
           _users_logins.Rep_ID
           FROM  _users_logins
           GROUP BY Rep_ID) AS REP_LOGINS
    ON _users.ID=REP_LOGINS.Rep_ID
LEFT JOIN (SELECT COUNT(Company_ID) AS costumers ,UserID
           FROM _users_companies
           GROUP BY UserID) AS REP_COMP
    ON REP_COMP.UserID=_users.ID
LEFT JOIN (SELECT COUNT(CompanyID) AS TALKS ,UserID
           FROM conversation
           GROUP BY UserID) AS REP_TALKS
    ON REP_TALKS.UserID=_users.ID
the secret is that since the selects arn't sub-selects but alias tables you dont get into nested selects but instead its like 'select 1, (another query with 1 result), 2' (or someting like that...)

Thursday, August 16, 2012

Passing DataTable with Ajax from C# to JavaScript

answer is - u cant!
but since ASP.NET WebMethod return Json we can do some things
about WebMethods see http://bresleveloper.blogspot.co.il/2012/04/ajax-3-simle-ways.html
the harder and smarter way is to serialize and de-serialize it but thats for next time, this post is for ANYBODY

1st thing 1st: DataRow is not serializeable so any doing with DataTable will be a mess so we create relevant class for them and into a list like that:

[WebMethod]
public static object GetDataTableJson()
{
   DataTable t =  MySqlDb.ExecuteSelect("QUERY");
   return GetList(t);
}

public static List<MyDataRow> GetList(DataTable t)
{
   List<MyDataRow> l = new List<MyDataRow>();
   foreach (DataRow r in t.Rows)
   {
      l.Add(
new MyDataRow()
      {
          DateAndTime = r[
"Date and Time"].ToString(),
          Name = r["Name"].ToString(),
          Comments = r["Comments"].ToString()
      });
   }
   return l;
}

public class MyDataRow
{
   public string DateAndTime { get; set; }
   public string Name { get; set; }
   public string Comments { get; set; }
}

now ur Javascript (with JQ):

$(function () {
   $("#btnTest").click(function () {
      var options = {
         type: "POST",
         url: "tester.aspx/GetDataTableJson",
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
            var d = msg.d;
            var newTable = document.createElement('table');
            var tbody = document.createElement('tbody');
            newTable.appendChild(tbody);

            var r = d[0];
            for (var p in r) {
               var th = document.createElement('th');
               th.innerText = p;
               tbody.appendChild(th);
            }
            for (var i = 0; i < d.length; i++) {
               var tr = document.createElement('tr');
               var r = d[i];
               for (var p in r) {
                  var td = document.createElement('td');
                  td.innerText = r[p];
                  tr.appendChild(td);
               }
               tbody.appendChild(tr);
            }
            $(
"#wrapper").html(newTable);
            $(newTable).addClass("GridStyle");
            newTable.setAttribute("border", "1");
         }
      };
   $.ajax(options);
});