SP—Angular ng-switch Directive

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

F111

Advertisements

how to replace “\” with “_” in string in c#.net

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

Let’s see how to replace “\” with “_” in string in c#.net

Since it’s not straight forward by using String.Replace method.

So let’s take move ahead with it

suppose your string item is like that
string filepath=”C:\\\\DemoFolder\\Claims”;

now use below code

filepath.Replace(@”\”, @”_”);

Output=>  “C:__DemoFolder_Claims”

 

How to check File/Directory Access for particular user and allow that user to read/Write into that directory.

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

Let’s see How to check File/Directory Access for particular user and allow that user to read/Write into that directory.

 

In order to do this perform below steps

 

Step-1)

Add this class in your project with name NetworkConnection

 

public class NetworkConnection : IDisposable
{
string _networkName;

public NetworkConnection(string networkName,
NetworkCredential credentials)
{
_networkName = networkName;

var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};

var result = WNetAddConnection2(
netResource,
credentials.Password,
credentials.UserName,
0);

if (result != 0)
{
//throw new Win32Exception(result, “Error connecting to remote share”);
}
}

~NetworkConnection()
{
Dispose(false);
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}

[DllImport(“mpr.dll”)]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);

[DllImport(“mpr.dll”)]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}

Step-2) also add this class as well NetResource

[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}

public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};

public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}

public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}

 

Step-3)

Let us see how to use it in order to check access for particular user with domain name and user  credentials:

NetworkCredential theNetworkCredential = new NetworkCredential(“username”, “password”, “domainName”);

//Here NetworkCredential  it’s from System.Net;

Now use it like

using (new NetworkConnection(FilePath , theNetworkCredential))
{

//your code goes here where you can perform operations on File
//FilePath should be with filename into it

byte[] fileData = Convert.FromBase64String(FileBinaryData);
Stream stream = new MemoryStream(fileData);

//Below code is for writing into file
using (new NetworkConnection(FilePath , theNetworkCredential))
{
File.WriteAllBytes(FilePath + item.FileName, fileData);
}
//OR

using (Stream file = File.Create(FilePath , fileData.Length, FileOptions.WriteThrough))
{
stream.CopyTo(file);

}

//Below code is for reading from file
byte[] fileBinary = null;
fileBinary = File.ReadAllBytes(FilePath);

//Use this fileBinary for rendering on UI

}

 

                                          OR

using ( new Impersonator( "YourUsername", "YourDomainname", "YourPassword" ) )
{
   //Here your all code goes which is going to perform I/O on
   // Files/Directories
//Which avoids all access path exceptions
}

 

add this class

 

refer:

https://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

 

How to download any kind of files with angularJs

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

Let’s see How to download any kind of files with angularJs

j1.png

 

j2.png

 

Note:-

Just we need to use contentType  in proper format

if (fileName.indexOf(“xls”) > -1 || fileName.indexOf(“xlsx”) > -1) {
var contentType = ‘application/octet-stream’;
} else if (fileName.indexOf(“pdf”) > -1) {
var contentType = ‘application/pdf’;
} else {
var contentType = ‘application/octet-stream’;
}
var fileDownLoadName = fileName;
var def = $q.defer();
$http.post(apiBase + “/portalDocumentDownload”, angular.toJson(helper), { responseType: ‘arraybuffer’ },
{ headers: { ‘Content-Type’: ‘application/json’ } })
.success(function (data, status, headers, config) {
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var blob = new window.Blob([data], {
type: contentType
});
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileDownLoadName);
}
else {
var file = new Blob([data], { type: contentType });
var fileURL = URL.createObjectURL(file);
var a = document.createElement(‘a’);
a.href = fileURL;
a.target = ‘_blank’;
a.download = fileDownLoadName;
document.body.appendChild(a);
a.click();
}
})

read all file names exists in perticular directory

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

 

Let’s see how to read all file names exists in perticular directory

 

dd1.png

 

