Posts

Showing posts from October, 2015

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

If you have web services and want to call the web service from your c# code, you can try to use this code example. The code example uses HttpWebRequest to create a request for the web service.  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(); ...

Decrypt web.config file - asp.net

Image
This is an example of how to decrypt a web.config file in asp.net. You can refer to this post on how to encrypt web config file. The example will decrypt web config file for 3 section which is ConnectionString, AppSetting, and system.web/authentication. Front End .aspx code <br /> This is button to decrypt web config.<br /> <asp:Button ID="Button2" runat="server" Text="Decrypt Web Config" OnClick="Button2_Click" /> Code behind private static string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" }; public static string[] SectionName { get { return sectionName; } set { sectionName = value; } } protected void Button2_Click(object sender, EventArgs e) { //decrypt UnProtectSection(); } /// <summary> /// Decrypted web conf...

Check if web.config file encrypted or not.

This is an example of how to check if the web.config file is encrypted or not. Refer to this article to encrypt and decrypt the web.config file. The example will check the 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. OpenWebConfigu...

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

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; } } ...

Encrypt Web.config file - asp.net

Image
This is an example of how to encrypt a web.config file in asp.net. The example will encrypt web config file for 3 section which is ConnectionString, AppSetting, and system.web/authentication. Front End .aspx Code  <br /> This is button to encrypt web config.<br /> <asp:Button ID="Button1" runat="server" Text="Encrypt Web config" OnClick="Button1_Click" /> Code Behind private static string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" }; public static string[] SectionName { get { return sectionName; } set { sectionName = value; } } protected void Button1_Click(object sender, EventArgs e) { //encrypt ProtectSection(); } /// <summary> /// Encrypte WebConfig file for certain section /// </summary> /// ...

Delete top N rows & Truncate table data - MSSQL

This example shows how to delete top N rows in MSSQL, where N is a 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 an example number. [table_name] is the table you want to delete a1 is just an example of sort by column a1 Thanks 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 If you want to delete all table data in the fastest way, you can use the Truncate Keyword.  The example Table name is: Analytics_Compaign TRUNCATE TABLE Analytics_Campaign; /* Reset ID to 1, normally primary key id is auto increment, so when you truncate table data, and when new data insert into database, the id will continue from what it left. This is how you reset the id to number 1 DBCC CHECKIDENT (<tablename>,RESEED,<number to set>)*/ DBCC CHECKIDENT (Analytics_Campa...

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

This is an example of 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" } } JSON Class after converted public class Websites { public string home_page { get; set; } public string blog { get; set; } } public class RootObject { public string name { get; set; } public List<string> email { get; set; } public Websites websites { get; set; } } ...

How to change the properties/method of one web part from within another web part - Kentico

This tutorial is to show how to access the web part properties/method from another web part. This situation basically when you use a repeater name repeater1 and inside repeater transformation you call another User control/web part name repeater2 . Every time you trigger an event on the repeater2 (ie: click, change the value, etc), you want to refresh the repeater1 value. But you cannot access the properties/method directly. Code Behind repeater / repeater1 Override OnInit Event protected override void OnInit(EventArgs e) { RequestStockHelper.Add("repeater2", this); base.OnInit(e); } Code Behind UserControl / repeater2 Called ReloadData() from another webpart. protected void LinkButton1_Click(object sender, EventArgs e) { CMSAbstractWebPart webpart = RequestStockHelper.GetItem("repeater2") as CMSAbstractWebPart; if (webpart != null) { webpart.OnContentLoaded(); } ...

How to convert JSON to C# Class

Today I found one very good tool 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 s...

Force form control to failed validation in Kentico BizForm - Code Behind

This is an example to manually force stop the biz form from continue processing save data and show error message to the Field Form Control. Note this is just an 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); } OnBeforeSave Method void viewBiz_OnBeforeSave(object sender, EventArgs e) { //get the field form controller FormEngineUserControl fieldFormController = viewBiz.FieldControls["<field name>"]; if (fieldFormController != null) { //do custom validation - example fieldFormControl dont have text "*" if (!fieldFormController.Text.Contains("*")) { //stop biz form from continue processing viewBiz.StopProcessing = true; //focus the fiel...

Compress and decompress stream object in asp.net - GZip

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" ...

Compress and decompress stream object in asp.net - Deflate

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" ...

Example code on how to open dialog box when click on the list AdapterView - Android

Image
Today I want to show how to open list items in the dialog box. For this tutorial, you need to have:- Dialog design view_item.xml MyDialogFragment.java class OnClick Event to call dialog. Announcement.java Class AnnouncementHelper Class 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_alig...

Add search condition on Kentico smart search API

Below is an example of using the 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) ...

How to target specific sub element using Jquery

Today I have experienced difficulty to target specific sub-element in my HTML document. So I would like to share the 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.? Below is my solution : <script> $(document).ready(function () { $(".content span:eq(2)").append(" <b>content three append using jquery</b><br/>"); }); </script> From the above solution, basically telling that you can target specific sub-element using "eq(2)" --> 2 is the index with no 2. (Remember index start with 0). Full Code Example : <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"...

Open url with section targeting with jQuery and HTML 5

Recently I have some projects that require targeting section in HTML 5 project. after doing some testing and research on google how to do it, finally, I think this snippet is the best that can work in a most modern browser. Let's see the code. HTML sample  <section id="mainIntro" class="" target-url="<target url>"> : : : </section> JQuery Code Snippet <script> $(window).load( function () { setTimeout(function(){ var current = window.location.href; current = current.substr(current.lastIndexOf('/') + 1); $( "section" ).each(function() { var targetURL = $(this).attr("target-url"); if(targetURL == current){ var mainContentH = $(this).offset().top + 1; $('body,html').animate({ scrollTop: mainContentH }, 150/*this is where you can control of page move to target*/ ); return false; } }); }, 100 /*...

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

Most of the websites and web applications must have an error handler. Some programmers might question what are the error handler should have on one website. Below is the basic error handler that you need to set in the website : Page Not Found - 404 Internal Server Error - 500 Access Denied - 403 The above error page must-have in one website. This is because when the application catch error, the end-users will see asp.net designed page without detailed error information that might not user friendly for the end-users. To handle these errors, all you need to do are two things which are Create the above error page and set in the web.config file in asp.net. Below is an example of a setting in the web.config file. Web.Config <configuration> <system.web> <customErrors defaultRedirect="~/500.html?" mode="RemoteOnly"> <error statusCode="404" redirect="~/404.html" /> <error statusCode="500" redirect=...

how to select date time using calendar android

Image
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  Add One EditText on the fragment Create DateTimeFragment.java class Copy Paste DateTimeFragment.java class below. Override onViewCreated event from fragment 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.w...