Adding remote URL with the JGit API - jgit

Is there a way to clone from a remote URL using JGit API in which I can somewhere change the origin which it takes by default and make it as origin2, as at origin there is another remote configured?

You can use CloneCommand::setRemote() to change the remote name of the repository that is about to be cloned. By default, it is named origin.
You can also change the remote name after it was added by directly manipulating the Git configuration:
Repository repository = ...;
String oldName = "origin";
String newName = "other-origin";
StoredConfig config = repository.getConfig();
Set<String> names = config.getNames( ConfigConstants.CONFIG_REMOTE_SECTION, oldName );
for( String name : names ) {
String value = config.getString( ConfigConstants.CONFIG_REMOTE_SECTION, oldName, name );
config.setString( ConfigConstants.CONFIG_REMOTE_SECTION, newName, name, value );
}
config.unsetSection( ConfigConstants.CONFIG_REMOTE_SECTION, oldName );
config.save();
In order to add a new remote, use the RemoteAddCommand like this:
git.remoteAdd().setName( "new-remote" ).setUri( new URIish( "..." ) ).call();

Related

Azure Resource Manager DNS: Sample code to create a DNS record

I'm currently trying to move out from using old Microsoft.Azure.Management.Dns package to the new Azure.ResourceManager.Dns.
However I've been having issues in our code that creates Dns records such as an Arecord.
I've tried to go through the official documentation https://learn.microsoft.com/en-us/dotnet/api/azure.resourcemanager.dns.dnsarecordcollection.createorupdate?view=azure-dotnet
But the classes that represent an Arecord are either read only or private so I have no idea how to update this simple lines:
RecordSet set = DnsManagementClient.client.RecordSets.Get(resourceGroupName, zone, recordSetName, RecordType.A);
set.ARecords = set.ARecords ?? new List<ARecord>();
set.ARecords.Add(new ARecord(ipAddress));
DnsManagementClient.client.RecordSets.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, zone, recordSetName, RecordType.A, set, ifNoneMatch: "*");
Currently documentation only talks about Zones, can an example be added to the official documentation on how to add or update a DNS record (A,CNAME,etc..)
https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/dns/Azure.ResourceManager.Dns
I'm expecting a method to create an A record that let's you specify an IP address, and currently all the classes that potentially can be used to do that are either read-only or internal.
DnsARecordData has an internal list of Arecords, DnsARecordData.DnsARecords is where we can invoke the Add method to create the record. The reason DnsARecordData doesn't have a setter method is due to the .Net framework design guideline..
An example of how to create an A record using Azure.Resourcemanager.Dns can be found here:
// Create or update A record
string myARecordName = "myrecord";
DnsARecordData dnsARecordData = new() {TtlInSeconds = (long)TimeSpan.FromHours(1).TotalSeconds};
dnsARecordData.DnsARecords.Add(new DnsARecordInfo { IPv4Address = IPAddress.Parse("127.0.0.1") });
DnsARecordCollection dnsARecordCollection1 = dnsZoneResource.GetDnsARecords();
dnsARecordCollection1.CreateOrUpdate(WaitUntil.Completed, myARecordName, dnsARecordData);
// Create or update CName pointing to A record
string myCnameName = "mycname";
DnsCnameRecordData dnsCnameRecordData = new() { Cname = $"{myARecordName}.{DnsZone}", TtlInSeconds = (long)TimeSpan.FromMinutes(10).TotalSeconds, };
DnsCnameRecordCollection cnameRecordCollection = dnsZoneResource.GetDnsCnameRecords();
cnameRecordCollection.CreateOrUpdate(WaitUntil.Completed, myCnameName, dnsCnameRecordData);
I tried in my environment and got below results:
You can create A record set using Azure.ResourceManager.Dns package. The version of NuGet package is beta-1.
NuGet Package:
Azure.ResourceManager.Dns 1.0.0 beta-1
Code:
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Dns;
using Azure.ResourceManager.Resources;
using System.Net;
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
// first we need to get the resource group
string rgName = "rg-name";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName);
string dnsZoneName = "dns name";
DnsZoneCollection dnsZoneCollection = resourceGroup.GetDnsZones();
DnsZoneData data1 = new DnsZoneData("Global")
{
};
ArmOperation<DnsZoneResource> lro = await dnsZoneCollection.CreateOrUpdateAsync(WaitUntil.Completed, dnsZoneName, data1);
DnsZoneResource dnsZone = lro.Value;
RecordSetACollection recordSetACollection = dnsZone.GetRecordSetAs();
string name = "cname1";
var parm = new ARecordSetData();
parm.TTL =600;
parm.ARecords = new List<ARecord>();
parm.ARecords.Add(new ARecord("1.2.3.4"));
ArmOperation<RecordSetAResource> recordSetAResource = recordSetACollection.CreateOrUpdate(WaitUntil.Completed, name,parm);
RecordSetAResource recordSetAs = recordSetAResource.Value;
Console:
Portal:
For more reference:
azure-sdk-for-net/Sample2_ManagingRecordSetPtrs.md at dvbb-mgmt-track2-dns-2 ยท dvbb/azure-sdk-for-net (github.com)

