Skip to main content

Posts

CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information

I created a new Blazor Server app in Visual Studio 2019 and tried to run it. But I was getting this error CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. I couldn't find any reason or solution to this problem. I tried creating the project multiple times but same error. I created a new .Net Core Web App and added a new razor component and included that component in a razor page (cshtml file) like this @(await Html.RenderComponentAsync<GeofenceWork>(RenderMode.ServerPrerendered)) and <component type="typeof(GeofenceWork)" render-mode="serverprerendered" /> As soon as I navigate to this page that has component added I got the same error: CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. This was very frustrating. After hours of trying and searching I figured out the solution.  ...

Freelancer.com has turned into a scam site

How I got scammed 3 times by Freelancer.com Freelancer.com , the most popular platform for freelancing has now turned into a scam machine. I am not talking about employers/freelancers running away but instead the staff of freelancer.com is involved.  I have recently lost $600 and I will explain how (the points I will mention below has happened to me 3 times in last 1 year): Project awarded -> milestones paid (lets say $300) -> everything good I withdraw my money after few days Suddenly in the morning I see that $300 are locked from my account mentioning security reasons I contact freelancer.com support they say that employer you worked for has some problem in their account verification and we have asked them to verify so your amount will be unlocked once they are verified I wait 3–4 days. No updates. My employer mentioned that they have submitted the required information and support has given them 48 hours to resolve the issue. I contact support again and they say that your...

Protecting APIs against Replay Attack

