|
How do I check for existance or clear the contents of a SharePoint List from C# code?
I have complete the code that creates a sharepoint List from scratch, creates the columns, and loads the data that I get from an API GET query of an external database.
How do I:
check and see if the SharePoint List already exists
clear the contents of the sharepoint list
load the list with new data.
Without doing these steps, I am left with creating the list from scratch each time and giving it a unique name each time.
Is there some source of information on how to do this that I can find online? The Microsoft AI chat bot has given me some code that does not work at all.
|
|
|
|
|
|
Hi Charles,
I sure can. Editing it or presenting it in such a way where company information is no there is going to take time. The code first assumes it is creating the list for the first time and when an exception is thrown if the list already exists, it just loads the list. Here is the code
string listTitle = "TripLegs" ;
string listDescription = "This is a new list created using CSOM";
Microsoft.SharePoint.Client.List? newList = null;
Next, we use the "using" method and start a block like this:
using (var authenticationManager = new AuthenticationManager())
using (var context = authenticationManager.GetContext(site, user, password))
{
context.Load(context.Web, p => p.Title);
await context.ExecuteQueryAsync();
Console.WriteLine($"Title: {context.Web.Title}");
Web web = context.Web;
ListCreationInformation creationInfo = new ListCreationInformation();
creationInfo.Title = listTitle;
creationInfo.Description = listDescription;
creationInfo.TemplateType = (int)ListTemplateType.GenericList;
newList = web.Lists.Add(creationInfo);
THis is when the try catch block is used if an exception is NOT thrown, then we assume that we are dealing with a list that has not been created yet and the use of the ListCreationInformation class is the proper thing to do. The code in the "TRY" block proceeds to create the columns.
try
{
context.Load(newList);
context.ExecuteQuery();
Console.WriteLine("List created successfully!");
FieldCollection fields = newList.Fields;
#region ColumnHeaders
<pre> FieldCreationInformation fieldInfo_1 = new FieldCreationInformation(FieldType.Number)
{
DisplayName = "TripId",
InternalName = "TripId",
Group = "Custom Columns",
AddToDefaultView = true
};
string fieldSchema_1 = $"<Field Type='{fieldInfo_1.FieldType}' Name='{fieldInfo_1.InternalName}' DisplayName='{fieldInfo_1.DisplayName}' Group='{fieldInfo_1.Group}' />";
Field Field_1 = newList.Fields.AddFieldAsXml(fieldSchema_1, true, AddFieldOptions.DefaultValue);
Field_1.Update();
context.ExecuteQuery();
then the code generates all the columns. The example I just posted shows the creation of just the first column.
So, now we get to the Catch block which would be executed if the list already exists and we just need to access it in order to load the already existing list
}
catch (Exception ex)
{
After this is some JSON code that deals with the parsing of the code to put in the list which I am intentionally leaving out. But the code is put into a class and then from the class, it is loaded into the Sharepoint List like this:
Legs singleTripLeg = JsonSerializer.Deserialize<Legs>(inputLegsJSON);
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem newItem = newList.AddItem(itemCreateInfo);
newItem["TripId"] = singleTripLeg.TripId;
newItem["ExternalReference"] = singleTripLeg.ExternalReference;
newItem["DepartureAirportId"] = singleTripLeg.DepartureAirportId;
newItem["ArrivalAirportId"] = singleTripLeg.ArrivalAirportId;
newItem["LandedLocal"] = singleTripLeg.LandedLocal;
newItem["LandedPinned"] = singleTripLeg.LandedPinned;
newItem.Update();
context.ExecuteQuery();
So there you have it.
Now I need to know the call to clear out the SharePoint List before I load it.
|
|
|
|
|
|
using locks, from my understanding this should work as long as lock is being called on the same object.
internal static async Task Lock<T>(this T lockObject, Action DoAction) where T : class
{
await Task.Run(() => { lock(lockObject)
{
DoAction();
}});
}
|
|
|
|
|
From what I can see, the code you've provided isn't going to achieve what you might expect it to achieve. I'm going to break the logic down so you can see where the confusion lies.- The await operator here does not appear to affect the locking behaviour. It's only waiting for the Task.Run to complete.
- Inside the
Task.Run , we have a lock statement. You can think of this as running on a different thread from the caller. - Each call to this method will create a new task, which will attempt to acquire the lock independently.
The end result is multiple calls to this method could run concurrently, each in its own task, defeating the purpose of the lock. The lock will still work within each individual task, but it won't prevent multiple tasks from running simultaneously. To my mind, a better version of this would be this:
private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
internal static async Task Lock<T>(this T lockObject, Action DoAction) where T : class
{
try
{
await _semaphore.WaitAsync();
DoAction();
}
finally
{
_semaphore.Release();
}
}
|
|
|
|
|
Thanks for the hint on the using the SemaphoreSlim. This works much better than the original extension I was using.
|
|
|
|
|
From what I can see, it should work. Whilst held, the lock prevents any other thread from obtaining the lock. And the thread that's holding the lock never* yields, so nothing else can be run on the same thread.
(* Assuming DoAction doesn't do anything odd, such as point to an async void method.)
But wouldn't it be better to use a proper async-friendly lock instead?
Building Async Coordination Primitives, Part 6: AsyncLock - .NET Parallel Programming[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Within the DoAction() it performs read/write operations on a memory pointer
|
|
|
|
|
This is how the lock is being used.
public async Task<short[]> GetSamples()
{
if (!ContainsAudio())
throw new ArgumentException(nameof(G711.Alaw));
short[] samples = [];
NativePointer pointer = _nativePointer!;
await pointer.Lock(() =>
{
unsafe
{
var sampleCount = pointer.Size >> 1;
samples = new short[sampleCount];
var memoryBlock = pointer.GetMemoryBlock();
var value = (short*)memoryBlock;
for (var i = 0; i < sampleCount; i++)
{
samples[i] = *value++;
}
}
});
return samples;
}
|
|
|
|
|
I have a dot net 8.0 C# DLL project that holds a reference to a C++ .net 8.0 mixed mode DLL project.
Whenever the mixed mode project is rebuilt, then none of the projects that depend upon it will load the previous build of the mixed mode DLL. It gives a library version not found error if I try to run the previous build.
This is annoying because this happens whenever the mixed mode DLL is rebuilt, even if there are zero code changes in that project.
Just where do you think Visual Studio is managing this auto-incrementing build number that is disrupting my development feng shui?
When I open the Properties dialog for the mixed mode DLL, I can't find anything that looks like it implements an auto-incrementing build number. Remember, this would be the Properties window that is presented for native projects, not dot net projects.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
If I understand the question correctly it is not a 'version number'
A dll has a header that describes the contents. That includes things like a version number but it also includes the code type which is something like '32bit', '64bit' and 'any'. There are other thinks in there like the full name, encryption info, etc.
I think the following page discusses some of this.
PE Format - Win32 apps | Microsoft Learn[^]
|
|
|
|
|
Yes, but it would refuse to load the DLL even if there were no code changes or assembly property changes.
I think I have solved it however. There is a file in the DLL project named AssemblyInfo.cpp, and it contains an assembly attribute named AssemblyVersionAttribute. And it was set to L"1.0.*". I think this was causing the problem. The asterisk means that it should autoincrement the version number.
I changed the value to L"1.0.0" and it no longer fails to load the DLL if the DLL is rebuilt.
Thanks for reading my post and for your input!
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I've been trying to convert ulaw to alaw following a few examples that I found online. I'm able to covert the alaw to ulaw quite well but when converting back to alaw the output becomes distorted. If anyone knows a better solution please do share. Here is the code that is producing the distorted alaw.
public static NativePointer Encode(G711.Ulaw ulaw)
{
if (ulaw == null || !ulaw.ContainsAudio()) throw new Exception(nameof(ulaw));
List<byte> bytes = [];
NativePointer pointer = ulaw._nativePointer!;
byte[] result = new byte[pointer.Size];
Marshal.Copy(pointer, result, 0, pointer.Size);
foreach(byte byt in result)
{
bytes.Add(LinearToALawSample(MuLawToLinearSample(byt)));
}
return new(bytes);
static byte LinearToALawSample(short pcm_val)
{
int mask;
int seg;
byte aval;
if (pcm_val >= 0)
{
mask = 0xD5;
}
else
{
mask = 0x55;
pcm_val = (short)-pcm_val;
if (pcm_val > EncoderInfo.ALAW_MAX)
{
pcm_val = EncoderInfo.ALAW_MAX;
}
}
if (pcm_val < 256)
{
aval = (byte)(pcm_val >> 4);
}
else
{
seg = 1;
for (int i = pcm_val; i > 256; i >>= 1)
{
seg++;
}
aval = (byte)((seg << EncoderInfo.SEG_SHIFT) | ((pcm_val >> (seg + 3)) & EncoderInfo.QUANT_MASK));
}
return (byte)(((aval & EncoderInfo.SEG_MASK) ^ mask) & EncoderInfo.SIGN_BIT);
}
static short MuLawToLinearSample(byte muLaw)
{
int sign = (muLaw & EncoderInfo.SIGN_BIT) >> 7;
int exponent = (muLaw & EncoderInfo.SEG_MASK) >> 4;
int mantissa = muLaw & 0x0F;
int sample = ((mantissa << 3) + EncoderInfo.BIAS) << (exponent + 2);
return (short)(sign == 0 ? sample : -sample);
}
}
Here is the EncoderInfo class.
internal static class EncoderInfo
{
public const int BIAS = 0x84;
public const int SEG_MASK = 0x70;
public const int SIGN_BIT = 0x80;
public const int ALAW_MAX = 0xFFF;
public const int QUANT_MASK = 0xF;
public const int SEG_SHIFT = 4;
}
modified 14-Sep-24 20:37pm.
|
|
|
|
|
Disclaimer: I never tried to do any such conversion myself.
But I read in the G.711 standard:
-------------------
If a m-A conversion is followed by an A-m conversion, most of the octets are restored to their original values. Only those octets which correspond to m-law decoder output value numbers 0, 2, 4, 6, 8, 10, 12, 14 are changed (the numbers being increased by 1). Moreover, in these octets, only bit No. 8 (least significant bit in PCM) is changed. Accordingly, the double conversion m-A-m is transparent to bits Nos. 1-7.
Similarly, if an A-m conversion is followed by a m-A conversion, only the octets corresponding to A-law decoder output value numbers 26, 28, 30, 32, 45, 47, 63 and 80 are changed. Again, only bit No. 8 is changed, i.e. the double conversion A-m-A, too, is transparent to bits No. 1-7.
A consequence of this property is that in most of the analogue voice frequency signal range the additional quantizing distortion caused by m-A-m or A-m-A conversion is considerably lower than that caused by either m-A or A-m conversion (see Recommendation G.113).
-------------------
It sounds to me like you cannot do a bit transparent mu-A-mu or A-mu-A conversion cycle. Extra distortion will be introduced. Maybe this is the distortion you are referring to.
In case you do not have the G.711 standard document (from which the above quote is taken), you can retrieve it from www.itu.int
Note the red text: Corresponding ANSI-C code is available in the G.711 module of the ITU-T G.191 Software Tools Library. This is a huge library; the source text fills almost 70 MB. You might find useful code there.
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
Thanks, I will look deeper into this and see where it leads. The distortion I speak of could very well be explained by this. I will need to look at a ulaw file that has not been encoded by my alaw/ulaw encoders first to determine if it's do to the specs or something within my encoders causing it.
|
|
|
|
|
Further to the above excellent suggestions, why not create a 0..FF ramp and pass it through your process? Spotting the distortion would be very easy then.
Anything involving bit-shifting like this makes me very wary about sign extension. I've been bitten by assuming something is unsigned, wondering where all the high order 1's came from when I used >> .
Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012
|
|
|
|
|
Maybe a simple translation table like the one in this link? g711/ulaw.go at master · zaf/g711 · GitHub[^]
"the debugger doesn't tell me anything because this code compiles just fine" - random QA comment
"Facebook is where you tell lies to your friends. Twitter is where you tell the truth to strangers." - chriselst
"I don't drink any more... then again, I don't drink any less." - Mike Mullikins uncle
|
|
|
|
|
Thanks for the link. The error was in fact in the Ulaw to Alaw Encoding, The output audio now sounds identical although the samples are different. I will have to look into this I assume it could be do to endianness.
modified 18-Sep-24 23:04pm.
|
|
|
|
|
hi all,
is there any option to get image file thumbnail ,but without open the image file.
please guide me for this.
thanks in advance.
|
|
|
|
|
Maybe hire a medium to generate their interpretation of the contents of a file they've never seen?
Seriously, how do you think it would be possible to generate a smaller version of the image in a file without opening that file to see what the image is?
This sounds like an XY problem[^]. Perhaps if you ask for help with the issue you're actually trying to solve, rather than asking for help implementing the solution you think you need, then you might have better luck.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
To back up what Richard says, what you are asking for is logically impossible: it's like saying "write me a summary of this book, but don't read it first". You can't write an accurate summary without knowing what happens in the story!
The same applies to images: you can't create a thumbnail without access to the original image.
So as Richard suggests: think about the problem you are trying to solve instead of the solution you have conceived - there may be a better way to complete your task. Or even a possible one!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
FileStream fs = new System.IO.FileStream(img_path, FileMode.Open, FileAccess.Read);
img = Image.FromStream(fs);
Image imgThumb = img.GetThumbnailImage(thumbnailSize.Width, thumbnailSize.Height, null, IntPtr.Zero);
fs.Close();
fs.Dispose();
img.Dispose();
i use this for getting thumbnail, but it takes time if file is large,or i take tumbnail of multiple big size images....
that's why i ask its possible to get image thumbnail without using the image file.
is this possible with the use of "IExtractImage"
|
|
|
|
|
You're going to have the performance problem no matter what. Even using whatever interface that is, it's going to have to open the file and read the entire thing to generate the thumbnail.
|
|
|
|
|
As Dave has said, no - it's not possible.
However, there are two things you might consider to speed things up:
1) Cache your thumbnails. Create a new folder (if it doesn't exist) below the source image folder called "Thumbs", and when you need a thumbnail check that folder first for a file of the same name. If it exists, just read the thumbnail file. If it doesn't, generate the thumbnail and add it to the Thumbs folder. That doesn't speed everything up, but the second and successive times it will.
2) Do the above, but add a background thread that checks the images folder for "missing thumbs" and create them as needed. That again doesn't speed anything up, but it moves the generation into the background and "pre-prepares" thumbs that haven't been asked for yet.
Obviously, it'll take some work to ensure everything doesn't start colliding and your app crashes as a result, but it's that or insist that the images need to be added to your app before they are used (and creating the thumbnail then) - which may not be possible / convenient for your users / app.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|