Saturday, June 9, 2018

The Security of FiiiPay & FiiiPOS

On June 5th and 6th, me and my marketing team colleagues attended the Singapore Smart Nation Innovation / Innovfest Unbound event, setting up booth and pitch to promote our FiiiPOS and FiiiPay. We received a lot very useful feedback and comment about our product. The most frequently asked question is related to security which I would like to explain more in this post.

HTTPS

Firstly, the most common way to secure a communication channel is to use encryption. Our POS terminal and digital wallet communicate with our payment gateway API using SSL. It is to prevent user data from being leaked when users or merchants are connecting their devices to a public WiFi. You do not know there may be someone who is also connecting to the same WiFi network implanted some sniffing script to the router to monitor the network traffic. If the communication is not encrypted, the hacker can see the data flow between your POS terminal or digital wallet.

Image via contextis.com

Therefore, we strongly encourage our merchant who is using our FiiiPOS terminal not to connect to a public free WiFi hotspot, but putting up a SIM card into the POS terminal to use own network instead.

DNSSEC

All our public domain are protected with Domain Name System Security Extension (DNSSEC). It is a mechanism to prevent hackers from hijacking the DNS and faking the response data to the user, which is known as man-in-the-middle attacks.


Image credit to Michael Earls


Firewall & DMZ

FiiiPay and FiiiPOS servers are secured with perimeter network (known as Demilitarized Zone - DMZ). All the servers are protected with firewall rules that locked down most of the network port access. The common default ports are being changed to random port to prevent hackers from using brute force attack to guess remote access password.

The web and API servers are separated from the database servers where by the public access servers sit in the DMZ but the database server sit in the trusted zone or local area network which restricted to be accessed by the dedicated servers and IP addresses only.




The Vault

With the firewall setup above, all our cryptocurrency nodes are being protected and the nodes access are being restricted. We call it the vault as it can only be accessed by the approved staffs. The servers password are changed frequently and it is strongly type password. The cryptocurrency private key are backed up regularly.

Full Disk Encryption

All the servers storage such as hard disks and solid state disks are all fully encrypted. The servers are setup in a remote data center managed by the service provider. The servers contain the very valuable cryptocurrency private keys. In order to prevent the system engineer in the data center access to the server disks, the disks are fully encrypted. So that, it could prevent the system engineer from trying to unplug the disk and put it into another server or computer to attempt to obtain the private key.

Mobile Application Digital Signature

All the FiiiPay and FiiiPOS application are digitally signed and published to the application store. FiiiPOS application can only be installed to the POS terminal. Hacker cannot install any malware, script, key logger or applet to the POS terminal physically or remotely. So the chances of Spectre and Meltdown exploit is very low and near impossible.

Two Factor Authentication (2FA)

FiiiPay & FiiiPOS provide optional feature for the users and merchants to enable which is the two factor authentication. By default, SMS authentication is enabled. When user or merchant attempt to withdraw cryptocurrency out from the digital wallet, they need to provide the OTP from the received SMS.

We also provide optional Google Authenticator and email authentication option for 2FA in order to reduce the risk of user crypto being stolen by the hacker who has cracked the user password and gained access to the user account.



Artificial Intelligent

FiiiFinance will be equipped with machine learning capability to review all the crypto withdrawal request submitted by the FiiiPay and FiiiPOS users. It collect all the withdrawal timestamp, IP address, geolocation, device ID, operating system, withdrawal amount, crypto type, etc data. Based on the user app usage behavior, pattern and the withdrawal request history, it can raise alert to the finance team and put the withdrawal transaction on hold for human review when it detect unusual activity for a particular account. This security measurement can ensure the lower risk of the crypto to be stolen by the hacker who has gained access to a FiiiPay/FiiiPOS user account.

Payment Code Algorithm

The QR code, Bluetooth and NFC payment mechanism actually rely on HMAC (hash-based message authentication code) to generate the unique OTP which is impossible forge and brute force attack. The generated payment code is always unique to different account at different time and it will be valid for a short period of time.



Summary

Our system architecture are setup in enterprise standard. Our customer digital asset and data are the utmost important, hence we are very serious and invest heavily on system and network security. Cyber security is always the hot topic in blockchain world as we occasionally read the news about X exchange platform had been hacked and lost X million of USD worth of cryptocurrency. We ensure this tragedy will not happen in our platform.

