Friday, November 28, 2014

Stripe Payment Gateway

Indroduction


Stripe is the one of the payment gateway to charge amount from credit card. Currently we are using Authorize.Net gateway. When we use Authorize.Net gateway, sometime it gets failure, by this time we can switch the Stripe Payment gateway.

Steps to Implement  Stripe

Step1 :

Let’s start by adding the latest Stripe.NET library to our project using NuGet. 


https://cmatskas.com/content/images/2014/Jan/AddNugetPackage_PNG.png


Step2 :

Next Step to the Stripe site to register for a free account and get your API keys

https://dashboard.stripe.com/register

To use Stripe on your site you will need to reference the stripe.dll in your controller or where your code will be running e.g. on the razor page etc.

https://cmatskas.com/content/images/2014/Jan/StripeApiKey_PNG.png


Step3 :

Add your Stripe public key to the web.config as per below:

<appSettings>  
       <add key="StripeApiKey" value="Your Public Key" />
</appSettings>

Note make sure you replace the StripeApiKey value with your public key.Because this key is used in stripe.dll


StripeApiKey  - This splling should not be change.



Step4 :

       StripeTokenCreateOptions myToken = new StripeTokenCreateOptions();


                myToken.CardAddressCountry = "USA";
                myToken.CardAddressLine1 = "Suite 200";
                myToken.CardAddressLine2 = "";
                myToken.CardAddressCity = "Alden";
                myToken.CardAddressZip = "60001";
                myToken.CardCvc = "123";
                myToken.CardExpirationMonth = "07";
                myToken.CardExpirationYear = "2018";
                myToken.CardName = "Join";
                myToken.CardNumber = "4111555588887777";

                try
                {
                    StripeTokenService tokenService = new StripeTokenService();
                    StripeToken stripeToken = tokenService.Create(myToken);   //Here we got token from stripe.

                    string _stripeToken = stripeToken.Id;

                    StripeChargeCreateOptions myCharge = new StripeChargeCreateOptions();
                    myCharge.Amount = Convert.ToInt32(creditCard.ChargeAmount*100);
                    myCharge.Currency = "usd";  //usd means US Doller. If we want indian rupee we can use "inr"
                    myCharge.Description = creditCard.Description;
                    myCharge.TokenId = _stripeToken;

                    StripeChargeService chargeService = new StripeChargeService();
                    StripeCharge stripeCharge = chargeService.Create(myCharge); //Here charge the amount from Creditcard
                }


Read More »

Monday, November 24, 2014

SignalR

                                       

What is SignalR?
SignalR  simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

Steps to Implement  SignalR

1. Create a sample web application from visual studio.

2. In Solution Explorer, right-click the project, select Add | SignalR Hub Class. Name the class ChatHub.cs and add it to the project. This step creates the ChatHub class and adds to the project a set of script files and assembly references that support SignalR.

3. You can also add SignalR to a project by opening the Tools | Library Package Manager | Package Manager Console and running a command:
install-package Microsoft.AspNet.SignalR.

Note: If you are using Visual Studio 2012, the SignalR Hub Class template will not be available. You can add a plain Class called ChatHub instead.

4. In Solution Explorer, expand the Scripts node. Script libraries for jQuery and SignalR are visible in the project.
Let us write a method in hub class

public void GetUsersNotifications()
{
      // Call the broadcastMessage method to update clients.
      Clients.All.ShowNotifications (notifications);
}


Note: In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub.

6. The HTML page in the code sample shows how to use the SignalR jQuery library to communicate with a SignalR hub.
<!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>

var chat = $.connection.chatHub;