Dynamic FTP Folder pipeline

I'm trying to set Dynamically the output folder of an FTP location.
Assignment, for each customer I need to create a separate folder to store an Excel file and / or XML file.
What I've tried
Created a Custom Pipeline Component to set all the required Properties into a FTP send port.
Tried the same pipeline into a Dynamic Send Port
For testing tried the code in an Orchestration.
What I've noticed:
When I send through the FTP Send Port the properties won't be overridden by the custom pipeline properties.
When I send through the Dynamic I always get the following error
A failure was encountered while transmiting the message
Even when I'm trying to set the properties into the Orchestration I get the same error.
Also when I'm trying to send through the Dynamic Send Port I notice that the pipeline component is not touched.
Execute code part of the custom pipeline component
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage inputMessage)
{
Guid callToken = TraceManager.PipelineComponent.TraceIn(CLASSNAME + ".Execute() - Start", pipelineContext.PipelineID, pipelineContext.PipelineName, pipelineContext.StageID);
if (!this.Active)
{
TraceManager.PipelineComponent.TraceOut(callToken, CLASSNAME + ".Execute() - Pipeline component is not active!");
return inputMessage;
}
try
{
string completeFTPUri = null;
string fileName = null;
string accountNumber = Convert.ToString(inputMessage.Context.Read(PROP_ACCOUNTNUMBER.Name.Name, PROP_ACCOUNTNUMBER.Name.Namespace));
if (!string.IsNullOrWhiteSpace(accountNumber))
this.Folder = string.Format("{0}/{1}", this.Folder, accountNumber);
if (!string.IsNullOrWhiteSpace(this.Folder))
completeFTPUri = string.Format("ftp://{0}:21/{1}", this.FTPUri, this.Folder);
else
completeFTPUri = this.FTPUri;
if (!UseDefaultFilename)
{
string receiveFilename = null;
receiveFilename = Convert.ToString(inputMessage.Context.Read(FTP_RECEIVED_FILENAME.Name.Name, FTP_RECEIVED_FILENAME.Name.Namespace));
if (!string.IsNullOrWhiteSpace(receiveFilename))
fileName = Path.GetFileName(receiveFilename);
}
if (string.IsNullOrWhiteSpace(fileName))
{
if (string.IsNullOrWhiteSpace(this.Filename))
fileName = DEFAULT_FILENAME;
else
fileName = this.Filename;
}
if (fileName.Contains("{0") || fileName.Contains("{1"))
{
fileName = string.Format(fileName, DateTime.Now, inputMessage.MessageID);
}
if (!string.IsNullOrWhiteSpace(this.Folder))
{
//inputMessage.Context.Write(FTP_BEFORE_PUT.Name.Name, FTP_BEFORE_PUT.Name.Namespace, string.Format("MKDIR {0}", string.Format("ftp://{0}:21/{1}", this.FTPUri, this.Folder)));
inputMessage.Context.Promote(FTP_BEFORE_PUT.Name.Name, FTP_BEFORE_PUT.Name.Namespace, string.Format("MKDIR {0}", completeFTPUri));
}
//inputMessage.Context.Write(OUTBOUND_TRANSPORT_LOCATION.Name.Name, OUTBOUND_TRANSPORT_LOCATION.Name.Namespace, completeFTPUri);
//inputMessage.Context.Write(FILE_RECEIVED_FILENAME.Name.Name, FILE_RECEIVED_FILENAME.Name.Namespace, fileName);
//inputMessage.Context.Write(FTP_USERNAME.Name.Name, FTP_USERNAME.Name.Namespace, _userName);
//inputMessage.Context.Write(FTP_PASSWORD.Name.Name, FTP_PASSWORD.Name.Namespace, _password);
inputMessage.Context.Promote(OUTBOUND_TRANSPORT_LOCATION.Name.Name, OUTBOUND_TRANSPORT_LOCATION.Name.Namespace, completeFTPUri);
inputMessage.Context.Promote(OUTBOUND_TRANSPORT_TYPE.Name.Name, OUTBOUND_TRANSPORT_TYPE.Name.Namespace, "FTP");
inputMessage.Context.Promote(FILE_RECEIVED_FILENAME.Name.Name, FILE_RECEIVED_FILENAME.Name.Namespace, fileName);
inputMessage.Context.Promote(FTP_USERNAME.Name.Name, FTP_USERNAME.Name.Namespace, this.UserName);
inputMessage.Context.Promote(FTP_PASSWORD.Name.Name, FTP_PASSWORD.Name.Namespace, this.Password);
}
catch (Exception ex)
{
TraceManager.PipelineComponent.TraceError(ex, false, callToken);
throw new Exception(CLASSNAME + ".Execute() - Failed to set the filename.", ex);
}
TraceManager.PipelineComponent.TraceOut(callToken, CLASSNAME + ".Execute() - Finished.");
return inputMessage;
}
EDIT:
After trying a lot this morging an update.
When I try to Send Dynamicly through the Static SendPort I keep the same issue.
When I try to Send Dynamicly through a Dynamic SendPort I'm getting different error:
Inner exception: The value assigned to property 'Microsoft.XLANGs.BaseTypes.Address' is not valid: 'FTP URI'.
I don't know what the best solution is to resolve this issue.
I can also write everything to a helper class en try to send through C# code. But I want to use the force of BizTalk and want to be able to enable en disable ports when necessary. That's the main reason.
I'm not afraid to write custom pipeline components or somthing else, so if someone could help. PLEASE
Code of the Message Assign of the Orchestration
MsgPublishArticleMessage = MsgFullArticleMessage;
MsgPublishArticleMessage(*) = MsgFullArticleMessage(*);
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Domain) = "ArticleMessage";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Service) = "PricatService";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Action) = "PublishPricatXLSX";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Version) = "1.0";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.AccountNumber) = articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportLocation) = "ftp://URI:21/Pricat/" + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportType) = "FTP";
MsgPublishArticleMessage(FTP.Password) = "********";
MsgPublishArticleMessage(FTP.UserName) = "UserName";
MsgPublishArticleMessage(FTP.BeforePut) = "MKDIR " + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(FTP.ReceivedFileName) = Destil.BizTalk.ArticleMessage.Components.OrchestrationHelper.CreateReceivedFileName(articleMessageRequest, ".xlsx");
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "FTPURI";
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.TransportType) = "FTP";
MsgPublishArticleMessage(BTS.IsDynamicSend) = true;
EDIT 2:
When I change the Message Assingment to below code I can send the file to a dynamic folder.
The only problem I'm running into now:
When the Folder already exist I'm getting a failure.
Does anyone know what FTP command I need to use to create a Folder only if it don't exist?
I've try'ed the following commands
MDK -p /Pricat/AccountNumber;
MDK /Pricat/AccountNumber;
if not exist "/Pricat/AccountNumber" MDK /Pricat/AccountNumber
Changed code of message assign in the orchestration
MsgPublishArticleMessage = MsgFullArticleMessage;
MsgPublishArticleMessage(*) = MsgFullArticleMessage(*);
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Domain) = "ArticleMessage";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Service) = "PricatService";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Action) = "PublishPricatXLSX";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Version) = "1.0";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.AccountNumber) = articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportLocation) = "ftp://URI:21/Pricat/" + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportType) = "FTP";
MsgPublishArticleMessage(FTP.Password) = "*********";
MsgPublishArticleMessage(FTP.UserName) = "username";
MsgPublishArticleMessage(FTP.BeforePut) = "MKD Pricat/" + articleMessageRequest.AccountNumber + "; CWD Pricat/" + articleMessageRequest.AccountNumber;
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "ftp://URI:21/" + DOMAIN.BizTalk.ArticleMessage.Components.OrchestrationHelper.CreateReceivedFileName(articleMessageRequest, ".xlsx");
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.TransportType) = "FTP";
MsgPublishArticleMessage(BTS.IsDynamicSend) = true;
From the code snippet you have provided, can you check the below line.
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "FTPURI";
You have declared FTPURI as a variable and assigning a constant string to the address. This might explain the error -
Inner exception: The value assigned to property 'Microsoft.XLANGs.BaseTypes.Address' is not valid: 'FTP URI'.
When overwriting static send port properties you have to give adapter know that it should use message properties instead of port properties.
Set IsDynamicSend property to true
inmsg.Context.Promote("IsDynamicSend", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);