If you are a cyber security expert or ethical hacker, please drop me a message by connecting to me at LinkedIn. We are planning for a hackathon event for our product to look for security exploit.

iOS - AppStore
Android - PlayStore

If you are interested in our multi-cryptocurrency POS machine - FiiiPOS, please drop me an email at sylvester.lee@fiiipay.com

If you are interested in our project, please visit our website at https://fiii.io

Facebook - https://www.facebook.com/fiiipay/
Telegram - https://t.me/fiiicoin




Tuesday, May 15, 2018

Hybrid Payment Network

Recently a lot of fans are curious about how our crypto digital wallet and payment work. Our payment solution has fasten the bitcoin payment process. As you may not know, a bitcoin transaction need at least 9 blocks confirmation in order to consider the transaction is confirmed, otherwise, the transaction has the potential to get reverted. Why the transaction get reverted if you ask, it is because your transaction in the block is being mined by a miner who has slow network connection, but another block which does not have your transaction included has been mined successfully at the same time by another miner with faster network and their block has been confirmed by majority of the peer nodes. Therefore, it is better not to assume all transaction will be confirmed in the matter of time.

Problem

Bitcoin transaction confirmation is slow. A block is propagated every 10 minutes, and to get 9 block confirmation, you need to wait 1 hour and 30 minutes to get your transaction confirmation. If you are trying to buy a cup of coffee using bitcoin, are you willing to stand in front of the cashier and wait for your payment is being confirmed for at least 1 hour? I doubt so.

Workaround, Not Solution!

Hence, we come out a workaround to solve this problem. If you understand how bitcoin work and how data are distributed among peers in a decentralized network, you should know there is a no silver bullet for the slow transaction confirmation problem. However, there is a project worth one's while to look into which has the capability to solve today's cryptocurrency common slow transaction problem: IOTA. It is a whole new solution design, it has no blockchain concept, it has no "mining" transaction confirmation concept, it uses Directed Acyclic Graph (DAG) or so called Tangle technique which rely on the network peers to co-audit and co-govern transactions with each other. The more the peers participate in the network, the faster the transaction to be confirmed and the harder the data can be tampered eventually the higher the security.

Back to FiiiPay payment solution, we go for hybrid. The reason is it is not feasible to just purely rely on decentralized network to achieve everything. I know a lot crypto fans out there are condemning about any cryptocurrency that has centralized service is not a good crypto and it could be a scam project which I actually disagree. If you truly understand how blockchain work, you should realize that in order to fasten the transaction confirmation, you need to sacrifice the security by increasing the fault tolerance level, the transaction audit is going to be lenient, validation work is reduced, hence it is vulnerable for attack.

Hybrid Payment Network



Firstly, we treat bitcoin and other cryptocurrency wallet as a bank account instead of a digital wallet. In order for the users to start using FiiiPay, they have to transfer bitcoin from their bitcoin wallet to our bitcoin wallet. Each FiiiPay user account will be given a unique bitcoin address. We have a separate cryptocurrency service, FiiiFinance, responsible to track the amount of bitcoin which has been deposited to the particular address that owned by particular FiiiPay user account.

The deposited bitcoin from the user will be recorded in our centralized database. From here onward, users proceed to transfer bitcoin to another FiiiPay user, or start making bitcoin payment to merchants who use FiiiPOS. All the transaction happen within our payment network. Therefore, we are no different from PayPal or Alipay.

Scalability & High Availability

Our architecture design is a distributed system design that support load balancing, it can easily scale by adding hardware to the network when the demand is getting higher. Currently, a single server can support up to 1500 transaction per second, for three servers can support up to 4500 transactions per second. Furthermore, it promote high availability by having multiple servers online at the same time.

Network Security

The API servers are only exposed to the public in strict firewall rules network zone, the FiiiFinance and KYC sensitive data servers are hosted in trusted zone which are interconnected within a secured tunnel virtual network. Our digital assets, the crypto nodes, are separately setup in different region. It is our risk mitigation strategy to avoid creating a single point of contact for hacker to access into our nodes.

