Posts

Showing posts from 2019

Scrollable readonly EditView in Kotlin

In the view xml file: <EditTextandroid:id="@+id/etResult" android:layout_width="match_parent" android:layout_height="343dp" android:background="@color/backgroundColor" android:backgroundTint="#00000000" android:ems="10"android:enabled="true"android:fontFamily="sans-serif-condensed"android:gravity="start|top"android:hint="@string/blankfoldermessage"android:importantForAutofill="no"android:inputType="none"android:paddingTop="2dp"android:singleLine="false"tools:targetApi="o" />in the kotlin file (init function): etResult.keyListener = nullthis will allow the edit text to be multiline, not editable but scrollable.

Simple use of Timer in Kotlin

the code below will set the button to clickable after 30 sec:btnOk.isClickable=falseTimer().schedule(timerTask {     btnOk.isClickable=true }, 1000*30)the above code runs in a separate thread, so the UI is responsive while running this code.

Working with UI controls from Non main thread in Kotlin

import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

fun anyFunction(){ doAsync {// Normal code inside Async threadI=I+1If(I=100){uiThread { tvResult.setText =”I is now 100!!”}}//More codeIf(x==0){uiThread { tvResult.setText =”there’s some problem!”}} }}
Note: - you can include multiple uiThread inside same doAsync           - you can include multiple doAsync inside any function

Permission request pop up in android

Image
Request user to give permission to read external storage in Android - (Kotlin)if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation?if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { } else { // No explanation needed, we can request the permission.ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), READ_STORAGE_CODE); } } else { // Permission has already been granted}NOTE: READ_STORAGE_CODE is just an int constant with fix value like 1001, or 2023and is a variable in class level.

TFS -GIT CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT

Image
Problem 1)
2019-07-02T14:19:12.5157398Z fatal: unable to access 'https://tfssite.company.com/tfs/UK_ProjectCollection/SalesPortal/_git/SalesPortalWeb/': SSL certificate problem: unable to get local issuer certificate 2019-07-02T14:19:12.9764145Z ##[error]Git fetch failed with exit code: 128 2019-07-02T14:19:12.9861630Z ##[section]Finishing: Get Sources












In the TFS_Build Server or App server(if build and app server is in the same machine) >

run the script from this url: https://blog.sanjeebojha.com.np/2019/06/git-ssl-certificate-problem-unable-to.html

Once this is done, you should get another problem:

Problem 2)  CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT

2019-07-02T14:24:57.1800199Z ##[command]git -c http.extraheader="AUTHORIZATION: bearer ***" fetch --tags --prune --progress --no-recurse-submodules origin 2019-07-02T14:24:57.4540146Z fatal: unable to access 'https://tfssite.company.com/tfs/UK_ProjectCollection/SalesPortal/_git/SalesPortalWeb/…

Insert Identity Column in a table

insert an identity column in that table by using the following code:

ALTERTABLE dbo.tablename ADD AUTOID INTIDENTITY(1,1) 

MSSQL Remove duplicate Rows

Select the duplicate key values into a holding table. For example:
SELECT col1, col2, col3=count(*) INTO holdkey FROM t1 GROUP BY col1, col2 HAVING count(*) > 1 Select the duplicate rows into a holding table, eliminating duplicates in the process. For example:       SELECT DISTINCT t1.*         INTO holddups FROM t1, holdkey  WHERE t1.col1 = holdkey.col1         AND t1.col2 = holdkey.col2At this point, the holddups table should have unique PKs, however, this will not be the case if t1 had        duplicate PKs, yet unique rows (as in the SSN example above). Verify that each key in holddups is unique, and that you do not have duplicate keys, yet unique rows. If so, you must stop here and reconcile which of the rows you wish to keep for a given duplicate key value. For example, the query: SELECT col1, col2, count(*) FROM holddups GROUP BY col1, col2 should return a count of 1 for each row. If yes, proceed to step 5 below. If no, yo…

Read TFS Project name from TFS Project collection using c#

Image
Using Team foundation api.
 References:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.dll
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Client.dll
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Common.dll
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.WorkItemTracking.Client.dll


Code:
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using System;
using System.Linq;

classProgram
{privatestatic ICommonStructureService _commonStructureService;
staticvoid Main(string[] args)
{
ReadProject("https://tfssite.com/tfs/UK_ProjectCollection");
ReadProject("https://tfssite.com/tfs/IN_ProjectCollection");
Console.ReadKey();
}publicstaticvoid Rea…

GIT - SSL certificate problem: unable to get local issuer certificate

Image
Error encountered while cloning the remote repository: Git failed with a fatal error. unable to access 'https://tfssite.company.com/tfs/uk_projectcollection/SalesPortal/_git/SalesPortalWeb/': SSL certificate problem: unable to get local issuer certificate
Cloning into 'C:\Users\sojha\Source\Repos\SalesPortalWeb'... Error encountered while cloning the remote repository: Git failed with a fatal error. unable to access 'https://tfssite.company.com/tfs/uk_projectcollection/SalesPortal/_git/SalesPortalWeb/': SSL certificate problem: unable to get local issuer certificate



Solution: Open Visual Studio Command prompt
GIT provides an option to choose from OpenSSL and Secure Channel. Choosing secure channel in git global solves this issue.
Run the script:
git config --global http.sslBackend schannel

Entity Framework Core with Existing Database

Image
Entity Framework Core with Existing Database
Entity Framework Core only supports code first database aproach.
To use existing database, we'll need to reverse Engineer Model from existing Database.
Open Visual studio.Menu > tools >Nuget Package Manager > Note: All the tables in the database must have Primary key defined. else you'll get error like:
Unable to generate entity type for table 'dbo.xOrdersMBS'.
Unable to identify the primary key for table 'dbo.xActivePricesEPB'.
Unable to generate entity type for table 'dbo.xActivePricesEPB'.
Unable to identify the primary key for table 'dbo.xLeadTimePBOM'.
Unable to generate entity type for table 'dbo.xLeadTimePBOM'.


 In the console, run the below power shell commands:

Using Windows Authentication:
Scaffold-DbContext "Server=DatabaseServerAddress;Database=DatabaseName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f

Using SQL Account:
Scaffold…

EntityFramework Insert error due to PrimaryKey

MyProject.Controllers.CurrencyCodesController Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
System.Data.Entity.Infrastructure.DbUpdateException: Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation. ---> System.Data.Entity.Core.UpdateException: Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.​

Scenario:
The error occured while trying to insert the currencycodes entity to the database.
[HttpPost]
[ValidateAntiForgeryToken]
publicActionResult Create([Bind(Include = "cucCurrencyCode…

Fix for SSIS not picking correct configuration file

When there are more then one configuration file for a single package, the SSIS jobs sometimes do not automatically pick the correct configuration depending on how the settings has been made.

In the SSIS package (using Visual Studio) Make sure you've done following correctly: 1) In the package property, Set Delay Validation =  false
2) Uncheck , Enable Package Configuration.


steps for 2):
a) open the ssis package in visual studio. b) In the Control flow tab, right click on the blank space of the canvas. c) go to Package Configurations... d) uncheck Enable Package Configuartion and press Close. e) Save the ssis package and copy that to the deployed folder.