AX 2012 - Get Instance Name not Server Name in X++

Is it possible to get the Instance Name instead of the Server Name in X++?
The attached image shows the field I am looking for:
When I use xSession.AOSName(); it returns the Server Name and when I use sysServerSessions..Instance_Name; an empty string is returned. The Instance_Name field only has "01" in the database so it would still be incorrect if it did return a value.
The Instance name (optional), I believe is just the folder name and the service display name. So when you create multiple instances, it creates a folder C:\Program Files\Microsoft Dynamics AX\60\Server\[InstanceName]\, and then an AOS service with that instance display name.
If you really want it, you could enumerate the folder and parse it using a regular expression or any number of other methods. To enumerate the folder, create this server static method somewhere and call it:
static server FilenameOpen pathServer()
{
return xInfo::directory(DirectoryType::Bin);
}
There is also a ServerId, which I don't think is the same as the Instance Name, but it's in the SysServerConfig table:
while select sysServerConfig
{
info(strFmt("%1", sysServerConfig.ServerId));
}
And the ServerId is a derived value from the AOSId and name, etc. You can see how it's derived in this method:
\Data Dictionary\Tables\SysServerConfig\Methods\delete
Below is the added logic to Alex's answer to get the Instance Name.
static server str getAOSInstanceName()
{
str serverPath;
str instanceName;
int fullPathLen;
int serverNameEnd;
int instanceNameStart;
//Get the full path of the AOS Server install.
serverPath = xInfo::directory(DirectoryType::Bin);
fullPathLen = strLen(serverPath);
//Get the location of where the Instance Names Ends. "-5" represents "\bin\" in the full path.
serverNameEnd = fullPathLen - 5;
//Get the location where the Instance Name Starts - 1.
instanceNameStart = strFind(serverPath, #"\", serverNameEnd, - fullPathLen);
//Get the Instance Name.
instanceName = subStr(serverPath, instanceNameStart + 1, serverNameEnd - serverNameStart);
return instanceName;
}

Resolve path of IVersionableHandle in RTC

How to get path of file which isn't in newest version but is a part of previous changelist in RTC scm.
All I could achieve so far is this:
IFileItemHandle fileItemHandle = (IFileItemHandle) IFileItem.ITEM_TYPE.createItemHandle(change.afterState().getItemId(), change.afterState().getStateId());
file = versionableManager.fetchCompleteState(fileItemHandle, monitor);
if (file instanceof IFolder) {
IFolder folder = (IFolder) file;
relativePath = getFilePath(file, workspaceConnection.configuration(changeSet.getComponent()), monitor);
fileName = folder.getName();
} else {
relativePath = getFilePath(file, workspaceConnection.configuration(changeSet.getComponent()), monitor);
fileName = ((FileItem) file).getName();
}
Where getFilePath is:
private String getFilePath(IVersionableHandle folder, IConfiguration config, IProgressMonitor monitor, Boolean searchInHistory) throws TeamRepositoryException {
List lst = new ArrayList<IVersionableHandle>(), ancestors;
lst.add(folder);
if (searchInHistory) {
ancestors = config.determineAncestorsInHistory(lst, monitor);
} else {
ancestors = config.locateAncestors(lst, monitor);
}
return getFullPath(ancestors);
}
private String getFullPath(List ancestor) throws TeamRepositoryException {
String directoryPath = "";
for (Object ancestorObj : ancestor) {
IAncestorReport ancestorImpl = (IAncestorReport) ancestorObj;
for (Object nameItemPairObj : ancestorImpl.getNameItemPairs()) {
INameItemPair nameItemPair = (INameItemPair) nameItemPairObj;
String pathName = nameItemPair.getName();
if (pathName != null && !pathName.equals("")) {
directoryPath = directoryPath + "\\" + pathName;
}
}
}
return directoryPath;
}
Unfortunately it doesn't work perfectly. If filename is changed in following changelists like on this example:
Changelist 1:
add file: src/newFile.java
Changelist 2:
modify file: src/newFile.java
Changelist 3:
rename file: src/newFile.java -> src/newFile_rename.java
The relative path resolved in first changelist would be:
src/newFile_rename.java
instead of
src/newFile.java
How to make it works good?
While the javadoc for IConfiguration.determineAncestorsInHistory doesn't specify, the server side equivalent IScmService.configurationDetermineAncestorsInHistory (which is what ends up being called) says this in the javadoc:
* #param versionableItemHandles
* a list of versionable items; only the item ids are needed;
* must not be <code>null</code>
Basically, the determineAncestorsInHistory is not looking at the state id on the file handles, it only looks at the item id.
The particular state of the file that will be considered is determined by the configuration. This is mostly because while the state of the file in the changeset will tell you the name of that file, it does not tell you the name of the parent folder. That will depend on the state of the folder that is present in the workspace at a particular time and could be different for different workspaces
You basically need to get an IConfiguration that represents your workspace at the time the change set was accepted/created.
The way I see to do this is to get the IWorkspaceConnection.changeHistory(component) (this is actually defined on IFlowNodeConnection). You will need to walk back through the histories by calling IChangeHistory.previousHistory(monitor) until you find one that contains your changeset in IChangeHistory.recent(monitor).
Once you find the appropriate IChangeHistory use IChangeHistory.configuration() for the determineAncestorsInHistory call.
Note that this configuration represents the state of the workspace at the end of that particular IChangeHistory, so to be completely accurate you would need to inspect the changesets that occur after your change in the IChangeHistory.recent to see if any of them modified your file name (or also any of the containing folders' file names).
(Another alternative is to use the history configuration 1 previous to the history that contains your changeset, and then look at the effects of the changes that happen before your change)

Upload files directly to Amazon S3 from ASP.NET application

My ASP.NET MVC application will take a lot of bandwidth and storage space. How can I setup an ASP.NET upload page so the file the user uploaded will go straight to Amazon S3 without using my web server's storage and bandwidth?
Update Feb 2016:
The AWS SDK can handle a lot more of this now. Check out how to build the form, and how to build the signature. That should prevent you from needing the bandwidth on your end, assuming you need to do no processing of the content yourself before sending it to S3.
If you need to upload large files and display a progress bar you should consider the flajaxian component.
It uses flash to upload files directly to amazon s3, saving your bandwidth.
The best and the easiest way to upload files to amazon S3 via asp.net . Have a look at following blog post by me . i think this one will help. Here i have explained from adding a S3 bucket to creating the API Key, Installing Amazon SDK and writing code to upload files. Following are are the sample code for uploading files to amazon S3 with asp.net C#.
using System
using System.Collections.Generic
using System.Linq
using System.Web
using Amazon
using Amazon.S3
using Amazon.S3.Transfer
///
/// Summary description for AmazonUploader
///
public class AmazonUploader
{
public bool sendMyFileToS3(System.IO.Stream localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
{
// input explained :
// localFilePath = we will use a file stream , instead of path
// bucketName : the name of the bucket in S3 ,the bucket should be already created
// subDirectoryInBucket : if this string is not empty the file will be uploaded to
// a subdirectory with this name
// fileNameInS3 = the file name in the S3
// create an instance of IAmazonS3 class ,in my case i choose RegionEndpoint.EUWest1
// you can change that to APNortheast1 , APSoutheast1 , APSoutheast2 , CNNorth1
// SAEast1 , USEast1 , USGovCloudWest1 , USWest1 , USWest2 . this choice will not
// store your file in a different cloud storage but (i think) it differ in performance
// depending on your location
IAmazonS3 client = new AmazonS3Client("Your Access Key", "Your Secrete Key", Amazon.RegionEndpoint.USWest2);
// create a TransferUtility instance passing it the IAmazonS3 created in the first step
TransferUtility utility = new TransferUtility(client);
// making a TransferUtilityUploadRequest instance
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
{
request.BucketName = bucketName; //no subdirectory just bucket name
}
else
{ // subdirectory and bucket name
request.BucketName = bucketName + #"/" + subDirectoryInBucket;
}
request.Key = fileNameInS3 ; //file name up in S3
//request.FilePath = localFilePath; //local file name
request.InputStream = localFilePath;
request.CannedACL = S3CannedACL.PublicReadWrite;
utility.Upload(request); //commensing the transfer
return true; //indicate that the file was sent
}
}
Here you can use the function sendMyFileToS3 to upload file stream to amazon S3.
For more details check my blog in the following link.
Upload File to Amazon S3 via asp.net
I hope the above mentioned link will help.
Look for a javascript library to handle the client side upload of these files. I stumbled upon a javascript and php example Dojo also seems to offer a clientside s3 file upload.
ThreeSharp is a library to facilitate interactions with Amazon S3 in a .NET environment.
You'll still need to host the logic to upload and send files to s3 in your mvc app, but you won't need to persist them on your server.
Save and GET data in aws s3 bucket in asp.net mvc :-
To save plain text data at amazon s3 bucket.
1.First you need a bucket created on aws than
2.You need your aws credentials like
a)aws key b) aws secretkey c) region
// code to save data at aws
// Note you can get access denied error. to remove this please check AWS account and give //read and write rights
Name space need to add from NuGet package
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
var credentials = new Amazon.Runtime.BasicAWSCredentials(awsKey, awsSecretKey);
try`
{
AmazonS3Client client = new AmazonS3Client(credentials, RegionEndpoint.APSouth1);
// simple object put
PutObjectRequest request = new PutObjectRequest()
{
ContentBody = "put your plain text here",
ContentType = "text/plain",
BucketName = "put your bucket name here",
Key = "1"
//put unique key to uniquly idenitify your data
// you can pass here any data with unique id like primary key
//in db
};
PutObjectResponse response = client.PutObject(request);
}
catch(exception ex)
{
//
}
Now go to your AWS account and check the bucket you can get data with "1" Name in the AWS s3 bucket.
Note:- if you get any other issue please ask me a question here will try to resolve it.
To get data from AWS s3 bucket:-
try
{
var credentials = new Amazon.Runtime.BasicAWSCredentials(awsKey, awsSecretKey);
AmazonS3Client client = new AmazonS3Client(credentials, RegionEndpoint.APSouth1);
GetObjectRequest request = new GetObjectRequest()
{
BucketName = bucketName,
Key = "1"// because we pass 1 as unique key while save
//data at the s3 bucket
};
using (GetObjectResponse response = client.GetObject(request))
{
StreamReader reader = new
StreamReader(response.ResponseStream);
vccEncryptedData = reader.ReadToEnd();
}
}
catch (AmazonS3Exception)
{
throw;
}

Resources