Wednesday, March 29, 2017

Set [Enter] key as default action to cause associated button to click

In the example below, each textbox has its own default button. While focus is in a text box, pressing [Enter] key will cause the associated button to click so that you do not need to click the associated button separately.



<!doctype html>
<html>
<head><title>Set Enter Key as default Click</title>
<style type="text/css">
 body { font-family: Verdana, Tahoma; line-height: 1.7em; font-size: 0.85em; }
</style>
<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>
</head>
<body>
 <h1>Enter Key Capture</h1>
 <div>
  <input type="text" id="txt1" />
  <input type="button" id="btn1" class="defaultButton" value="Button1" />
 </div>
 <div>
  <input type="text" id="txt2" />
  <input type="button" id="btn2" class="defaultButton" value="Button2" />
 </div>
</body>
<script type="text/javascript">
 $( document ).ready( function() {
  
  $( 'input[type=text]' ).bind({
   keypress: function( event ){
    if( checkIfEnterKeyPressed() ){
     
     var message = "Enter key has been pressed while in " + 
         $(this).attr("id") + ".";
     
     $(this).siblings(".defaultButton").bind(
      "click", 
      { msg: message }, 
      function( event ){
       alert( event.data.msg + "\n" + $(this).val() + " clicked." );
      }
     ).click();
    }
   }
  });
 
  var checkIfEnterKeyPressed = function(){
   var keycode = ( event.keyCode ? event.keyCode : event.which );
   return ( keycode == '13' ? true : false );
  };
 });

</script>
</html>

Good old popup dialog

Good old popup dialog example: parent page collects data from child popup dialog.


parent.html
<!doctype html>
<html><head><title>parent</title>
</head>
<body>
Name: <input type="text" id="txtName" readonly="readonly" />
<input type="button" value="Open Popup" onclick="openPopup()" />
</body>
<script type="text/javascript">
 var openPopup = function(){
  popup = window.open( "popup.html", "Select Name", "width=300,height=100;" );
  popup.focus();
 };
</script>
<html>


popup.html
<select name="ddlNames" id="ddlNames">
 <option value="Ken">Ken</option>
 <option value="Steve">Steve</option>
 <option value="Sam">Sam</option>
 <option value="Kirk">Kirk</option>
</select
<br /><br />
<input type="button" value="Make Selection" onclick="makeSelection()" />
<script type="text/javascript">
 var makeSelection = function(){
  if( window.opener != null && !window.opener.closed ){
   var nameSelected = document.getElementById( "ddlNames" ).value;
   var txtName = window.opener.document.getElementById( "txtName" );
   txtName.value = nameSelected;   
  } 
  window.close();
 };
</script>

Linq Example of Group-By

Group-By Example in Linq.

var groupByResult = 
    from p in db.Person
    join s in db.School
    on p.SchoolID = s.SchoolID
    group new { p, s } by new { p.SchoolID, s.SchoolName }
    into grp
    select new
    {
        Count     = grp.Count(),
        SchoolID  = grp.Key.SchoolID,
        SpaceName = grp.Key.SchoolName
    }

Monday, January 16, 2017

Dismiss Keyboard When Tapping Outside UITextField

A quick way to dismiss keyboard when tapping outside a UITextField can be done as follows.
- (void)viewDidLoad {
    ...
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] 
                                       initWithTarget:self.view 
                                               action:@selector(endEditing:)]];
    ...
}

The same can be re-written with a selector method as follows.
- (void)viewDidLoad {
    ...
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] 
                                     initWithTarget:self
                                             action:@selector(hideKeyboard)];
    [self.view addGestureRegnizer:tap];
    ...
}

- (void)hideKeyboard {
    [self.view endEditing:YES];
}

Friday, January 13, 2017

Async Request using dataTaskWithRequest

Here is a simple example of Async Request using [NSURLSession dataTaskWithURL].

- (void) asyncDemo1 { NSURL *url = [NSURL URLWithString:@"https://mysite.com/sampleData.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable taskError) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ // ----- Place background thread operations here ----- // dispatch_async(dispatch_get_main_queue(), ^(void){ // ----- Place async UI update, etc here ----- // if(taskError){ NSLog(@"taskError is %@", [taskError localizedDescription]); } else{ NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } }); }); }]; [task resume]; }

App Transport Security Exception using Info.plist

Here's a short snippet to allow domain exceptions in Info.plist. Method 1 is not recommended, because it will allow all domains. Method 2 is recommended.

Method 1: Not recommended (all domains are accessible) <plist> <dict> . . . <key>NSAppTransportSecurity</key> <dict> <!-- Allows all connections regardless --> <key>NSAllowsArbitraryLoads</key> <true /> </dict> . . . </dict> </plist>
Medhod 2: Recommended (only mysite.com is allowed) <plist> <dict> . . . <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>mysite.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true /> <key>NSIncludesSubdomains</key> <true /> </dict> </dict> </dict> . . . </dict> </plist>

Friday, January 6, 2017

WCF Configuration for Response in JSON Format

Below is a simple example of WCF that returns data in JSON format.

  • When using UriTemplate in WebInvoke attribute, all parameters should be of string type.
  • In the web.config, don't forget to add serviceBehavior and endpointBehavior. 
  • The endpointBehavior needs to have <webHttp /> and not <enableWebScript />.
  • When using WCF for Ajax client (i.e., $.ajax()), keep in mind that Ajax client only knows "GET" and "POST" and not "PUT" or "DELETE".

IService2.cs
[OperationContract]
[WebInvoke(Method ="GET", 
   UriTemplate = "/CategoryName/{id}", 
   ResponseFormat = WebMessageFormat.Json, 
   RequestFormat =WebMessageFormat.Json)]
string GetCategoryName(string id);

Service2.svc.cs
public class Service2 : IService2
  public string GetCategoryName(string id)
  {
     string retVal = "NotFound";
     int categoryID = Convert.ToInt32(id);
     using (NorthwindEntities db = new NorthwindEntities())
     {                
        var category = db.Categories.Find(categoryID);
        if(category != null)
        {
           retVal = category.CategoryName;
        }
     }
     return string.Format("Category with ID {0} is {1}.", categoryID, retVal);
   }
}

web.config

<system .servicemodel="">
    <behaviors>
      <servicebehaviors>
        <behavior name="default">
          <servicemetadata httpgetenabled="true" httpsgetenabled="true">          
          <servicedebug includeexceptiondetailinfaults="false">
        </servicedebug></servicemetadata></behavior>
      </servicebehaviors>
      <endpointbehaviors>
        <behavior name="default">
          <webHttp/>
        </behavior>
      </endpointbehaviors>
    </behaviors>
    <services>
      <service behaviorconfiguration="default" name="NorthwindWCF.Service2">
        <host>
          <baseaddresses>
            <add baseaddress="http://localhost:4957">
          </add></baseaddresses>
        </host>
        <endpoint behaviorconfiguration="default" binding="webHttpBinding" contract="NorthwindWCF.IService2">
        </endpoint>
      </service>
    </services>
    <protocolmapping>
      <add binding="basicHttpsBinding" scheme="https">
    </add></protocolmapping>
    <servicehostingenvironment aspnetcompatibilityenabled="true" multiplesitebindingsenabled="true">
  </servicehostingenvironment></system>