How to remove Workspace in TFS 2010-2018

This solution Works for TFS 2010+.

Open Visual studio Command prompt and run the following script.


tf workspace /delete /server:[Site:Port/path] WORKSPACENAME


for example:
tf workspace /delete /server:http://tfs.site.com:8080/tfs sanjeebPC

Use log4net for all logging in c# application

Exception logging is hugely important within an application, not just to ensure we know when an error has occured but also to help use trace back the thread to help investigate where the error originated. Our strategy is to use log4net for all our logging needs. This page helps cover the follow areas 1. Setting up logging across the entire applications 2. Including 2 appenders so we can be notified when they occur and ensure a tracable debug log file is available. Setting up your Applications for Logging Reference log4net in your applications in Global.asax under the start_application method include the following void Application_Start(object sender, EventArgs e) { // link up log4net configuration log4net.Config.XmlConfigurator.Configure(); } On the page where you wish to log information declare a new static variable in the class header log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); Whenever you wis…

Create XML from class or Object in C-Sharp

public static string SerializeObjectToXML(object item)
        {
            try
            {
                string xmlText;
                Type objectType = item.GetType();
                XmlSerializer xmlSerializer = new XmlSerializer(objectType);
                MemoryStream memoryStream = new MemoryStream();
                using (XmlTextWriter xmlTextWriter =
                    new XmlTextWriter(memoryStream, Encoding.UTF8) { Formatting = Formatting.Indented })
                {
                    xmlSerializer.Serialize(xmlTextWriter, item);
                    memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                    xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());
                    memoryStream.Dispose();
                    return xmlText;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Write(e.ToString());
                return null;
            }
        }

Powershell script to create OS disk in azure from storage account blob image file (vhd)

Powershell script to create OS disk in azure from storage account blob image file (vhd)
#Provide the subscription Id where Managed Disks will be created
$subscriptionId = 'd7x2bxx8-62xe-4xdx-xa8x-20x0x3x2x5xx'

#Provide the name of your resource group where Managed Disks will be created. 
$resourceGroupName ='MYResourceGroupName'

#Provide the name of the Managed Disk
$diskName = 'Project_Disk2'

#Provide the size of the disks in GB. It should be greater than the VHD file size.
$diskSize = '90'

#Provide the storage type for Managed Disk. PremiumLRS or StandardLRS.
$storageType = 'Premium_LRS'

#Provide the Azure region (e.g. westus) where Managed Disk will be located.
#This location should be same as the storage account where VHD file is stored
#Get all the Azure location using command below:
#Get-AzLocation
$location = 'ukwest'

#Provide the URI of the VHD file (page blob) in a storage account. Please not that this is NOT the SAS URI of the storage containe…