string downloadpath = @”C:\\1″;
DirectoryInfo dir = new DirectoryInfo(downloadpath);
var files = dir.GetFiles(“*.*”);
foreach (var file in files)
{
FilesInfo obj = new FilesInfo();
obj.FileName = file.Name;
lstFileinfo.Add(obj);
}

upload file in angular with own directive

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

 

j1

 

 

Code-

<input type=”text” class=”form-control” ng-model=”filePath” ng-file-select=”onFileSelect($files)” ng-disabled=”isBrowseDisabled”>
<label class=”input-group-btn”>
<span class=”btn btn-primary”>
Browse <input type=”file” style=”display: none;” ng-file-select=”onFileSelect($files)” ng-disabled=”isBrowseDisabled”>
</span>
</label>

 

j2

 

 

Code-

 

app.directive(“ngFileSelect“, function () {
return {
link: function ($scope, el) {
el.bind(“change”, function (e) {
$scope.file = (e.srcElement || e.target).files[0];
var path = e.target.value;
path = path.substring(0, 3);
$scope.filePath = path + $scope.file.name;
//$scope.filePath = e.target.value;
$scope.getFile();
})
}
}
})

 

 

Controller.js

j3

$scope.onLoad = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
$scope.onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
$scope.onProgress = function (reader, scope) {
return function (event) {
scope.$broadcast(“fileProgress”,
{
total: event.total,
loaded: event.loaded
});
};
};
$scope.getReader = function (deferred, scope) {
var reader = new FileReader();
reader.onload = $scope.onLoad(reader, deferred, scope);
reader.onerror = $scope.onError(reader, deferred, scope);
reader.onprogress = $scope.onProgress(reader, scope);
return reader;
};
$scope.readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = $scope.getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};

 

j4

 

$scope.getFile = function () {
$scope.progress = 0;
$scope.readAsDataURL($scope.file, $scope)
.then(function (result) {
$scope.xslData = result; // result This is Binary Data
$scope.uploadedDocName = $scope.file.name;
$scope.fileInfodetails = “File name: ” + $scope.filePath + ” ” + $scope.file.size + ” ” + “Bytes”;
//$scope.fileDetails = $scope.filePath;
});
};

Upload Multiple files in angular js with collecting binary data of each of them

