Get list of files in a specific Netsuite folder - c#

I'm trying to retrieve a list of files in a specific folder in the file cabinet. When I execute the search, I'm given all files in the specified folder and all folders underneath that folder. I've tried with FileSearchBasic and FileSearchAdvanced, both give me the same results.
Is there a way to get only files in the specified folder id?
var search = new FileSearchBasic
{
folder = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
#operatorSpecified = true,
searchValue = new[] { new RecordRef
{
internalId = "1234"
}}
}
};
var result = ns.search(search);
if (result.status.isSuccess)
{
foreach (var record in result.recordList)
{
if (record is File file)
{
Console.WriteLine($"{file.folder.internalId} - {file.name}");
}
}
}
This code results in the following list where folder 1236 is a sub folder of folder 1234
1234 - lodash.js
1234 - dt.timer.js
1234 - dt.search.js
1234 - dt.customer.js
1234 - dt.safeExecute.js
1236 - processRawLocationData.js

I was able to get only the files in the specified folder by performing a FolderSearchAdvanced() and using a file join rather than a FileSearchAdvanced(). It sort of makes sense since you have to do it this way in SuiteScript as well.
Still open to alternative methods.
var search = new FolderSearchAdvanced()
{
criteria = new FolderSearch()
{
basic = new FolderSearchBasic()
{
internalId = new SearchMultiSelectField()
{
#operator = SearchMultiSelectFieldOperator.anyOf,
searchValue = new[] { searchValue },
operatorSpecified = true
},
}
},
columns = new FolderSearchRow
{
basic = new FolderSearchRowBasic()
{
internalId = new[] { new SearchColumnSelectField() },
name = new [] { new SearchColumnStringField() }
},
fileJoin = new FileSearchRowBasic()
{
internalId = new[] { new SearchColumnSelectField() },
name = new[] { new SearchColumnStringField() },
modified = new[] { new SearchColumnDateField() },
documentSize = new[] { new SearchColumnLongField() }
}
}
};
var results = ns.search(search);
if (results.status.isSuccess)
{
foreach (var result in results.searchRowList)
{
if (result is FolderSearchRow row)
{
var fileId = row.fileJoin.internalId[0].searchValue.internalId;
var fileName = row.fileJoin.name[0].searchValue;
Console.WriteLine($"{fileId} - {fileName}");
}
}
}

Related

Start or Run ECS or Fargate Task Through the C# Client Sdk

I am trying to run or start an existing task definition within ECS but the documentation is lacking and I cant seem to find any examples online. I have hit a wall and I was wondering if anyone else has done a similar thing.
I am using the AWSSDK.ECS packages.
var request = JsonConvert.DeserializeObject<Request>(record.Sns.Message);
var task = new RunTaskRequest
{
Count = 1,
NetworkConfiguration = new NetworkConfiguration
{
AwsvpcConfiguration = new AwsVpcConfiguration
{
Subnets = new List<string>() { request.SubnetId},
SecurityGroups = new List<string>() { request.SecurityGroupId},
AssignPublicIp = AssignPublicIp.DISABLED
}
},
Cluster = request.Cluster,
LaunchType = LaunchType.FARGATE,
Overrides = new TaskOverride
{
ContainerOverrides = new List<ContainerOverride>
{
new ContainerOverride
{
Name = request.ContainerName,
Environment = request.EnvironmentVariables
.Select(kvp => new Amazon.ECS.Model.KeyValuePair()
{
Name = kvp.Key,
Value = kvp.Value
}).ToList()
}
}
},
TaskDefinition = request.TaskDefinitionUri
};
await new AmazonEcsClient().RunTaskAsync(task);
Check on your task definition. If the NetworkMode is awsvpc, then you must provide NetworkConfiguration parameter. This works for me:
var runTaskRequest = new ECSModel.RunTaskRequest
{
Cluster = "cluster-name",
Count = 1,
LaunchType = LaunchType.FARGATE,
TaskDefinition = "task-definition",
NetworkConfiguration = new ECSModel.NetworkConfiguration
{
AwsvpcConfiguration = new ECSModel.AwsVpcConfiguration
{
SecurityGroups = new List<string> { "security-group" },
Subnets = new List<string> { "subnet" }
}
},
Overrides = new ECSModel.TaskOverride
{
ContainerOverrides = new List<ECSModel.ContainerOverride>
{
new ECSModel.ContainerOverride
{
Name = "container-name",
Command = new List<string>
{
// In case if you need to pass parameters to your instance:
"parameter-one", "parameter-two", "etc"
}
}
}
}
};
await new AmazonEcsClient().RunTaskAsync(runTaskRequest);

