Saturday 3 October 2015

How to make request to webservice with soap message - asp.net /C#

Leave a Comment
If you have webservice and want to call the web service from your c# code, you can try to use this method example.

Code Behind

         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(<web service address>);  
         request.Headers.Add("SOAPAction", "http://tempuri.org/" + <web service method>);  
         request.ContentType = "text/xml;charset=\"utf-8\"";  
         request.KeepAlive = false;  
         request.Timeout = 300000; // - in millisecond. (5 minit)  
         request.Method = "POST";  
         request.Credentials = CredentialCache.DefaultCredentials;  
         byte[] byteArray = Encoding.ASCII.GetBytes(<data you want to send to webservice>);  
         request.ContentLength = byteArray.Length;  
         Stream s = request.GetRequestStream();  
         s.Write(byteArray, 0, byteArray.Length);  
         s.Dispose();  
         s.Close();  
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
         Encoding enc = System.Text.Encoding.GetEncoding(1252);  
         StreamReader resStream = new StreamReader(response.GetResponseStream());  
         result = resStream.ReadToEnd(); // read webservice response
         dataToSend = "";  
         resStream.Dispose();  
         resStream.Close();  
         response.Close();  
         return result;  


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Method snippet to remove space between words - asp.net

Leave a Comment
This is the method that can use in c# application or asp.net to remove space between words.

Example :


Hello World  --> HelloWorld

Method 

    /// <summary>  
     /// Method to remove space in a string example : Hello world --> HelloWorld  
     /// </summary>  
     /// <param name="data"></param>  
     /// <returns></returns>  
     public static string removeSpace(string data)  
     {  
       Regex r = new Regex(@"\s+");  
       string _temp = "";  
       _temp = r.Replace(data, @"");  
       return _temp;  
     }  

OR without static

    /// <summary>  
     /// Method to remove space in a string example : Hello world --> HelloWorld  
     /// </summary>  
     /// <param name="data"></param>  
     /// <returns></returns>  
     public string removeSpace(string data)  
     {  
       Regex r = new Regex(@"\s+");  
       string _temp = "";  
       _temp = r.Replace(data, @"");  
       return _temp;  
     }  




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Check web config file either encrypt or not.

Leave a Comment
This is example how to check if web.config file is encrypt or not. refer this article to encrypt and decrypt web config file.

The example will check web config file for 3 section which is ConnectionString, AppSetting, and system.web/authentication .

Code Behind

  private static string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" };  
     public static string[] SectionName  
     {  
       get  
       {  
         return sectionName;  
       }  
       set  
       {  
         sectionName = value;  
       }  
     }  
     /// <summary>  
     /// method to check if web config file is encrypted or not  
     /// </summary>  
     /// <returns></returns>  
     private bool CheckWebConfigIfEncrypt()  
     {  
       bool isEncrypt = false;  
       foreach (string a in SectionName)  
       {  
         Configuration config =  
           WebConfigurationManager.  
             OpenWebConfiguration("~" + HttpContext.Current.Request.ApplicationPath);  
         ConfigurationSection section =  
              config.GetSection(a);  
         if (section != null &&  
            section.SectionInformation.IsProtected)  
           isEncrypt = true;  
         else  
         {  
           return false;  
         }  
       }  
       return isEncrypt;  
     }  


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Kentico 8.xx - Snippet to check if page type have alternative form name

Leave a Comment
This is the snippet for Kentico version 8.xx to check if page type have alternative form.

Code Behind

  public bool CheckIfPageTypeHaveAlternativeForm(string EditFormName,string classID)  
     {        
       bool haveForm = false;        
       string strEditFormName = ValidationHelper.GetString(EditFormName, "");              
       if (classID != "")  
       {  
         if (CMS.DocumentEngine.CMSDataContext.Current.AlternativeForms.GetSubsetWhere("FormClassID = " + classID).Count > 0)  
         {  
           var DataInfo = CMS.DocumentEngine.CMSDataContext.Current.AlternativeForms.GetSubsetWhere("FormClassID = " + classID);  
           foreach (CMS.DataEngine.BaseInfo a in DataInfo)  
           {  
             string formName = ValidationHelper.GetString(a.GetValue("FormName"), "");  
             if (formName.Contains(strEditFormName))  
             {  
               haveForm = true; break;  
             }  
           }  
         }  
       }  
       return haveForm;  
     }  


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