Data Protection & Disaster Recovery

Since all the crypto transaction are happening within our network, our database to be of utmost importance to ensure the data are well kept and recoverable due to technical failure or disaster, and also making sure performance meet the expectation and does not affect the user experience.

Artificial Intelligent

FiiiFinance will be equipped with machine learning capability to review all the crypto withdrawal request submitted by the FiiiPay and FiiiPOS users. It collect all the withdrawal timestamp, IP address, geolocation, device ID, operating system, withdrawal amount, crypto type, etc data. Based on the user app usage behavior, pattern and the withdrawal request history, it can raise alert to the finance team and put the withdrawal transaction on hold for human review when it detect unusual activity for a particular account. This security measurement can ensure the lower risk of the crypto to be stolen by the hacker who has gained access to a FiiiPay/FiiiPOS user account.

Summary

Hybrid Payment Network is a workaround for all crypto common slow transaction confirmation problem. It enable any crypto payment to be made immediately. This solution is not new as it is commonly found in today's cryptocurrency exchange platform.

Our FiiiPay Beta version is ready for download. Feel free to share your thought at the comment section below.

iOS - AppStore
Android - PlayStore

If you are interested in our multi-cryptocurrency POS machine - FiiiPOS, please drop me an email at sylvester.lee@fiiipay.com

If you are interested in our project, please visit our website at https://fiii.io

Facebook - https://www.facebook.com/fiiipay/
Telegram - https://t.me/fiiicoin


Sunday, April 22, 2018

FiiiChain

Due to the recent workload, the new post update come a bit late. Today's topic is about our customizable blockchain solution - FiiiChain.



FiiiChain is a blockchain code foundation written in C# programming language. It is a framework which can be customized base on business requirement, be it whether you want to use it to keep transaction data (like Bitcoin to create a crypto coin) or any custom format data.

When do I need to use FiiiChain?

1. You have a database which would like to be open for everyone to access.
2. You allow everyone to make data changes in the database together.
3. You want to ensure no one can modify the history of data.
4. You want everyone to take part in governing the data integrity.

If your business model do not have the above requirement, you do not need blockchain or FiiiChain. I discover that a lot of ICO projects do not actually need a blockchain solution but yet still utilizing the technology just for the sake of crowd funding. In the end, the technology does not help in the business but creating scalability issue to the business ecosystem. The situation is like using the wrong tool to solve the wrong problem.

FiiiChain Foundation

FiiiChain is coded base on layered architecture design pattern. If you are a coder and curious about what is layered architecture, feel free to read this post. In short, it is a design pattern that segregate the whole chunk of source code into a few small modules for a specific task at the same time flexible enough in making them work independently but also anytime can combine them into a 2-tier or 3-tier or N-tier solution. It is like a car as a whole, split it into multiple parts, each part play a different role. You can combine the parts to become a bicycle or motorbike or car or bus depending on your requirement.


Block Data Structure

In FiiiChain foundation, you can define your block data structure, the data format that you want. In fact, you may just treat blockchain as an encrypted database. It is not a fancy or complicated technology once you have understood it.

The difference between a blockchain and a RDMS database is the data is not kept in a structured manner. There is no "table" concept in the block. You may define a JSON data structure and store in the block. The blocks are chained between each other base on the current block hash and previous block hash. The hash value is calculated based on the overall data of the block. The way how it use the hash to verify block is similar to verify a file checksum. If the block data has been modified, the hash value of the block will be changed, then the link between current block and previous block will be broken.

The blocks are stacked in a line from bottom to top, hence you will notice the keyword "block height" in the blockchain explorer. It mean the height of the block that you are looking at. The higher the block, the latest the block is and the latest data it stored.

FiiiChain can be customized to store block, transaction, memory pool data and so on into LevelDB (current Bitcoin DB) or the famous SQLite or any other lightweight file base client-side database.

Components

So for FiiiChain core component, it has been segregated into the following modules:

1. Network
2. Blockchain
3. Transaction
4. Consensus
5. Account
6. Hash Algorithm

Each module play a different role and their code logic can be changed easily in plug and play style as long as you code the component base on the interface defined in the FiiiChain foundation guideline.

Network