R(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

 

Let’s see how to collect binary data of each file which is uploaded through input type files

 

HTML CODE:

1.png
<input type=”file” name=”files” id=”files” multiple onchange=”angular.element(this).scope().getDocs(this)”>

<button id=”btnSubmit” data-ng-click=”vm.saveDocs()”>Submit</button>

 

controller.js code=>

 

2.png

 

 Code-

$scope.getDocs = function () {
vm.data = ‘none’;
var len = document.getElementById(‘files’).files.length;
for (var i = 0; i < len; i++) {
var filesInfo = document.getElementById(‘files’).files[i],
r = new FileReader();
var fileName = filesInfo.name;
var fileSize = filesInfo.size;
var fileType = filesInfo.type;
var re = /(?:\.([^.]+))?$/;
var fileExtension = re.exec(filesInfo.name)[1];

if (vm.filesUploadInfo.length == 0) {
vm.filesUploadInfo.push({
FileId: i,
FileName: fileName,
FileSize: fileSize,
FileType: fileType,
FileExtension: fileExtension
});
}
else {
var existingFiles = Enumerable.From(vm.filesUploadInfo).Where(function (x) { return x.FileName == fileName }).ToArray();
if (existingFiles.length == 0) {
vm.filesUploadInfo.push({
FileId: vm.filesUploadInfo.length,
FileName: fileName,
FileSize: fileSize,
FileType: fileType,
FileExtension: fileExtension
});
}
}
}
vm.filesData = “”;
getColumnsUploadedDocs();
vm.portalUploadDocsData.data(vm.filesUploadInfo);
}

 

aq1

 

 

Code-

//QQ1
var binaryData = null;
$scope.onLoad = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
$scope.onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
$scope.onProgress = function (reader, scope) {
return function (event) {
scope.$broadcast(“fileProgress”,
{
total: event.total,
loaded: event.loaded
});
};
};
$scope.getReader = function (deferred, scope) {
var reader = new FileReader();
reader.onload = $scope.onLoad(reader, deferred, scope);
reader.onerror = $scope.onError(reader, deferred, scope);
reader.onprogress = $scope.onProgress(reader, scope);
return reader;
};
$scope.readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = $scope.getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
//QQ2

 

aq2

 

Code-

vm.i = 0;
var k = parseInt(vm.i);

$scope.getFile = function (fileInfoDetails) {
$scope.progress = 0;
$scope.readAsDataURL(fileInfoDetails, $scope)
.then(function (result) {
binaryData = result;
createFilesBinaryDataInfo(fileInfoDetails,binaryData);
});
};

function saveDocs() {
if (isValidData()) {
vm.i = 0;
vm.data = ‘none’;
vm.filesInfo = [];
var len = document.getElementById(‘files’).files.length;
for (var i = 0; i < len; i++) {
var filesInfo = document.getElementById(‘files’).files[i];
$scope.getFile(filesInfo);
}
}
}

 

aq3

 

CODE-

 

function createFilesBinaryDataInfo(filesInfo, binaryData)
{
k = parseInt(vm.i);
var fileName = filesInfo.name;
var fileType = filesInfo.type;
var fileSize = filesInfo.size;
var re = /(?:\.([^.]+))?$/;
var fileExtension = re.exec(filesInfo.name)[1];
var binaryFileInfo = binaryData;
var existingFiles = Enumerable.From(vm.filesInfo).Where(function (x) { return x.FileName == fileName }).ToArray();
if (existingFiles.length == 0) {
var tmpParam = {
FileName: fileName,
FileType: fileType,
FileSize: fileSize,
FileExtension: fileExtension,
FileBinaryData: binaryFileInfo
};
vm.filesInfo.push(tmpParam);
}
k++;
vm.i = k;
senduploadedDOcs();
}

 

Let’s see how to send it to the WebAPI Controller through [FromBody]

 

//controller.js

bt4

Code-

 

function senduploadedDOcs()
{
if (document.getElementById(‘files’).files.length == vm.filesInfo.length) {
vm.selectedDocTypeId = angular.element(“#drpUploadType option:selected”).val();
vm.SelectedDocTypeName = angular.element(“#drpUploadType option:selected”).text();
vm.SelectedDocTypeName = vm.SelectedDocTypeName.trim();
vm.claimPatientFirstName = vm.claimPatientFirstName.trim();
vm.claimPatientLastName = vm.claimPatientLastName.trim();
vm.claimMemberId = vm.claimMemberId.trim();
vm.claimNumber = vm.claimNumber.trim();

if (vm.claimDOSFrom.length > 0 && isNaN(Date.parse(vm.claimDOSFrom)))
vm.claimDOSFrom = “”;

var currentFselectedFiles = vm.filesInfo;

if (vm.claimPatientFirstName.length > 0 ||
vm.claimPatientLastName.length > 0 ||
vm.claimMemberId.length > 0 ||
vm.claimNumber.length > 0 ||
vm.claimDOSFrom ||
vm.selectedDocTypeId ||
vm.filesInfo)
dataservice.uploadPortaldocs(vm.selectedDocTypeId, vm.SelectedDocTypeName,vm.claimPatientFirstName, vm.claimPatientLastName, vm.claimMemberId, vm.claimNumber,
vm.claimDOSFrom, vm.filesInfo).then(function (response) {
if (response.length > 0) {

} else {

}
}, function () {
logger.error(‘Failed Getting Claim Search Results’, ”, ‘Member API’);
});
}
}

 

 

 

service.js

 

var IdentityDTO = {
UserId: $rootScope.userProfile.userId,
SelectedOrganizationId: $rootScope.userProfile.selectedRCMOrg.organizationIdField,
SelectedCrmClientId: $rootScope.userProfile.selectedRCMOrg.crmClientIdField,
UserName: $rootScope.userProfile.firstName + ‘ ‘ + $rootScope.userProfile.lastName
};

var helper = {
user: IdentityDTO,
param: ClaimPortalDocsDTO,
filesInfo: filesInfo,
}

var def = $q.defer();
$http.post(apiBase + “/portalDocumentUpload“, angular.toJson(helper),
{ headers: { ‘Content-Type’: ‘application/json’ } })
.success(function (data, status, headers, config) {

}

bt2

 

APIController.cs

 

public class PortalDocumentUploadController : ApiController
{
public class ClaimPortalDocsDTO
{
public int SelectedDocTypeId { get; set; }
public string SelectedDocTypeName { get; set; }
public string PatientFirstName { get; set; }
public string PatientLastName { get; set; }
public string MemberId { get; set; }
public string ClaimNumber { get; set; }
public DateTime? DOSFrom { get; set; }
public Guid ClientId { get; set; }
}
public class FilesInfo
{
public string FileName { get; set; }
public string FileType { get; set; }
public int FileSize { get; set; }
public string FileExtension { get; set; }
// public byte[] FileBinaryData { get; set; } //Won’t works
public string FileBinaryData { get; set; }
}
public class ClaimPortalDocsHelper
{
public UserIdentity user { get; set; }
public ClaimPortalDocsDTO param { get; set; }
public List<FilesInfo> filesInfo { get; set; }
}
public class UserIdentity
{
public int UserId { get; set; }
public int SelectedOrganizationId { get; set; }
public Guid SelectedCrmClientId { get; set; }
}
// Handle CORS options pre-flight check
[AllowAnonymous]
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

[Authorize]
public HttpResponseMessage Post([FromBody]ClaimPortalDocsHelper helper)
{
HttpResponseMessage resp;
resp = Request.CreateResponse(HttpStatusCode.OK);
return resp;
}

}

 

bt3

 

Let’s see in Debug mode ,How data comes to WebAPI Controller

bt5

 

aq4

 

Now in controller.cs do below changes to get exact binary Data

h1

[Authorize]
public HttpResponseMessage Post([FromBody]ClaimPortalDocsHelper helper)
{
HttpResponseMessage resp;
resp = Request.CreateResponse(HttpStatusCode.OK);
List<FilesInfo> filesInfo = helper.filesInfo;
for (var i = 0; i < filesInfo.Count;i++ )
{
string fileType = filesInfo[i].FileType;
string fContent = filesInfo[i].FileBinaryData;
fContent = fContent.Replace(fileType, String.Empty);
fContent = fContent.Replace(“data:;base64,”, String.Empty);
filesInfo[i].FileBinaryData = fContent;
}

resp = Request.CreateResponse(HttpStatusCode.OK);
return resp;
}

 

h2.png

 

 

h3

 

Now let’s see how to write this code to Local Drive or Path:

hg1.png

 

CODE

[Authorize]
public HttpResponseMessage Post([FromBody]ClaimPortalDocsHelper helper)
{
HttpResponseMessage resp;
resp = Request.CreateResponse(HttpStatusCode.OK);
List<FilesInfo> filesInfo = helper.filesInfo;
for (var i = 0; i < filesInfo.Count;i++ )
{
string fileType = filesInfo[i].FileType;
string fContent = filesInfo[i].FileBinaryData;
fContent = fContent.Replace(fileType, String.Empty);
fContent = fContent.Replace(“data:;base64,”, String.Empty);
byte[] fileData = Convert.FromBase64String(fContent);
//Code indicates how to write files on local drive
string filePath = @”C:\\1\\” + filesInfo[i].FileName;
Stream stream = new MemoryStream(fileData);
using (Stream file = File.Create(filePath))
{
stream.CopyTo(file);
}

//Stream stream = new MemoryStream(fileData);
//using (Stream file = File.Create(filePath))
//{
//stream.CopyTo(file);
//}

//for above line

//OR

//You can use

File.WriteAllBytes(filePath , fileData);
}

resp = Request.CreateResponse(HttpStatusCode.OK);
return resp;
}