delete top N rows mssql

Leave a Comment
This example show how to delete top N rows in mssql, where N is dynamic number. It could be 1000, 100, or 10 .

  ;WITH CTE AS  
 (  
 SELECT TOP 1000 *  
 FROM [table_name]  
 ORDER BY a1  
 )  
 DELETE FROM CTE  


  • 1000 is the example number.
  • [table_name] is the table you want to delete
  • a1 is just a example of sort by column a1
Tanks to stack overflow for this help :

http://stackoverflow.com/questions/8955897/how-to-delete-the-top-1000-rows-from-a-table-using-sql-server-2008


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

How to read JSON Data and convert to DataTable - asp.net / c#

Leave a Comment
This is example how to read JSON Data using c# code.

First before you start coding, please read this post on how to convert json data to c# class.

How to convert JSON data to Class - C#

After finish convert json data to c# class, write this code to read your json data.

Example JSON Data

  {   
      "name":"swengineercode",  
      "email":  
      [  
           "swengineercode@gmail.com","swengineercode@gmail.com"  
      ],  
      "websites":   
      {  
           "home_page":"http:\/\/swengineercode.blogspot.com",  
           "blog":"http:\/\/swengineercode.blogspot.com"  
      }  
 }  

Read More...

How to convert JSON data to Class - C#

Leave a Comment
Today i found one very good tools to convert JSON data to c# class.

Please go to this link : http://json2csharp.com/

You just paste the json data, and it will give you the class for each element in the json data.

Example JSON Data :