Once FiiiChain has been deployed into a node. It must be interconnected between nodes and must be in peer-2-peer (P2P) method since blockchain is a decentralized database, hence the only way to synchronize data is to connect and retrieve data from the peers in the same network. The more node we have, the tighter the security and data governance.

Blockchain

Blockchain is the key component of all, it responsible in following the consensus rule to identify the eligibility and ingenuity of a block passing down by the peers and chaining the block to the main chain by verifying the block hash, transaction signature and the proof of work.

FiiiChain has the flexibility to generate multiple side chain to cater for certain business scenario or solving certain problem. For example, it is possible to work on the lightning network implementation that leveraging on a side chain to create a payment channel for peers to make transaction in a temporary chain then finalize the settlement after a period of time to reduce number of transaction written into the main chain. This is considered as a workaround to solve today's Bitcoin scalability issue.

Transaction

Transaction component responsible in maintaining and managing all the transaction data in memory pool by working closely with Blockchain and Consensus component. It also backtrack all the unspent transaction output (UTXO) to calculate particular account wallet balance. It also verify the transaction hash and signing the transaction with private key.

Consensus

Consensus is the rule that defined in the blockchain to generate blocks, store transactions, create mining work. This is where you define the hash algorithm for proof of work, genesis block setting, coin supply limit, block generation time, block difficulty setting, coin base reward rules and mining fee setting.

You may define a new rule here such as Proof of Stake, Proof of Capacity or Practical Byzantine Fault Tolerance.

Accounts

In FiiiChain, it shall not be limited and not necessary must be using ECC or PGP/RSA method to generate private/public key set, as long as the method to generate account is unique, unpredictable and secured.

Hash Algorithm

There are quite a number of the hash algorithm available in the market. You can pick one base on your requirement such as ASIC counter or CPU/GPU friendly for your proof of work.

Summary

FiiiChain foundation is a highly flexible and customizable blockchain framework. Our main goal is to train up the existing corporate C# developer to pick up blockchain to solve the blockchain talent shortage problem in the world. C# is a higher level programming level which is easier to read and understand compare to C++.

We want to remove the dependency on the current available blockchain platform in the market. There are a lot of restriction that you have to play with them. Our solution promote fast code development and deployment to the market since we will have Bitcoin template in FiiiChain and programmers can easily pick up, learn and build from there.

Please follow us if you are a C# developer and would like to learn more about FiiiChain.

Facebook - https://www.facebook.com/fiiipay/
Telegram - https://t.me/fiiicoin

If you are interested about our project, you may download our whitepaper here:
English Version
Chinese Version

My LinkedIn Profile

#redefinecryptocurrency
#fiiichain

Tuesday, April 3, 2018

FiiiPOS

As promised, one post per week, if you missed my first post about my startup story, feel free to read from here.

Today topic is about FiiiPOS. I received a lot of questions regarding FiiiPOS. People are interested to know more about it but our official website is still under construction, hence have no other choice but to share the information through my blog here.

FiiiPOS stand for Fiii (our trademark) Point-of-Sales, it is a POS terminal that can accept cryptocurrency as payment. At this moment, we are avoiding fiat currency and limiting to support cryptocurrency payment only due to the rules and regulations about cryptocurrency is still unclear and yet to be confirmed in Malaysia, China and other country.


FiiiPOS support multi-cryptocurrency which mean not limited to Bitcoin only. We are progressively increasing more cryptocurrency support. The top 20 most popular cryptocurrency you can find in coinmarketcap.com will be supported.

The Purpose

Our main purpose of this product is to provide a platform for all the cryptocurrency available in the market to circulate and usable for transaction. A cryptocurrency value is determined by its supply and demand. If a cryptocurrency cannot be used for transaction, it is useless and valueless despite of how good the technology behind it can offer.

How It Works?

FiiiPOS
is considered as FiiiPay Merchant Edition and will be used by valid merchant only. We have a KYC process for merchant and it is differ from User Edition, the FiiiPay app. Merchant need to submit valid business licence, owner detail, contact and shop location while setting up FiiiPOS for the first time.