AWS SDK .NET DynamoDB ASYNC

I am trying to use AWS SDK for .NET Core.
Create a table to count views on videos.
Add a view count for a day.
Increment existing count for a day.
Query for video counts between two dates for a video.
.NET Core AWS SDK uses Async methods which are not documented in AWS. There is a feature request on their github page for this to happen.... but it is dated from last year. (https://github.com/aws/aws-sdk-net/issues/787)
CREATE THE TABLE
This works and creates a table on the AWS Console.
var ctRequest = new CreateTableRequest
{
AttributeDefinitions = new List<AttributeDefinition>()
{
new AttributeDefinition
{
AttributeName = "ViewUid",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "ViewDate",
AttributeType = ScalarAttributeType.S
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "ViewUid",
KeyType = KeyType.HASH //Partition key
},
new KeySchemaElement
{
AttributeName = "ViewDate",
KeyType = KeyType.RANGE
}
},
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 6
},
TableName = _settings.AWSDynamoDBViewCountTable
};
var response = _client.CreateTableAsync(ctRequest).Result;
UPDATE AND ITEM WITH AUTO-INCREMENT A FIELD
This, sadly, is where i hit issues. The old docs are found here under the Atomic Counter section. (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html)
Invalid ConditionExpression: Syntax error; token: \"SET\", near: \"SET
VC\"
var viewData = new Document();
viewData["ViewUid"] = videoUid; //Table entry UID
viewData["VideoId"] = videoId; // Video ID
viewData["ViewDate"] = date;
viewData["ViewCount"] = 0;
//Document result = await _viewCountTable.PutItemAsync(viewData);
Expression expr = new Expression();
expr.ExpressionStatement = "SET #VC = #VC + :val";
expr.ExpressionAttributeValues[":val"] = 1;
expr.ExpressionAttributeNames["#VC"] = "ViewCount";
var updateConfig = new UpdateItemOperationConfig() {
ConditionalExpression = expr,
ReturnValues = ReturnValues.UpdatedNewAttributes
};
var result = await _viewCountTable.UpdateItemAsync(viewData, updateConfig);
return result;
QUERY FOR DATE RANGE
Get one video's view count for a date range.
string queryTimeSpanStartString = dateFrom.ToString(AWSSDKUtils.ISO8601DateFormat);
string queryTimeSpanEndString = dateTo.ToString(AWSSDKUtils.ISO8601DateFormat);
var request = new QueryRequest
{
TableName = _settings.AWSDynamoDBViewCountTable,
KeyConditions = new Dictionary<string, Condition>()
{
{
"VideoId", new Condition()
{
ComparisonOperator = "EQ",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = videoId }
}
}
},
{
"ViewDate",
new Condition
{
ComparisonOperator = "BETWEEN",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = queryTimeSpanStartString },
new AttributeValue { S = queryTimeSpanEndString }
}
}
}
}
};
var response = await _client.QueryAsync(request);
Any help would be appreciated.
I was able to update the ViewCount with the following code:
string tableName = "videos";
var request = new UpdateItemRequest
{
Key = new Dictionary<string, AttributeValue>() { { "ViewUid", new AttributeValue { S = "replaceVideoIdhere" } } },
ExpressionAttributeNames = new Dictionary<string, string>()
{
{"#Q", "ViewCount"}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{":incr", new AttributeValue {N = "1"}}
},
UpdateExpression = "SET #Q = #Q + :incr",
TableName = tableName
};
var response = await _dynamoDbClient.UpdateItemAsync(request);
I created a table called "videos" with a partition key named "ViewUid" as string. Let me know if this works for you.

ElasticSearch filtered query _search 400 error response

I am trying to use filter with search query. Search requset works correctly without filter. But using filter I get 400 error as response.
This is type mapping:
var mapp = new
{
mappings = new
{
posts = new
{
properties = new
{
FullText = new
{
type = "string",
analyzer = "russian"
},
Title = new
{
type = "string",
analyzer = "russian"
},
PostPubDate = new
{
type = "date"
},
Link = new
{
type = "string",
index = "not_analyzed"
},
RubricsIds = new
{
type = "integer"
},
ObjectsIds = new
{
type = "integer"
},
SourceId = new
{
type = "integer"
}
}
}
}
};
This is a request to index with filtered query:
string url = "http://localhost:9200/neg_collector/posts/_search";
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var o = new
{
size = 20,
query = new
{
filtered = new
{
query = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
#bool = new
{
should = new
{
term = new
{
SourceId = sIds
}
}
}
}
}
}
};
request.Method = "POST";
var jsonObj = JsonConvert.SerializeObject(o);
var data = Encoding.UTF8.GetBytes(jsonObj);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
I want to use an array of integers to filter result with certain SourceId-s. But I got error 400.
What am I doing wrong? Thank you
So the problem was that this syntax was for elasticsearch 2 version (And it worked nice on another computer). Here I have ElasticSearch 5 and should use another was of filtering:
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
}
}
}
}
};
It is describerd HERE

