Monday, December 7, 2009
jQuery web service interaction
1. Insert the following into a script tag;
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "wsTestAjax.asmx/HelloWorld",
data: "{}",
datatype: "json",
success: function(msg) {
var message = eval('(' + msg + ')');
$(".lblTestAjax").text(message.d);
}
});
});
2. Have a literal tag as such within the form;
asp:Label ID="lblTestAjax" runat="server" CssClass="lblTestAjax"
3. Create a web service. In this particular case, I've called it wsTestAjax.asmx and within it, I had the basic function of "Hello World". Code as below:-
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//This was the 1 line that I was missing, please don't forget to include the next
//line, if not you'll spend the whole day wondering what happened.
[System.Web.Script.Services.ScriptService]
public class wsTestAjax : System.Web.Services.WebService
{
[WebMethod(EnableSession=true)]
public string HelloWorld()
{
return "Hello World";
}
}
Wednesday, November 4, 2009
Dynamic LINQ
Alright, I shall stop before I get sued for copyright infringements
I was at work today and the boss decided to throw me a challenge. Basically, he wanted to custom-build a SQL query but instead of hitting the database, obtain the data from cache.
I suggested LINQ but as soon as I said that, I had to swallow my words as to my knowledge, LINQ allow filtering but not dynamically.
I trolled the web and discovered that Scott, did blog about this 2 years back. Yes, I know I am 2 years late but better than never, right?
You can find it @ Dynamic LINQ - Part 1
I did a basic LINQ query and use the Where method extension but still to no avail but after some more poking around the web, a break through!
This is how you do it.
1. Download the samples from the Dynamic LINQ url (see above).
2. Extract the Dynamic.cs file from the DynamicLinq directory and include that into your project.
3. In the work-space that you would like to use this powerful class, simply declare the following
IQueryable
select someLinqVar;
var otherLinqVar = linqVar.Where("whr clause with @val", param object[] paramValsArrayObj);
Note: the "val" in @val is of integer type that ties into the object array, paramValsArrayObj.
An example LINQ-WHERE clause will be as follows :-
"Value = @0 && Text = @1"
4. You will also have to include the System.Linq.Dynamic library in the Using clause at the very top of the intended work-space.
Friday, October 30, 2009
Lambda expression
var mainLinqQuery = from someVar1 in someCollection select someVar1;
some while later after typing more lines of code.
var filteredLinqQuery = mainLinqQuery.Where(someVar2 => someVar2.someProperty == itemToFilterBy);
The result of the filtered LINQ query, filteredLinqQuery will be the specific result that we require.
Friday, October 23, 2009
Converting IList to List
After trolling the intertubes, I found the following, tried it out and what do we know; it works!
Step 1
Declare an empty generic list of whatever type you want.
eg: List
Step 2
Use the AddRange method from the generic list class.
eg: object1.AddRange(IList_object);
Wednesday, October 14, 2009
Left Join revisited.
Click here to navigate to the post
As I recently found out, should you attempt to left join 2 complex objects, you MUST instantiate the object of which will be null (the right sequence, object).
A better way to explain this is to provide an example.
C# code
-------
List
List
var linqQuery = from eList in employeeList
join cList in companyList on
eList.CompanyId equals cList.Id
into joinEmpCompany
from jec in joinEmpCompany.DefaultIfEmpty(new Company())
select new
{
// insert whatever values you want here.
}
As you can see above, I instantiate a new Company object as there could be instances where the join will produce null results for the right-hand side (Company object).
Instantiating the Company object when using the DefaultIfEmpty function will allow LINQ to execute and not produce Null Reference errors.
Thursday, October 8, 2009
Access to Modified Closure error
Franc's blog
I realized the error and would like to point out that LINQ doesn't like empty or null values in the WHERE clause. Be careful unless you like to get a generic LINQ error and go bonkers and waste countless hours scratching your head wondering what went wrong.
245 private void DoNothing(List<SomeObject.SomeClass> someList1, List<SomeObject.RoomRateType> someList2)
246 {
247 string rphValue = String.Empty;
248 List<SomeClass> someClassList = new List<SomeClass>();
249 SomeClass someObjectVar = new SomeClass();
250
251 foreach (SomeObject.SomeClass someObjectVar in someList1)
252 {
253 if (someObjectVar.RPHSpecified)
254 {
255 rphValue = someObjectVar.RPH.ToString();
256 var linqQuery = from rrl in someList2
257 where (rrl.RatePlanCode == rphValue) && (rrl.Rates[0].Base.AdditionalFeesExcludedIndicator == true)
258 select rrl.RoomRateDescription.Name;
259
260 foreach (var linqItem in linqQuery)
261 {
262 someObjectVar.MoreDescription += linqItem;
263 }
264
265 someObjectVar.RphCode = someObjectVar.RPH;
266 }
267 }
268 }
the "rphValue" variable can be null or empty and although I know that what I am doing may not cause any trouble, I am sure in some more complex situation, the results will be dire
Wednesday, October 7, 2009
More on MVC
eg: return Redirect("INSERT_URL_HERE");
MVC allows 1 to use the current http context for validation; As a check on whether the user has logged on or not.
25 if (HttpContext.User.Identity.IsAuthenticated)
26 {
27 //View my previous blog @ http://zacthetechie.blogspot.com/2009/10/mvc-with-web-services.html
28 //on how to access a web service from MVC.
29 return View();
30 }
31 else
32 {
33 return RedirectToAction("LogOn", "Account");
34 }
Thursday, October 1, 2009
MVC with web services
Now, my previous experience with MVC Model is with the conventional SQL database interaction using LINQ to retrieve data.
This time, however, I had to interact with web services. Trolling the web resulted in suggestion such as using a REST architecture structure and others which is quite a good read, especially the post by Rob Conery
Rob Conery - ASPNet MVC : Using Restful Architecture
I decided to experiment with using classes instead and it works. Ok, maybe the guys at the Big Blue will knock me down for this but see below for my explaination
This is what I did.
1. I built a web service library, compiled and NUnit tested thoroughly.
2. In the Model of the MVC Application, I added a "Code File". This resulted in an empty C# file being created.
3. From scratch, I built my Web Service Layer (WSL) class (I wonder if you can just add a class from the "Add") with the required properties to interact with the Web Service library.
1 using System.Collections.Generic;
2 using Your_WebService_ObjectName;
3 using Your_WebService_ObjectName.WSCustomObjects.Availibility.Responses;
4 using Your_WebService_ObjectName.WSObjects.ResLinkAvailibility;
5
6 namespace MVCDemoApplication.Models
7 {
8 public class Your_WebService_Layer_Object
9 {
10 #region Private Fields
11 private Application _app = null;
12 private ResourceTypes _resourceTypes = null;
13 private List<Your_WebService_ObjectName.WSCustomObjects.Availibility.Responses.GetResourceTypeResponse>
14 _getResourceTypeResponseList = null;
15 #endregion
16
17 #region Public Property
18 public ResourceTypes ResourceTypes
19 {
20 get { return _resourceTypes; }
21 set { _resourceTypes = value; }
22 }
23
24 /// <summary>
25 /// A list of GetResourceType response object.
26 /// </summary>
27 public List<Your_WebService_ObjectName.WSCustomObjects.Availibility.Responses.GetResourceTypeResponse> GetResourceTypeResponseList
28 {
29 get { return _getResourceTypeResponseList; }
30 set { _getResourceTypeResponseList = value;}
31 }
32 #endregion
33
34 public Your_WebService_Layer_Object()
35 {
36 _app = new Application("GUID", "PASSWORD", "Another GUID", "<INSERT_YOUR _ URL_HERE>");
37 _resourceTypes = new ResourceTypes(_app);
38 _getResourceTypeResponseList = _resourceTypes.GetResourceType();
39 }
40 }
41 }
4. Added a View that was strongly typed to the class in the Web Service DLL.
And the result generated is as below.
Friday, September 11, 2009
LINQ left join
More LINQ (in Jeremy Clarkson's voice - POWER!!!!)
In the attempt of making a left join in LINQ with my recent work, I had to troll through the web and found the following from Naveen's blog
Essentially, in its most generic form of a LINQ Left Join is something like below
var LeftJoin = from linqObj1 in List1
join linqObj2 in List2
on linqObj1.Field1 equals linqObj2.Field1 into JoinedList1List2
from linqObj2 in JoinedList1List2t.DefaultIfEmpty()
select new
{
RequiredField1 = linqObj1.RequiredField22,
RequiredField2 = linqObj2!= null ? linqObj2.RequiredField45 : null
};
Wednesday, April 8, 2009
Fascination with LINQ
Speaking of which, "what are these?" one may ask.
It is basically simplification of LINQ query statements.
For example, the where-clause in LINQ.
From s In Someone _
Where s.Age > 0 _
Select s
can be simplified to a 1-liner.
Someone.Where(Function(s) s.Age > 0)
A point to note however is that my 1-liner is in VB.
Interesting, don't you think?
For more on this, visit Wiki-LINQ here
Friday, April 3, 2009
Properties (Getters and Setters)
This might be trivial, although I recently discovered that storing the data for later use may not require caching, viewstates or sessions.
Interesting as it be, data can be stored in properties (VB.Net specific) or simply Getters and Setters in the general object-orientation methology sense.
It is important to note that this will only work if you are not deviating from the current class.
How did this came in handy for me? Web development tends to rely on UI objects on the web page. So much so that we forget that essentially the "code-behind" contains of methods wrap within a class.
Hence, using OO methology, we can simply create a property (getters and setters) to maintain data for any data that we would like to preserve.
Example. (VB.Net code)
Public Property orderByStr() As String
Get Return _OrderBy End Get
Set(ByVal value As String) _OrderBy = value End Set
End Property
In this case, for example, I had a data table that I wanted to sort by a certain order.
To determine whether I would have the table ordered by ascending or descending order, I simply use the property above. This can also be expanded to determine how to sort if the previous sorting column is different than the current one.
So much so for a relevation. I was brought down despite thinking that this may work.
Someone proof me wrong but I ended up caching.
Disappointment
Thursday, March 26, 2009
Dates and AJAX Calendar Controller
1. The Date.Today function can be used to find dates in the past and in the future.
Eg: finding what the date is for tomorrow
Tomorrow = Date.Today.AddDays(1.0)
Yesterday = Date.Today.AddDays(-1.0)
There is also the AddTicks, Seconds, Minutes, Days, Months and Years that you can use to get a date in the future or past.
2. The Calendar Extender in AJAX.
I wouldn't want to blog much about this as much has already been said at the location below.
Tone's blog
Wednesday, March 25, 2009
Designing - A dilemma
In fact, it got me confused with it for awhile.
Since leaving the safe-haven of education, my designing skills have eroded and it is good to re-acquaint myself with it once again, at least of what I still remember.
At the current moment, I am using the factory pattern with a service layer with an interface join all the different objects. I do, however have the need to access a database, thus that makes the necessity for a repository to be in place.
I wonder if all I do at work is having this design pattern in place. It seems to be the case with all the projects that I stumble across. Is this the industry standard? Thoughts, anyone?
Tuesday, March 24, 2009
LINQ statement similar to SQL "In" statement
I can't quite post my work here but essentially, it is quite possible to imitate the "IN" statement in SQL.
What I meant by the "IN" query is for example;
SELECT * FROM [table]
WHERE id IN (1, 2, 3)
Using the extension method of "Contains" method, we achieve the SQL "In" method using LINQ. See below.
Have 2 list.
Eg: listOfElements1, listOfElements2
Depending on which list you would like to obtain the information from, perform a LINQ query on that list. For the purpose of this example, I am going to be using the LINQ query on the 1st list of elements.
VB Code
Dim linqToTest = From le1 In listOfElements1.ToArray() _
Where listOfElements2.Contains(le1.[elementName]) _
Select le1
A point to note is that 1 of my list is a list of primitive variables (listOfElements2) and the other (listOfElements1) is a list of objects.
Should you require joining of 2 list of similar types, primitive variables list with primitive variables list of the same type or list of objects that have 1 similar property, the LINQ "intersect" function should suffice.
References:
1. Rob Conery's blog; Wekeroad