Prior to the user make payment to the merchant using FiiiPay app, firstly both party must come into a mutual agreement of selecting which cryptocurrency for payment. FiiiPOS has a series of cryptocurrency choices to pick, however, the condition is merchant must be willing to accept the particular cryptocurrency.

Payment

Once both party agreed upon using one particular crypto, for example: Bitcoin, merchant setup from the FiiiPOS by choosing Bitcoin, then enter the local fiat currency amount (we make it easy fiat-2-crypto conversion calculation), then choose the payment acceptance method. FiiiPOS support 3 payment methods so far:

1. QR Code
2. Bluetooth
3. NFC

Step 1: Choose Cryptocurrency


Step 2: Enter local fiat currency amount and it will instantly calculate fiat-2-crypto conversion base on the price reference from coinmarketcap.com.

Step 3: Choose payment method.


Step 4: User open up FiiiPay app then scan the QR code appear on the FiiiPOS


The payment is made instantly once user scan the QR code appear on the FiiiPOS. If you wonder how does the FiiiPay app link with your cryptocurrency wallet, the answer is NO. FiiiPay does not link directly to your cryptocurrency wallet. FiiiPay is not a crypto wallet. FiiiPay does not request your crypto wallet private key. FiiiPay is just a third party centralized digital wallet, same goes to FiiiPOS. 

Deposit

Before user begin to use FiiiPay, user need to deposit some amount of crypto to FiiiPay first. Every FiiiPay newly registered account will be given a public key address for every particular cryptocurrency. The concept is similar to the cryptocurrency trading platform available in today's market.

Withdrawal

User and merchant can withdraw the collected crypto out from FiiiPay/FiiiPOS to their own crypto wallet anytime anywhere with a small charge of transaction fee.

Mining

FiiiPOS has a unique feature which other POS terminal does not have which is mining FiiiCoin (will be covered in the next few posts). FiiiCoin is a newly developed cryptocurrency by FiiiGroup using FiiiChain (proprietary blockchain framework) and Delegated Proof of Capacity (DPoC) consensus algorithm which uses FiiiPOS available storage space and CPU power for mining to maintain the blockchain network. When FiiiPOS is idle and plugged in to charge the battery, it will automatically bring up the mining page and start mining automatically. The idea is to maximize the usage of the POS machine.

The idea is to let our merchant who have purchased FiiiPOS to earn some reward in FiiiCoin which is treated as a token of appreciation in supporting our cause. At least our merchants feel compensated in another way after paying transaction fee for every received payment.

Mining hash rate is determined by the allocated storage space

Reporting

FiiiPOS is equipped with a thermal printer. When every transaction has been made, it will print a copy of payment slip for the user and a duplicate copy for the merchant.

FiiiPOS track every transaction and is capable of generating and exporting report data in spreadsheet or PDF format for the merchant. Due to the size of the FiiiPOS is small, merchant can open the FiiiPOS web edition using a PC/laptop browser to access the report and download the exported file.

Security

FiiiPOS is a restricted device. Merchant cannot install any application into the device. It is to prevent hacker from installing virus, malware, key logger, etc to the device. Hence, the Meltdown and Spectre vulnerabilities are low.

FiiiPOS is equipped with GPS, in case merchant lost the device, we can assist to detect and recover. We has a customer service team to assist user and merchant 24/7 to lock down their account or recover the device once their phone device or POS device is missing.

Maintainability

FiiiPOS is monitored by a central monitoring system. FiiiPOS software occasionally will receive patch for bug fix and security update.

We offer one year warranty for FiiiPOS device in case of any hardware failure. We have a technical support team standby in every operating country for hardware repair or parts replacement.

Hardware Spec

Processor: 4 core CPU
Memory: 1GB RAM, 8GB Flash
Display: 4.8"
Printer: High speed thermal printer, 40mm paper roll
Communication: 4G LTE/Wi-Fi/Bluetooth/NFC
SD Card Slot: 1
SIM Card Slot: 1
Device Port: 1 micro-USB OTG
Front Camera: 2MP
Rear Camera: 5MP
Speaker: Yes
Battery: Li-ion 5200 mAh
Power: Input - 100-240V, 50-60 Hz, Output - 5V/2A
OS: Android 5.X

More Photos

















Collaboration Opportunity / White Label

