We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
az monitor app-insights query Execute a simple query over past 3.5 days.
## Describe the bug
Trying to query Application Insights via the example provided via the [az monitor app-insights query](https://docs.microsoft.com/en-us/cli/azure/ext/application-insights/monitor/app-insights?view=azure-cli-latest#ext-application-insights-az-monitor-app-insights-query) docs.

**Command Name**
`az monitor app-insights query
Extension Name: application-insights. Version: 0.1.1.`

**Errors:**
```
unsupported operand type(s) for -: 'datetime.datetime' and 'str'
Traceback (most recent call last):
python3.6/site-packages/knack/cli.py, ln 206, in invoke
    cmd_result = self.invocation.execute(args)
cli/core/commands/__init__.py, ln 603, in execute
    raise ex
cli/core/commands/__init__.py, ln 661, in _run_jobs_serially
    results.append(self._run_job(expanded_arg, cmd_copy))
...
cliextensions/application-insights/azext_applicationinsights/util.py, ln 40, in get_timespan
    start_time = (dateutil.parser.parse(end_time) - offset).isoformat()
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'
```

## To Reproduce:
Steps to reproduce the behavior. Note that argument values have been redacted, as they may contain sensitive information.

- _Put any pre-requisite steps here..._
- `az monitor app-insights query --app <Your-GUID> --analytics-query 'requests | summarize count() by bin(timestamp, 1h)' --offset P3DT12H`

## Expected Behavior
Execute a simple query over the past 3.5 days.

## Environment Summary
```
Linux-4.4.0-18362-Microsoft-x86_64-with-debian-buster-sid
Python 3.6.5
Shell: bash

azure-cli 2.0.75

Extensions:
application-insights 0.1.1
log-analytics 0.1.3

```
## Additional Context

<!--Please don't remove this:-->
<!--auto-generated-->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/application-insights/azext_applicationinsights/custom.py`
Content:
```
1 # --------------------------------------------------------------------------------------------
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See License.txt in the project root for license information.
4 # --------------------------------------------------------------------------------------------
5 
6 # pylint: disable=line-too-long, protected-access
7 
8 from knack.util import CLIError
9 from knack.log import get_logger
10 from azext_applicationinsights.vendored_sdks.applicationinsights.models import ErrorResponseException
11 from msrestazure.azure_exceptions import CloudError
12 from .util import get_id_from_azure_resource, get_query_targets, get_timespan, get_linked_properties
13 
14 logger = get_logger(__name__)
15 HELP_MESSAGE = " Please use `az feature register --name AIWorkspacePreview --namespace microsoft.insights` to register the feature"
16 
17 
18 def execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):
19     """Executes a query against the provided Application Insights application."""
20     from .vendored_sdks.applicationinsights.models import QueryBody
21     targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)
22     try:
23         return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))
24     except ErrorResponseException as ex:
25         if "PathNotFoundError" in ex.message:
26             raise ValueError("The Application Insight is not found. Please check the app id again.")
27         raise ex
28 
29 
30 def get_events(cmd, client, application, event_type, event=None, start_time=None, end_time=None, offset='1h', resource_group_name=None):
31     timespan = get_timespan(cmd.cli_ctx, start_time, end_time, offset)
32     if event:
33         return client.events.get(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), event_type, event, timespan=timespan)
34     return client.events.get_by_type(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), event_type, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset))
35 
36 
37 def get_metric(cmd, client, application, metric, start_time=None, end_time=None, offset='1h', interval=None, aggregation=None, segment=None, top=None, orderby=None, filter_arg=None, resource_group_name=None):
38     return client.metrics.get(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), metric, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), interval=interval, aggregation=aggregation, segment=segment, top=top, orderby=orderby, filter_arg=filter_arg)
39 
40 
41 def get_metrics_metadata(cmd, client, application, resource_group_name=None):
42     return client.metrics.get_metadata(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name))
43 
44 
45 def create_or_update_component(cmd, client, application, resource_group_name, location, tags=None,
46                                kind="web", application_type='web', workspace_resource_id=None,
47                                public_network_access_for_ingestion=None, public_network_access_for_query=None):
48     # due to service limitation, we have to do such a hack. We must refract the logic later.
49     if workspace_resource_id is None:
50         from .vendored_sdks.mgmt_applicationinsights.v2018_05_01_preview.models import ApplicationInsightsComponent
51         component = ApplicationInsightsComponent(location=location, kind=kind, application_type=application_type, tags=tags,
52                                                  public_network_access_for_ingestion=public_network_access_for_ingestion,
53                                                  public_network_access_for_query=public_network_access_for_query)
54         return client.create_or_update(resource_group_name, application, component)
55 
56     from .vendored_sdks.mgmt_applicationinsights.v2020_02_02_preview.models import ApplicationInsightsComponent
57     component = ApplicationInsightsComponent(location=location, kind=kind, application_type=application_type,
58                                              tags=tags, workspace_resource_id=workspace_resource_id,
59                                              public_network_access_for_ingestion=public_network_access_for_ingestion,
60                                              public_network_access_for_query=public_network_access_for_query)
61     from ._client_factory import applicationinsights_mgmt_plane_client
62     client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components
63     try:
64         return client.create_or_update(resource_group_name, application, component)
65     except CloudError as ex:
66         ex.error._message = ex.error._message + HELP_MESSAGE
67         raise ex
68 
69 
70 def update_component(cmd, client, application, resource_group_name, kind=None, workspace_resource_id=None,
71                      public_network_access_for_ingestion=None, public_network_access_for_query=None):
72     from ._client_factory import applicationinsights_mgmt_plane_client
73     existing_component = None
74     if workspace_resource_id is not None:
75         latest_client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components
76         try:
77             existing_component = latest_client.get(resource_group_name, application)
78         except CloudError as ex:
79             ex.error._message = ex.error._message + HELP_MESSAGE
80             raise ex
81         existing_component.workspace_resource_id = workspace_resource_id or None
82     else:
83         existing_component = client.get(resource_group_name, application)
84     if kind:
85         existing_component.kind = kind
86     if public_network_access_for_ingestion is not None:
87         existing_component.public_network_access_for_ingestion = public_network_access_for_ingestion
88     if public_network_access_for_query is not None:
89         existing_component.public_network_access_for_query = public_network_access_for_query
90 
91     if hasattr(existing_component, 'workspace_resource_id') and existing_component.workspace_resource_id is not None:
92         client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components
93         return client.create_or_update(resource_group_name, application, existing_component)
94 
95     from .vendored_sdks.mgmt_applicationinsights.v2018_05_01_preview.models import ApplicationInsightsComponent
96     component = ApplicationInsightsComponent(**(vars(existing_component)))
97     return client.create_or_update(resource_group_name, application, component)
98 
99 
100 def update_component_tags(client, application, resource_group_name, tags):
101     return client.update_tags(resource_group_name, application, tags)
102 
103 
104 def get_component(client, application, resource_group_name):
105     return client.get(resource_group_name, application)
106 
107 
108 def show_components(cmd, client, application=None, resource_group_name=None):
109     from ._client_factory import applicationinsights_mgmt_plane_client
110     if application:
111         if resource_group_name:
112             latest_client = applicationinsights_mgmt_plane_client(cmd.cli_ctx,
113                                                                   api_version='2020-02-02-preview').components
114             try:
115                 return latest_client.get(resource_group_name, application)
116             except CloudError:
117                 logger.warning(HELP_MESSAGE)
118                 return client.get(resource_group_name, application)
119         raise CLIError("Application provided without resource group. Either specify app with resource group, or remove app.")
120     if resource_group_name:
121         return client.list_by_resource_group(resource_group_name)
122     return client.list()
123 
124 
125 def delete_component(client, application, resource_group_name):
126     return client.delete(resource_group_name, application)
127 
128 
129 def create_api_key(cmd, client, application, resource_group_name, api_key, read_properties=None, write_properties=None):
130     from .vendored_sdks.mgmt_applicationinsights.models import APIKeyRequest
131     if read_properties is None:
132         read_properties = ['ReadTelemetry', 'AuthenticateSDKControlChannel']
133     if write_properties is None:
134         write_properties = ['WriteAnnotations']
135     linked_read_properties, linked_write_properties = get_linked_properties(cmd.cli_ctx, application, resource_group_name, read_properties, write_properties)
136     api_key_request = APIKeyRequest(name=api_key,
137                                     linked_read_properties=linked_read_properties,
138                                     linked_write_properties=linked_write_properties)
139     return client.create(resource_group_name, application, api_key_request)
140 
141 
142 def show_api_key(client, application, resource_group_name, api_key=None):
143     if api_key is None:
144         return client.list(resource_group_name, application)
145     result = list(filter(lambda result: result.name == api_key, client.list(resource_group_name, application)))
146     if len(result) == 1:
147         return result[0]
148     if len(result) > 1:
149         return result
150     return None
151 
152 
153 def delete_api_key(client, application, resource_group_name, api_key):
154     existing_key = list(filter(lambda result: result.name == api_key, client.list(resource_group_name, application)))
155     if existing_key != []:
156         return client.delete(resource_group_name, application, existing_key[0].id.split('/')[-1])
157     raise CLIError('--api-key provided but key not found for deletion.')
158 
159 
160 def show_component_billing(client, application, resource_group_name):
161     return client.get(resource_group_name=resource_group_name, resource_name=application)
162 
163 
164 def update_component_billing(client, application, resource_group_name, cap=None, stop_sending_notification_when_hitting_cap=None):
165     billing_features = client.get(resource_group_name=resource_group_name, resource_name=application)
166     if cap is not None:
167         billing_features.data_volume_cap.cap = cap
168     if stop_sending_notification_when_hitting_cap is not None:
169         billing_features.data_volume_cap.stop_send_notification_when_hit_cap = stop_sending_notification_when_hitting_cap
170     return client.update(resource_group_name=resource_group_name,
171                          resource_name=application,
172                          data_volume_cap=billing_features.data_volume_cap,
173                          current_billing_features=billing_features.current_billing_features)
174 
175 
176 def get_component_linked_storage_account(client, resource_group_name, application):
177     return client.get(resource_group_name=resource_group_name, resource_name=application)
178 
179 
180 def create_component_linked_storage_account(client, resource_group_name, application, storage_account_id):
181     return client.create_and_update(resource_group_name=resource_group_name, resource_name=application, linked_storage_account=storage_account_id)
182 
183 
184 def update_component_linked_storage_account(client, resource_group_name, application, storage_account_id):
185     return client.update(resource_group_name=resource_group_name, resource_name=application, linked_storage_account=storage_account_id)
186 
187 
188 def delete_component_linked_storage_account(client, resource_group_name, application):
189     return client.delete(resource_group_name=resource_group_name, resource_name=application)
190
```

Path: `src/application-insights/setup.py`
Content:
```
1 #!/usr/bin/env python
2 
3 # --------------------------------------------------------------------------------------------
4 # Copyright (c) Microsoft Corporation. All rights reserved.
5 # Licensed under the MIT License. See License.txt in the project root for license information.
6 # --------------------------------------------------------------------------------------------
7 
8 from codecs import open
9 from setuptools import setup, find_packages
10 
11 VERSION = "0.1.7"
12 
13 CLASSIFIERS = [
14     'Development Status :: 4 - Beta',
15     'Intended Audience :: Developers',
16     'Intended Audience :: System Administrators',
17     'Programming Language :: Python',
18     'Programming Language :: Python :: 2',
19     'Programming Language :: Python :: 2.7',
20     'Programming Language :: Python :: 3',
21     'Programming Language :: Python :: 3.4',
22     'Programming Language :: Python :: 3.5',
23     'Programming Language :: Python :: 3.6',
24     'License :: OSI Approved :: MIT License',
25 ]
26 
27 DEPENDENCIES = []
28 
29 with open('README.rst', 'r', encoding='utf-8') as f:
30     README = f.read()
31 with open('HISTORY.rst', 'r', encoding='utf-8') as f:
32     HISTORY = f.read()
33 
34 setup(
35     name='application-insights',
36     version=VERSION,
37     description='Support for managing Application Insights components and querying metrics, events, and logs from such components.',
38     long_description=README + '\n\n' + HISTORY,
39     license='MIT',
40     author='Ace Eldeib',
41     author_email='aleldeib@microsoft.com',
42     url='https://github.com/Azure/azure-cli-extensions/tree/master/src/application-insights',
43     classifiers=CLASSIFIERS,
44     packages=find_packages(exclude=["tests"]),
45     package_data={'azext_applicationinsights': ['azext_metadata.json']},
46     install_requires=DEPENDENCIES
47 )
48
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/application-insights/azext_applicationinsights/custom.py b/src/application-insights/azext_applicationinsights/custom.py
--- a/src/application-insights/azext_applicationinsights/custom.py
+++ b/src/application-insights/azext_applicationinsights/custom.py
@@ -5,6 +5,8 @@
 
 # pylint: disable=line-too-long, protected-access
 