Replay attacks are very popular against public APIs.  What is a replay attack ? When an attacker intercepts a valid HTTP request to your API and then replay the same request again and again tricking your API into thinking that it is a valid HTTP request coming from your user. Protection Here is a very simple method that I use to protect my APIs from Replay Attacks . Client side steps 1. Generate a unique token on server for the device when app is used for the first time or if app requires login then generate token on successful login. 2. Whenever app makes a call to server it adds the following in HTTP headers Token 128 characters long random value (call it Random1 ) Current Unix Timestamp of device SHA256 of "Token+|||+Random1+|||+Timestamp" (call this result Random2 ) Server side steps When a HTTP request is received by any API it takes the following steps to verify the validity of request Check if Token is a valid token that exists in database (you can implement expiry mec...

Failed to resolve: com.android.support:cardview-v7:26.0.0 android and similar

Recently I updated my android SDK tools and I started getting this error Failed to resolve: com.android.support:cardview-v7:26.0.0 android Solution to this or any other similar error is to add maven end point in your build.gradle file allprojects {     repositories {         jcenter()         maven {             url 'https://maven.google.com'         }     } } 

Ionic2 Error Could not find an installed version of Gradle either in Android Studio, or on your system to install the gradle wrapper

Recently I upgraded to latest version of ionic and started getting following error when building app for android Error: Could not find an installed version of Gradle either in Android Studio, or on your system to install the gradle wrapper. Please include gradle in your path, or install Android Studio To solve this issue you have to perform following steps Download Gradle from https://gradle.org/install/#manually Extract the downloaded zip file somewhere (e.g. D:\gradle) Add "D:\gradle\bin" to Path in your Environment variables After performing these steps everything started working fine for me. Hope you find this helpful :)

Encoding raw images to Ogg Theora video using libavcodec

In one of the blog posts we learned how to decode jpeg images using libavcodec. This is the second part of that post. In this we will learn how to encode decoded images (raw images) to theora and write them in ogg video file. In the end of the first part we saved our raw image in raw_data variable and its length in raw_data_size variable. Lets assume that we packaged all our decoding code in one function called "decode_jpeg_image" which has following signature int decode_jpeg_image(char *filename,int file_name_size,uint8_t *raw_data,int *raw_data_size) filename = name of jpeg file to decode file_name_size = length of jpeg file's name raw_data = contains decoded raw image on return raw_data_size = contains length of raw_data on return Now let's start working on how to encode this image in raw_data to theora and write that image to ogg video file. Finding Theora encoder We first have to find encoder for THEORA which is represented by AVCodec structure. He...

Ionic1 scrolling bounce effect not working in android

I faced a weird problem in my recent ionic1 app. App is a social network that shows news feed. When I tested in browsers scrolling was smooth and when end of list is reached ionic's bouncing effect shows up. But running the app in android do not show any bouncy effects instead its just a "hard scrolling". After reading the docs I realized that bouncy effect is disabled in android by default so i have to add has-bouncing="true" in ion-content . So I added it <ion-content class="has-header" has-bouncing="true"> But still I didn't  get bouncy effect on end of scroll. It was same "hard scrolling" that just stops when end of list is reached without showing any effect. To solve this issue we have to add overflow-scrolling="false" in our ion-content along with has-bouncing="true" <ion-content class="has-header" overflow-scroll="false" has-bouncing="true">

ionic2 - cordova camera plugin content:// in img tag , image not displayed

Recently in ionic2 I faced a weird problem when using camera plugin  in android  . My app simply allows user to either take picture from camera or select image from gallery. When user takes picture from camera everything works fine but if user selects image from gallery , image is not displayed (using img tag). Very first difference i spotted between camera and gallery image was the uri of file. Camera image has following format file:///path/to/image.jpg where gallery image has following format content://media/external/image/238 I debugged my project using Android Studio and I found that when i try to display gallery image using img tag , following error is shown in console URL blocked by whitelist  It was clear that whitelist plugin is blocking content:// requests so I tried to add content:// as whitelisted uri in my config.xml . I added the following lines <access origin="content://*" /> <allow-nagivation href="content://*" /> BUT TO NO...

Ionic2 - Blank white screen for long time before showing root page

I recently upgraded to ionic2 from ionic1. Ionic2 is better than ionic1 in so many ways but one problem that I started facing in my apps built for android was annoying the hell out of my clients. Problem was, that before showing the first screen of app (a.k.a root page) there was a blank white screen for approx 10-12 (and sometimes 15) seconds. First I thought it may be because of many plugins installed but problem was there even in a newly created project based on blank template. How I was building my apk was very simple cordova build --release android After completing all the steps listed here I deploy my apk to device. But after little reading on internet about this white screen issue I found that command to generate production ready build is as follows ionic build android --release --prod This solved my white screen problem and now my Root page appears just after 1-2 secs of launching my app. 

Screen capture and save to SDCard in Blackberry Java (OS4.3 and above)

Blackberry OS (4.3 and above) provides a very easy way to capture screen of device. We can use screenshot(Bitmap bmp) method of Display class. In this post you will see how to capture screen contents and save to a file on SDCard. First we will get width and height of screen. This is very important because Bitmap we pass to screenshot method must have same width and height as of screen. int screenWidth=Display.getWidth(); int screenHeight=Display.getHeight(); Next, create a Bitmap object of dimensions equivalent to width and height of screen. Bitmap bmpScreen=new Bitmap(screenWidth,screenHeight); Take screenshot using screenshot method of Display class Dispaly.screenshot(bmpScreen); Now bmpScreen contains our screen image data. Our next task is to save this data in a file on SDCard. Let's create PNGEncodedImage from this Bitmap. PNGEncodedImage imgToSave=PNGEncodedImage.encode(bmpScreen); Open a file to write this image FileConnection fc=(FileConnection)Connector...

zipalign tool not found in SDK - Eclipse

While exporting Android signed application package through Eclipse you get this warning The zipalign tool was not found in the SDK. Please update to the latest SDK and re-export your application or run zipalign manually After getting this warning I started looking for zipalign tool. After searching in SDK folder I found zipalign.exe under copy_tools folder. This folder is used by Android SDK update to keep copy of old tools. What is zipalign tool ? From Android documentation zipalign is an archive alignment tool that provides important optimization to Android application (.apk) files. The purpose is to ensure that all uncompressed data starts with a particular alignment relative to the start of the file. How to make Eclipse find this zipalign tool To make eclipse use this zipalign.exe you have to copy it in a proper SDK folder. You can find SDK folder in %android-sdk-path% / build_tools / {sdkfolder} After copying zipalign.exe to this folder when you run Eclipse to s...

Resizing image in Blackberry 10 Cascades

In this post we will learn how to re-size an image stored on file or in memory. Cascades provide Image class to perform loading of images but it do not have any support for manipulating the image especially re-sizing of image. But we have a class QImage from Qt that support re-sizing of images. So first lets see how we can load image through QImage class Loading image QImage has many overloaded constructors for loading images from different sources or just create an empty QImage of given height and width. We will cover two constructors here, one for loading image from file and other to load image from image data in memory. Loading from file We will use a constructor that takes file name (QString) as a parameter. We can optionally pass format as a char* parameter but its better to skip that so QImage will detect format from the filename QImage img("asset:///testimage.jpg"); Loading from in memory data QImage provides another constructor to load image data stored ...

How to change JVM for Eclipse

I have following JDKs installed 1) JDK7 64 bit 2) JDK6 64 bit 3) JDK6 32 bit Also I have multiple Eclipse installed. They run on different JVM. For example Eclipse for Blackberry runs on 32 bit JDK and Eclipse for Android runs on 64 bit JDK. You can put only one JDK to PATH in Environment variable or JAVA_HOME environment variable. To configure Eclipse to use specific JVM you have to modify configuration file for your eclipse (usually eclipse.ini). Add following lines just before the line which says “-vmargs”. -vm D:\TOOLS\Java\JDK6-32bit\bin\javaw.exe {this should be the path to your desired JDK bin\javaw.exe }

15 Mistakes to Avoid When Traveling Solo (IndependentTraveler.com)