If you are an owner of a cryptocurrency, you wish to circulate your crypto to the market and expand your merchant network, feel free to drop us an email to enquire: sylvester.lee@fiiipay.com

Whitepaper

If you are interested about our project, you may download our whitepaper here:
English Version
Chinese Version

My LinkedIn Profile

Follow us on Facebook Page and Telegram to get the latest news and update.

Facebook - https://www.facebook.com/fiiipay/
Telegram - https://t.me/fiiicoin


#redefinecryptocurrencies
#spendborderless


Thursday, March 29, 2018

FiiiPay - Prologue

I am back! I had stopped blogging since 2 years ago when I started to venture into the startup world. Since then, I had very limited time in blogging, I gave up the daily 9 to 5 job, no more annual leave nor sick leave, I had been selflessly involving all the problem area and solving any surfaced issue despite not under my expertise.

In year 2015 August, I resigned as a Technical Lead Consultant from HP,  joining my school mate founded a company in Shenzhen, China to build an O2O (Online to Offline) payment solution along with vouchers app which is similar to Groupon, unfortunately, we failed due to over estimated the China spending behavior and applied wrong marketing strategy.

We went through a lot, facing customers and merchants everyday problem, going around the world pitching ideas looking for funding, encountered hackers attacking our system, corrupting database, even were once happy generating CNY$ 1.4M highest revenue in a month, but things did not get along well all the time. Our operation cost was high due to over staffing and giving out too much freebies attempt to attract user to gain traction, then hacker exploited our reward system, plus the generated revenue were not be able to cover the monthly expenses. We paid a big price to learn from mistake, we dismissed all our staffs and shutdown our project in January, 2017.

However, failure did not stop us, we stand up where we fall! We tried to recover with very minimal remaining resource, a group of 4 programmers including myself, by starting to accept external software development projects. We save money, we build software for others at the same time working on our new project - FiiiPay. It is a multi-cryptocurrencies digital wallet. We also build a multi-cryptocurrencies point-of-sales terminal - FiiiPOS for merchant to accept crypto payment from the FiiiPay users.

Why multi-cryptocurrencies?

We do not want to limit ourselves to accept one kind of cryptocurrency. We do not know the exact market demand, but we do know about the volatility of a bitcoin, we do not want to restrict merchant to accept one kind of cryptocurrency. Different people different thought, we open for all.

Secondly, we consider ourselves as cryptocurrency service provider. I want to help cryptocurrency company or project to be successful by creating a method for them to circulate their coins to the market. Anyone who want to circulate their coin, you may come and look for me to discuss collaboration. We can make your crypto coin to become acceptable as payment among all our merchants.

User and Merchant Sharing Mechanism

We have two collaboration partners so far. From here, we can see it as merchant sharing. Two partners purchase our POS terminals and is going to expand their own merchant network. However, both network are sharing the same platform - FiiiPay. The combined effort result in exponentially gaining traction.

Chicken and Egg Issue

My past experience tell me that user will not use your platform unless you have a lot of freebies and merchants or you provide something that they need. On the other hand, the merchant is willing to join your platform only when you have a lot of users that could bring sales to them. So, here come the chicken and egg issue, whose problem should be tackled first? Our solution is both party requests need to be fulfilled at the same time, and that our business model can solve the problem.

Blockchain

Blockchain is the top Google search keyword in the recent years. In fact, we are also one of the companies explored into this technology last year. We are not just another payment solution provider,  we are here to provide Blockchain Solution as a Service, helping companies to learn and adopt blockchain technology in their existing business. We build customizable blockchain code - FiiiChain in C# with layered architecture design pattern and modular programming. We promote the reusability of existing organization programmers resource to pickup and improve blockchain learning curve, solving the shortage of blockchain developer talent problem. With FiiiChain code base foundation, we can easily develop any decentralized application for any industry.

Community

I am actively looking for C# or blockchain talent, if you are interested and located in Kuala Lumpur, Malaysia or Shenzhen, China, you may drop me an email at sylvester.lee@fiiipay.com. We will conduct "Blockchain in C#" training in the near future, we welcome you to join our Telegram group at https://t.me/fiiicoin and Facebook Page to follow us to get the latest news about our project, company and event.