Note : This example JSON data from TripAdvisor API.

  {  
  "address_obj": {  
   "street1": "Lot PTB22819 ",  
   "street2": "Jalan Skudai",  
   "city": "Johor Bahru",  
   "state": "Johor",  
   "country": "Malaysia",  
   "postalcode": "80200",  
   "address_string": "Lot PTB22819 Jalan Skudai, Johor Bahru 80200 Malaysia"  
  },  
  "latitude": "1.485111",  
  "rating": "4.0",  
  "description": "Staying true to our unique no frills concept, we provide you a good night's sleep at outstanding value. Our hotels come with high quality beds, power showers, 24-hour security system, and are conveniently located near transportation hubs and popular local attractions. Unnecessary costs are kept at bay by eliminating facilities that you might not need such as swimming pools, gyms, spa rooms etc.\n\nTune Hotel Danga Bay Johor offers easy access to Asia's first LEGOLAND(R) theme park which is 15-minutes' drive away, or you can hitch a ride with the shuttle bus provided by our hotel. Kids would love exploring the Sanrio Hello Kitty Town, Little Big Club, Thomas and Friends, and Barney at Puteri Harbour which is next to LEGOLAND(R). Daily shuttles transfers are also available to the doorstep of Resorts World Sentosa and Universal Studios Singapore. If you want to just shop, don't miss out on an exquisite shopping experience at Johor Premium Outlets!",  
  "location_id": "1770042",  
  "trip_types": [  
   {  
    "name": "business",  
    "value": "49",  
    "localized_name": "Business"  
   },  
Read More...

How to access webpart method from another webpart - Kentico

Leave a Comment
This tutorial is to show how to access web part method from another webpart. This situation basically when you use repeater(webpartA) and inside repeater transformation you call another User control / webpart(webpartB). Everytime the you trigger event on the webpartB (ie: click, change value, etc), you want to refresh the webpartA value. But you cannot access the method directly.

Code Behind repeater / WebartA

Override OnInit Event
   protected override void OnInit(EventArgs e)  
   {  
   
     RequestStockHelper.Add("WebPartB", this); 
     base.OnInit(e);  
   }  


Read More...

Example to force form control to failed in Kentico BizForm - Code Behind

Leave a Comment
This is a example to manually force stop the bizform to continue processing save data and show error message to the Field Form Control.

Note this is just example. You may use this approach to set very complex validation on the Field in BizForm.


OnLoad Method

   protected override void OnLoad(EventArgs e)  
   {  
     viewBiz.OnAfterSave += viewBiz_OnAfterSave;  
     viewBiz.OnBeforeSave += viewBiz_OnBeforeSave;  
     base.OnLoad(e);  
   }  

Read More...

Compress and decompress stream object in asp.net - Deflate

Leave a Comment
This is a snippet code to provides methods and properties for compressing and decompressing streams using the Deflate algorithm.

abstract class Stream

  using System;  
 using System.IO;  
 namespace CompressionMethod  
 {  
   /// <summary>  
   /// Provides a generic view of a sequence of bytes.  
   /// </summary>  
   public abstract class Stream : IDisposable  
   {  
     #region "Properties"  
     /// <summary>  
     /// Gets or sets system stream.  
     /// </summary>  
     public abstract System.IO.Stream SystemStream  
     {  
       get;  
     }  
     /// <summary>  
     /// Gets the length in bytes of the stream.  
     /// </summary>  
     public abstract long Length  
     {  
       get;  
     }  
     /// <summary>  
     /// Gets or sets the position within the current stream.  
     /// </summary>  
     public abstract long Position  
     {  
       get;  
       set;  
     }  
     #endregion  
     #region "Methods"  
     /// <summary>  
     /// Sets the position within the current stream to the specified value.  
     /// </summary>  
     /// <param name="offset">Offset</param>  
     /// <param name="loc">Location</param>  
     public abstract long Seek(long offset, SeekOrigin loc);  
     /// <summary>  
     /// Reads from stream.  
     /// </summary>  
     /// <param name="array">Array where result is stored</param>  
     /// <param name="offset">Offset from beginning of file</param>  
     /// <param name="count">Number of characters which are read</param>  
     public abstract int Read(byte[] array, int offset, int count);  
     /// <summary>  
     /// Releases all resources.  
     /// </summary>  
     public abstract void Dispose();  
     /// <summary>  
     /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.  
     /// </summary>  
     public abstract void Close();  
     /// <summary>  
     /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.  
     /// </summary>  
     /// <param name="buffer">Buffer</param>  
     /// <param name="offset">Offset</param>  
     /// <param name="count">Number of chars</param>  
     public abstract void Write(byte[] buffer, int offset, int count);  
     /// <summary>  
     /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.  
     /// </summary>  
     public abstract void Flush();  
     /// <summary>  
     /// Sets length to stream.  
     /// </summary>  
     /// <param name="value">Value to set</param>  
     public abstract void SetLength(long value);  
     /// <summary>  
     /// Writes byte to stream.  
     /// </summary>  
     /// <param name="value">Value to write</param>  
     public abstract void WriteByte(byte value);  
     #endregion  
   }  
 }  


Read More...

Compress and decompress stream object in asp.net - GZip

Leave a Comment
This is a snippet code to provides methods and properties for compressing and decompressing streams using the GZip algorithm.

abstract class Stream


  using System;  
 using System.IO;  
 namespace CompressionMethod  
 {  
   /// <summary>  
   /// Provides a generic view of a sequence of bytes.  
   /// </summary>  
   public abstract class Stream : IDisposable  
   {  
     #region "Properties"  
     /// <summary>  
     /// Gets or sets system stream.  
     /// </summary>  
     public abstract System.IO.Stream SystemStream  
     {  
       get;  
     }  
     /// <summary>  
     /// Gets the length in bytes of the stream.  
     /// </summary>  
     public abstract long Length  
     {  
       get;  
     }  
     /// <summary>  
     /// Gets or sets the position within the current stream.  
     /// </summary>  
     public abstract long Position  
     {  
       get;  
       set;  
     }  
     #endregion  
     #region "Methods"  
     /// <summary>  
     /// Sets the position within the current stream to the specified value.  
     /// </summary>  
     /// <param name="offset">Offset</param>  
     /// <param name="loc">Location</param>  
     public abstract long Seek(long offset, SeekOrigin loc);  
     /// <summary>  
     /// Reads from stream.  
     /// </summary>  
     /// <param name="array">Array where result is stored</param>  
     /// <param name="offset">Offset from beginning of file</param>  
     /// <param name="count">Number of characters which are read</param>  
     public abstract int Read(byte[] array, int offset, int count);  
     /// <summary>  
     /// Releases all resources.  
     /// </summary>  
     public abstract void Dispose();  
     /// <summary>  
     /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.  
     /// </summary>  
     public abstract void Close();  
     /// <summary>  
     /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.  
     /// </summary>  
     /// <param name="buffer">Buffer</param>  
     /// <param name="offset">Offset</param>  
     /// <param name="count">Number of chars</param>  
     public abstract void Write(byte[] buffer, int offset, int count);  
     /// <summary>  
     /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.  
     /// </summary>  
     public abstract void Flush();  
     /// <summary>  
     /// Sets length to stream.  
     /// </summary>  
     /// <param name="value">Value to set</param>  
     public abstract void SetLength(long value);  
     /// <summary>  
     /// Writes byte to stream.  
     /// </summary>  
     /// <param name="value">Value to write</param>  
     public abstract void WriteByte(byte value);  
     #endregion  
   }  
 }  

Read More...

How to do Search Condition on Kentico Smart Search Module Using API

2 comments
Below is an example of using Smart Search API module in Kentico.
The API Example inside kentico not telling this, but i was able to figure out the way. 

Kindly have a try on the snippet example 

Smart Search Module API - Search With Condition 

   public void SmartSearchWithCondition(string searchText,string ClassName,string extraCondition)  
   {       
     DocumentSearchCondition docCondition = new DocumentSearchCondition();  
     docCondition.ClassNames = ClassName;  
     docCondition.Culture = "en-US";  
     //refer https://docs.kentico.com/display/K82/Smart+search+syntax for the extra condition syntax  
     var condition = new SearchCondition(extraCondition, SearchModeEnum.AllWords, SearchOptionsEnum.FullSearch, docCondition, true);  
     searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);  
      // Get the search index  
     SearchIndexInfo index = SearchIndexInfoProvider.GetSearchIndexInfo("SearchIndex");  
     if (index != null)  
     {  
       // Prepare parameters  
       SearchParameters parameters = new SearchParameters()  
       {  
         SearchFor = searchText,  
         SearchSort = "##SCORE##",  
         CurrentCulture = "EN-US",  
         DefaultCulture = CultureHelper.EnglishCulture.IetfLanguageTag,  
         CombineWithDefaultCulture = false,  
         CheckPermissions = false,  
         SearchInAttachments = false,  
         User = (UserInfo)MembershipContext.AuthenticatedUser,  
         SearchIndexes = index.IndexName,  
         StartingPosition = 0,  
         AttachmentWhere = String.Empty,  
         AttachmentOrderBy = String.Empty,  
       };  
       // Search  
       DataSet results = SearchHelper.Search(parameters);  
       // If found at least one item  
       if (parameters.NumberOfResults > 0)  
       {  
         //do your works here  
       }  
     }  
   }  

Have a try!


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Android on click list item open in dialog

Leave a Comment
Today i want to show how to open list item in dialog.

For this tutorial you need to have :-

  1. Dialog design view_item.xml
  2. MyDialogFragment.java class
  3. OnClick Event to call dialog.
  4. Announcement.java Class
  5. AnnouncementHelper Class
  6. OnCreateView Method

view_item.xml


  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent" >  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="match_parent"  
   android:orientation="horizontal"  
   android:padding="5dip"  
   android:id="@+id/Announcement"  
   android:transitionGroup="false">  
   <ImageView android:id="@+id/icon" android:layout_width="wrap_content"  
     android:layout_height="wrap_content" android:layout_alignParentTop="true"  
     android:layout_alignParentBottom="true" android:layout_marginRight="4dip"  
     android:src="@drawable/icon" />  
   <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"  
     android:orientation="vertical">  
     <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"  
       android:layout_weight="1" android:gravity="center_vertical" android:textStyle="bold"  
       android:singleLine="false" android:ellipsize="end" />  
     <TextView android:id="@+id/datepublish" android:layout_width="wrap_content"  
       android:layout_height="wrap_content" android:layout_weight="1"  
       android:gravity="center_vertical" android:singleLine="false" android:ellipsize="end" />  
     <TextView android:id="@+id/summarycontent" android:layout_width="wrap_content"  
       android:layout_height="wrap_content" android:layout_weight="1"  
       android:gravity="center_vertical" android:singleLine="false" android:ellipsize="end" />  
     <Button android:layout_width="fill_parent" android:layout_height="wrap_content"  
       android:text="Close Announcement"  
       android:id="@+id/button"  
       android:layout_gravity="fill_horizontal"  
       />  
   </LinearLayout>  
 </LinearLayout>  
 </RelativeLayout>  

Read More...

How to target specific sub element Jquery

Leave a Comment
Today i have experience difficulty to target specific sub element in my html document. So i would like to share my solution that i have.

Example HTML :


  <div class="content">  
     <span>element one</span>  
     <span>element two</span>  
     <span>element three</span>  
     <span>element four</span>  
   </div>  

The problem is how to append text on the third sub element under div with class content.?

Read More...

Open url with section targeting with jQuery and HTML 5

Leave a Comment
Recently I have some project that require to target certain section in my HTML 5 project. after do some testing and research on google how to do it, finally I think this snippet is the best that can work in most modern browser.

Lets see the code .

HTML sample 

  <section id="mainIntro" class="" target-url="<target url>">  
   :  
   :  
   :  
 </section>  


Read More...

how to select date time using calendar android

Leave a Comment
This tutorial shows how to set date time in android app when you click on the textbox.

Note : This example using Andorid Studio to create project. Im using Sample Blank Activity with Fragment sample.

Step By Step 

  1. Add One EditText on the fragment
  2. Create DateTimeFragment.java class
  3. Copy Paste DateTimeFragment.java class below.
  4. Override onViewCreated event from fragment
  5. Done.

Full Source Code of MainActivity class + Fragment / placeholder class

  package com.test.selectdatetime;  
 import android.app.Dialog;  
 import android.content.Context;  
 import android.support.annotation.Nullable;  
 import android.support.v4.app.DialogFragment;  
 import android.support.v7.app.ActionBarActivity;  
 import android.support.v4.app.Fragment;  
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.view.inputmethod.InputMethodManager;  
 import android.widget.EditText;  
 public class MainActivity extends ActionBarActivity {  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     if (savedInstanceState == null) {  
       getSupportFragmentManager().beginTransaction()  
           .add(R.id.container, new PlaceholderFragment())  
           .commit();  
     }  
Read More...

Handle Error Modes in ASP.NET redirec to proper page - Web.config

Leave a Comment
Most of the website and web application must have error handler. Some beginner might question what are the error handler should have in one website. Below are the basic error handler that you need to set in the website :
  1. Page Not Found - 404
  2. Internal server Error - 500
  3. Access Denied - 403
The above error page must have in one website. This is because when application catch error, the end users will see asp.net designed page without details error information that might not user friendly for the end users. To handle this errors, all you need to do are two things which is Create the above error page and set in Web.Config file in asp.net.

Below is a example of setting in web.config file.

Read More...

How to create multiple tab with different fragment / view - Android app

Leave a Comment
Most beginner android developer wonder how to create different fragment for each tab in their android app. Please follow this tutorial to create basic android app with 3 tab before continue with this tutorial. ( http://swengineercode.blogspot.com/2015/05/how-to-create-multiple-tab-on-android.html )

This example using android studio. Kindly download the studio here ( https://developer.android.com/sdk/index.html )

Step By Step 

1. Open "Three tab example" android app. ( Refer this tutorial to create "Three tab example" project )
2. Create New Fragment
























Read More...

Friday 2 October 2015

How to create multiple tab on android app

Leave a Comment
This tutorial to show how to create multiple tab on Android App.

This example using android studio. Kindly download the studio here ( https://developer.android.com/sdk/index.html )

Step By Step

1. Open Android Studio.
2. Choose Start New Android Studio Project




















Read More...

Kentico 7 Get Current Date Time using macro

Leave a Comment
In kentico 8, you can call macro method to show date time information just like C# code which is :

{%DateTime.Now%}

But for kentico version 7, you can not call date time in macro using above code. So i have wondering how to call the date time using macro? and also want to format the date time.

Below is a example how you can show date time in kentico 7 using macro.

Get Date Time

{% CurrentDateTime%}

Read More...

Make Big project compilation faster - Optimize Compilation

Leave a Comment
Most of the web application nowadays are complex application that maybe have more than 50MB source code to deploy on the server and it will lead to the long compilation time around 3-10 minute depends on the server resources. Some will says, it still ok to wait the compilation since it only happen for the first time.

What about require to change the source code with very minimal code of line.? Like one line only.?
Do you still love to wait 3-10 minute.

The answer is no.
Read More...

Jquery Mobile, document ready not fire.

Leave a Comment
Today i have experience some weird situation which i already put the alert script on my mobile html page, but the alert didn't show. The alert script not put at the homepage, but at the url provided, when click the button then will redirect current page to the new page with contain alert script.

For me,this is so weird.

No error on script.

At the first place i though it was cache.. so i click on refresh button.. So i just assume it is cache. But after a while, it always need to refresh only show the alert message. So i start googling the problem.

Some folks says need to clear  cache, close open the browser, and put some funny funny script just to clear the cache.. But still the problem exist.
Read More...

Multiview + File Upload + UpdatePanel , selected file not upload to server

Leave a Comment
Recently I have developed some module to upload the file to server. In my code i have Update panel and also the multiview. Somehow the upload not working. So i though i was not set the full postback for upload process in the trigger section under update panel. But actually the full postback was set correctly. So i wonder, why the upload not work. Why server detected that no file submit to server.

So i start investigate my code, and luckily i found the solution.

The solution 

I just need to set enctype attribute at the form and value multipart/form-data .

This is the code i use.
Read More...

Force Download File in ASP.NET

Leave a Comment
This is example how to force current HTTP Context Response to download file.

Before that, you need to set path / folder in your web application to store file that you just created or pre set the file to download.

In ASP.NET this is the way to set path. Since we can use tiddler("~") symbol to referring to the root with virtual path set from IIS.

  string pathFile = Server.MapPath(Request.ApplicationPath);  

Read More...

Javascript to redirect page to search page with passing query string

Leave a Comment
This is a example method in javascript to redirect page searching page plus carry whatever value type in the textbox after press enter button or click submit button.

Requirement

  • JQuery library

HTML


  <div class="input-group search-btn">  
       <input id="textSearch" type="text" onkeypress="keypressSearch(e);" class="form-control">  
       <span class="input-group-btn">  
        <button class="btn btn-default" onclick="return Search();return false;" type="button">SEARCH</button>  
       </span>  
      </div>  

Read More...

Example Lock Dataset in C#

Leave a Comment
This is example how to lock your database or prevent data in dataset to changed (read only dataset).

In large web application, you may have reference table in database, and the application no need to read on the reference table every time the application need to get reference. You can store the reference table in cache memory. But you afraid that the data might accidentally  changed by your code. This is the way to make your dataset lock / readonly.

Lock Dataset method

  /// <summary>   
     /// Makes the given DataSet read-only   
     /// </summary>   
     /// <param name="ds">DataSet</param>   
     public static void LockDataSet(DataSet ds)  
     {  
       // Do not lock null   
       if (ds == null)  
       {  
         return;  
       }  
       EventHandler locked = (sender, e) =>  
       {  
         string msg = String.Format("DataSet '{0}' cannot be modified, it is read-only.", ds.DataSetName);  
         throw new InvalidOperationException(msg);  
       };  
       // Prevent table modification   
       foreach (DataTable t in ds.Tables)  
       {  
         t.RowChanging += new DataRowChangeEventHandler(locked);  
         t.RowDeleted += new DataRowChangeEventHandler(locked);  
         t.ColumnChanging += new DataColumnChangeEventHandler(locked);  
         t.TableClearing += new DataTableClearEventHandler(locked);  
         t.TableNewRow += new DataTableNewRowEventHandler(locked);  
       }        
     }   


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Combine / Union two dataset

Leave a Comment
This method is example to combine two dataset into single dataset.

This method also called Union two dataset meaning that if both dataset contains same data, the combined dataset will not included.

Method Union Dataset :

   /// <summary>  
     /// Creates the union of two Datasets, the values are compared for uniqueness by the given ID column name.  
     /// </summary>  
     /// <param name="ds1">First DataSet</param>  
     /// <param name="ds2">Second DataSet</param>  
     /// <param name="idColumn">ID column name</param>  
     public static DataSet Union(DataSet ds1, DataSet ds2, string idColumn)  
     {  
       if (ds1 == null)  
       {  
         return ds2;  
       }  
       if (ds2 == null)  
       {  
         return ds1;  
       }  
Read More...

Splits the camel cased input text into separate words.

Leave a Comment
This is example method to split "Camel Cased" into seperated Words.

Example Camel Cased

  • ThisIsOneExample
  • TomorrowIsWhatDay
  • ThisIsAnotherExample

ASPX Page

   <asp:Label ID="Label1" runat="server" Text="Camel Words"></asp:Label>:  
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
   <br />  
   <br />  
   <asp:Button ID="Button1" runat="server" Text="Convert"   
     onclick="Button1_Click" />  
   <br />  
   Preview :  
   <asp:Literal ID="Literal1" runat="server"></asp:Literal>  
   <br />  
   <p>&nbsp;</p>  
   <p>&nbsp;</p>  


Read More...

Detect request is a Crawler / bot or End user request

Leave a Comment
Some project might store some information where is the request come.

This code snippet is show how you can determine the request is a crawler or not.

Code Behind 

   /// <summary>  
     /// Returns whether browsing device is search engine crawler (spider, bot).  
     /// </summary>      
     public bool IsCrawler()  
     {  
       if (HttpContext.Current != null)  
       {  
         HttpRequest currentRequest = HttpContext.Current.Request;  
         return (currentRequest.Browser != null) && currentRequest.Browser.Crawler;  
       }  
       return false;  
     }  

You can put this method under static class and call it from Global.asax file.

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Detect Browser Name And Version

Leave a Comment
This is example in asp.net how to detect client browser and version.

The method used in this example can work after copy paste in the Visual Studio.

Aspx Code


   <br />  
   <h5>  
     <asp:Literal ID="Literal1" runat="server"></asp:Literal>  
   </h5>  
   <p>  
     &nbsp;</p>  
   <p>  
     &nbsp;</p>  

Read More...

Example to remove all script block in HTML

Leave a Comment
This is example how to remove script block in HTML.
This method will be very useful if you want to validate the html passed from input string do not have any script block.

Example HTML have script block :

<div> this is the information </div>
<script>alert('Your computer have security vulnerable');</script>

Example ASPX Code :

Note : This html using Editor Controller in AjaxToolkit library
 <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">  
 </asp:Content>  
 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
   <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
   </ajaxToolkit:ToolkitScriptManager>  
   Input Text :  
   <cc1:Editor ID="Editor1" runat="server" />  
   <br />  
   <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />  
   <br />  
   <asp:Literal ID="Literal1" runat="server"></asp:Literal>  
 </asp:Content>  


Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.