This blog posts contain excerpts from advice given by Ed Hewitt on IndependentTraveler.com  . View original article here What hostels and guesthouses are great for is meeting other folks doing the same thing that you are -- true fellow travelers. But you don't have to commit to them unrelentingly; your choice of lodging is just another tool in your solo traveler bag. When in need of comfort, safety and convenience, choose a reputable hotel; when in need of companionship, think about hostels and other alternative lodging options. Don't feel obligated to stay in hostels. On these nights, take it easy on yourself; you might stay near the airport or train station, or splurge on a well-known hotel, or take a cab when you might otherwise save money by taking public transit. Don't get too ambitious at the beginning or end of a trip. Having no money in your pocket and no way to get any is a problem for any traveler, but even more so when traveling solo.  Don...

Implementing OAuth2 consumer in C#

Recently I worked on a project that involved integrating with social networking and jobs websites like Elance. These days almost all major services that allow applications to access users' data, perform authorization/authentication using OAuth1.0 or OAuth2. OAuth2 compared to OAuth1 is very easy to implement. OAuth1 involves generating nonce,timestamp,signaturebase and signing the request with any algorithm like HMAC-SHA1 and appending data to query string of URL and passing in Authorization header of HTTP. OAuth2 removed all these requirements. Following is OAuth2 process in a nutshell 1) Redirect user to Authorization url passing client_id and redirect_url in query parameters 2) If user authenticates successfully through service provider it will redirect user to the redirect_url passed with authorization access code in query parameters. 3) After getting authorization access code you exchange this to receive access token. You make a POST HTTP request to a URL passing client_id ...

JEE File Upload - Handling Multipart requests in Servlets 3.0

Prior to Servlets 3.0 developers have to use 3rd party libraries to process complex multipart request that is sent when file is uploaded by user. Starting from Servlets 3.0 JEE provides a better way to handle file uploads (multipart requests) without using any 3rd party library. Making your Servlet ready to handle Multipart requests All you have to do is to add  @MultipartConfig annotation on your servlet class and it is ready to handle Multipart requests. @MultipartConfig   public class FileUploadServlet extends HttpServlet { Our example HTML form <form method="POST" enctype=" multipart/form-data "> <input type="file" name="ufile" /> <input type="submit" value="Submit" /> </form> Handling the POST in processRequest method of Servlet protected void processRequest (HttpServletRequest request,         HttpServletResponse response)         throws ServletException, IOException { Gettin...

Truncate/Ignore time part of DateTime column in Entity Framework

There are times when you want to perform query on only date part of the column that has type DateTime in database. Entity framework does not support DateTime.Date property but provides a helper class EntityFunctions . EntityFunctions has a method TruncateTime that can be called in Linq2Entities query and truncates the time part from datetime. Here is how to use it using (AccountEntities dal = new AccountEntities ()) {               DateTime dtStart=DateTime.Now.AddDays(-20).Date;               DateTime dtEnd=DateTime.Now.Date;     transactions = (from t in dal.Transactions                             where                             EntityFunctions.TruncateTime (t.TransactionDate.Value)                     ...

Android pull down to refresh implementation

There are many apps that allow you to refresh content by simply pulling down the list. I had a similar requirement in one of my projects. I decided to write a blog post that how easily I implemented this feature. For simplicity I will remove code of setting Adapter to ListView etc.I will only show code to detect pull down on ListView First lets see the layout of my screen <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >       <!-- this linear layout will contain our content which we will show -->     <!-- to user while refreshing -->     <LinearLayout android:id="@+id/layoutRefresh"         android:orientation="vertical"         android:layout_height="wrap_content"...

Multithreaded C# TCP server to handle multiple clients

I decided to write a minimal multithreaded TCP based server as a blog post. Following class can serve as a skeleton for any small or large scale multithreaded TCP socket server. It do not contain much error handling , it is only to give an idea that how multithreaded server works and how it can process multiple clients using threading. using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; namespace RandomStuffMine { public class MTServer {     public int Port{get;set;}     public Socket ServerSocket{get;set;}     private List<Client> Clients=new List<Client>();     private bool runServer=true;     public MTServer(int port)     {         Port=port;         ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     }   ...

Playing with Date and Time in MySQL

Manipulating date and time in database is an important task in any database driven application. MySQL is the most popular open source database deployed widely. Here are some tasks that you can perform on date and time using MySQL built in functions. Adding interval to a date DATE_ADD function allows adding/subtracting(using - sign) any interval to date/datetime. The usage of this function is as follows DATE_ADD(date,INTERVAL  [expression] [unit] ) unit can be one of the following MICROSECOND,SECOND,MINUTE,HOUR,DAY,WEEK,MONTH,QUARTER,YEAR,SECOND_MICROSECOND,MINUTE_MICROSECOND,MINUTE_SECOND,HOUR_MICROSECOND,HOUR_SECOND,HOUR_MINUTE,DAY_MICROSECOND,DAY_SECOND,DAY_MINUTE,DAY_HOUR,YEAR_MONTH expression  depends upon the unit. We will explore some units and respected expressions in this post. Note: All example queries use column name "column_dt" for a column of type datetime. Adding SECOND(s) to DATETIME Following query will add 1 second to the value of column_dt...