Next Update

Since I am back to blog, stay tune for my next update about Blockchain in C# - Part 1. We build our first cryptocurrency - FiiiCoin using our C# blockchain foundation code. I am sure a lot of C# developers and my blog followers out there wish to get to know more about it.

Whitepaper

If you are interested about our project, you may download our whitepaper here:
English Version
Chinese Version

My LinkedIn Profile



#redefinecryptocurrencies
#spendborderless





Sunday, May 24, 2015

C# - Programmatically Add/Delete Membership Rule To/From SCCM Query Based Collection

I had been working on how to create membership rule into query based collection using SCCM SDK with C#. The article from MSDN has limited information especially in this area using C#. What I have found mostly are done using PowerShell script. Luckily, PowerShell and C# are somehow similar and I am able to base on the sample to convert it to the C# code to perform the automation work that I want. I am going to share the detail in my today's post.

Pre-requisite

Before we can begin, we need to include the following DLLs into your project assembly reference.

adminui.wqlqueryengine.dll
Microsoft.ConfigurationManagement.ManagementProvider.dll

Both DLLs can be obtained from SCCM installed directory which default at C:\Program Files\ConfigMgr2012\bin

If you download the SCCM 2012 SDK from this Microsoft Download Center link, it does not include the Microsoft.ConfigurationManagement.ManagementProvider.dll. The sample code provided from the SDK does not work as it miss out this dll. So, you have to get it from the SCCM 2012 server.

Query

Basically what we want to achieve here is to add multiple users into a membership rule then add the rule into the SCCM query based collection. Instead of manually doing it, we are going to automate it. First, we need to identify how the query should look like which to be added into SCCM collection.

We can check it out by opening the Configuration Manager Console. Then, go to the SCCM collection page. Open the Collection Properties.



Click the Add Rule button, then select Query Rule.



Enter a name for the query, then click Edit Query Statement.


Choose Criteria tab then click the little sun button.


I am going to add multiple users into a rule, so select Criterion Type as List of values. Then, click the Select button.


In my environment, I use Unique User Name to identify the users. Therefore, select Unique User Name as the attribute.

After clicking the OK button, it will lead me back to Criterion Properties page. Then, type the unique user name into the Value to add textbox or click the Values button to select the user that you want to add them into the membership rule. Once you have done adding all the users into the list, click the OK button.


The query is displayed in the Query Statement page. That query is going to be needed to be added to the SCCM query based collection programmatically later.

Coding

Add Membership To Collection

The following are the source code to add the query to membership rule to SCCM collection.

The semantic flow is as follow:

1. Connect to SCCM server.
2. Form the WQL query as you have seen from the Configuration Manager Console.
3. Validate the WQL query.
4. Create a new collection query instance.
5. Invoke AddMembershipRule method.
6. Request collection membership refresh.