NetSuite. How to select all attached files for current user (filter by InternalId)

I am using C# implementation of netsuite api from web reference com.netsuite.webservices
I released filter fileSearch.basic by name (you can see it commented) it is working fine.
Please help to write function to achieve all attached files for current user. Something is wrong in this code, it filters nothing and showing me all files as it is without any filter. Please help me.
public static void GetFileAttachmentByCustomerId(string customerId)
{
using (NetSuiteService netSuiteService = GetNetSuiteService())
{
FileSearch fileSearch = new FileSearch();
// this works fine (filter files by name)
//SearchStringField nameSearchParams = new SearchStringField
//{
// #operator = SearchStringFieldOperator.contains,
// operatorSpecified = true,
// searchValue = "some name",
//};
//fileSearch.basic = new FileSearchBasic() { name = nameSearchParams };
// this code not filter files at all
{
RecordRef nsCustomerRef = new RecordRef
{
internalId = customerId,
type = RecordType.customer,
typeSpecified = true,
};
SearchMultiSelectField shopperSearchParam = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new RecordRef[] { nsCustomerRef }
};
fileSearch.shopperJoin = new CustomerSearchBasic { internalId = shopperSearchParam };
}
SearchResult result = netSuiteService.search(fileSearch);
// Get connected objects
{
Customer customer = GetCustomerById(netSuiteService, customerId);
Account account = GetAccountById(netSuiteService, "301395"); //
Folder folder = GetFolderById(netSuiteService, "3962");
}
File file = (File)result.recordList.First();
byte[] fileContent = GetFileContentByInternalId(file.internalId);
}
}
.
Try this:
var nsCustomerRef = new RecordRef
{
internalId = "4",
type = RecordType.employee,
typeSpecified = true,
};
var currentUser = new SearchMultiSelectField()
{
operatorSpecified = true,
#operator = SearchMultiSelectFieldOperator.anyOf,
searchValue = new List<RecordRef>() {nsCustomerRef}.ToArray()
};
var fileSearchBasic = new FileSearchBasic() {owner = currentUser};
var fileSearch = new FileSearch() { basic = fileSearchBasic };
var result = netSuiteService.search(fileSearch);
var file = (File)result.recordList.First();

Creating a breadcrumb like hierarchy using LINQ

I'm building a dropbox -like application to store images.
I have a database table called Images:
ImageId [PK]
ParentImageId [FK]
Name
Path
I want to create a breadcrumb from the above structure lets say I have the following data:
Is it possible using LINQ to be able to create a breadcrumb that looks like (if I am at sub folder 2)
:
Folder 1 > Sub Folder 1 > Sub Folder 2
How do I build a query to return the desired results? Any assistance would be of great help!
With Entity Framework you can do next:
And code will look like this:
var image = db.Images.FirstOrDefault(i => i.Id == currImageId);
var imagesHierarchy = new List<Image>();
if (image != null)
{
var parent = image.Parent;
while (parent != null)
{
imagesHierarchy.Insert(0, parent);
parent = parent.Parent;
}
}
var breadcrumb = string.Join(" > ", imagesHierarchy.Select(i => i.Name));
This will do it:
var current = new Record
{ ImageId = 4, ParentImageId = 3, Name = "Sub Folder 2" };
var records = new []
{
new Record { ImageId = 1, ParentImageId = 1, Name = "Folder 1" },
new Record { ImageId = 2, ParentImageId = 1, Name = "Image 1" },
new Record { ImageId = 3, ParentImageId = 1, Name = "Sub Folder 1" },
current,
new Record { ImageId = 5, ParentImageId = 4, Name = "Sub Image" },
};
var index = records.ToDictionary(r => r.ImageId);
Func<Record, IEnumerable<Record>> traverseUp = null;
traverseUp = r =>
{
var rs = new [] { r, };
if (r.ParentImageId == r.ImageId)
{
return rs;
}
else
{
return traverseUp(index[r.ParentImageId]).Concat(rs);
}
};
var breadcrumb = String.Join(" > ", traverseUp(current).Select(r => r.Name));

Categories