chat.client.shownotifications = function (notifications) {
  //To show notifications for the user.
           $(‘#divDisplay’).html(notifications);
          };
7. The below approach ensures that the connection is established before the event handler executes.
        
  $.connection.hub.start().done(function () {
           chat.server.send.getusersnotifications ();
          });


8. so, your final html code will be as,

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>

    <div id="divDisplay">
    </div>
</body>
</html>


<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>

<script>
    $(function () {
          
        callSignalRIndex();
        var myVar = setInterval(function () {callSignalRIndex() }, 10000);
    });

    function callSignalRIndex() {
        var chat = $.connection.chatHub;

        chat.client.shownotifications = function (count)
        {
            //To show notifications for the user.
            $('#divDisplay').html(count);
        }


        // Start the connection.
        $.connection.hub.start().done(function () {
            chat.server.send.getusersnotifications ();
        });
    }

</script>


Read More »

Date Validation Using Regex (While onTextChanged) in EditText

A regular expression is a string of characters that describes a character sequence. This general description, called a pattern, can then be used to find matches in other character sequences. Regular expressions can specify wildcard characters, sets of characters, and various quantifiers. Thus, you can specify a regular expression that represents a general form that can match several different specific character sequences. There are two classes that support regular expression processing: Pattern and Matcher.

The Following code only for US Date Format (MM-DD-YYYY)


public boolean validate(final String validateDateStr) {

try {

if (validateDateStr.length() != 0) {

if (validateDateStr.matches("(0?[1-9]|1[012])")) {

return true;

} else if (validateDateStr.matches("(0?[1-9]|1[012])[-]")) {

return true;

} else if (validateDateStr.matches("(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])")) {
String[] StartDate = validateDateStr.toString().split("-");
String month = StartDate[0];
String day = StartDate[1];
if (day.equals("31") && (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11") || month.equals("04") || month.equals("06") || month.equals("09"))) {
return false; // only 1,3,5,7,8,10,12 has 31 days
}

else if (month.equals("2") || month.equals("02")) {
if (day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}

} else {
return true;
}
} else if (validateDateStr.matches(("(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])[-]")) || (validateDateStr.matches("(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])[-]([2])")) || (validateDateStr.matches("(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])[-]([2][01])")) || (validateDateStr.matches("(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])[-]([2][0][0-9])"))) {
String[] StartDate = validateDateStr.toString().split("-");
String month = StartDate[0];
String day = StartDate[1];
if (day.equals("31") && (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11") || month.equals("04") || month.equals("06") || month.equals("09"))) {
return false; // only 1,3,5,7,8,10,12 has 31 days
}
return true;
}

else if (validateDateStr.matches("(0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])[-]([2][0][0-9][0-9])")) {

String[] StartDate = validateDateStr.toString().split("-");
String month = StartDate[0];
String day = StartDate[1];
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date myDate = null;
try {
myDate = dateFormat.parse(validateDateStr.toString());
} catch (ParseException e) {
e.printStackTrace();
}

SimpleDateFormat DateFormatyyyy = new SimpleDateFormat("yyyy");
String year = DateFormatyyyy.format(myDate);
if (day.equals("31") && (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11") || month.equals("04") || month.equals("06") || month.equals("09"))) {
return false; // only 1,3,5,7,8,10,12 has 31 days
} else if (month.equals("2") || month.equals("02")) {
if (Integer.parseInt(year) % 4 == 0) {
if (day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
} else {
if (day.equals("29") || day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
}
} else {
return true;
}

}

else {
return false;
}
}

} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {

}
return false;
}

Read More »

How to use CSS specificity



If you plan to use CSS on a regular basis you need to develop an understanding of what specificity is and how it is applied.

Other than floats and positions, specificity may be one of the hardest things to get used to, let alone master. The selectors you use in your CSS all have different weights and those are controlled by specificity. That’s why sometimes, when you apply a rule to an element, it isn’t reflected in your design.

If you’ve ever relied on the dreaded !important keyword to hack your CSS, then this article is for you.

How a browser reads CSS

To get your foundations solid, you need know how the browser actually reads CSS and how rules are overridden.

Firstly the browser will read a stylesheet from top to bottom meaning that with this code:


/*Line 10*/
ul li a {
 color: red;
}

/*Line 90*/
ul li a {
 color: blue;
}

The rule you specified at line 10 will get overridden and that anchor tag will be blue because the browser will consider rules further down your CSS to hold a greater priority.

This also works with the actual order you import your css files , for example:

<link href='css/style.css' rel='stylesheet'>
<link href='css/custom.css' rel='stylesheet'>

Since you placed the custom.css after the the style.css anything you write in the style.css (discounting for now, the weight of selectors ) will get overridden and substituted for what is in the custom.css, this technique is often used by theme creators to give the user some room to add their own styles without changing the main file. (Note however that custom.css doesn’t replace style.css entirely, only those rules that are specifically overridden will be replaced.)


Specificity

Everything above only applies if you are using the same weight on every selector. If you’re specifying IDs, classes or stacking elements then you’re giving them weight, and that is specificity.

There are four categories that define the specificity level of a selector: inline styles (these ones are sometimes used by javascript), ID’s, Classes and elements. How to measure specificity? Specificity is measured in points, with the highest points value being applied.

  1.     ID’s are worth a 100 points.
  2.     Classes are worth 10 points.
  3.     Elements are worth 1 point.

Knowing this, if you use a selector like so:
#content .sidebar .module li a

Its total weight is 122 points ( 100 + 10 + 10 + 1 +1 ), which is an ID, two classes and two elements.

Things to remember

  1.     ID’s have way too much weight compared to classes and elements so you should limit the use of  ID’s in your stylesheets to the bare minimum.
  2.     In cases where the selectors have the same weight the order they appear is reverted to, the latter being the higher priority.
  3.     Styles embedded in your HTML trump styles in stylesheets, because they are closer to the element.
  4.     The only way to override inline styles is to use the !important statement.
  5.     Pseudo classes and attributes have the same weight as normal classes.
  6.     Pseudo elements also have the same weight as a normal element.
  7.     The universal selector (*) holds no weight.


Examples

ul li a {
 color: red;
}

This selector will hold a weight of 3 , which means that just by adding a class somewhere else, you can override it.


.content #sidebar {
 width: 30%;
}

This selector has a weight of 110 points mainly because of the ID that adds 100 points of the 110 total.


.post p:first-letter {
 font-size: 16px;
}

This selector has a weight of 12 points ,since the pseudo-element :first-letter only weighs 1 point and so does the p tag.


p {
font-family: Helvetica, arial, sans-serif;
}

This selector only weighs 1 point , this type of selector should be used at the top of the page when you marking the basic styles that later on may be overridden for specific areas.

Always bear in mind that to override an ID selector you have to write 256 classes for the same element , like so:


#title {
 font-weight: bold;
}

.home .page .content .main .posts .post .post-content .headline-area .wrapper /* ... etc. ... */ .title {
  font-weight: normal;
}
Only this way will the second selector beat the one using the ID.

Read More »

How to detect android Accelerometer Sensor


Introduction:

Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. These sensors are capable of providing raw data with high precision and accuracy.we are going to make use of a shake gesture, it's a good idea to lock the device's orientation. This will ensure that the application's user interface isn't constantly switching between portrait and landscape. Open the project's manifest file and set the screenOrientation option to portrait.

Setting Up the Sensor:

The Main class implements the SensorEventListener interface:

Main.Java

public class Main extends Activity implements SensorEventListener {

private SensorManager senSensorManager;

private Sensor senAccelerometer;

FrameLayout mImageView;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

getSystemService(Context.SENSOR_SERVICE);

}

protected void onPause() {

}

protected void onResume() {

}

//Change ImageView using accelerometer

private void getRandomNumber() {

}

@Override

public void onSensorChanged(SensorEvent event) {

}

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

Manifest File:


 android:screenOrientation="portrait"

 android:label="@string/app_name">

 

 

 

 

main.xml





 android:orientation="vertical"

 android:layout_width="fill_parent"

 android:layout_height="fill_parent">

 
 android:layout_height="wrap_content"

 android:layout_width="fill_parent"

 android:gravity="center"

 android:orientation="horizontal">

 
 android:layout_height="wrap_content"

 android:layout_width="wrap_content"

 android:layout_margin="5dp"

 android:layout_weight="2"

 android:id="@+id/ball_1"

 android:background="@drawable/blue">

 


 

As for the animations, take a look at the contents of the animation file below. Note that

you need to create an anim folder in your project's resources directory and name it

move_down_ball_first.xml. By adjusting the values of the scale element, you can modify

the animation's duration and the position of each ball.




 android:fillAfter="true"

 android:interpolator="@android:anim/bounce_interpolator">

 
 android:duration="1500"

 android:fromXScale="1.0"

 android:fromYScale="-10.0"

 android:toXScale="1.0"

 android:toYScale="1.0" />
Read More »

Unified Storyboards in Xcode 6

Adaptive applications


Overview

A major topic at this year's WWDC(2014) was building adaptive applications. Instead of building applications that target specific screen sizes, developers are encouraged to develop applications that adapt to the device they run on, irrespective of its screen size.


iOS 8 makes dealing with screen size and orientation much more versatile. It is easier than ever to create a single interface for an application that works well on both iPad and iPhone, adjusting to orientation changes and different screen sizes as needed.


This is a move that started a couple of releases back with the introduction of Auto Layout in iOS 6, enabling developers to create apps that work on both the 3.5" and 4.0" screens. It's now been further improved to enable iOS developers to build apps that run on all supported iPhones, including the new 4.7" iPhone 6 and 5.5" iPhone 6 Plus, and iPads using the same code base.


Since the developer no longer needs to create separate and specific storyboard for iPhone and iPad devices, they have flexibility to design applications with a common interface and then customize that interface for different size classes. In this way, an application can be adapted to the strengths of each form factor and tune the user interface to provide the best experience.


Size Classes
Size classes define the canvas size used in layouts. They allow you to specify how the application's user interface changes when the available size of your view controller changes. This makes it possible to have a unified storyboard when building a universal application. Previously you had to design two separate storyboards, one for iPad and one for iPhone.


Prior to iOS 8, the developer used UIInterfaceOrientation and UIInterfaceIdiom to differentiate between portrait and landscape modes and iPhone and iPad devices. In iOS8, the method of determining orientation and device is by using Size Classes. Every device is defined by a Size Class, in both vertically and horizontally axis, and there are two types of size classes in iOS 8:


  • Regular

  • Compact


But you should note that a size class doesn't necessarily map to one device in one orientation. For instance, an iPad can have a view with an iPhone style layout (a compact horizontal and a regular vertical size class) when presented on a smaller space on the device, and an iPad style layout (a regular horizontal and a regular vertical size class) when the available space is larger.


You change size classes by using the Size Classes control near the layout toolbar at the bottom of the Interface Builder canvas. Interface Builder starts you out in the any width and any height size class where you can layout common user interface components and constraints for the different screen sizes and orientations. You then update the parts that need to change when the available screen size changes by making changes to the user interface in the different size classes.


Let us look at the steps on how to use auto-layout for both iPhone and iPad application development in Xcode 6 by using default “Inferred” view.

  1. Open Xcode 6.
  2. Select Single View Application and create new project in Xcode.
  3. Give Project Name as AutoLayoutUniversalDemo
  4. Choose Language : Swift/Objective – C
  5. Select Device : Select Universal
  6. Now in project navigator you will find “Main.Storyboard”.
  7. Click on “Main.Storyboard”, select View Controller you will see “Attribute inspector” in “Utility Area”. Keep size as Inferred so that your View Controller does not change according to specific device.
  8. Drag button to the center of view controller. You can check how button will be displayed in different device using Assistant editor without running the application.

 Screen Shot 2014-11-24 at 11.13.24 am.png
(Look at the different size of screen 3.5 inch, 4 inch, 4.7 inch, 5.5 inch, iPad)


  1. Lets look how to set its position using Auto Layout.
  2. Select View controller on left hand side and select button present at   the center.
    1. At the bottom you can see “Screen Shot 2014-11-24 at 11.52.46 am.png” (pin) in Editor area.


  1. Clicking on it will pop the current constraints for controller which will display its position and height and width. Now set spacing to nearest neighbor.


Screen Shot 2014-11-24 at 11.57.15 am.png



  1. This will change the size of the button but it will remain at the center. Set its height and width and see what happens.


  1. If still it is not displayed according to it is height and width then remove all the constraints first

Screen Shot 2014-11-24 at 12.14.17 pm.png



  1. Click on button and drag mouse upward/downward/left/right it will display certain options when you release mouse in popover. Select center horizontally/vertically.

    Screen Shot 2014-11-24 at 12.33.56 pm.png

  2. As you can now see, the button will be displayed at the center but its size gets reduced.

  1. The application you will get the button exactly in center for all the device and its size won’t even get changed.

    Screen Shot 2014-11-24 at 12.40.23 pm.png
Read More »

Tuesday, November 18, 2014

Convert List as Excel Sheet



1. Include Closed XML & DocumentFormat.OpenXml  dll in the project. (refer this https://closedxml.codeplex.com/documentation for dll)

2. Create an instance of workbook -> Var excel =new XLWorkbook();

3. Add sheets to excel workbook -> var excelsheet = excel.Worksheets.Add(“sheetname”);

4. Create rows in excel sheet -> Row(1).Style.Font.Bold = true;

5. Add column to excel sheet -> var column1 = Worksheets.Column("A");

6. Add cells to excel sheet -> excelsheet.Cell(int row, int column).Value = “value";

7. Add Author & Title to excel if necessary

8. Clear all headers and content output from the current response

9. Get or Set the HTTP MIME type of the current response

10.Add an HTTP header to the current response  for compatibility with earlier versions of ASP

11.Save excel into memory stream & Writes the entire contents to it. Then Close the current  memory stream and release any resources. Send all currently buffered output to the client


sample:

   var ws = wb.Worksheets.Add(sheetName);    ws.Row(1).Style.Font.Bold = true;
   var col1 = ws.Column("A");
   var col2 = ws.Column("B");
   var col3 = ws.Column("C");
   var col4 = ws.Column("D");
   col1.Width = 30;
   col2.Width = 10;
   col3.Width = 15;
   col4.Width = 10;

   var i = 1;
   foreach (var exceldata in _exceldatalst)
   {
        ws.Cell(i, 1).Value = exceldata.aaa != null && !string.IsNullOrEmpty(exceldata.aaa) ? exceldata.aaa : "";
        ws.Cell(i, 2).Value = exceldata.bbb != null && !string.IsNullOrEmpty(exceldata.bbb) ? exceldata.bbb : "";
        ws.Cell(i, 3).Value = exceldata.ccc != null && !string.IsNullOrEmpty(exceldata.ccc) ? exceldata.ccc : "";
        ws.Cell(i, 4).Value = exceldata.ddd != null && !string.IsNullOrEmpty(exceldata.ddd) ? exceldata.ddd : "";
        i++;
   }
 
    wb.Properties.Author = "Sam";
    wb.Properties.Title = "Title";
    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=MySample.xlsx");

    using (MemoryStream memoryStream = new MemoryStream())
    {
        wb.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        _bytes = memoryStream.ToArray();
        string filepath = ConfigurationManager.AppSettings["FolderPath"].ToString();
        if (!Directory.Exists(filepath))
        {
           Directory.CreateDirectory(filepath);
        }
        filepath = Path.Combine(filepath, "MySample.xls");
        memoryStream.Close();
    }

    if (_IsResponse)
    {
        Response.Flush();
    }

    return _bytes;









Read More »

:eq() selector example-demo in jQuery

jQuery API provides another selector ":eq(n)" which allows to select particular child element from its parent. For example, if you want to select 2nd li element from the ul tag. See below code.
     <ul>
            <li>jQuery</li>
            <li>By</li>
            <li>Example</li>
     </ul>
This code will find the 2nd li element and makes it forecolor to "Red".

Note: With eq() selector index starts from 0.

         $(function()
        {
             $('ul li:eq(1)').css('color', 'Red');
          });

The difference between :nth-child() and :eq() is that with :nth-child you can select a series of elements which is not possible with .eq(). .eq(n) will always select the nth element in its parent.


OUTPUT:

jQuery

By

Example



Read More »

Things I Learned about SEO Tools #Keywords

Hello SPAN,

Well, I’m excited now. It is my first blog. I would like to share with you a thought which I was having in mind. In this blog you are going to know about Keyword tools that popular in SEO.

Why the keyword tool is necessary? 
Choosing the keyword is an important element in SEO process and it never gets outdated. In place of select the right keyword, source must be gathered and analyzed. So projections on return can be made.
  
Source based on

1. Website Theme (ex: Business, Medical, Entertainment, etc,.)
2. Domain Name
3. Geo Location
4. Language 
5. Time Range
6. Competition


There are a lot of data sources and research tools available for free (or) offer free versions. By using keyword tools, promoters (SEO's) can generate information to make decisions on keyword targets and set themselves up for successful SEO campaigns.

Image 1: Google Keywords Tools
Below you can find best free SEO tools for reviewing and troubleshooting.

1. Google Adwords: Keyword Planner   
2. Google Trends


1. Google Adwords Keyword Planner

To understand what keywords consumers are searching and the necessity of each of those keywords. This can be determined using Google Adwords: Keyword Tool. To begin, Sign in to Google Adwords. Click on ‘Tools‘ and then ‘Keyword Planner‘. 


There are 4 way to search in keyword planner,
  
Google Adwords
Image 2: Google Adwords
Search for new keyword and ad group ideas 

Find new keywords related to a phrase, website, or category.

In order to see the demand of the keywords, switch "ON" keyword options for "only show ideas closely related to my search terms".

> Get search volume for a list of keywords or group them into ad groups

Enter or upload keywords to research historical stats like search volume, or group them into ad groups

Get traffic forecasts for a list of keywords

Enter or upload keywords to get click and cost forecasts

To specify a match type, add punctuation. For Broad match, "Phrase match", [Exact Match].
   
Multiply keyword lists to get new keyword ideas

Create new keyword combinations and get search volume stats or traffic forecasts.

Image 3: Keyword Planner

Choosing the Right Keyword

Use more detailed keywords that should be always relevant to your website. Remember that if the keywords are too specific, you could not be able to reach many people. Try less specific keywords and then decide which one will give you better results.


2. Google Trends

Another attractive Google product is Google Trends. It will provide you the popular keywords which resemble to your search term. 

Image 4: Google Trends
In Trends we can use operators to filter the types of results. 

Ex: 

Form 2290     - Results Include both Form and 2290.

"Form 2290"   - Result shows Exact match case.

HVUT + 2290 - Include searches contain form or 2290.

HVUT - 2290  - Include searches contain HVUT, but exclude 2290.


To refine results you can sort by change time, location, categories and type of search (Web, Image, News, Google shopping and YouTube search). 


Image 5: Google Trends


It also gives you a graphical representation of the changing trends throughout the years. The tool shows you the country and city your term is popularly searched in, as well. 



Image 6: Google Trends

The above two free google tools are for my references which are used by SEO marketers. In my next blog, I will bring some more Google SEO tools for keyword researching and more. 


Your Questions & Comments Are Always Welcome.


Read More »