+import datetime
+import isodate
 from knack.util import CLIError
 from knack.log import get_logger
 from azext_applicationinsights.vendored_sdks.applicationinsights.models import ErrorResponseException
@@ -19,6 +21,8 @@
     """Executes a query against the provided Application Insights application."""
     from .vendored_sdks.applicationinsights.models import QueryBody
     targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)
+    if not isinstance(offset, datetime.timedelta):
+        offset = isodate.parse_duration(offset)
     try:
         return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))
     except ErrorResponseException as ex:
diff --git a/src/application-insights/setup.py b/src/application-insights/setup.py
--- a/src/application-insights/setup.py
+++ b/src/application-insights/setup.py
@@ -8,7 +8,7 @@
 from codecs import open
 from setuptools import setup, find_packages
 
-VERSION = "0.1.7"
+VERSION = "0.1.8"
 
 CLASSIFIERS = [
     'Development Status :: 4 - Beta',
@@ -24,7 +24,9 @@
     'License :: OSI Approved :: MIT License',
 ]
 
-DEPENDENCIES = []
+DEPENDENCIES = [
+    "isodate~=0.6.0"
+]
 
 with open('README.rst', 'r', encoding='utf-8') as f:
     README = f.read()

{"golden_diff": "diff --git a/src/application-insights/azext_applicationinsights/custom.py b/src/application-insights/azext_applicationinsights/custom.py\n--- a/src/application-insights/azext_applicationinsights/custom.py\n+++ b/src/application-insights/azext_applicationinsights/custom.py\n@@ -5,6 +5,8 @@\n \n # pylint: disable=line-too-long, protected-access\n \n+import datetime\n+import isodate\n from knack.util import CLIError\n from knack.log import get_logger\n from azext_applicationinsights.vendored_sdks.applicationinsights.models import ErrorResponseException\n@@ -19,6 +21,8 @@\n     \"\"\"Executes a query against the provided Application Insights application.\"\"\"\n     from .vendored_sdks.applicationinsights.models import QueryBody\n     targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)\n+    if not isinstance(offset, datetime.timedelta):\n+        offset = isodate.parse_duration(offset)\n     try:\n         return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))\n     except ErrorResponseException as ex:\ndiff --git a/src/application-insights/setup.py b/src/application-insights/setup.py\n--- a/src/application-insights/setup.py\n+++ b/src/application-insights/setup.py\n@@ -8,7 +8,7 @@\n from codecs import open\n from setuptools import setup, find_packages\n \n-VERSION = \"0.1.7\"\n+VERSION = \"0.1.8\"\n \n CLASSIFIERS = [\n     'Development Status :: 4 - Beta',\n@@ -24,7 +24,9 @@\n     'License :: OSI Approved :: MIT License',\n ]\n \n-DEPENDENCIES = []\n+DEPENDENCIES = [\n+    \"isodate~=0.6.0\"\n+]\n \n with open('README.rst', 'r', encoding='utf-8') as f:\n     README = f.read()\n", "issue": "az monitor app-insights query Execute a simple query over past 3.5 days.\n## Describe the bug\r\nTrying to query Application Insights via the example provided via the [az monitor app-insights query](https://docs.microsoft.com/en-us/cli/azure/ext/application-insights/monitor/app-insights?view=azure-cli-latest#ext-application-insights-az-monitor-app-insights-query) docs.\r\n\r\n**Command Name**\r\n`az monitor app-insights query\r\nExtension Name: application-insights. Version: 0.1.1.`\r\n\r\n**Errors:**\r\n```\r\nunsupported operand type(s) for -: 'datetime.datetime' and 'str'\r\nTraceback (most recent call last):\r\npython3.6/site-packages/knack/cli.py, ln 206, in invoke\r\n    cmd_result = self.invocation.execute(args)\r\ncli/core/commands/__init__.py, ln 603, in execute\r\n    raise ex\r\ncli/core/commands/__init__.py, ln 661, in _run_jobs_serially\r\n    results.append(self._run_job(expanded_arg, cmd_copy))\r\n...\r\ncliextensions/application-insights/azext_applicationinsights/util.py, ln 40, in get_timespan\r\n    start_time = (dateutil.parser.parse(end_time) - offset).isoformat()\r\nTypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'\r\n```\r\n\r\n## To Reproduce:\r\nSteps to reproduce the behavior. Note that argument values have been redacted, as they may contain sensitive information.\r\n\r\n- _Put any pre-requisite steps here..._\r\n- `az monitor app-insights query --app <Your-GUID> --analytics-query 'requests | summarize count() by bin(timestamp, 1h)' --offset P3DT12H`\r\n\r\n## Expected Behavior\r\nExecute a simple query over the past 3.5 days.\r\n\r\n## Environment Summary\r\n```\r\nLinux-4.4.0-18362-Microsoft-x86_64-with-debian-buster-sid\r\nPython 3.6.5\r\nShell: bash\r\n\r\nazure-cli 2.0.75\r\n\r\nExtensions:\r\napplication-insights 0.1.1\r\nlog-analytics 0.1.3\r\n\r\n```\r\n## Additional Context\r\n\r\n<!--Please don't remove this:-->\r\n<!--auto-generated-->\r\n\n", "before_files": [{"content": "# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n# pylint: disable=line-too-long, protected-access\n\nfrom knack.util import CLIError\nfrom knack.log import get_logger\nfrom azext_applicationinsights.vendored_sdks.applicationinsights.models import ErrorResponseException\nfrom msrestazure.azure_exceptions import CloudError\nfrom .util import get_id_from_azure_resource, get_query_targets, get_timespan, get_linked_properties\n\nlogger = get_logger(__name__)\nHELP_MESSAGE = \" Please use `az feature register --name AIWorkspacePreview --namespace microsoft.insights` to register the feature\"\n\n\ndef execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):\n    \"\"\"Executes a query against the provided Application Insights application.\"\"\"\n    from .vendored_sdks.applicationinsights.models import QueryBody\n    targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)\n    try:\n        return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))\n    except ErrorResponseException as ex:\n        if \"PathNotFoundError\" in ex.message:\n            raise ValueError(\"The Application Insight is not found. Please check the app id again.\")\n        raise ex\n\n\ndef get_events(cmd, client, application, event_type, event=None, start_time=None, end_time=None, offset='1h', resource_group_name=None):\n    timespan = get_timespan(cmd.cli_ctx, start_time, end_time, offset)\n    if event:\n        return client.events.get(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), event_type, event, timespan=timespan)\n    return client.events.get_by_type(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), event_type, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset))\n\n\ndef get_metric(cmd, client, application, metric, start_time=None, end_time=None, offset='1h', interval=None, aggregation=None, segment=None, top=None, orderby=None, filter_arg=None, resource_group_name=None):\n    return client.metrics.get(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), metric, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), interval=interval, aggregation=aggregation, segment=segment, top=top, orderby=orderby, filter_arg=filter_arg)\n\n\ndef get_metrics_metadata(cmd, client, application, resource_group_name=None):\n    return client.metrics.get_metadata(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name))\n\n\ndef create_or_update_component(cmd, client, application, resource_group_name, location, tags=None,\n                               kind=\"web\", application_type='web', workspace_resource_id=None,\n                               public_network_access_for_ingestion=None, public_network_access_for_query=None):\n    # due to service limitation, we have to do such a hack. We must refract the logic later.\n    if workspace_resource_id is None:\n        from .vendored_sdks.mgmt_applicationinsights.v2018_05_01_preview.models import ApplicationInsightsComponent\n        component = ApplicationInsightsComponent(location=location, kind=kind, application_type=application_type, tags=tags,\n                                                 public_network_access_for_ingestion=public_network_access_for_ingestion,\n                                                 public_network_access_for_query=public_network_access_for_query)\n        return client.create_or_update(resource_group_name, application, component)\n\n    from .vendored_sdks.mgmt_applicationinsights.v2020_02_02_preview.models import ApplicationInsightsComponent\n    component = ApplicationInsightsComponent(location=location, kind=kind, application_type=application_type,\n                                             tags=tags, workspace_resource_id=workspace_resource_id,\n                                             public_network_access_for_ingestion=public_network_access_for_ingestion,\n                                             public_network_access_for_query=public_network_access_for_query)\n    from ._client_factory import applicationinsights_mgmt_plane_client\n    client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components\n    try:\n        return client.create_or_update(resource_group_name, application, component)\n    except CloudError as ex:\n        ex.error._message = ex.error._message + HELP_MESSAGE\n        raise ex\n\n\ndef update_component(cmd, client, application, resource_group_name, kind=None, workspace_resource_id=None,\n                     public_network_access_for_ingestion=None, public_network_access_for_query=None):\n    from ._client_factory import applicationinsights_mgmt_plane_client\n    existing_component = None\n    if workspace_resource_id is not None:\n        latest_client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components\n        try:\n            existing_component = latest_client.get(resource_group_name, application)\n        except CloudError as ex:\n            ex.error._message = ex.error._message + HELP_MESSAGE\n            raise ex\n        existing_component.workspace_resource_id = workspace_resource_id or None\n    else:\n        existing_component = client.get(resource_group_name, application)\n    if kind:\n        existing_component.kind = kind\n    if public_network_access_for_ingestion is not None:\n        existing_component.public_network_access_for_ingestion = public_network_access_for_ingestion\n    if public_network_access_for_query is not None:\n        existing_component.public_network_access_for_query = public_network_access_for_query\n\n    if hasattr(existing_component, 'workspace_resource_id') and existing_component.workspace_resource_id is not None:\n        client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components\n        return client.create_or_update(resource_group_name, application, existing_component)\n\n    from .vendored_sdks.mgmt_applicationinsights.v2018_05_01_preview.models import ApplicationInsightsComponent\n    component = ApplicationInsightsComponent(**(vars(existing_component)))\n    return client.create_or_update(resource_group_name, application, component)\n\n\ndef update_component_tags(client, application, resource_group_name, tags):\n    return client.update_tags(resource_group_name, application, tags)\n\n\ndef get_component(client, application, resource_group_name):\n    return client.get(resource_group_name, application)\n\n\ndef show_components(cmd, client, application=None, resource_group_name=None):\n    from ._client_factory import applicationinsights_mgmt_plane_client\n    if application:\n        if resource_group_name:\n            latest_client = applicationinsights_mgmt_plane_client(cmd.cli_ctx,\n                                                                  api_version='2020-02-02-preview').components\n            try:\n                return latest_client.get(resource_group_name, application)\n            except CloudError:\n                logger.warning(HELP_MESSAGE)\n                return client.get(resource_group_name, application)\n        raise CLIError(\"Application provided without resource group. Either specify app with resource group, or remove app.\")\n    if resource_group_name:\n        return client.list_by_resource_group(resource_group_name)\n    return client.list()\n\n\ndef delete_component(client, application, resource_group_name):\n    return client.delete(resource_group_name, application)\n\n\ndef create_api_key(cmd, client, application, resource_group_name, api_key, read_properties=None, write_properties=None):\n    from .vendored_sdks.mgmt_applicationinsights.models import APIKeyRequest\n    if read_properties is None:\n        read_properties = ['ReadTelemetry', 'AuthenticateSDKControlChannel']\n    if write_properties is None:\n        write_properties = ['WriteAnnotations']\n    linked_read_properties, linked_write_properties = get_linked_properties(cmd.cli_ctx, application, resource_group_name, read_properties, write_properties)\n    api_key_request = APIKeyRequest(name=api_key,\n                                    linked_read_properties=linked_read_properties,\n                                    linked_write_properties=linked_write_properties)\n    return client.create(resource_group_name, application, api_key_request)\n\n\ndef show_api_key(client, application, resource_group_name, api_key=None):\n    if api_key is None:\n        return client.list(resource_group_name, application)\n    result = list(filter(lambda result: result.name == api_key, client.list(resource_group_name, application)))\n    if len(result) == 1:\n        return result[0]\n    if len(result) > 1:\n        return result\n    return None\n\n\ndef delete_api_key(client, application, resource_group_name, api_key):\n    existing_key = list(filter(lambda result: result.name == api_key, client.list(resource_group_name, application)))\n    if existing_key != []:\n        return client.delete(resource_group_name, application, existing_key[0].id.split('/')[-1])\n    raise CLIError('--api-key provided but key not found for deletion.')\n\n\ndef show_component_billing(client, application, resource_group_name):\n    return client.get(resource_group_name=resource_group_name, resource_name=application)\n\n\ndef update_component_billing(client, application, resource_group_name, cap=None, stop_sending_notification_when_hitting_cap=None):\n    billing_features = client.get(resource_group_name=resource_group_name, resource_name=application)\n    if cap is not None:\n        billing_features.data_volume_cap.cap = cap\n    if stop_sending_notification_when_hitting_cap is not None:\n        billing_features.data_volume_cap.stop_send_notification_when_hit_cap = stop_sending_notification_when_hitting_cap\n    return client.update(resource_group_name=resource_group_name,\n                         resource_name=application,\n                         data_volume_cap=billing_features.data_volume_cap,\n                         current_billing_features=billing_features.current_billing_features)\n\n\ndef get_component_linked_storage_account(client, resource_group_name, application):\n    return client.get(resource_group_name=resource_group_name, resource_name=application)\n\n\ndef create_component_linked_storage_account(client, resource_group_name, application, storage_account_id):\n    return client.create_and_update(resource_group_name=resource_group_name, resource_name=application, linked_storage_account=storage_account_id)\n\n\ndef update_component_linked_storage_account(client, resource_group_name, application, storage_account_id):\n    return client.update(resource_group_name=resource_group_name, resource_name=application, linked_storage_account=storage_account_id)\n\n\ndef delete_component_linked_storage_account(client, resource_group_name, application):\n    return client.delete(resource_group_name=resource_group_name, resource_name=application)\n", "path": "src/application-insights/azext_applicationinsights/custom.py"}, {"content": "#!/usr/bin/env python\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom codecs import open\nfrom setuptools import setup, find_packages\n\nVERSION = \"0.1.7\"\n\nCLASSIFIERS = [\n    'Development Status :: 4 - Beta',\n    'Intended Audience :: Developers',\n    'Intended Audience :: System Administrators',\n    'Programming Language :: Python',\n    'Programming Language :: Python :: 2',\n    'Programming Language :: Python :: 2.7',\n    'Programming Language :: Python :: 3',\n    'Programming Language :: Python :: 3.4',\n    'Programming Language :: Python :: 3.5',\n    'Programming Language :: Python :: 3.6',\n    'License :: OSI Approved :: MIT License',\n]\n\nDEPENDENCIES = []\n\nwith open('README.rst', 'r', encoding='utf-8') as f:\n    README = f.read()\nwith open('HISTORY.rst', 'r', encoding='utf-8') as f:\n    HISTORY = f.read()\n\nsetup(\n    name='application-insights',\n    version=VERSION,\n    description='Support for managing Application Insights components and querying metrics, events, and logs from such components.',\n    long_description=README + '\\n\\n' + HISTORY,\n    license='MIT',\n    author='Ace Eldeib',\n    author_email='aleldeib@microsoft.com',\n    url='https://github.com/Azure/azure-cli-extensions/tree/master/src/application-insights',\n    classifiers=CLASSIFIERS,\n    packages=find_packages(exclude=[\"tests\"]),\n    package_data={'azext_applicationinsights': ['azext_metadata.json']},\n    install_requires=DEPENDENCIES\n)\n", "path": "src/application-insights/setup.py"}], "after_files": [{"content": "# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n# pylint: disable=line-too-long, protected-access\n\nimport datetime\nimport isodate\nfrom knack.util import CLIError\nfrom knack.log import get_logger\nfrom azext_applicationinsights.vendored_sdks.applicationinsights.models import ErrorResponseException\nfrom msrestazure.azure_exceptions import CloudError\nfrom .util import get_id_from_azure_resource, get_query_targets, get_timespan, get_linked_properties\n\nlogger = get_logger(__name__)\nHELP_MESSAGE = \" Please use `az feature register --name AIWorkspacePreview --namespace microsoft.insights` to register the feature\"\n\n\ndef execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):\n    \"\"\"Executes a query against the provided Application Insights application.\"\"\"\n    from .vendored_sdks.applicationinsights.models import QueryBody\n    targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)\n    if not isinstance(offset, datetime.timedelta):\n        offset = isodate.parse_duration(offset)\n    try:\n        return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))\n    except ErrorResponseException as ex:\n        if \"PathNotFoundError\" in ex.message:\n            raise ValueError(\"The Application Insight is not found. Please check the app id again.\")\n        raise ex\n\n\ndef get_events(cmd, client, application, event_type, event=None, start_time=None, end_time=None, offset='1h', resource_group_name=None):\n    timespan = get_timespan(cmd.cli_ctx, start_time, end_time, offset)\n    if event:\n        return client.events.get(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), event_type, event, timespan=timespan)\n    return client.events.get_by_type(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), event_type, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset))\n\n\ndef get_metric(cmd, client, application, metric, start_time=None, end_time=None, offset='1h', interval=None, aggregation=None, segment=None, top=None, orderby=None, filter_arg=None, resource_group_name=None):\n    return client.metrics.get(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name), metric, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), interval=interval, aggregation=aggregation, segment=segment, top=top, orderby=orderby, filter_arg=filter_arg)\n\n\ndef get_metrics_metadata(cmd, client, application, resource_group_name=None):\n    return client.metrics.get_metadata(get_id_from_azure_resource(cmd.cli_ctx, application, resource_group=resource_group_name))\n\n\ndef create_or_update_component(cmd, client, application, resource_group_name, location, tags=None,\n                               kind=\"web\", application_type='web', workspace_resource_id=None,\n                               public_network_access_for_ingestion=None, public_network_access_for_query=None):\n    # due to service limitation, we have to do such a hack. We must refract the logic later.\n    if workspace_resource_id is None:\n        from .vendored_sdks.mgmt_applicationinsights.v2018_05_01_preview.models import ApplicationInsightsComponent\n        component = ApplicationInsightsComponent(location=location, kind=kind, application_type=application_type, tags=tags,\n                                                 public_network_access_for_ingestion=public_network_access_for_ingestion,\n                                                 public_network_access_for_query=public_network_access_for_query)\n        return client.create_or_update(resource_group_name, application, component)\n\n    from .vendored_sdks.mgmt_applicationinsights.v2020_02_02_preview.models import ApplicationInsightsComponent\n    component = ApplicationInsightsComponent(location=location, kind=kind, application_type=application_type,\n                                             tags=tags, workspace_resource_id=workspace_resource_id,\n                                             public_network_access_for_ingestion=public_network_access_for_ingestion,\n                                             public_network_access_for_query=public_network_access_for_query)\n    from ._client_factory import applicationinsights_mgmt_plane_client\n    client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components\n    try:\n        return client.create_or_update(resource_group_name, application, component)\n    except CloudError as ex:\n        ex.error._message = ex.error._message + HELP_MESSAGE\n        raise ex\n\n\ndef update_component(cmd, client, application, resource_group_name, kind=None, workspace_resource_id=None,\n                     public_network_access_for_ingestion=None, public_network_access_for_query=None):\n    from ._client_factory import applicationinsights_mgmt_plane_client\n    existing_component = None\n    if workspace_resource_id is not None:\n        latest_client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components\n        try:\n            existing_component = latest_client.get(resource_group_name, application)\n        except CloudError as ex:\n            ex.error._message = ex.error._message + HELP_MESSAGE\n            raise ex\n        existing_component.workspace_resource_id = workspace_resource_id or None\n    else:\n        existing_component = client.get(resource_group_name, application)\n    if kind:\n        existing_component.kind = kind\n    if public_network_access_for_ingestion is not None:\n        existing_component.public_network_access_for_ingestion = public_network_access_for_ingestion\n    if public_network_access_for_query is not None:\n        existing_component.public_network_access_for_query = public_network_access_for_query\n\n    if hasattr(existing_component, 'workspace_resource_id') and existing_component.workspace_resource_id is not None:\n        client = applicationinsights_mgmt_plane_client(cmd.cli_ctx, api_version='2020-02-02-preview').components\n        return client.create_or_update(resource_group_name, application, existing_component)\n\n    from .vendored_sdks.mgmt_applicationinsights.v2018_05_01_preview.models import ApplicationInsightsComponent\n    component = ApplicationInsightsComponent(**(vars(existing_component)))\n    return client.create_or_update(resource_group_name, application, component)\n\n\ndef update_component_tags(client, application, resource_group_name, tags):\n    return client.update_tags(resource_group_name, application, tags)\n\n\ndef get_component(client, application, resource_group_name):\n    return client.get(resource_group_name, application)\n\n\ndef show_components(cmd, client, application=None, resource_group_name=None):\n    from ._client_factory import applicationinsights_mgmt_plane_client\n    if application:\n        if resource_group_name:\n            latest_client = applicationinsights_mgmt_plane_client(cmd.cli_ctx,\n                                                                  api_version='2020-02-02-preview').components\n            try:\n                return latest_client.get(resource_group_name, application)\n            except CloudError:\n                logger.warning(HELP_MESSAGE)\n                return client.get(resource_group_name, application)\n        raise CLIError(\"Application provided without resource group. Either specify app with resource group, or remove app.\")\n    if resource_group_name:\n        return client.list_by_resource_group(resource_group_name)\n    return client.list()\n\n\ndef delete_component(client, application, resource_group_name):\n    return client.delete(resource_group_name, application)\n\n\ndef create_api_key(cmd, client, application, resource_group_name, api_key, read_properties=None, write_properties=None):\n    from .vendored_sdks.mgmt_applicationinsights.models import APIKeyRequest\n    if read_properties is None:\n        read_properties = ['ReadTelemetry', 'AuthenticateSDKControlChannel']\n    if write_properties is None:\n        write_properties = ['WriteAnnotations']\n    linked_read_properties, linked_write_properties = get_linked_properties(cmd.cli_ctx, application, resource_group_name, read_properties, write_properties)\n    api_key_request = APIKeyRequest(name=api_key,\n                                    linked_read_properties=linked_read_properties,\n                                    linked_write_properties=linked_write_properties)\n    return client.create(resource_group_name, application, api_key_request)\n\n\ndef show_api_key(client, application, resource_group_name, api_key=None):\n    if api_key is None:\n        return client.list(resource_group_name, application)\n    result = list(filter(lambda result: result.name == api_key, client.list(resource_group_name, application)))\n    if len(result) == 1:\n        return result[0]\n    if len(result) > 1:\n        return result\n    return None\n\n\ndef delete_api_key(client, application, resource_group_name, api_key):\n    existing_key = list(filter(lambda result: result.name == api_key, client.list(resource_group_name, application)))\n    if existing_key != []:\n        return client.delete(resource_group_name, application, existing_key[0].id.split('/')[-1])\n    raise CLIError('--api-key provided but key not found for deletion.')\n\n\ndef show_component_billing(client, application, resource_group_name):\n    return client.get(resource_group_name=resource_group_name, resource_name=application)\n\n\ndef update_component_billing(client, application, resource_group_name, cap=None, stop_sending_notification_when_hitting_cap=None):\n    billing_features = client.get(resource_group_name=resource_group_name, resource_name=application)\n    if cap is not None:\n        billing_features.data_volume_cap.cap = cap\n    if stop_sending_notification_when_hitting_cap is not None:\n        billing_features.data_volume_cap.stop_send_notification_when_hit_cap = stop_sending_notification_when_hitting_cap\n    return client.update(resource_group_name=resource_group_name,\n                         resource_name=application,\n                         data_volume_cap=billing_features.data_volume_cap,\n                         current_billing_features=billing_features.current_billing_features)\n\n\ndef get_component_linked_storage_account(client, resource_group_name, application):\n    return client.get(resource_group_name=resource_group_name, resource_name=application)\n\n\ndef create_component_linked_storage_account(client, resource_group_name, application, storage_account_id):\n    return client.create_and_update(resource_group_name=resource_group_name, resource_name=application, linked_storage_account=storage_account_id)\n\n\ndef update_component_linked_storage_account(client, resource_group_name, application, storage_account_id):\n    return client.update(resource_group_name=resource_group_name, resource_name=application, linked_storage_account=storage_account_id)\n\n\ndef delete_component_linked_storage_account(client, resource_group_name, application):\n    return client.delete(resource_group_name=resource_group_name, resource_name=application)\n", "path": "src/application-insights/azext_applicationinsights/custom.py"}, {"content": "#!/usr/bin/env python\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom codecs import open\nfrom setuptools import setup, find_packages\n\nVERSION = \"0.1.8\"\n\nCLASSIFIERS = [\n    'Development Status :: 4 - Beta',\n    'Intended Audience :: Developers',\n    'Intended Audience :: System Administrators',\n    'Programming Language :: Python',\n    'Programming Language :: Python :: 2',\n    'Programming Language :: Python :: 2.7',\n    'Programming Language :: Python :: 3',\n    'Programming Language :: Python :: 3.4',\n    'Programming Language :: Python :: 3.5',\n    'Programming Language :: Python :: 3.6',\n    'License :: OSI Approved :: MIT License',\n]\n\nDEPENDENCIES = [\n    \"isodate~=0.6.0\"\n]\n\nwith open('README.rst', 'r', encoding='utf-8') as f:\n    README = f.read()\nwith open('HISTORY.rst', 'r', encoding='utf-8') as f:\n    HISTORY = f.read()\n\nsetup(\n    name='application-insights',\n    version=VERSION,\n    description='Support for managing Application Insights components and querying metrics, events, and logs from such components.',\n    long_description=README + '\\n\\n' + HISTORY,\n    license='MIT',\n    author='Ace Eldeib',\n    author_email='aleldeib@microsoft.com',\n    url='https://github.com/Azure/azure-cli-extensions/tree/master/src/application-insights',\n    classifiers=CLASSIFIERS,\n    packages=find_packages(exclude=[\"tests\"]),\n    package_data={'azext_applicationinsights': ['azext_metadata.json']},\n    install_requires=DEPENDENCIES\n)\n", "path": "src/application-insights/setup.py"}]}