public void AddUsersToCollectionMembership(string sccmCollectionID, params string[] userNames)
{
    SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
    WqlConnectionManager connectionManager = new WqlConnectionManager(namedValues);

    if (string.IsNullOrWhiteSpace(sccmCollectionID) || userNames == null)
        throw new ArgumentException("The parameter collectionID value cannot be null or empty or whitespace.");

    try
    {
        connectionManager.Connect(this.SccmServerName);
        WqlResultObject collection = (WqlResultObject)connectionManager.GetInstance("SMS_Collection.CollectionID='" + sccmCollectionID + "'");

        string[] users = userNames.Select(x => x.Replace("\\", "\\\\")).ToArray();
        string query = string.Format("SELECT * " +
            "FROM SMS_R_User " +
            "WHERE SMS_R_User.UniqueUserName IN ({0})", string.Join(",", users));

        //Validate the query before adding the query to SCCM collection
        var validateQueryParam = new Dictionary<string, object>();
        validateQueryParam.Add("WQLQuery", query);
        IResultObject validationResult = connectionManager.ExecuteMethod("SMS_CollectionRuleQuery", "ValidateQuery", validateQueryParam);

        if (validationResult["ReturnValue"].BooleanValue == true)
        {
            //Create collection rule query instance
            IResultObject rule = connectionManager.CreateInstance("SMS_CollectionRuleQuery");
            rule["QueryExpression"].StringValue = query;
            rule["RuleName"].StringValue = "Members of collection " + sccmCollectionID; //The rule name will reflect in the CM Console

            //Add the rule into a parameter object
            var membershipRuleParam = new Dictionary<string, object>();
            membershipRuleParam.Add("collectionRule", rule);

            //Add new rule to SCCM collection
            IResultObject addResult = collection.ExecuteMethod("AddMembershipRule", membershipRuleParam);
           
            //NOTE: The added rule will have an ID return. You need to store it somewhere, e.g: database
            //You need this query ID to delete this rule later
            int sccmQueryID = addResult["QueryID"].IntegerValue;


            if (addResult["ReturnValue"].IntegerValue != 0)
            {
                Debug.WriteLine("Failed to add membership rule to SCCM Collection.");
                throw new ApplicationException("Failed to add membership rule to SCCM Collection.");
            }

            //Refresh the SCCM collection membership
            Dictionary<string, object> requestRefreshParameters = new Dictionary<string, object>();
            requestRefreshParameters.Add("IncludeSubCollections", false);
            collection.ExecuteMethod("RequestRefresh", requestRefreshParameters);
        }
        else
        {
            Debug.WriteLine(string.Format("Invalid WQL query: ", query));
            throw new ApplicationException(string.Format("Invalid WQL query: ", query));
        }
    }
    catch (SmsException smsEx)
    {
        Debug.WriteLine("Failed to run queries. Error: " + smsEx.Details);
        throw;
    }
    catch (UnauthorizedAccessException accessEx)
    {
        Debug.WriteLine("Failed to authenticate. Error:" + accessEx.Message);
        throw;
    }
    finally
    {
        connectionManager.Close();
        connectionManager.Dispose();
    }

}

Delete Membership From Collection

Similar concept in adding membership to collection. One thing to take note is the SCCM Query ID to be passed to the DeleteMembershipRule method.

The SCCM Query ID was obtained during AddMembershipRule method from above code (highlighted yellow).

public void DeleteSccmCollectionRule(string sccmCollectionID, int sccmQueryID)
{
    SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
    WqlConnectionManager connectionManager = new WqlConnectionManager(namedValues);

    if (string.IsNullOrWhiteSpace(sccmCollectionID))
        throw new ArgumentException("The parameter collectionID value cannot be null or empty or whitespace.");

    try
    {
        connectionManager.Connect(this.SccmServerName);
        WqlResultObject collection = (WqlResultObject)connectionManager.GetInstance("SMS_Collection.CollectionID='" + sccmCollectionID + "'");

        //Create collection rule query instance
        IResultObject rule = connectionManager.CreateInstance("SMS_CollectionRuleQuery");
        rule["QueryID"].IntegerValue = sccmQueryID;

        //Add the rule into a parameter object
        var membershipRuleParam = new Dictionary<string, object>();
        membershipRuleParam.Add("collectionRule", rule);

        //Delete existing rule from SCCM collection
        IResultObject deleteResult = collection.ExecuteMethod("DeleteMembershipRule", membershipRuleParam);
        if (deleteResult["ReturnValue"].IntegerValue != 0)
        {
            Debug.WriteLine("Failed to delete membership rule from SCCM Collection.");
            throw new ApplicationException("Failed to delete membership rule from SCCM Collection.");
        }

        //Refresh the SCCM collection membership
        Dictionary<string, object> requestRefreshParameters = new Dictionary<string, object>();
        requestRefreshParameters.Add("IncludeSubCollections", false);
        collection.ExecuteMethod("RequestRefresh", requestRefreshParameters);
    }
    catch (SmsException smsEx)
    {
        Debug.WriteLine("Failed to run queries. Error: " + smsEx.Details);
        throw;
    }
    catch (UnauthorizedAccessException accessEx)
    {
        Debug.WriteLine("Failed to authenticate. Error:" + accessEx.Message);
        throw;
    }
    finally
    {
        connectionManager.Close();
        connectionManager.Dispose();
    }

}


That's all. Happy coding!




Send Transactional SMS with API

This post cover how to send transactional SMS using the Alibaba Cloud Short Message Service API. Transactional SMS usually come with One Tim...