Azure Function How To Return XML Not A String
I am trying to return a XML config file from an Azure Function. The config is being written into a string like below.
xml = @"<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
I am then returning it like this
return req.CreateResponse(HttpStatusCode.OK, xml.Replace("\r\n",""));
However the result from the HTTP call is like this
"
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>"
How do I get rid of the enclosing quotation marks?
1 answer
-
answered 2022-05-04 14:16
FreemanRU
You can use https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.contentresult?view=aspnetcore-6.0
var xml = @"<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>"; return new ContentResult() { Content = xml, ContentType = "text/xml"};
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
Java - Update Elements in Large XML Files
I work with very large XML datasets (1 GB+) and need to backtrack and update specific elements per node, depending on the values of other elements that follow.
For example, in this record/node:
<user> <role>Associate</role> <team>Hufflepuff</team> <experience>7</experience> </user>
Since "experience" is greater than 5 years, the role needs to be updated from "Associate" to "Senior."
I would like to avoid loading the entire file into memory via the DOM.
Ideally, I would process each single "user" in the XML and append the data to a new XML file one at a time. I started off by processing in a stream using StAX, but I don't know how to transform each XMLEventWriter event content into a useable DOM document that writes to an XML file and clears from memory afterwards.
If the description is unclear in any way, please let me know. Any help on this will be greatly appreciated.
Thanks.
-
cant read field in xml section
Using python I got to the correct iteration of the XML (forecast) section, but one child field I cant seem to be able to read here is the section from the XML
<forecast> <fcst_time_from>2022-05-04T16:00:00Z</fcst_time_from> <fcst_time_to>2022-05-04T20:00:00Z</fcst_time_to> <change_indicator>FM</change_indicator> <wind_dir_degrees>110</wind_dir_degrees> <wind_speed_kt>6</wind_speed_kt> <visibility_statute_mi>6.21</visibility_statute_mi> <sky_condition sky_cover="SCT" cloud_base_ft_agl="4500"/> <sky_condition sky_cover="SCT" cloud_base_ft_agl="25000"/> </forecast>
I can get every field except
<sky_condition sky_cover="SCT" cloud_base_ft_agl="25000"/>
here is the code where I pull the fields
if startTime_new <= Cur_Date_UTC <= EndTime_new: #Cil2 = (l.find('sky_cover')).text wDir = (l.find('wind_dir_degrees')).text wSpd = (l.find('wind_speed_kt')).text vis = (l.find('visibility_statute_mi')).text Cil = (l.find('sky_condition')).text print(wDir) print(wSpd) print(vis) print(Cil) print(l)
The answer given did work in a comand window but I am using beautifulsoup to get the XML . I tried to import from datetime import datetime however Cil = [x.get('sky_cover') for x in elt.findall('sky_condition')] did not work
here is my full code
from bs4 import BeautifulSoup as bs import requests import pytz from datetime import datetime #pirip=False def SetDateTimes(): utc_time = datetime.now(pytz.utc) Cur_Date_UTC = utc_time.strftime("%d/%m/%y %H:%M:%S") return Cur_Date_UTC def FixDateTime(workingTime): workingTime = workingTime.replace('T', ' ') workingTime = workingTime.replace('Z', '') format = "%Y-%m-%d %H:%M:%S" dt_object = datetime.strptime(workingTime, format) day_st = dt_object.strftime("%d") month_st = dt_object.strftime("%m") year_st = dt_object.strftime("%y") time_st = dt_object.strftime("%H:%M:%S") workingTime = day_st + '/' + month_st + '/' + year_st + ' ' + time_st return workingTime def GetTAF3(): USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36" url = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=tafs&requestType=retrieve&format=xml&hoursBeforeNow=3&timeType=issue&mostRecent=true&stationString=KEWR' session = requests.Session() session.headers['User-Agent'] = USER_AGENT html = session.get(url) soup = bs(html.text, 'html.parser') taf = soup.find_all("forecast") for l in soup.findAll('forecast'): startTime = l.find('fcst_time_from').text EndTime = (l.find('fcst_time_to')).text #print(startTime) startTime_new = FixDateTime(startTime) #print(startTime_new) #print(EndTime) EndTime_new = FixDateTime(EndTime) #print(EndTime_new) #break if startTime_new <= Cur_Date_UTC <= EndTime_new: #Cil2 = (l.find('sky_cover')).text print(l) wDir = (l.find('wind_dir_degrees')).text wSpd = (l.find('wind_speed_kt')).text vis = (l.find('visibility_statute_mi')).text Cil = (l.find('sky_condition')) print(wDir) print(wSpd) print(vis) print(Cil) print(l) if 'OVC' in Cil: print("OVC Found") pirip = True else: print('No PIRIP') if float(vis) < 5: print("pirip for vis") pirip = True else: print('No PIRIP') Cur_Date_UTC = SetDateTimes() GetTAF3() #print(pirip)
-
How can I use Continue in a choose statement in xslt
I want to continue to check for other if statements if the first one is met. From what I read, Choose statement does not have this functionality like other languages do. One post suggested to just run multiple if statements but this is not working. After the first if statement is met it stops there, I want it to keep running.
How can I achieve this? This is my code:
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="root"> { "entityList": [ <xsl:for-each select="//entityList"> { "notes":"<xsl:call-template name="replace"> <xsl:with-param name="text" select="./Notes"/> </xsl:call-template>", } <xsl:if test="position() != last()">,</xsl:if> </xsl:for-each> ] } </xsl:template> <xsl:template name="replace"> <xsl:param name="text"/> <xsl:param name="searchString">"</xsl:param> <xsl:param name="replaceString">\"</xsl:param> <xsl:param name="searchStringSpace">	</xsl:param> <xsl:param name="searchStringBackslash">\</xsl:param> <xsl:if test="contains($text,$searchString)"> <xsl:value-of select="replace(./Notes,'"','\\"')"/> </xsl:if> <xsl:if test="contains($text,$searchStringSpace)"> <xsl:value-of select="replace(./Notes,'	','\\t')"/> </xsl:if> </xsl:template> </xsl:stylesheet>
<root> <totalRecords>429</totalRecords> <offset>0</offset> <entityList> <Notes>Dear Deans, Chairs and "Directors,There was a 	ANDOR question about scheduling Mac Hall Auditorium,for regular classes and policy/procedure around it.,Mac Hall Auditorium was intended to be available as a,regular classroom. That is why the seats have built-in mini,desks.,Your programs are welcome to schedule classes in,Mac Auditorium - you can request it when submitting your,course schedules for the Semester or through the Schedule,Change Request Form.,There are, however, some conditions:,1)faculty members who teach in Mac Auditorium should,anticipate that their class may be displaced if the,University-wide function (president?s address, a conference,,etc.) is scheduled at the time of their class. It would be,up to the faculty to either reschedule that,class meeting for a different time, find another room/space,or substitute the class meeting with an alternative activity,There is no easy way to inform faculty about the upcoming,events, so they would have to watch University Calendar to,determine when their classes might be affected.,2)Mac Hall will be unavailable for scheduling regular,courses during evening hours (6-10 pm) ? that time will be,set aside for Pegasus Players practices.,Natalia F. Blank, Ph.D. 2/17/21</Notes> </entityList> <totalPages>1</totalPages> <page>0</page> <status>success</status> </root>
-
Deploy VueJS + API app to Azure Static Web App with Gitlab doesn't create functions
I've started creating a small application that will use VueJS as a frontend with Azure Functions as the backend. I was looking at using Azure Static Web Apps to host both components for the application and Gitlab to store / deploy the app.
Everything but the creation of the Azure functions works. Following https://docs.microsoft.com/en-us/azure/static-web-apps/gitlab?tabs=vue
The output from the deploy step, listed below is:
App Directory Location: '/builds/*/valhalla/valhalla-client/dist/spa' was found. Api Directory Location: '/builds/*/valhalla/valhalla-api/dist' was found. Looking for event info Could not get event info. Proceeding Starting to build app with Oryx Azure Static Web Apps utilizes Oryx to build both static applications and Azure Functions. You can find more details on Oryx here: https://github.com/microsoft/Oryx ---Oryx build logs--- Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx You can report issues at https://github.com/Microsoft/Oryx/issues Oryx Version: 0.2.20220131.3, Commit: ec344c058843461525ff03b46031553b6e15a47a, ReleaseTagName: 20220131.3 Build Operation ID: |qAffRWArEg8=.deee9498_ Repository Commit : 7cdd5b61f956e6cb8459b13a42af363c4440a97b Detecting platforms... Could not detect any platform in the source directory. Error: Could not detect the language from repo. ---End of Oryx build logs--- Oryx was unable to determine the build steps. Continuing assuming the assets in this folder are already built. If this is an unexpected behavior please contact support. Finished building app with Oryx Starting to build function app with Oryx ---Oryx build logs--- Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx You can report issues at https://github.com/Microsoft/Oryx/issues Oryx Version: 0.2.20220131.3, Commit: ec344c058843461525ff03b46031553b6e15a47a, ReleaseTagName: 20220131.3 Build Operation ID: |NGXLP5bVBRk=.705477f6_ Repository Commit : 7cdd5b61f956e6cb8459b13a42af363c4440a97b Detecting platforms... Could not detect any platform in the source directory. Error: Could not detect the language from repo. ---End of Oryx build logs--- Oryx was unable to determine the build steps. Continuing assuming the assets in this folder are already built. If this is an unexpected behavior please contact support. [WARNING] The function language could not be detected. The language will be defaulted to node. Function Runtime Information. OS: linux, Functions Runtime: ~3, node version: 12 Finished building function app with Oryx Zipping Api Artifacts Done Zipping Api Artifacts Zipping App Artifacts Done Zipping App Artifacts Uploading build artifacts. Finished Upload. Polling on deployment. Status: InProgress. Time: 0.1762737(s) Status: InProgress. Time: 15.3950401(s) Status: Succeeded. Time: 30.5043965(s) Deployment Complete :) Visit your site at: https://polite-pebble-0dc00000f.1.azurestaticapps.net Thanks for using Azure Static Web Apps! Exiting Cleaning up project directory and file based variables 00:00 Job succeeded
The deploy step appears to have succeeded, and the frontend is deployed, but there are no Azure Functions showing up in this Static Web App. Is something missed here? So far, the Azure Functions I have are the boiler-plate from instantiating a new Azure Function folder.
image: node:latest variables: API_TOKEN: $DEPLOYMENT_TOKEN APP_PATH: '$CI_PROJECT_DIR/valhalla-client/dist/spa' API_PATH: '$CI_PROJECT_DIR/valhalla-api/dist' stages: - install_api - build_api - install_client - build_client - deploy install_api: stage: install_api script: - cd valhalla-api - npm ci artifacts: paths: - valhalla-api/node_modules/ cache: key: node paths: - valhalla-api/node_modules/ only: - master install_client: stage: install_client script: - cd valhalla-client - npm ci artifacts: paths: - valhalla-client/node_modules/ cache: key: node paths: - valhalla-client/node_modules/ only: - master build_api: stage: build_api dependencies: - install_api script: - cd valhalla-api - npm install -g azure-functions-core-tools@3 --unsafe-perm true - npm run build artifacts: paths: - valhalla-api/dist cache: key: build_api paths: - valhalla-api/dist only: - master needs: - job: install_api artifacts: true optional: true build_client: stage: build_client dependencies: - install_client script: - cd valhalla-client - npm i -g @quasar/cli - quasar build artifacts: paths: - valhalla-client/dist/spa cache: key: build_client paths: - valhalla-client/dist/spa only: - master needs: - job: install_client artifacts: true optional: true deploy: stage: deploy dependencies: - build_api - build_client image: registry.gitlab.com/static-web-apps/azure-static-web-apps-deploy script: - echo "App deployed successfully." only: - master
-
Azure Synapse Notebooks Vs Azure Databricks notebooks
I was going through the features of Azure Synapse Notebooks Vs Azure Databricks notebooks.
- Are there any major differences between these apart from the component they belong to ?
- Are there any scenarios where one is more appropriate over other?
-
How to authorize azure container registry requests from .NET CORE C#
I have a web application which creates ContainerInstances, I have specific container registry images I want to use. As a result, I use this code to get my azure container registry
IAzure azure = Azure.Authenticate($"{applicationDirectory}/Resources/my.azureauth").WithDefaultSubscription(); IRegistry azureRegistry = azure.ContainerRegistries.GetByResourceGroup("testResourceGroup", "testContainerRegistryName");
I get this error when the second line of code is hit
The client 'bc8fd78c-2b1b-4596-827e-6a3c918b7c17' with object id 'bc8fd78c-2b1b-4596-827e-6a3c918b7c17' does not have authorization to perform action 'Microsoft.ContainerRegistry/registries/read' over scope '/subscriptions/506b787d-83ef-426a-b7b8-7bfcdd475855/resourceGroups/testapp-live/providers/Microsoft.ContainerRegistry/registries/testapp' or the scope is invalid. If access was recently granted, please refresh your credentials.
I literally have no idea what to do about this. I have seen so many articles talking about Azure AD and giving user roles and stuff. Can someone please walk me step by step how to fix this? I REALLY appreciate the help. Thanks.
I cannot find any client under that object ID so perfectly fine starting from scratch again with a better understanding of what I am doing.
-
How can I use functional update with event.currentTarget.value in React?
First, please check my code.
const [name, setName] = useState('nick'); const handleChangeName = (e) => { setName(prevState => e.currentTarget.value) } return ( <input value={name} onChange={handleChangeName} /> )
I'm trying to do functional update not
setName(e.currentTarget.value)
However, with this code,
const handleChangeName = (e) => { setName(prevState => e.currentTarget.value) }
I am not getting the right value for some reason. If you know what is the problem or the answer, please let me know! Thank you.
-
How to get pass an array through a function with a user input?
I want to ask the user for the size of a 2D array arr[][], but also pass it through the function initializeArray. However, if I pass it through the function, I would have to have a size declarator for col, which doesn't allow the user to enter their own value for the size
#include<iostream> using namespace std; void initializeArray(arr[][10], int N); int main() { int N; cout << "enter an array size: "; cin >> N; int arr[N][N]; initializeArray(arr, N); // I get an error here for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; } } void initializeArray(int arr[][10], int N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) arr[i][j] = 0; }
The only solution I found was the make arr[][] a global array, but in that case, I would have to still declare the size parameters, and I want the user to enter whatever they want. Is there another way to fix this?
-
Two-dimensional array C++
Problem: Write a program of a two dimensional integer array of exactly four rows and four columns, and find the sum of the integers each row of the array as well as determine the smallest inputted element/data in the array. The user will input the elements. Display the elements in tabular form. Make the program user friendly. Use a Class and a member function for the process involve.